contract_name
stringlengths
1
61
file_path
stringlengths
5
50.4k
contract_address
stringlengths
42
42
language
stringclasses
1 value
class_name
stringlengths
1
61
class_code
stringlengths
4
330k
class_documentation
stringlengths
0
29.1k
class_documentation_type
stringclasses
6 values
func_name
stringlengths
0
62
func_code
stringlengths
1
303k
func_documentation
stringlengths
2
14.9k
func_documentation_type
stringclasses
4 values
compiler_version
stringlengths
15
42
license_type
stringclasses
14 values
swarm_source
stringlengths
0
71
meta
dict
__index_level_0__
int64
0
60.4k
InariV1
@boringcrypto/boring-solidity/contracts/BoringBatchable.sol
0x195e8262aa81ba560478ec6ca4da73745547073f
Solidity
InariV1
contract InariV1 is BoringBatchableWithDai, SushiZap { using SafeMath for uint256; using BoringERC20 for IERC20; IERC20 constant sushiToken = IERC20(0x6B3595068778DD592e39A122f4f5a5cF09C90fE2); // SUSHI token contract address constant sushiBar = 0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272; // xSUSHI staking contract for SUSHI ISushiSwap constant sushiSwapSushiETHPair = ISushiSwap(0x795065dCc9f64b5614C407a6EFDC400DA6221FB0); // SUSHI/ETH pair on SushiSwap IMasterChefV2 constant masterChefv2 = IMasterChefV2(0xEF0881eC094552b2e128Cf945EF17a6752B4Ec5d); // SUSHI MasterChef v2 contract IAaveBridge constant aave = IAaveBridge(0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9); // AAVE lending pool contract for xSUSHI staking into aXSUSHI IERC20 constant aaveSushiToken = IERC20(0xF256CC7847E919FAc9B808cC216cAc87CCF2f47a); // aXSUSHI staking contract for xSUSHI IBentoBridge constant bento = IBentoBridge(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966); // BENTO vault contract address constant crSushiToken = 0x338286C0BC081891A4Bda39C7667ae150bf5D206; // crSUSHI staking contract for SUSHI address constant crXSushiToken = 0x228619CCa194Fbe3Ebeb2f835eC1eA5080DaFbb2; // crXSUSHI staking contract for xSUSHI /// @notice Initialize this Inari contract. constructor() { bento.registerProtocol(); // register this contract with BENTO } /// @notice Helper function to approve this contract to spend tokens and enable strategies. function bridgeToken(IERC20[] calldata token, address[] calldata to) external { for (uint256 i = 0; i < token.length; i++) { token[i].safeApprove(to[i], type(uint256).max); // max approve `to` spender to pull `token` from this contract } } /********** TKN HELPERS **********/ function withdrawToken(IERC20 token, address to, uint256 amount) external { token.safeTransfer(to, amount); } function withdrawTokenBalance(IERC20 token, address to) external { token.safeTransfer(to, token.safeBalanceOfSelf()); } /*********** CHEF HELPERS ***********/ function depositToMasterChefv2(uint256 pid, uint256 amount, address to) external { masterChefv2.deposit(pid, amount, to); } function balanceToMasterChefv2(uint256 pid, address to) external { IERC20 lpToken = masterChefv2.lpToken(pid); masterChefv2.deposit(pid, lpToken.safeBalanceOfSelf(), to); } /// @notice Liquidity zap into CHEF. function zapToMasterChef( address to, address _FromTokenContractAddress, uint256 _amount, uint256 _minPoolTokens, uint256 pid, address _swapTarget, bytes calldata swapData ) external payable returns (uint256 LPBought) { uint256 toInvest = _pullTokens( _FromTokenContractAddress, _amount ); IERC20 _pairAddress = masterChefv2.lpToken(pid); LPBought = _performZapIn( _FromTokenContractAddress, address(_pairAddress), toInvest, _swapTarget, swapData ); require(LPBought >= _minPoolTokens, "ERR: High Slippage"); emit ZapIn(to, address(_pairAddress), LPBought); masterChefv2.deposit(pid, LPBought, to); } /************ KASHI HELPERS ************/ function assetToKashi(IKashiBridge kashiPair, address to, uint256 amount) external returns (uint256 fraction) { IERC20 asset = kashiPair.asset(); asset.safeTransferFrom(msg.sender, address(bento), amount); IBentoBridge(bento).deposit(asset, address(bento), address(kashiPair), amount, 0); fraction = kashiPair.addAsset(to, true, amount); } function assetToKashiChef(uint256 pid, uint256 amount, address to) external returns (uint256 fraction) { address kashiPair = address(masterChefv2.lpToken(pid)); IERC20 asset = IKashiBridge(kashiPair).asset(); asset.safeTransferFrom(msg.sender, address(bento), amount); IBentoBridge(bento).deposit(asset, address(bento), address(kashiPair), amount, 0); fraction = IKashiBridge(kashiPair).addAsset(address(this), true, amount); masterChefv2.deposit(pid, fraction, to); } function assetBalanceToKashi(IKashiBridge kashiPair, address to) external returns (uint256 fraction) { IERC20 asset = kashiPair.asset(); uint256 balance = asset.safeBalanceOfSelf(); IBentoBridge(bento).deposit(asset, address(bento), address(kashiPair), balance, 0); fraction = kashiPair.addAsset(to, true, balance); } function assetBalanceToKashiChef(uint256 pid, address to) external returns (uint256 fraction) { address kashiPair = address(masterChefv2.lpToken(pid)); IERC20 asset = IKashiBridge(kashiPair).asset(); uint256 balance = asset.safeBalanceOfSelf(); IBentoBridge(bento).deposit(asset, address(bento), address(kashiPair), balance, 0); fraction = IKashiBridge(kashiPair).addAsset(address(this), true, balance); masterChefv2.deposit(pid, fraction, to); } function assetBalanceFromKashi(address kashiPair, address to) external returns (uint256 share) { share = IKashiBridge(kashiPair).removeAsset(to, IERC20(kashiPair).safeBalanceOfSelf()); } /// @notice Liquidity zap into KASHI. function zapToKashi( address to, address _FromTokenContractAddress, IKashiBridge kashiPair, uint256 _amount, uint256 _minPoolTokens, address _swapTarget, bytes calldata swapData ) external payable returns (uint256 fraction) { uint256 toInvest = _pullTokens( _FromTokenContractAddress, _amount ); IERC20 _pairAddress = kashiPair.asset(); uint256 LPBought = _performZapIn( _FromTokenContractAddress, address(_pairAddress), toInvest, _swapTarget, swapData ); require(LPBought >= _minPoolTokens, "ERR: High Slippage"); emit ZapIn(to, address(_pairAddress), LPBought); _pairAddress.safeTransfer(address(bento), LPBought); IBentoBridge(bento).deposit(_pairAddress, address(bento), address(kashiPair), LPBought, 0); fraction = kashiPair.addAsset(to, true, LPBought); } /* β–ˆβ–ˆ β–ˆβ–ˆ β–„ β–„β–ˆβ–ˆβ–ˆβ–„ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆβ–€ β–€ β–ˆβ–„β–„β–ˆ β–ˆβ–„β–„β–ˆ β–ˆ β–ˆ β–ˆβ–ˆβ–„β–„ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆβ–„ β–„β–€ β–ˆ β–ˆ β–ˆ β–ˆ β–€β–ˆβ–ˆβ–ˆβ–€ β–ˆ β–ˆ β–ˆβ– β–€ β–€ ▐ */ /*********** AAVE HELPERS ***********/ function balanceToAave(address underlying, address to) external { aave.deposit(underlying, IERC20(underlying).safeBalanceOfSelf(), to, 0); } function balanceFromAave(address aToken, address to) external { address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token aave.withdraw(underlying, IERC20(aToken).safeBalanceOfSelf(), to); } /************************** AAVE -> UNDERLYING -> BENTO **************************/ /// @notice Migrate AAVE `aToken` underlying `amount` into BENTO for benefit of `to` by batching calls to `aave` and `bento`. function aaveToBento(address aToken, address to, uint256 amount) external returns (uint256 amountOut, uint256 shareOut) { IERC20(aToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `aToken` `amount` into this contract address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token aave.withdraw(underlying, amount, address(bento)); // burn deposited `aToken` from `aave` into `underlying` (amountOut, shareOut) = bento.deposit(IERC20(underlying), address(bento), to, amount, 0); // stake `underlying` into BENTO for `to` } /************************** BENTO -> UNDERLYING -> AAVE **************************/ /// @notice Migrate `underlying` `amount` from BENTO into AAVE for benefit of `to` by batching calls to `bento` and `aave`. function bentoToAave(IERC20 underlying, address to, uint256 amount) external { bento.withdraw(underlying, msg.sender, address(this), amount, 0); // withdraw `amount` of `underlying` from BENTO into this contract aave.deposit(address(underlying), amount, to, 0); // stake `underlying` into `aave` for `to` } /************************* AAVE -> UNDERLYING -> COMP *************************/ /// @notice Migrate AAVE `aToken` underlying `amount` into COMP/CREAM `cToken` for benefit of `to` by batching calls to `aave` and `cToken`. function aaveToCompound(address aToken, address cToken, address to, uint256 amount) external { IERC20(aToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `aToken` `amount` into this contract address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token aave.withdraw(underlying, amount, address(this)); // burn deposited `aToken` from `aave` into `underlying` ICompoundBridge(cToken).mint(amount); // stake `underlying` into `cToken` IERC20(cToken).safeTransfer(to, IERC20(cToken).safeBalanceOfSelf()); // transfer resulting `cToken` to `to` } /************************* COMP -> UNDERLYING -> AAVE *************************/ /// @notice Migrate COMP/CREAM `cToken` underlying `amount` into AAVE for benefit of `to` by batching calls to `cToken` and `aave`. function compoundToAave(address cToken, address to, uint256 amount) external { IERC20(cToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `cToken` `amount` into this contract ICompoundBridge(cToken).redeem(amount); // burn deposited `cToken` into `underlying` address underlying = ICompoundBridge(cToken).underlying(); // sanity check for `underlying` token aave.deposit(underlying, IERC20(underlying).safeBalanceOfSelf(), to, 0); // stake resulting `underlying` into `aave` for `to` } /********************** SUSHI -> XSUSHI -> AAVE **********************/ /// @notice Stake SUSHI `amount` into aXSUSHI for benefit of `to` by batching calls to `sushiBar` and `aave`. function stakeSushiToAave(address to, uint256 amount) external { // SAAVE sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI into `sushiBar` xSUSHI aave.deposit(sushiBar, IERC20(sushiBar).safeBalanceOfSelf(), to, 0); // stake resulting xSUSHI into `aave` aXSUSHI for `to` } /********************** AAVE -> XSUSHI -> SUSHI **********************/ /// @notice Unstake aXSUSHI `amount` into SUSHI for benefit of `to` by batching calls to `aave` and `sushiBar`. function unstakeSushiFromAave(address to, uint256 amount) external { aaveSushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` aXSUSHI `amount` into this contract aave.withdraw(sushiBar, amount, address(this)); // burn deposited aXSUSHI from `aave` into xSUSHI ISushiBarBridge(sushiBar).leave(amount); // burn resulting xSUSHI from `sushiBar` into SUSHI sushiToken.safeTransfer(to, sushiToken.safeBalanceOfSelf()); // transfer resulting SUSHI to `to` } /* β–ˆβ–ˆβ–ˆ β–„β–ˆβ–ˆβ–ˆβ–„ β–„ β–„β–„β–„β–„β–€ β–ˆβ–ˆβ–ˆβ–ˆβ–„ β–ˆ β–ˆ β–ˆβ–€ β–€ β–ˆ β–€β–€β–€ β–ˆ β–ˆ β–ˆ β–ˆ β–€ β–„ β–ˆβ–ˆβ–„β–„ β–ˆβ–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–„β–€ β–ˆβ–„ β–„β–€ β–ˆ β–ˆ β–ˆ β–ˆ β–€β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–€β–ˆβ–ˆβ–ˆβ–€ β–ˆ β–ˆ β–ˆ β–€ β–ˆ β–ˆβ–ˆ */ /************ BENTO HELPERS ************/ function balanceToBento(IERC20 token, address to) external returns (uint256 amountOut, uint256 shareOut) { (amountOut, shareOut) = bento.deposit(token, address(this), to, token.safeBalanceOfSelf(), 0); } /// @dev Included to be able to approve `bento` in the same transaction (using `batch()`). function setBentoApproval( address user, address masterContract, bool approved, uint8 v, bytes32 r, bytes32 s ) external { bento.setMasterContractApproval(user, masterContract, approved, v, r, s); } /// @notice Liquidity zap into BENTO. function zapToBento( address to, address _FromTokenContractAddress, address _pairAddress, uint256 _amount, uint256 _minPoolTokens, address _swapTarget, bytes calldata swapData ) external payable returns (uint256 LPBought) { uint256 toInvest = _pullTokens( _FromTokenContractAddress, _amount ); LPBought = _performZapIn( _FromTokenContractAddress, _pairAddress, toInvest, _swapTarget, swapData ); require(LPBought >= _minPoolTokens, "ERR: High Slippage"); emit ZapIn(to, _pairAddress, LPBought); bento.deposit(IERC20(_pairAddress), address(this), to, LPBought, 0); } /// @notice Liquidity unzap from BENTO. function zapFromBento( address pair, address to, uint256 amount ) external returns (uint256 amount0, uint256 amount1) { bento.withdraw(IERC20(pair), msg.sender, pair, amount, 0); // withdraw `amount` to `pair` from BENTO (amount0, amount1) = ISushiSwap(pair).burn(to); // trigger burn to redeem liquidity for `to` } /*********************** SUSHI -> XSUSHI -> BENTO ***********************/ /// @notice Stake SUSHI `amount` into BENTO xSUSHI for benefit of `to` by batching calls to `sushiBar` and `bento`. function stakeSushiToBento(address to, uint256 amount) external returns (uint256 amountOut, uint256 shareOut) { sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI into `sushiBar` xSUSHI (amountOut, shareOut) = bento.deposit(IERC20(sushiBar), address(this), to, IERC20(sushiBar).safeBalanceOfSelf(), 0); // stake resulting xSUSHI into BENTO for `to` } /*********************** BENTO -> XSUSHI -> SUSHI ***********************/ /// @notice Unstake xSUSHI `amount` from BENTO into SUSHI for benefit of `to` by batching calls to `bento` and `sushiBar`. function unstakeSushiFromBento(address to, uint256 amount) external { bento.withdraw(IERC20(sushiBar), msg.sender, address(this), amount, 0); // withdraw `amount` of xSUSHI from BENTO into this contract ISushiBarBridge(sushiBar).leave(amount); // burn withdrawn xSUSHI from `sushiBar` into SUSHI sushiToken.safeTransfer(to, sushiToken.safeBalanceOfSelf()); // transfer resulting SUSHI to `to` } /* β–„β–ˆβ–„ β–ˆβ–„β–„β–„β–„ β–„β–ˆβ–ˆβ–ˆβ–„ β–ˆβ–ˆ β–ˆβ–€β–„β–€β–ˆ β–ˆβ–€ β–€β–„ β–ˆ β–„β–€ β–ˆβ–€ β–€ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–€ β–ˆβ–€β–€β–Œ β–ˆβ–ˆβ–„β–„ β–ˆβ–„β–„β–ˆ β–ˆ β–„ β–ˆ β–ˆβ–„ β–„β–€ β–ˆ β–ˆ β–ˆβ–„ β–„β–€ β–ˆ β–ˆ β–ˆ β–ˆ β–€β–ˆβ–ˆβ–ˆβ–€ β–ˆ β–€β–ˆβ–ˆβ–ˆβ–€ β–ˆ β–ˆ β–€ β–ˆ β–€ β–€ */ // - COMPOUND - // /*********** COMP HELPERS ***********/ function balanceToCompound(ICompoundBridge cToken) external { IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token cToken.mint(underlying.safeBalanceOfSelf()); } function balanceFromCompound(address cToken) external { ICompoundBridge(cToken).redeem(IERC20(cToken).safeBalanceOfSelf()); } /************************** COMP -> UNDERLYING -> BENTO **************************/ /// @notice Migrate COMP/CREAM `cToken` `cTokenAmount` into underlying and BENTO for benefit of `to` by batching calls to `cToken` and `bento`. function compoundToBento(address cToken, address to, uint256 cTokenAmount) external returns (uint256 amountOut, uint256 shareOut) { IERC20(cToken).safeTransferFrom(msg.sender, address(this), cTokenAmount); // deposit `msg.sender` `cToken` `cTokenAmount` into this contract ICompoundBridge(cToken).redeem(cTokenAmount); // burn deposited `cToken` into `underlying` IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token (amountOut, shareOut) = bento.deposit(underlying, address(this), to, underlying.safeBalanceOfSelf(), 0); // stake resulting `underlying` into BENTO for `to` } /************************** BENTO -> UNDERLYING -> COMP **************************/ /// @notice Migrate `cToken` `underlyingAmount` from BENTO into COMP/CREAM for benefit of `to` by batching calls to `bento` and `cToken`. function bentoToCompound(address cToken, address to, uint256 underlyingAmount) external { IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token bento.withdraw(underlying, msg.sender, address(this), underlyingAmount, 0); // withdraw `underlyingAmount` of `underlying` from BENTO into this contract ICompoundBridge(cToken).mint(underlyingAmount); // stake `underlying` into `cToken` IERC20(cToken).safeTransfer(to, IERC20(cToken).safeBalanceOfSelf()); // transfer resulting `cToken` to `to` } /********************** SUSHI -> CREAM -> BENTO **********************/ /// @notice Stake SUSHI `amount` into crSUSHI and BENTO for benefit of `to` by batching calls to `crSushiToken` and `bento`. function sushiToCreamToBento(address to, uint256 amount) external returns (uint256 amountOut, uint256 shareOut) { sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ICompoundBridge(crSushiToken).mint(amount); // stake deposited SUSHI into crSUSHI (amountOut, shareOut) = bento.deposit(IERC20(crSushiToken), address(this), to, IERC20(crSushiToken).safeBalanceOfSelf(), 0); // stake resulting crSUSHI into BENTO for `to` } /********************** BENTO -> CREAM -> SUSHI **********************/ /// @notice Unstake crSUSHI `cTokenAmount` into SUSHI from BENTO for benefit of `to` by batching calls to `bento` and `crSushiToken`. function sushiFromCreamFromBento(address to, uint256 cTokenAmount) external { bento.withdraw(IERC20(crSushiToken), msg.sender, address(this), cTokenAmount, 0); // withdraw `cTokenAmount` of `crSushiToken` from BENTO into this contract ICompoundBridge(crSushiToken).redeem(cTokenAmount); // burn deposited `crSushiToken` into SUSHI sushiToken.safeTransfer(to, sushiToken.safeBalanceOfSelf()); // transfer resulting SUSHI to `to` } /*********************** SUSHI -> XSUSHI -> CREAM ***********************/ /// @notice Stake SUSHI `amount` into crXSUSHI for benefit of `to` by batching calls to `sushiBar` and `crXSushiToken`. function stakeSushiToCream(address to, uint256 amount) external { // SCREAM sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI `amount` into `sushiBar` xSUSHI ICompoundBridge(crXSushiToken).mint(IERC20(sushiBar).safeBalanceOfSelf()); // stake resulting xSUSHI into crXSUSHI IERC20(crXSushiToken).safeTransfer(to, IERC20(crXSushiToken).safeBalanceOfSelf()); // transfer resulting crXSUSHI to `to` } /*********************** CREAM -> XSUSHI -> SUSHI ***********************/ /// @notice Unstake crXSUSHI `cTokenAmount` into SUSHI for benefit of `to` by batching calls to `crXSushiToken` and `sushiBar`. function unstakeSushiFromCream(address to, uint256 cTokenAmount) external { IERC20(crXSushiToken).safeTransferFrom(msg.sender, address(this), cTokenAmount); // deposit `msg.sender` `crXSushiToken` `cTokenAmount` into this contract ICompoundBridge(crXSushiToken).redeem(cTokenAmount); // burn deposited `crXSushiToken` `cTokenAmount` into xSUSHI ISushiBarBridge(sushiBar).leave(IERC20(sushiBar).safeBalanceOfSelf()); // burn resulting xSUSHI `amount` from `sushiBar` into SUSHI sushiToken.safeTransfer(to, sushiToken.safeBalanceOfSelf()); // transfer resulting SUSHI to `to` } /******************************** SUSHI -> XSUSHI -> CREAM -> BENTO ********************************/ /// @notice Stake SUSHI `amount` into crXSUSHI and BENTO for benefit of `to` by batching calls to `sushiBar`, `crXSushiToken` and `bento`. function stakeSushiToCreamToBento(address to, uint256 amount) external returns (uint256 amountOut, uint256 shareOut) { sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI `amount` into `sushiBar` xSUSHI ICompoundBridge(crXSushiToken).mint(IERC20(sushiBar).safeBalanceOfSelf()); // stake resulting xSUSHI into crXSUSHI (amountOut, shareOut) = bento.deposit(IERC20(crXSushiToken), address(this), to, IERC20(crXSushiToken).safeBalanceOfSelf(), 0); // stake resulting crXSUSHI into BENTO for `to` } /******************************** BENTO -> CREAM -> XSUSHI -> SUSHI ********************************/ /// @notice Unstake crXSUSHI `cTokenAmount` into SUSHI from BENTO for benefit of `to` by batching calls to `bento`, `crXSushiToken` and `sushiBar`. function unstakeSushiFromCreamFromBento(address to, uint256 cTokenAmount) external { bento.withdraw(IERC20(crXSushiToken), msg.sender, address(this), cTokenAmount, 0); // withdraw `cTokenAmount` of `crXSushiToken` from BENTO into this contract ICompoundBridge(crXSushiToken).redeem(cTokenAmount); // burn deposited `crXSushiToken` `cTokenAmount` into xSUSHI ISushiBarBridge(sushiBar).leave(IERC20(sushiBar).safeBalanceOfSelf()); // burn resulting xSUSHI from `sushiBar` into SUSHI sushiToken.safeTransfer(to, sushiToken.safeBalanceOfSelf()); // transfer resulting SUSHI to `to` } /* β–„β–„β–„β–„β–„ β–„ β–„ β–ˆβ–ˆ β–ˆ β–„β–„ β–ˆ β–€β–„ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–„ β–€β–€β–€β–€β–„ β–ˆ β–„ β–ˆ β–ˆβ–„β–„β–ˆ β–ˆβ–€β–€β–€ β–€β–„β–„β–„β–„β–€ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–€ β–€ β–ˆ β–€ β–€ */ /// @notice Fallback for received ETH - SushiSwap ETH to stake SUSHI into xSUSHI and BENTO for benefit of `to`. receive() external payable { // INARIZUSHI (uint256 reserve0, uint256 reserve1, ) = sushiSwapSushiETHPair.getReserves(); uint256 amountInWithFee = msg.value.mul(997); uint256 out = amountInWithFee.mul(reserve0) / reserve1.mul(1000).add(amountInWithFee); IWETH(wETH).deposit{value: msg.value}(); IERC20(wETH).safeTransfer(address(sushiSwapSushiETHPair), msg.value); sushiSwapSushiETHPair.swap(out, 0, address(this), ""); ISushiBarBridge(sushiBar).enter(sushiToken.safeBalanceOfSelf()); // stake resulting SUSHI into `sushiBar` xSUSHI bento.deposit(IERC20(sushiBar), address(this), msg.sender, IERC20(sushiBar).safeBalanceOfSelf(), 0); // stake resulting xSUSHI into BENTO for `to` } /// @notice SushiSwap ETH to stake SUSHI into xSUSHI and BENTO for benefit of `to`. function inariZushi(address to) external payable returns (uint256 amountOut, uint256 shareOut) { (uint256 reserve0, uint256 reserve1, ) = sushiSwapSushiETHPair.getReserves(); uint256 amountInWithFee = msg.value.mul(997); uint256 out = amountInWithFee.mul(reserve0) / reserve1.mul(1000).add(amountInWithFee); IWETH(wETH).deposit{value: msg.value}(); IERC20(wETH).safeTransfer(address(sushiSwapSushiETHPair), msg.value); sushiSwapSushiETHPair.swap(out, 0, address(this), ""); ISushiBarBridge(sushiBar).enter(sushiToken.safeBalanceOfSelf()); // stake resulting SUSHI into `sushiBar` xSUSHI (amountOut, shareOut) = bento.deposit(IERC20(sushiBar), address(this), to, IERC20(sushiBar).safeBalanceOfSelf(), 0); // stake resulting xSUSHI into BENTO for `to` } /// @notice Simple SushiSwap `fromToken` `amountIn` to `toToken` for benefit of `to`. function swap(address fromToken, address toToken, address to, uint256 amountIn) external returns (uint256 amountOut) { (address token0, address token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken); ISushiSwap pair = ISushiSwap( uint256( keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash)) ) ); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); uint256 amountInWithFee = amountIn.mul(997); IERC20(fromToken).safeTransferFrom(msg.sender, address(pair), amountIn); if (toToken > fromToken) { amountOut = amountInWithFee.mul(reserve1) / reserve0.mul(1000).add(amountInWithFee); pair.swap(0, amountOut, to, ""); } else { amountOut = amountInWithFee.mul(reserve0) / reserve1.mul(1000).add(amountInWithFee); pair.swap(amountOut, 0, to, ""); } } /// @notice Simple SushiSwap local `fromToken` balance in this contract to `toToken` for benefit of `to`. function swapBalance(address fromToken, address toToken, address to) external returns (uint256 amountOut) { (address token0, address token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken); ISushiSwap pair = ISushiSwap( uint256( keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash)) ) ); uint256 amountIn = IERC20(fromToken).safeBalanceOfSelf(); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); uint256 amountInWithFee = amountIn.mul(997); IERC20(fromToken).safeTransfer(address(pair), amountIn); if (toToken > fromToken) { amountOut = amountInWithFee.mul(reserve1) / reserve0.mul(1000).add(amountInWithFee); pair.swap(0, amountOut, to, ""); } else { amountOut = amountInWithFee.mul(reserve0) / reserve1.mul(1000).add(amountInWithFee); pair.swap(amountOut, 0, to, ""); } } }
/// @notice Contract that batches SUSHI staking and DeFi strategies - V1 'iroirona'.
NatSpecSingleLine
/// @notice Fallback for received ETH - SushiSwap ETH to stake SUSHI into xSUSHI and BENTO for benefit of `to`.
NatSpecSingleLine
v0.7.6+commit.7338295f
GNU GPLv2
ipfs://89a5125d850fb87a89b52e2cb580c7d062e507e61b962188e0983cbea998b8cd
{ "func_code_index": [ 23208, 23997 ] }
11,800
InariV1
@boringcrypto/boring-solidity/contracts/BoringBatchable.sol
0x195e8262aa81ba560478ec6ca4da73745547073f
Solidity
InariV1
contract InariV1 is BoringBatchableWithDai, SushiZap { using SafeMath for uint256; using BoringERC20 for IERC20; IERC20 constant sushiToken = IERC20(0x6B3595068778DD592e39A122f4f5a5cF09C90fE2); // SUSHI token contract address constant sushiBar = 0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272; // xSUSHI staking contract for SUSHI ISushiSwap constant sushiSwapSushiETHPair = ISushiSwap(0x795065dCc9f64b5614C407a6EFDC400DA6221FB0); // SUSHI/ETH pair on SushiSwap IMasterChefV2 constant masterChefv2 = IMasterChefV2(0xEF0881eC094552b2e128Cf945EF17a6752B4Ec5d); // SUSHI MasterChef v2 contract IAaveBridge constant aave = IAaveBridge(0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9); // AAVE lending pool contract for xSUSHI staking into aXSUSHI IERC20 constant aaveSushiToken = IERC20(0xF256CC7847E919FAc9B808cC216cAc87CCF2f47a); // aXSUSHI staking contract for xSUSHI IBentoBridge constant bento = IBentoBridge(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966); // BENTO vault contract address constant crSushiToken = 0x338286C0BC081891A4Bda39C7667ae150bf5D206; // crSUSHI staking contract for SUSHI address constant crXSushiToken = 0x228619CCa194Fbe3Ebeb2f835eC1eA5080DaFbb2; // crXSUSHI staking contract for xSUSHI /// @notice Initialize this Inari contract. constructor() { bento.registerProtocol(); // register this contract with BENTO } /// @notice Helper function to approve this contract to spend tokens and enable strategies. function bridgeToken(IERC20[] calldata token, address[] calldata to) external { for (uint256 i = 0; i < token.length; i++) { token[i].safeApprove(to[i], type(uint256).max); // max approve `to` spender to pull `token` from this contract } } /********** TKN HELPERS **********/ function withdrawToken(IERC20 token, address to, uint256 amount) external { token.safeTransfer(to, amount); } function withdrawTokenBalance(IERC20 token, address to) external { token.safeTransfer(to, token.safeBalanceOfSelf()); } /*********** CHEF HELPERS ***********/ function depositToMasterChefv2(uint256 pid, uint256 amount, address to) external { masterChefv2.deposit(pid, amount, to); } function balanceToMasterChefv2(uint256 pid, address to) external { IERC20 lpToken = masterChefv2.lpToken(pid); masterChefv2.deposit(pid, lpToken.safeBalanceOfSelf(), to); } /// @notice Liquidity zap into CHEF. function zapToMasterChef( address to, address _FromTokenContractAddress, uint256 _amount, uint256 _minPoolTokens, uint256 pid, address _swapTarget, bytes calldata swapData ) external payable returns (uint256 LPBought) { uint256 toInvest = _pullTokens( _FromTokenContractAddress, _amount ); IERC20 _pairAddress = masterChefv2.lpToken(pid); LPBought = _performZapIn( _FromTokenContractAddress, address(_pairAddress), toInvest, _swapTarget, swapData ); require(LPBought >= _minPoolTokens, "ERR: High Slippage"); emit ZapIn(to, address(_pairAddress), LPBought); masterChefv2.deposit(pid, LPBought, to); } /************ KASHI HELPERS ************/ function assetToKashi(IKashiBridge kashiPair, address to, uint256 amount) external returns (uint256 fraction) { IERC20 asset = kashiPair.asset(); asset.safeTransferFrom(msg.sender, address(bento), amount); IBentoBridge(bento).deposit(asset, address(bento), address(kashiPair), amount, 0); fraction = kashiPair.addAsset(to, true, amount); } function assetToKashiChef(uint256 pid, uint256 amount, address to) external returns (uint256 fraction) { address kashiPair = address(masterChefv2.lpToken(pid)); IERC20 asset = IKashiBridge(kashiPair).asset(); asset.safeTransferFrom(msg.sender, address(bento), amount); IBentoBridge(bento).deposit(asset, address(bento), address(kashiPair), amount, 0); fraction = IKashiBridge(kashiPair).addAsset(address(this), true, amount); masterChefv2.deposit(pid, fraction, to); } function assetBalanceToKashi(IKashiBridge kashiPair, address to) external returns (uint256 fraction) { IERC20 asset = kashiPair.asset(); uint256 balance = asset.safeBalanceOfSelf(); IBentoBridge(bento).deposit(asset, address(bento), address(kashiPair), balance, 0); fraction = kashiPair.addAsset(to, true, balance); } function assetBalanceToKashiChef(uint256 pid, address to) external returns (uint256 fraction) { address kashiPair = address(masterChefv2.lpToken(pid)); IERC20 asset = IKashiBridge(kashiPair).asset(); uint256 balance = asset.safeBalanceOfSelf(); IBentoBridge(bento).deposit(asset, address(bento), address(kashiPair), balance, 0); fraction = IKashiBridge(kashiPair).addAsset(address(this), true, balance); masterChefv2.deposit(pid, fraction, to); } function assetBalanceFromKashi(address kashiPair, address to) external returns (uint256 share) { share = IKashiBridge(kashiPair).removeAsset(to, IERC20(kashiPair).safeBalanceOfSelf()); } /// @notice Liquidity zap into KASHI. function zapToKashi( address to, address _FromTokenContractAddress, IKashiBridge kashiPair, uint256 _amount, uint256 _minPoolTokens, address _swapTarget, bytes calldata swapData ) external payable returns (uint256 fraction) { uint256 toInvest = _pullTokens( _FromTokenContractAddress, _amount ); IERC20 _pairAddress = kashiPair.asset(); uint256 LPBought = _performZapIn( _FromTokenContractAddress, address(_pairAddress), toInvest, _swapTarget, swapData ); require(LPBought >= _minPoolTokens, "ERR: High Slippage"); emit ZapIn(to, address(_pairAddress), LPBought); _pairAddress.safeTransfer(address(bento), LPBought); IBentoBridge(bento).deposit(_pairAddress, address(bento), address(kashiPair), LPBought, 0); fraction = kashiPair.addAsset(to, true, LPBought); } /* β–ˆβ–ˆ β–ˆβ–ˆ β–„ β–„β–ˆβ–ˆβ–ˆβ–„ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆβ–€ β–€ β–ˆβ–„β–„β–ˆ β–ˆβ–„β–„β–ˆ β–ˆ β–ˆ β–ˆβ–ˆβ–„β–„ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆβ–„ β–„β–€ β–ˆ β–ˆ β–ˆ β–ˆ β–€β–ˆβ–ˆβ–ˆβ–€ β–ˆ β–ˆ β–ˆβ– β–€ β–€ ▐ */ /*********** AAVE HELPERS ***********/ function balanceToAave(address underlying, address to) external { aave.deposit(underlying, IERC20(underlying).safeBalanceOfSelf(), to, 0); } function balanceFromAave(address aToken, address to) external { address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token aave.withdraw(underlying, IERC20(aToken).safeBalanceOfSelf(), to); } /************************** AAVE -> UNDERLYING -> BENTO **************************/ /// @notice Migrate AAVE `aToken` underlying `amount` into BENTO for benefit of `to` by batching calls to `aave` and `bento`. function aaveToBento(address aToken, address to, uint256 amount) external returns (uint256 amountOut, uint256 shareOut) { IERC20(aToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `aToken` `amount` into this contract address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token aave.withdraw(underlying, amount, address(bento)); // burn deposited `aToken` from `aave` into `underlying` (amountOut, shareOut) = bento.deposit(IERC20(underlying), address(bento), to, amount, 0); // stake `underlying` into BENTO for `to` } /************************** BENTO -> UNDERLYING -> AAVE **************************/ /// @notice Migrate `underlying` `amount` from BENTO into AAVE for benefit of `to` by batching calls to `bento` and `aave`. function bentoToAave(IERC20 underlying, address to, uint256 amount) external { bento.withdraw(underlying, msg.sender, address(this), amount, 0); // withdraw `amount` of `underlying` from BENTO into this contract aave.deposit(address(underlying), amount, to, 0); // stake `underlying` into `aave` for `to` } /************************* AAVE -> UNDERLYING -> COMP *************************/ /// @notice Migrate AAVE `aToken` underlying `amount` into COMP/CREAM `cToken` for benefit of `to` by batching calls to `aave` and `cToken`. function aaveToCompound(address aToken, address cToken, address to, uint256 amount) external { IERC20(aToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `aToken` `amount` into this contract address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token aave.withdraw(underlying, amount, address(this)); // burn deposited `aToken` from `aave` into `underlying` ICompoundBridge(cToken).mint(amount); // stake `underlying` into `cToken` IERC20(cToken).safeTransfer(to, IERC20(cToken).safeBalanceOfSelf()); // transfer resulting `cToken` to `to` } /************************* COMP -> UNDERLYING -> AAVE *************************/ /// @notice Migrate COMP/CREAM `cToken` underlying `amount` into AAVE for benefit of `to` by batching calls to `cToken` and `aave`. function compoundToAave(address cToken, address to, uint256 amount) external { IERC20(cToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `cToken` `amount` into this contract ICompoundBridge(cToken).redeem(amount); // burn deposited `cToken` into `underlying` address underlying = ICompoundBridge(cToken).underlying(); // sanity check for `underlying` token aave.deposit(underlying, IERC20(underlying).safeBalanceOfSelf(), to, 0); // stake resulting `underlying` into `aave` for `to` } /********************** SUSHI -> XSUSHI -> AAVE **********************/ /// @notice Stake SUSHI `amount` into aXSUSHI for benefit of `to` by batching calls to `sushiBar` and `aave`. function stakeSushiToAave(address to, uint256 amount) external { // SAAVE sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI into `sushiBar` xSUSHI aave.deposit(sushiBar, IERC20(sushiBar).safeBalanceOfSelf(), to, 0); // stake resulting xSUSHI into `aave` aXSUSHI for `to` } /********************** AAVE -> XSUSHI -> SUSHI **********************/ /// @notice Unstake aXSUSHI `amount` into SUSHI for benefit of `to` by batching calls to `aave` and `sushiBar`. function unstakeSushiFromAave(address to, uint256 amount) external { aaveSushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` aXSUSHI `amount` into this contract aave.withdraw(sushiBar, amount, address(this)); // burn deposited aXSUSHI from `aave` into xSUSHI ISushiBarBridge(sushiBar).leave(amount); // burn resulting xSUSHI from `sushiBar` into SUSHI sushiToken.safeTransfer(to, sushiToken.safeBalanceOfSelf()); // transfer resulting SUSHI to `to` } /* β–ˆβ–ˆβ–ˆ β–„β–ˆβ–ˆβ–ˆβ–„ β–„ β–„β–„β–„β–„β–€ β–ˆβ–ˆβ–ˆβ–ˆβ–„ β–ˆ β–ˆ β–ˆβ–€ β–€ β–ˆ β–€β–€β–€ β–ˆ β–ˆ β–ˆ β–ˆ β–€ β–„ β–ˆβ–ˆβ–„β–„ β–ˆβ–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–„β–€ β–ˆβ–„ β–„β–€ β–ˆ β–ˆ β–ˆ β–ˆ β–€β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–€β–ˆβ–ˆβ–ˆβ–€ β–ˆ β–ˆ β–ˆ β–€ β–ˆ β–ˆβ–ˆ */ /************ BENTO HELPERS ************/ function balanceToBento(IERC20 token, address to) external returns (uint256 amountOut, uint256 shareOut) { (amountOut, shareOut) = bento.deposit(token, address(this), to, token.safeBalanceOfSelf(), 0); } /// @dev Included to be able to approve `bento` in the same transaction (using `batch()`). function setBentoApproval( address user, address masterContract, bool approved, uint8 v, bytes32 r, bytes32 s ) external { bento.setMasterContractApproval(user, masterContract, approved, v, r, s); } /// @notice Liquidity zap into BENTO. function zapToBento( address to, address _FromTokenContractAddress, address _pairAddress, uint256 _amount, uint256 _minPoolTokens, address _swapTarget, bytes calldata swapData ) external payable returns (uint256 LPBought) { uint256 toInvest = _pullTokens( _FromTokenContractAddress, _amount ); LPBought = _performZapIn( _FromTokenContractAddress, _pairAddress, toInvest, _swapTarget, swapData ); require(LPBought >= _minPoolTokens, "ERR: High Slippage"); emit ZapIn(to, _pairAddress, LPBought); bento.deposit(IERC20(_pairAddress), address(this), to, LPBought, 0); } /// @notice Liquidity unzap from BENTO. function zapFromBento( address pair, address to, uint256 amount ) external returns (uint256 amount0, uint256 amount1) { bento.withdraw(IERC20(pair), msg.sender, pair, amount, 0); // withdraw `amount` to `pair` from BENTO (amount0, amount1) = ISushiSwap(pair).burn(to); // trigger burn to redeem liquidity for `to` } /*********************** SUSHI -> XSUSHI -> BENTO ***********************/ /// @notice Stake SUSHI `amount` into BENTO xSUSHI for benefit of `to` by batching calls to `sushiBar` and `bento`. function stakeSushiToBento(address to, uint256 amount) external returns (uint256 amountOut, uint256 shareOut) { sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI into `sushiBar` xSUSHI (amountOut, shareOut) = bento.deposit(IERC20(sushiBar), address(this), to, IERC20(sushiBar).safeBalanceOfSelf(), 0); // stake resulting xSUSHI into BENTO for `to` } /*********************** BENTO -> XSUSHI -> SUSHI ***********************/ /// @notice Unstake xSUSHI `amount` from BENTO into SUSHI for benefit of `to` by batching calls to `bento` and `sushiBar`. function unstakeSushiFromBento(address to, uint256 amount) external { bento.withdraw(IERC20(sushiBar), msg.sender, address(this), amount, 0); // withdraw `amount` of xSUSHI from BENTO into this contract ISushiBarBridge(sushiBar).leave(amount); // burn withdrawn xSUSHI from `sushiBar` into SUSHI sushiToken.safeTransfer(to, sushiToken.safeBalanceOfSelf()); // transfer resulting SUSHI to `to` } /* β–„β–ˆβ–„ β–ˆβ–„β–„β–„β–„ β–„β–ˆβ–ˆβ–ˆβ–„ β–ˆβ–ˆ β–ˆβ–€β–„β–€β–ˆ β–ˆβ–€ β–€β–„ β–ˆ β–„β–€ β–ˆβ–€ β–€ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–€ β–ˆβ–€β–€β–Œ β–ˆβ–ˆβ–„β–„ β–ˆβ–„β–„β–ˆ β–ˆ β–„ β–ˆ β–ˆβ–„ β–„β–€ β–ˆ β–ˆ β–ˆβ–„ β–„β–€ β–ˆ β–ˆ β–ˆ β–ˆ β–€β–ˆβ–ˆβ–ˆβ–€ β–ˆ β–€β–ˆβ–ˆβ–ˆβ–€ β–ˆ β–ˆ β–€ β–ˆ β–€ β–€ */ // - COMPOUND - // /*********** COMP HELPERS ***********/ function balanceToCompound(ICompoundBridge cToken) external { IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token cToken.mint(underlying.safeBalanceOfSelf()); } function balanceFromCompound(address cToken) external { ICompoundBridge(cToken).redeem(IERC20(cToken).safeBalanceOfSelf()); } /************************** COMP -> UNDERLYING -> BENTO **************************/ /// @notice Migrate COMP/CREAM `cToken` `cTokenAmount` into underlying and BENTO for benefit of `to` by batching calls to `cToken` and `bento`. function compoundToBento(address cToken, address to, uint256 cTokenAmount) external returns (uint256 amountOut, uint256 shareOut) { IERC20(cToken).safeTransferFrom(msg.sender, address(this), cTokenAmount); // deposit `msg.sender` `cToken` `cTokenAmount` into this contract ICompoundBridge(cToken).redeem(cTokenAmount); // burn deposited `cToken` into `underlying` IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token (amountOut, shareOut) = bento.deposit(underlying, address(this), to, underlying.safeBalanceOfSelf(), 0); // stake resulting `underlying` into BENTO for `to` } /************************** BENTO -> UNDERLYING -> COMP **************************/ /// @notice Migrate `cToken` `underlyingAmount` from BENTO into COMP/CREAM for benefit of `to` by batching calls to `bento` and `cToken`. function bentoToCompound(address cToken, address to, uint256 underlyingAmount) external { IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token bento.withdraw(underlying, msg.sender, address(this), underlyingAmount, 0); // withdraw `underlyingAmount` of `underlying` from BENTO into this contract ICompoundBridge(cToken).mint(underlyingAmount); // stake `underlying` into `cToken` IERC20(cToken).safeTransfer(to, IERC20(cToken).safeBalanceOfSelf()); // transfer resulting `cToken` to `to` } /********************** SUSHI -> CREAM -> BENTO **********************/ /// @notice Stake SUSHI `amount` into crSUSHI and BENTO for benefit of `to` by batching calls to `crSushiToken` and `bento`. function sushiToCreamToBento(address to, uint256 amount) external returns (uint256 amountOut, uint256 shareOut) { sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ICompoundBridge(crSushiToken).mint(amount); // stake deposited SUSHI into crSUSHI (amountOut, shareOut) = bento.deposit(IERC20(crSushiToken), address(this), to, IERC20(crSushiToken).safeBalanceOfSelf(), 0); // stake resulting crSUSHI into BENTO for `to` } /********************** BENTO -> CREAM -> SUSHI **********************/ /// @notice Unstake crSUSHI `cTokenAmount` into SUSHI from BENTO for benefit of `to` by batching calls to `bento` and `crSushiToken`. function sushiFromCreamFromBento(address to, uint256 cTokenAmount) external { bento.withdraw(IERC20(crSushiToken), msg.sender, address(this), cTokenAmount, 0); // withdraw `cTokenAmount` of `crSushiToken` from BENTO into this contract ICompoundBridge(crSushiToken).redeem(cTokenAmount); // burn deposited `crSushiToken` into SUSHI sushiToken.safeTransfer(to, sushiToken.safeBalanceOfSelf()); // transfer resulting SUSHI to `to` } /*********************** SUSHI -> XSUSHI -> CREAM ***********************/ /// @notice Stake SUSHI `amount` into crXSUSHI for benefit of `to` by batching calls to `sushiBar` and `crXSushiToken`. function stakeSushiToCream(address to, uint256 amount) external { // SCREAM sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI `amount` into `sushiBar` xSUSHI ICompoundBridge(crXSushiToken).mint(IERC20(sushiBar).safeBalanceOfSelf()); // stake resulting xSUSHI into crXSUSHI IERC20(crXSushiToken).safeTransfer(to, IERC20(crXSushiToken).safeBalanceOfSelf()); // transfer resulting crXSUSHI to `to` } /*********************** CREAM -> XSUSHI -> SUSHI ***********************/ /// @notice Unstake crXSUSHI `cTokenAmount` into SUSHI for benefit of `to` by batching calls to `crXSushiToken` and `sushiBar`. function unstakeSushiFromCream(address to, uint256 cTokenAmount) external { IERC20(crXSushiToken).safeTransferFrom(msg.sender, address(this), cTokenAmount); // deposit `msg.sender` `crXSushiToken` `cTokenAmount` into this contract ICompoundBridge(crXSushiToken).redeem(cTokenAmount); // burn deposited `crXSushiToken` `cTokenAmount` into xSUSHI ISushiBarBridge(sushiBar).leave(IERC20(sushiBar).safeBalanceOfSelf()); // burn resulting xSUSHI `amount` from `sushiBar` into SUSHI sushiToken.safeTransfer(to, sushiToken.safeBalanceOfSelf()); // transfer resulting SUSHI to `to` } /******************************** SUSHI -> XSUSHI -> CREAM -> BENTO ********************************/ /// @notice Stake SUSHI `amount` into crXSUSHI and BENTO for benefit of `to` by batching calls to `sushiBar`, `crXSushiToken` and `bento`. function stakeSushiToCreamToBento(address to, uint256 amount) external returns (uint256 amountOut, uint256 shareOut) { sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI `amount` into `sushiBar` xSUSHI ICompoundBridge(crXSushiToken).mint(IERC20(sushiBar).safeBalanceOfSelf()); // stake resulting xSUSHI into crXSUSHI (amountOut, shareOut) = bento.deposit(IERC20(crXSushiToken), address(this), to, IERC20(crXSushiToken).safeBalanceOfSelf(), 0); // stake resulting crXSUSHI into BENTO for `to` } /******************************** BENTO -> CREAM -> XSUSHI -> SUSHI ********************************/ /// @notice Unstake crXSUSHI `cTokenAmount` into SUSHI from BENTO for benefit of `to` by batching calls to `bento`, `crXSushiToken` and `sushiBar`. function unstakeSushiFromCreamFromBento(address to, uint256 cTokenAmount) external { bento.withdraw(IERC20(crXSushiToken), msg.sender, address(this), cTokenAmount, 0); // withdraw `cTokenAmount` of `crXSushiToken` from BENTO into this contract ICompoundBridge(crXSushiToken).redeem(cTokenAmount); // burn deposited `crXSushiToken` `cTokenAmount` into xSUSHI ISushiBarBridge(sushiBar).leave(IERC20(sushiBar).safeBalanceOfSelf()); // burn resulting xSUSHI from `sushiBar` into SUSHI sushiToken.safeTransfer(to, sushiToken.safeBalanceOfSelf()); // transfer resulting SUSHI to `to` } /* β–„β–„β–„β–„β–„ β–„ β–„ β–ˆβ–ˆ β–ˆ β–„β–„ β–ˆ β–€β–„ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–„ β–€β–€β–€β–€β–„ β–ˆ β–„ β–ˆ β–ˆβ–„β–„β–ˆ β–ˆβ–€β–€β–€ β–€β–„β–„β–„β–„β–€ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–€ β–€ β–ˆ β–€ β–€ */ /// @notice Fallback for received ETH - SushiSwap ETH to stake SUSHI into xSUSHI and BENTO for benefit of `to`. receive() external payable { // INARIZUSHI (uint256 reserve0, uint256 reserve1, ) = sushiSwapSushiETHPair.getReserves(); uint256 amountInWithFee = msg.value.mul(997); uint256 out = amountInWithFee.mul(reserve0) / reserve1.mul(1000).add(amountInWithFee); IWETH(wETH).deposit{value: msg.value}(); IERC20(wETH).safeTransfer(address(sushiSwapSushiETHPair), msg.value); sushiSwapSushiETHPair.swap(out, 0, address(this), ""); ISushiBarBridge(sushiBar).enter(sushiToken.safeBalanceOfSelf()); // stake resulting SUSHI into `sushiBar` xSUSHI bento.deposit(IERC20(sushiBar), address(this), msg.sender, IERC20(sushiBar).safeBalanceOfSelf(), 0); // stake resulting xSUSHI into BENTO for `to` } /// @notice SushiSwap ETH to stake SUSHI into xSUSHI and BENTO for benefit of `to`. function inariZushi(address to) external payable returns (uint256 amountOut, uint256 shareOut) { (uint256 reserve0, uint256 reserve1, ) = sushiSwapSushiETHPair.getReserves(); uint256 amountInWithFee = msg.value.mul(997); uint256 out = amountInWithFee.mul(reserve0) / reserve1.mul(1000).add(amountInWithFee); IWETH(wETH).deposit{value: msg.value}(); IERC20(wETH).safeTransfer(address(sushiSwapSushiETHPair), msg.value); sushiSwapSushiETHPair.swap(out, 0, address(this), ""); ISushiBarBridge(sushiBar).enter(sushiToken.safeBalanceOfSelf()); // stake resulting SUSHI into `sushiBar` xSUSHI (amountOut, shareOut) = bento.deposit(IERC20(sushiBar), address(this), to, IERC20(sushiBar).safeBalanceOfSelf(), 0); // stake resulting xSUSHI into BENTO for `to` } /// @notice Simple SushiSwap `fromToken` `amountIn` to `toToken` for benefit of `to`. function swap(address fromToken, address toToken, address to, uint256 amountIn) external returns (uint256 amountOut) { (address token0, address token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken); ISushiSwap pair = ISushiSwap( uint256( keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash)) ) ); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); uint256 amountInWithFee = amountIn.mul(997); IERC20(fromToken).safeTransferFrom(msg.sender, address(pair), amountIn); if (toToken > fromToken) { amountOut = amountInWithFee.mul(reserve1) / reserve0.mul(1000).add(amountInWithFee); pair.swap(0, amountOut, to, ""); } else { amountOut = amountInWithFee.mul(reserve0) / reserve1.mul(1000).add(amountInWithFee); pair.swap(amountOut, 0, to, ""); } } /// @notice Simple SushiSwap local `fromToken` balance in this contract to `toToken` for benefit of `to`. function swapBalance(address fromToken, address toToken, address to) external returns (uint256 amountOut) { (address token0, address token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken); ISushiSwap pair = ISushiSwap( uint256( keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash)) ) ); uint256 amountIn = IERC20(fromToken).safeBalanceOfSelf(); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); uint256 amountInWithFee = amountIn.mul(997); IERC20(fromToken).safeTransfer(address(pair), amountIn); if (toToken > fromToken) { amountOut = amountInWithFee.mul(reserve1) / reserve0.mul(1000).add(amountInWithFee); pair.swap(0, amountOut, to, ""); } else { amountOut = amountInWithFee.mul(reserve0) / reserve1.mul(1000).add(amountInWithFee); pair.swap(amountOut, 0, to, ""); } } }
/// @notice Contract that batches SUSHI staking and DeFi strategies - V1 'iroirona'.
NatSpecSingleLine
inariZushi
function inariZushi(address to) external payable returns (uint256 amountOut, uint256 shareOut) { (uint256 reserve0, uint256 reserve1, ) = sushiSwapSushiETHPair.getReserves(); uint256 amountInWithFee = msg.value.mul(997); uint256 out = amountInWithFee.mul(reserve0) / reserve1.mul(1000).add(amountInWithFee); IWETH(wETH).deposit{value: msg.value}(); IERC20(wETH).safeTransfer(address(sushiSwapSushiETHPair), msg.value); sushiSwapSushiETHPair.swap(out, 0, address(this), ""); ISushiBarBridge(sushiBar).enter(sushiToken.safeBalanceOfSelf()); // stake resulting SUSHI into `sushiBar` xSUSHI (amountOut, shareOut) = bento.deposit(IERC20(sushiBar), address(this), to, IERC20(sushiBar).safeBalanceOfSelf(), 0); // stake resulting xSUSHI into BENTO for `to` }
/// @notice SushiSwap ETH to stake SUSHI into xSUSHI and BENTO for benefit of `to`.
NatSpecSingleLine
v0.7.6+commit.7338295f
GNU GPLv2
ipfs://89a5125d850fb87a89b52e2cb580c7d062e507e61b962188e0983cbea998b8cd
{ "func_code_index": [ 24094, 24953 ] }
11,801
InariV1
@boringcrypto/boring-solidity/contracts/BoringBatchable.sol
0x195e8262aa81ba560478ec6ca4da73745547073f
Solidity
InariV1
contract InariV1 is BoringBatchableWithDai, SushiZap { using SafeMath for uint256; using BoringERC20 for IERC20; IERC20 constant sushiToken = IERC20(0x6B3595068778DD592e39A122f4f5a5cF09C90fE2); // SUSHI token contract address constant sushiBar = 0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272; // xSUSHI staking contract for SUSHI ISushiSwap constant sushiSwapSushiETHPair = ISushiSwap(0x795065dCc9f64b5614C407a6EFDC400DA6221FB0); // SUSHI/ETH pair on SushiSwap IMasterChefV2 constant masterChefv2 = IMasterChefV2(0xEF0881eC094552b2e128Cf945EF17a6752B4Ec5d); // SUSHI MasterChef v2 contract IAaveBridge constant aave = IAaveBridge(0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9); // AAVE lending pool contract for xSUSHI staking into aXSUSHI IERC20 constant aaveSushiToken = IERC20(0xF256CC7847E919FAc9B808cC216cAc87CCF2f47a); // aXSUSHI staking contract for xSUSHI IBentoBridge constant bento = IBentoBridge(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966); // BENTO vault contract address constant crSushiToken = 0x338286C0BC081891A4Bda39C7667ae150bf5D206; // crSUSHI staking contract for SUSHI address constant crXSushiToken = 0x228619CCa194Fbe3Ebeb2f835eC1eA5080DaFbb2; // crXSUSHI staking contract for xSUSHI /// @notice Initialize this Inari contract. constructor() { bento.registerProtocol(); // register this contract with BENTO } /// @notice Helper function to approve this contract to spend tokens and enable strategies. function bridgeToken(IERC20[] calldata token, address[] calldata to) external { for (uint256 i = 0; i < token.length; i++) { token[i].safeApprove(to[i], type(uint256).max); // max approve `to` spender to pull `token` from this contract } } /********** TKN HELPERS **********/ function withdrawToken(IERC20 token, address to, uint256 amount) external { token.safeTransfer(to, amount); } function withdrawTokenBalance(IERC20 token, address to) external { token.safeTransfer(to, token.safeBalanceOfSelf()); } /*********** CHEF HELPERS ***********/ function depositToMasterChefv2(uint256 pid, uint256 amount, address to) external { masterChefv2.deposit(pid, amount, to); } function balanceToMasterChefv2(uint256 pid, address to) external { IERC20 lpToken = masterChefv2.lpToken(pid); masterChefv2.deposit(pid, lpToken.safeBalanceOfSelf(), to); } /// @notice Liquidity zap into CHEF. function zapToMasterChef( address to, address _FromTokenContractAddress, uint256 _amount, uint256 _minPoolTokens, uint256 pid, address _swapTarget, bytes calldata swapData ) external payable returns (uint256 LPBought) { uint256 toInvest = _pullTokens( _FromTokenContractAddress, _amount ); IERC20 _pairAddress = masterChefv2.lpToken(pid); LPBought = _performZapIn( _FromTokenContractAddress, address(_pairAddress), toInvest, _swapTarget, swapData ); require(LPBought >= _minPoolTokens, "ERR: High Slippage"); emit ZapIn(to, address(_pairAddress), LPBought); masterChefv2.deposit(pid, LPBought, to); } /************ KASHI HELPERS ************/ function assetToKashi(IKashiBridge kashiPair, address to, uint256 amount) external returns (uint256 fraction) { IERC20 asset = kashiPair.asset(); asset.safeTransferFrom(msg.sender, address(bento), amount); IBentoBridge(bento).deposit(asset, address(bento), address(kashiPair), amount, 0); fraction = kashiPair.addAsset(to, true, amount); } function assetToKashiChef(uint256 pid, uint256 amount, address to) external returns (uint256 fraction) { address kashiPair = address(masterChefv2.lpToken(pid)); IERC20 asset = IKashiBridge(kashiPair).asset(); asset.safeTransferFrom(msg.sender, address(bento), amount); IBentoBridge(bento).deposit(asset, address(bento), address(kashiPair), amount, 0); fraction = IKashiBridge(kashiPair).addAsset(address(this), true, amount); masterChefv2.deposit(pid, fraction, to); } function assetBalanceToKashi(IKashiBridge kashiPair, address to) external returns (uint256 fraction) { IERC20 asset = kashiPair.asset(); uint256 balance = asset.safeBalanceOfSelf(); IBentoBridge(bento).deposit(asset, address(bento), address(kashiPair), balance, 0); fraction = kashiPair.addAsset(to, true, balance); } function assetBalanceToKashiChef(uint256 pid, address to) external returns (uint256 fraction) { address kashiPair = address(masterChefv2.lpToken(pid)); IERC20 asset = IKashiBridge(kashiPair).asset(); uint256 balance = asset.safeBalanceOfSelf(); IBentoBridge(bento).deposit(asset, address(bento), address(kashiPair), balance, 0); fraction = IKashiBridge(kashiPair).addAsset(address(this), true, balance); masterChefv2.deposit(pid, fraction, to); } function assetBalanceFromKashi(address kashiPair, address to) external returns (uint256 share) { share = IKashiBridge(kashiPair).removeAsset(to, IERC20(kashiPair).safeBalanceOfSelf()); } /// @notice Liquidity zap into KASHI. function zapToKashi( address to, address _FromTokenContractAddress, IKashiBridge kashiPair, uint256 _amount, uint256 _minPoolTokens, address _swapTarget, bytes calldata swapData ) external payable returns (uint256 fraction) { uint256 toInvest = _pullTokens( _FromTokenContractAddress, _amount ); IERC20 _pairAddress = kashiPair.asset(); uint256 LPBought = _performZapIn( _FromTokenContractAddress, address(_pairAddress), toInvest, _swapTarget, swapData ); require(LPBought >= _minPoolTokens, "ERR: High Slippage"); emit ZapIn(to, address(_pairAddress), LPBought); _pairAddress.safeTransfer(address(bento), LPBought); IBentoBridge(bento).deposit(_pairAddress, address(bento), address(kashiPair), LPBought, 0); fraction = kashiPair.addAsset(to, true, LPBought); } /* β–ˆβ–ˆ β–ˆβ–ˆ β–„ β–„β–ˆβ–ˆβ–ˆβ–„ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆβ–€ β–€ β–ˆβ–„β–„β–ˆ β–ˆβ–„β–„β–ˆ β–ˆ β–ˆ β–ˆβ–ˆβ–„β–„ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆβ–„ β–„β–€ β–ˆ β–ˆ β–ˆ β–ˆ β–€β–ˆβ–ˆβ–ˆβ–€ β–ˆ β–ˆ β–ˆβ– β–€ β–€ ▐ */ /*********** AAVE HELPERS ***********/ function balanceToAave(address underlying, address to) external { aave.deposit(underlying, IERC20(underlying).safeBalanceOfSelf(), to, 0); } function balanceFromAave(address aToken, address to) external { address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token aave.withdraw(underlying, IERC20(aToken).safeBalanceOfSelf(), to); } /************************** AAVE -> UNDERLYING -> BENTO **************************/ /// @notice Migrate AAVE `aToken` underlying `amount` into BENTO for benefit of `to` by batching calls to `aave` and `bento`. function aaveToBento(address aToken, address to, uint256 amount) external returns (uint256 amountOut, uint256 shareOut) { IERC20(aToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `aToken` `amount` into this contract address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token aave.withdraw(underlying, amount, address(bento)); // burn deposited `aToken` from `aave` into `underlying` (amountOut, shareOut) = bento.deposit(IERC20(underlying), address(bento), to, amount, 0); // stake `underlying` into BENTO for `to` } /************************** BENTO -> UNDERLYING -> AAVE **************************/ /// @notice Migrate `underlying` `amount` from BENTO into AAVE for benefit of `to` by batching calls to `bento` and `aave`. function bentoToAave(IERC20 underlying, address to, uint256 amount) external { bento.withdraw(underlying, msg.sender, address(this), amount, 0); // withdraw `amount` of `underlying` from BENTO into this contract aave.deposit(address(underlying), amount, to, 0); // stake `underlying` into `aave` for `to` } /************************* AAVE -> UNDERLYING -> COMP *************************/ /// @notice Migrate AAVE `aToken` underlying `amount` into COMP/CREAM `cToken` for benefit of `to` by batching calls to `aave` and `cToken`. function aaveToCompound(address aToken, address cToken, address to, uint256 amount) external { IERC20(aToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `aToken` `amount` into this contract address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token aave.withdraw(underlying, amount, address(this)); // burn deposited `aToken` from `aave` into `underlying` ICompoundBridge(cToken).mint(amount); // stake `underlying` into `cToken` IERC20(cToken).safeTransfer(to, IERC20(cToken).safeBalanceOfSelf()); // transfer resulting `cToken` to `to` } /************************* COMP -> UNDERLYING -> AAVE *************************/ /// @notice Migrate COMP/CREAM `cToken` underlying `amount` into AAVE for benefit of `to` by batching calls to `cToken` and `aave`. function compoundToAave(address cToken, address to, uint256 amount) external { IERC20(cToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `cToken` `amount` into this contract ICompoundBridge(cToken).redeem(amount); // burn deposited `cToken` into `underlying` address underlying = ICompoundBridge(cToken).underlying(); // sanity check for `underlying` token aave.deposit(underlying, IERC20(underlying).safeBalanceOfSelf(), to, 0); // stake resulting `underlying` into `aave` for `to` } /********************** SUSHI -> XSUSHI -> AAVE **********************/ /// @notice Stake SUSHI `amount` into aXSUSHI for benefit of `to` by batching calls to `sushiBar` and `aave`. function stakeSushiToAave(address to, uint256 amount) external { // SAAVE sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI into `sushiBar` xSUSHI aave.deposit(sushiBar, IERC20(sushiBar).safeBalanceOfSelf(), to, 0); // stake resulting xSUSHI into `aave` aXSUSHI for `to` } /********************** AAVE -> XSUSHI -> SUSHI **********************/ /// @notice Unstake aXSUSHI `amount` into SUSHI for benefit of `to` by batching calls to `aave` and `sushiBar`. function unstakeSushiFromAave(address to, uint256 amount) external { aaveSushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` aXSUSHI `amount` into this contract aave.withdraw(sushiBar, amount, address(this)); // burn deposited aXSUSHI from `aave` into xSUSHI ISushiBarBridge(sushiBar).leave(amount); // burn resulting xSUSHI from `sushiBar` into SUSHI sushiToken.safeTransfer(to, sushiToken.safeBalanceOfSelf()); // transfer resulting SUSHI to `to` } /* β–ˆβ–ˆβ–ˆ β–„β–ˆβ–ˆβ–ˆβ–„ β–„ β–„β–„β–„β–„β–€ β–ˆβ–ˆβ–ˆβ–ˆβ–„ β–ˆ β–ˆ β–ˆβ–€ β–€ β–ˆ β–€β–€β–€ β–ˆ β–ˆ β–ˆ β–ˆ β–€ β–„ β–ˆβ–ˆβ–„β–„ β–ˆβ–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–„β–€ β–ˆβ–„ β–„β–€ β–ˆ β–ˆ β–ˆ β–ˆ β–€β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–€β–ˆβ–ˆβ–ˆβ–€ β–ˆ β–ˆ β–ˆ β–€ β–ˆ β–ˆβ–ˆ */ /************ BENTO HELPERS ************/ function balanceToBento(IERC20 token, address to) external returns (uint256 amountOut, uint256 shareOut) { (amountOut, shareOut) = bento.deposit(token, address(this), to, token.safeBalanceOfSelf(), 0); } /// @dev Included to be able to approve `bento` in the same transaction (using `batch()`). function setBentoApproval( address user, address masterContract, bool approved, uint8 v, bytes32 r, bytes32 s ) external { bento.setMasterContractApproval(user, masterContract, approved, v, r, s); } /// @notice Liquidity zap into BENTO. function zapToBento( address to, address _FromTokenContractAddress, address _pairAddress, uint256 _amount, uint256 _minPoolTokens, address _swapTarget, bytes calldata swapData ) external payable returns (uint256 LPBought) { uint256 toInvest = _pullTokens( _FromTokenContractAddress, _amount ); LPBought = _performZapIn( _FromTokenContractAddress, _pairAddress, toInvest, _swapTarget, swapData ); require(LPBought >= _minPoolTokens, "ERR: High Slippage"); emit ZapIn(to, _pairAddress, LPBought); bento.deposit(IERC20(_pairAddress), address(this), to, LPBought, 0); } /// @notice Liquidity unzap from BENTO. function zapFromBento( address pair, address to, uint256 amount ) external returns (uint256 amount0, uint256 amount1) { bento.withdraw(IERC20(pair), msg.sender, pair, amount, 0); // withdraw `amount` to `pair` from BENTO (amount0, amount1) = ISushiSwap(pair).burn(to); // trigger burn to redeem liquidity for `to` } /*********************** SUSHI -> XSUSHI -> BENTO ***********************/ /// @notice Stake SUSHI `amount` into BENTO xSUSHI for benefit of `to` by batching calls to `sushiBar` and `bento`. function stakeSushiToBento(address to, uint256 amount) external returns (uint256 amountOut, uint256 shareOut) { sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI into `sushiBar` xSUSHI (amountOut, shareOut) = bento.deposit(IERC20(sushiBar), address(this), to, IERC20(sushiBar).safeBalanceOfSelf(), 0); // stake resulting xSUSHI into BENTO for `to` } /*********************** BENTO -> XSUSHI -> SUSHI ***********************/ /// @notice Unstake xSUSHI `amount` from BENTO into SUSHI for benefit of `to` by batching calls to `bento` and `sushiBar`. function unstakeSushiFromBento(address to, uint256 amount) external { bento.withdraw(IERC20(sushiBar), msg.sender, address(this), amount, 0); // withdraw `amount` of xSUSHI from BENTO into this contract ISushiBarBridge(sushiBar).leave(amount); // burn withdrawn xSUSHI from `sushiBar` into SUSHI sushiToken.safeTransfer(to, sushiToken.safeBalanceOfSelf()); // transfer resulting SUSHI to `to` } /* β–„β–ˆβ–„ β–ˆβ–„β–„β–„β–„ β–„β–ˆβ–ˆβ–ˆβ–„ β–ˆβ–ˆ β–ˆβ–€β–„β–€β–ˆ β–ˆβ–€ β–€β–„ β–ˆ β–„β–€ β–ˆβ–€ β–€ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–€ β–ˆβ–€β–€β–Œ β–ˆβ–ˆβ–„β–„ β–ˆβ–„β–„β–ˆ β–ˆ β–„ β–ˆ β–ˆβ–„ β–„β–€ β–ˆ β–ˆ β–ˆβ–„ β–„β–€ β–ˆ β–ˆ β–ˆ β–ˆ β–€β–ˆβ–ˆβ–ˆβ–€ β–ˆ β–€β–ˆβ–ˆβ–ˆβ–€ β–ˆ β–ˆ β–€ β–ˆ β–€ β–€ */ // - COMPOUND - // /*********** COMP HELPERS ***********/ function balanceToCompound(ICompoundBridge cToken) external { IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token cToken.mint(underlying.safeBalanceOfSelf()); } function balanceFromCompound(address cToken) external { ICompoundBridge(cToken).redeem(IERC20(cToken).safeBalanceOfSelf()); } /************************** COMP -> UNDERLYING -> BENTO **************************/ /// @notice Migrate COMP/CREAM `cToken` `cTokenAmount` into underlying and BENTO for benefit of `to` by batching calls to `cToken` and `bento`. function compoundToBento(address cToken, address to, uint256 cTokenAmount) external returns (uint256 amountOut, uint256 shareOut) { IERC20(cToken).safeTransferFrom(msg.sender, address(this), cTokenAmount); // deposit `msg.sender` `cToken` `cTokenAmount` into this contract ICompoundBridge(cToken).redeem(cTokenAmount); // burn deposited `cToken` into `underlying` IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token (amountOut, shareOut) = bento.deposit(underlying, address(this), to, underlying.safeBalanceOfSelf(), 0); // stake resulting `underlying` into BENTO for `to` } /************************** BENTO -> UNDERLYING -> COMP **************************/ /// @notice Migrate `cToken` `underlyingAmount` from BENTO into COMP/CREAM for benefit of `to` by batching calls to `bento` and `cToken`. function bentoToCompound(address cToken, address to, uint256 underlyingAmount) external { IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token bento.withdraw(underlying, msg.sender, address(this), underlyingAmount, 0); // withdraw `underlyingAmount` of `underlying` from BENTO into this contract ICompoundBridge(cToken).mint(underlyingAmount); // stake `underlying` into `cToken` IERC20(cToken).safeTransfer(to, IERC20(cToken).safeBalanceOfSelf()); // transfer resulting `cToken` to `to` } /********************** SUSHI -> CREAM -> BENTO **********************/ /// @notice Stake SUSHI `amount` into crSUSHI and BENTO for benefit of `to` by batching calls to `crSushiToken` and `bento`. function sushiToCreamToBento(address to, uint256 amount) external returns (uint256 amountOut, uint256 shareOut) { sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ICompoundBridge(crSushiToken).mint(amount); // stake deposited SUSHI into crSUSHI (amountOut, shareOut) = bento.deposit(IERC20(crSushiToken), address(this), to, IERC20(crSushiToken).safeBalanceOfSelf(), 0); // stake resulting crSUSHI into BENTO for `to` } /********************** BENTO -> CREAM -> SUSHI **********************/ /// @notice Unstake crSUSHI `cTokenAmount` into SUSHI from BENTO for benefit of `to` by batching calls to `bento` and `crSushiToken`. function sushiFromCreamFromBento(address to, uint256 cTokenAmount) external { bento.withdraw(IERC20(crSushiToken), msg.sender, address(this), cTokenAmount, 0); // withdraw `cTokenAmount` of `crSushiToken` from BENTO into this contract ICompoundBridge(crSushiToken).redeem(cTokenAmount); // burn deposited `crSushiToken` into SUSHI sushiToken.safeTransfer(to, sushiToken.safeBalanceOfSelf()); // transfer resulting SUSHI to `to` } /*********************** SUSHI -> XSUSHI -> CREAM ***********************/ /// @notice Stake SUSHI `amount` into crXSUSHI for benefit of `to` by batching calls to `sushiBar` and `crXSushiToken`. function stakeSushiToCream(address to, uint256 amount) external { // SCREAM sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI `amount` into `sushiBar` xSUSHI ICompoundBridge(crXSushiToken).mint(IERC20(sushiBar).safeBalanceOfSelf()); // stake resulting xSUSHI into crXSUSHI IERC20(crXSushiToken).safeTransfer(to, IERC20(crXSushiToken).safeBalanceOfSelf()); // transfer resulting crXSUSHI to `to` } /*********************** CREAM -> XSUSHI -> SUSHI ***********************/ /// @notice Unstake crXSUSHI `cTokenAmount` into SUSHI for benefit of `to` by batching calls to `crXSushiToken` and `sushiBar`. function unstakeSushiFromCream(address to, uint256 cTokenAmount) external { IERC20(crXSushiToken).safeTransferFrom(msg.sender, address(this), cTokenAmount); // deposit `msg.sender` `crXSushiToken` `cTokenAmount` into this contract ICompoundBridge(crXSushiToken).redeem(cTokenAmount); // burn deposited `crXSushiToken` `cTokenAmount` into xSUSHI ISushiBarBridge(sushiBar).leave(IERC20(sushiBar).safeBalanceOfSelf()); // burn resulting xSUSHI `amount` from `sushiBar` into SUSHI sushiToken.safeTransfer(to, sushiToken.safeBalanceOfSelf()); // transfer resulting SUSHI to `to` } /******************************** SUSHI -> XSUSHI -> CREAM -> BENTO ********************************/ /// @notice Stake SUSHI `amount` into crXSUSHI and BENTO for benefit of `to` by batching calls to `sushiBar`, `crXSushiToken` and `bento`. function stakeSushiToCreamToBento(address to, uint256 amount) external returns (uint256 amountOut, uint256 shareOut) { sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI `amount` into `sushiBar` xSUSHI ICompoundBridge(crXSushiToken).mint(IERC20(sushiBar).safeBalanceOfSelf()); // stake resulting xSUSHI into crXSUSHI (amountOut, shareOut) = bento.deposit(IERC20(crXSushiToken), address(this), to, IERC20(crXSushiToken).safeBalanceOfSelf(), 0); // stake resulting crXSUSHI into BENTO for `to` } /******************************** BENTO -> CREAM -> XSUSHI -> SUSHI ********************************/ /// @notice Unstake crXSUSHI `cTokenAmount` into SUSHI from BENTO for benefit of `to` by batching calls to `bento`, `crXSushiToken` and `sushiBar`. function unstakeSushiFromCreamFromBento(address to, uint256 cTokenAmount) external { bento.withdraw(IERC20(crXSushiToken), msg.sender, address(this), cTokenAmount, 0); // withdraw `cTokenAmount` of `crXSushiToken` from BENTO into this contract ICompoundBridge(crXSushiToken).redeem(cTokenAmount); // burn deposited `crXSushiToken` `cTokenAmount` into xSUSHI ISushiBarBridge(sushiBar).leave(IERC20(sushiBar).safeBalanceOfSelf()); // burn resulting xSUSHI from `sushiBar` into SUSHI sushiToken.safeTransfer(to, sushiToken.safeBalanceOfSelf()); // transfer resulting SUSHI to `to` } /* β–„β–„β–„β–„β–„ β–„ β–„ β–ˆβ–ˆ β–ˆ β–„β–„ β–ˆ β–€β–„ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–„ β–€β–€β–€β–€β–„ β–ˆ β–„ β–ˆ β–ˆβ–„β–„β–ˆ β–ˆβ–€β–€β–€ β–€β–„β–„β–„β–„β–€ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–€ β–€ β–ˆ β–€ β–€ */ /// @notice Fallback for received ETH - SushiSwap ETH to stake SUSHI into xSUSHI and BENTO for benefit of `to`. receive() external payable { // INARIZUSHI (uint256 reserve0, uint256 reserve1, ) = sushiSwapSushiETHPair.getReserves(); uint256 amountInWithFee = msg.value.mul(997); uint256 out = amountInWithFee.mul(reserve0) / reserve1.mul(1000).add(amountInWithFee); IWETH(wETH).deposit{value: msg.value}(); IERC20(wETH).safeTransfer(address(sushiSwapSushiETHPair), msg.value); sushiSwapSushiETHPair.swap(out, 0, address(this), ""); ISushiBarBridge(sushiBar).enter(sushiToken.safeBalanceOfSelf()); // stake resulting SUSHI into `sushiBar` xSUSHI bento.deposit(IERC20(sushiBar), address(this), msg.sender, IERC20(sushiBar).safeBalanceOfSelf(), 0); // stake resulting xSUSHI into BENTO for `to` } /// @notice SushiSwap ETH to stake SUSHI into xSUSHI and BENTO for benefit of `to`. function inariZushi(address to) external payable returns (uint256 amountOut, uint256 shareOut) { (uint256 reserve0, uint256 reserve1, ) = sushiSwapSushiETHPair.getReserves(); uint256 amountInWithFee = msg.value.mul(997); uint256 out = amountInWithFee.mul(reserve0) / reserve1.mul(1000).add(amountInWithFee); IWETH(wETH).deposit{value: msg.value}(); IERC20(wETH).safeTransfer(address(sushiSwapSushiETHPair), msg.value); sushiSwapSushiETHPair.swap(out, 0, address(this), ""); ISushiBarBridge(sushiBar).enter(sushiToken.safeBalanceOfSelf()); // stake resulting SUSHI into `sushiBar` xSUSHI (amountOut, shareOut) = bento.deposit(IERC20(sushiBar), address(this), to, IERC20(sushiBar).safeBalanceOfSelf(), 0); // stake resulting xSUSHI into BENTO for `to` } /// @notice Simple SushiSwap `fromToken` `amountIn` to `toToken` for benefit of `to`. function swap(address fromToken, address toToken, address to, uint256 amountIn) external returns (uint256 amountOut) { (address token0, address token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken); ISushiSwap pair = ISushiSwap( uint256( keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash)) ) ); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); uint256 amountInWithFee = amountIn.mul(997); IERC20(fromToken).safeTransferFrom(msg.sender, address(pair), amountIn); if (toToken > fromToken) { amountOut = amountInWithFee.mul(reserve1) / reserve0.mul(1000).add(amountInWithFee); pair.swap(0, amountOut, to, ""); } else { amountOut = amountInWithFee.mul(reserve0) / reserve1.mul(1000).add(amountInWithFee); pair.swap(amountOut, 0, to, ""); } } /// @notice Simple SushiSwap local `fromToken` balance in this contract to `toToken` for benefit of `to`. function swapBalance(address fromToken, address toToken, address to) external returns (uint256 amountOut) { (address token0, address token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken); ISushiSwap pair = ISushiSwap( uint256( keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash)) ) ); uint256 amountIn = IERC20(fromToken).safeBalanceOfSelf(); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); uint256 amountInWithFee = amountIn.mul(997); IERC20(fromToken).safeTransfer(address(pair), amountIn); if (toToken > fromToken) { amountOut = amountInWithFee.mul(reserve1) / reserve0.mul(1000).add(amountInWithFee); pair.swap(0, amountOut, to, ""); } else { amountOut = amountInWithFee.mul(reserve0) / reserve1.mul(1000).add(amountInWithFee); pair.swap(amountOut, 0, to, ""); } } }
/// @notice Contract that batches SUSHI staking and DeFi strategies - V1 'iroirona'.
NatSpecSingleLine
swap
function swap(address fromToken, address toToken, address to, uint256 amountIn) external returns (uint256 amountOut) { (address token0, address token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken); ISushiSwap pair = ISushiSwap( uint256( keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash)) ) ); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); uint256 amountInWithFee = amountIn.mul(997); IERC20(fromToken).safeTransferFrom(msg.sender, address(pair), amountIn); if (toToken > fromToken) { amountOut = amountInWithFee.mul(reserve1) / reserve0.mul(1000).add(amountInWithFee); pair.swap(0, amountOut, to, ""); } else { amountOut = amountInWithFee.mul(reserve0) / reserve1.mul(1000).add(amountInWithFee); pair.swap(amountOut, 0, to, ""); } }
/// @notice Simple SushiSwap `fromToken` `amountIn` to `toToken` for benefit of `to`.
NatSpecSingleLine
v0.7.6+commit.7338295f
GNU GPLv2
ipfs://89a5125d850fb87a89b52e2cb580c7d062e507e61b962188e0983cbea998b8cd
{ "func_code_index": [ 25051, 26167 ] }
11,802
InariV1
@boringcrypto/boring-solidity/contracts/BoringBatchable.sol
0x195e8262aa81ba560478ec6ca4da73745547073f
Solidity
InariV1
contract InariV1 is BoringBatchableWithDai, SushiZap { using SafeMath for uint256; using BoringERC20 for IERC20; IERC20 constant sushiToken = IERC20(0x6B3595068778DD592e39A122f4f5a5cF09C90fE2); // SUSHI token contract address constant sushiBar = 0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272; // xSUSHI staking contract for SUSHI ISushiSwap constant sushiSwapSushiETHPair = ISushiSwap(0x795065dCc9f64b5614C407a6EFDC400DA6221FB0); // SUSHI/ETH pair on SushiSwap IMasterChefV2 constant masterChefv2 = IMasterChefV2(0xEF0881eC094552b2e128Cf945EF17a6752B4Ec5d); // SUSHI MasterChef v2 contract IAaveBridge constant aave = IAaveBridge(0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9); // AAVE lending pool contract for xSUSHI staking into aXSUSHI IERC20 constant aaveSushiToken = IERC20(0xF256CC7847E919FAc9B808cC216cAc87CCF2f47a); // aXSUSHI staking contract for xSUSHI IBentoBridge constant bento = IBentoBridge(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966); // BENTO vault contract address constant crSushiToken = 0x338286C0BC081891A4Bda39C7667ae150bf5D206; // crSUSHI staking contract for SUSHI address constant crXSushiToken = 0x228619CCa194Fbe3Ebeb2f835eC1eA5080DaFbb2; // crXSUSHI staking contract for xSUSHI /// @notice Initialize this Inari contract. constructor() { bento.registerProtocol(); // register this contract with BENTO } /// @notice Helper function to approve this contract to spend tokens and enable strategies. function bridgeToken(IERC20[] calldata token, address[] calldata to) external { for (uint256 i = 0; i < token.length; i++) { token[i].safeApprove(to[i], type(uint256).max); // max approve `to` spender to pull `token` from this contract } } /********** TKN HELPERS **********/ function withdrawToken(IERC20 token, address to, uint256 amount) external { token.safeTransfer(to, amount); } function withdrawTokenBalance(IERC20 token, address to) external { token.safeTransfer(to, token.safeBalanceOfSelf()); } /*********** CHEF HELPERS ***********/ function depositToMasterChefv2(uint256 pid, uint256 amount, address to) external { masterChefv2.deposit(pid, amount, to); } function balanceToMasterChefv2(uint256 pid, address to) external { IERC20 lpToken = masterChefv2.lpToken(pid); masterChefv2.deposit(pid, lpToken.safeBalanceOfSelf(), to); } /// @notice Liquidity zap into CHEF. function zapToMasterChef( address to, address _FromTokenContractAddress, uint256 _amount, uint256 _minPoolTokens, uint256 pid, address _swapTarget, bytes calldata swapData ) external payable returns (uint256 LPBought) { uint256 toInvest = _pullTokens( _FromTokenContractAddress, _amount ); IERC20 _pairAddress = masterChefv2.lpToken(pid); LPBought = _performZapIn( _FromTokenContractAddress, address(_pairAddress), toInvest, _swapTarget, swapData ); require(LPBought >= _minPoolTokens, "ERR: High Slippage"); emit ZapIn(to, address(_pairAddress), LPBought); masterChefv2.deposit(pid, LPBought, to); } /************ KASHI HELPERS ************/ function assetToKashi(IKashiBridge kashiPair, address to, uint256 amount) external returns (uint256 fraction) { IERC20 asset = kashiPair.asset(); asset.safeTransferFrom(msg.sender, address(bento), amount); IBentoBridge(bento).deposit(asset, address(bento), address(kashiPair), amount, 0); fraction = kashiPair.addAsset(to, true, amount); } function assetToKashiChef(uint256 pid, uint256 amount, address to) external returns (uint256 fraction) { address kashiPair = address(masterChefv2.lpToken(pid)); IERC20 asset = IKashiBridge(kashiPair).asset(); asset.safeTransferFrom(msg.sender, address(bento), amount); IBentoBridge(bento).deposit(asset, address(bento), address(kashiPair), amount, 0); fraction = IKashiBridge(kashiPair).addAsset(address(this), true, amount); masterChefv2.deposit(pid, fraction, to); } function assetBalanceToKashi(IKashiBridge kashiPair, address to) external returns (uint256 fraction) { IERC20 asset = kashiPair.asset(); uint256 balance = asset.safeBalanceOfSelf(); IBentoBridge(bento).deposit(asset, address(bento), address(kashiPair), balance, 0); fraction = kashiPair.addAsset(to, true, balance); } function assetBalanceToKashiChef(uint256 pid, address to) external returns (uint256 fraction) { address kashiPair = address(masterChefv2.lpToken(pid)); IERC20 asset = IKashiBridge(kashiPair).asset(); uint256 balance = asset.safeBalanceOfSelf(); IBentoBridge(bento).deposit(asset, address(bento), address(kashiPair), balance, 0); fraction = IKashiBridge(kashiPair).addAsset(address(this), true, balance); masterChefv2.deposit(pid, fraction, to); } function assetBalanceFromKashi(address kashiPair, address to) external returns (uint256 share) { share = IKashiBridge(kashiPair).removeAsset(to, IERC20(kashiPair).safeBalanceOfSelf()); } /// @notice Liquidity zap into KASHI. function zapToKashi( address to, address _FromTokenContractAddress, IKashiBridge kashiPair, uint256 _amount, uint256 _minPoolTokens, address _swapTarget, bytes calldata swapData ) external payable returns (uint256 fraction) { uint256 toInvest = _pullTokens( _FromTokenContractAddress, _amount ); IERC20 _pairAddress = kashiPair.asset(); uint256 LPBought = _performZapIn( _FromTokenContractAddress, address(_pairAddress), toInvest, _swapTarget, swapData ); require(LPBought >= _minPoolTokens, "ERR: High Slippage"); emit ZapIn(to, address(_pairAddress), LPBought); _pairAddress.safeTransfer(address(bento), LPBought); IBentoBridge(bento).deposit(_pairAddress, address(bento), address(kashiPair), LPBought, 0); fraction = kashiPair.addAsset(to, true, LPBought); } /* β–ˆβ–ˆ β–ˆβ–ˆ β–„ β–„β–ˆβ–ˆβ–ˆβ–„ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆβ–€ β–€ β–ˆβ–„β–„β–ˆ β–ˆβ–„β–„β–ˆ β–ˆ β–ˆ β–ˆβ–ˆβ–„β–„ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆβ–„ β–„β–€ β–ˆ β–ˆ β–ˆ β–ˆ β–€β–ˆβ–ˆβ–ˆβ–€ β–ˆ β–ˆ β–ˆβ– β–€ β–€ ▐ */ /*********** AAVE HELPERS ***********/ function balanceToAave(address underlying, address to) external { aave.deposit(underlying, IERC20(underlying).safeBalanceOfSelf(), to, 0); } function balanceFromAave(address aToken, address to) external { address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token aave.withdraw(underlying, IERC20(aToken).safeBalanceOfSelf(), to); } /************************** AAVE -> UNDERLYING -> BENTO **************************/ /// @notice Migrate AAVE `aToken` underlying `amount` into BENTO for benefit of `to` by batching calls to `aave` and `bento`. function aaveToBento(address aToken, address to, uint256 amount) external returns (uint256 amountOut, uint256 shareOut) { IERC20(aToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `aToken` `amount` into this contract address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token aave.withdraw(underlying, amount, address(bento)); // burn deposited `aToken` from `aave` into `underlying` (amountOut, shareOut) = bento.deposit(IERC20(underlying), address(bento), to, amount, 0); // stake `underlying` into BENTO for `to` } /************************** BENTO -> UNDERLYING -> AAVE **************************/ /// @notice Migrate `underlying` `amount` from BENTO into AAVE for benefit of `to` by batching calls to `bento` and `aave`. function bentoToAave(IERC20 underlying, address to, uint256 amount) external { bento.withdraw(underlying, msg.sender, address(this), amount, 0); // withdraw `amount` of `underlying` from BENTO into this contract aave.deposit(address(underlying), amount, to, 0); // stake `underlying` into `aave` for `to` } /************************* AAVE -> UNDERLYING -> COMP *************************/ /// @notice Migrate AAVE `aToken` underlying `amount` into COMP/CREAM `cToken` for benefit of `to` by batching calls to `aave` and `cToken`. function aaveToCompound(address aToken, address cToken, address to, uint256 amount) external { IERC20(aToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `aToken` `amount` into this contract address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token aave.withdraw(underlying, amount, address(this)); // burn deposited `aToken` from `aave` into `underlying` ICompoundBridge(cToken).mint(amount); // stake `underlying` into `cToken` IERC20(cToken).safeTransfer(to, IERC20(cToken).safeBalanceOfSelf()); // transfer resulting `cToken` to `to` } /************************* COMP -> UNDERLYING -> AAVE *************************/ /// @notice Migrate COMP/CREAM `cToken` underlying `amount` into AAVE for benefit of `to` by batching calls to `cToken` and `aave`. function compoundToAave(address cToken, address to, uint256 amount) external { IERC20(cToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `cToken` `amount` into this contract ICompoundBridge(cToken).redeem(amount); // burn deposited `cToken` into `underlying` address underlying = ICompoundBridge(cToken).underlying(); // sanity check for `underlying` token aave.deposit(underlying, IERC20(underlying).safeBalanceOfSelf(), to, 0); // stake resulting `underlying` into `aave` for `to` } /********************** SUSHI -> XSUSHI -> AAVE **********************/ /// @notice Stake SUSHI `amount` into aXSUSHI for benefit of `to` by batching calls to `sushiBar` and `aave`. function stakeSushiToAave(address to, uint256 amount) external { // SAAVE sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI into `sushiBar` xSUSHI aave.deposit(sushiBar, IERC20(sushiBar).safeBalanceOfSelf(), to, 0); // stake resulting xSUSHI into `aave` aXSUSHI for `to` } /********************** AAVE -> XSUSHI -> SUSHI **********************/ /// @notice Unstake aXSUSHI `amount` into SUSHI for benefit of `to` by batching calls to `aave` and `sushiBar`. function unstakeSushiFromAave(address to, uint256 amount) external { aaveSushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` aXSUSHI `amount` into this contract aave.withdraw(sushiBar, amount, address(this)); // burn deposited aXSUSHI from `aave` into xSUSHI ISushiBarBridge(sushiBar).leave(amount); // burn resulting xSUSHI from `sushiBar` into SUSHI sushiToken.safeTransfer(to, sushiToken.safeBalanceOfSelf()); // transfer resulting SUSHI to `to` } /* β–ˆβ–ˆβ–ˆ β–„β–ˆβ–ˆβ–ˆβ–„ β–„ β–„β–„β–„β–„β–€ β–ˆβ–ˆβ–ˆβ–ˆβ–„ β–ˆ β–ˆ β–ˆβ–€ β–€ β–ˆ β–€β–€β–€ β–ˆ β–ˆ β–ˆ β–ˆ β–€ β–„ β–ˆβ–ˆβ–„β–„ β–ˆβ–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–„β–€ β–ˆβ–„ β–„β–€ β–ˆ β–ˆ β–ˆ β–ˆ β–€β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–€β–ˆβ–ˆβ–ˆβ–€ β–ˆ β–ˆ β–ˆ β–€ β–ˆ β–ˆβ–ˆ */ /************ BENTO HELPERS ************/ function balanceToBento(IERC20 token, address to) external returns (uint256 amountOut, uint256 shareOut) { (amountOut, shareOut) = bento.deposit(token, address(this), to, token.safeBalanceOfSelf(), 0); } /// @dev Included to be able to approve `bento` in the same transaction (using `batch()`). function setBentoApproval( address user, address masterContract, bool approved, uint8 v, bytes32 r, bytes32 s ) external { bento.setMasterContractApproval(user, masterContract, approved, v, r, s); } /// @notice Liquidity zap into BENTO. function zapToBento( address to, address _FromTokenContractAddress, address _pairAddress, uint256 _amount, uint256 _minPoolTokens, address _swapTarget, bytes calldata swapData ) external payable returns (uint256 LPBought) { uint256 toInvest = _pullTokens( _FromTokenContractAddress, _amount ); LPBought = _performZapIn( _FromTokenContractAddress, _pairAddress, toInvest, _swapTarget, swapData ); require(LPBought >= _minPoolTokens, "ERR: High Slippage"); emit ZapIn(to, _pairAddress, LPBought); bento.deposit(IERC20(_pairAddress), address(this), to, LPBought, 0); } /// @notice Liquidity unzap from BENTO. function zapFromBento( address pair, address to, uint256 amount ) external returns (uint256 amount0, uint256 amount1) { bento.withdraw(IERC20(pair), msg.sender, pair, amount, 0); // withdraw `amount` to `pair` from BENTO (amount0, amount1) = ISushiSwap(pair).burn(to); // trigger burn to redeem liquidity for `to` } /*********************** SUSHI -> XSUSHI -> BENTO ***********************/ /// @notice Stake SUSHI `amount` into BENTO xSUSHI for benefit of `to` by batching calls to `sushiBar` and `bento`. function stakeSushiToBento(address to, uint256 amount) external returns (uint256 amountOut, uint256 shareOut) { sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI into `sushiBar` xSUSHI (amountOut, shareOut) = bento.deposit(IERC20(sushiBar), address(this), to, IERC20(sushiBar).safeBalanceOfSelf(), 0); // stake resulting xSUSHI into BENTO for `to` } /*********************** BENTO -> XSUSHI -> SUSHI ***********************/ /// @notice Unstake xSUSHI `amount` from BENTO into SUSHI for benefit of `to` by batching calls to `bento` and `sushiBar`. function unstakeSushiFromBento(address to, uint256 amount) external { bento.withdraw(IERC20(sushiBar), msg.sender, address(this), amount, 0); // withdraw `amount` of xSUSHI from BENTO into this contract ISushiBarBridge(sushiBar).leave(amount); // burn withdrawn xSUSHI from `sushiBar` into SUSHI sushiToken.safeTransfer(to, sushiToken.safeBalanceOfSelf()); // transfer resulting SUSHI to `to` } /* β–„β–ˆβ–„ β–ˆβ–„β–„β–„β–„ β–„β–ˆβ–ˆβ–ˆβ–„ β–ˆβ–ˆ β–ˆβ–€β–„β–€β–ˆ β–ˆβ–€ β–€β–„ β–ˆ β–„β–€ β–ˆβ–€ β–€ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–€ β–ˆβ–€β–€β–Œ β–ˆβ–ˆβ–„β–„ β–ˆβ–„β–„β–ˆ β–ˆ β–„ β–ˆ β–ˆβ–„ β–„β–€ β–ˆ β–ˆ β–ˆβ–„ β–„β–€ β–ˆ β–ˆ β–ˆ β–ˆ β–€β–ˆβ–ˆβ–ˆβ–€ β–ˆ β–€β–ˆβ–ˆβ–ˆβ–€ β–ˆ β–ˆ β–€ β–ˆ β–€ β–€ */ // - COMPOUND - // /*********** COMP HELPERS ***********/ function balanceToCompound(ICompoundBridge cToken) external { IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token cToken.mint(underlying.safeBalanceOfSelf()); } function balanceFromCompound(address cToken) external { ICompoundBridge(cToken).redeem(IERC20(cToken).safeBalanceOfSelf()); } /************************** COMP -> UNDERLYING -> BENTO **************************/ /// @notice Migrate COMP/CREAM `cToken` `cTokenAmount` into underlying and BENTO for benefit of `to` by batching calls to `cToken` and `bento`. function compoundToBento(address cToken, address to, uint256 cTokenAmount) external returns (uint256 amountOut, uint256 shareOut) { IERC20(cToken).safeTransferFrom(msg.sender, address(this), cTokenAmount); // deposit `msg.sender` `cToken` `cTokenAmount` into this contract ICompoundBridge(cToken).redeem(cTokenAmount); // burn deposited `cToken` into `underlying` IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token (amountOut, shareOut) = bento.deposit(underlying, address(this), to, underlying.safeBalanceOfSelf(), 0); // stake resulting `underlying` into BENTO for `to` } /************************** BENTO -> UNDERLYING -> COMP **************************/ /// @notice Migrate `cToken` `underlyingAmount` from BENTO into COMP/CREAM for benefit of `to` by batching calls to `bento` and `cToken`. function bentoToCompound(address cToken, address to, uint256 underlyingAmount) external { IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token bento.withdraw(underlying, msg.sender, address(this), underlyingAmount, 0); // withdraw `underlyingAmount` of `underlying` from BENTO into this contract ICompoundBridge(cToken).mint(underlyingAmount); // stake `underlying` into `cToken` IERC20(cToken).safeTransfer(to, IERC20(cToken).safeBalanceOfSelf()); // transfer resulting `cToken` to `to` } /********************** SUSHI -> CREAM -> BENTO **********************/ /// @notice Stake SUSHI `amount` into crSUSHI and BENTO for benefit of `to` by batching calls to `crSushiToken` and `bento`. function sushiToCreamToBento(address to, uint256 amount) external returns (uint256 amountOut, uint256 shareOut) { sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ICompoundBridge(crSushiToken).mint(amount); // stake deposited SUSHI into crSUSHI (amountOut, shareOut) = bento.deposit(IERC20(crSushiToken), address(this), to, IERC20(crSushiToken).safeBalanceOfSelf(), 0); // stake resulting crSUSHI into BENTO for `to` } /********************** BENTO -> CREAM -> SUSHI **********************/ /// @notice Unstake crSUSHI `cTokenAmount` into SUSHI from BENTO for benefit of `to` by batching calls to `bento` and `crSushiToken`. function sushiFromCreamFromBento(address to, uint256 cTokenAmount) external { bento.withdraw(IERC20(crSushiToken), msg.sender, address(this), cTokenAmount, 0); // withdraw `cTokenAmount` of `crSushiToken` from BENTO into this contract ICompoundBridge(crSushiToken).redeem(cTokenAmount); // burn deposited `crSushiToken` into SUSHI sushiToken.safeTransfer(to, sushiToken.safeBalanceOfSelf()); // transfer resulting SUSHI to `to` } /*********************** SUSHI -> XSUSHI -> CREAM ***********************/ /// @notice Stake SUSHI `amount` into crXSUSHI for benefit of `to` by batching calls to `sushiBar` and `crXSushiToken`. function stakeSushiToCream(address to, uint256 amount) external { // SCREAM sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI `amount` into `sushiBar` xSUSHI ICompoundBridge(crXSushiToken).mint(IERC20(sushiBar).safeBalanceOfSelf()); // stake resulting xSUSHI into crXSUSHI IERC20(crXSushiToken).safeTransfer(to, IERC20(crXSushiToken).safeBalanceOfSelf()); // transfer resulting crXSUSHI to `to` } /*********************** CREAM -> XSUSHI -> SUSHI ***********************/ /// @notice Unstake crXSUSHI `cTokenAmount` into SUSHI for benefit of `to` by batching calls to `crXSushiToken` and `sushiBar`. function unstakeSushiFromCream(address to, uint256 cTokenAmount) external { IERC20(crXSushiToken).safeTransferFrom(msg.sender, address(this), cTokenAmount); // deposit `msg.sender` `crXSushiToken` `cTokenAmount` into this contract ICompoundBridge(crXSushiToken).redeem(cTokenAmount); // burn deposited `crXSushiToken` `cTokenAmount` into xSUSHI ISushiBarBridge(sushiBar).leave(IERC20(sushiBar).safeBalanceOfSelf()); // burn resulting xSUSHI `amount` from `sushiBar` into SUSHI sushiToken.safeTransfer(to, sushiToken.safeBalanceOfSelf()); // transfer resulting SUSHI to `to` } /******************************** SUSHI -> XSUSHI -> CREAM -> BENTO ********************************/ /// @notice Stake SUSHI `amount` into crXSUSHI and BENTO for benefit of `to` by batching calls to `sushiBar`, `crXSushiToken` and `bento`. function stakeSushiToCreamToBento(address to, uint256 amount) external returns (uint256 amountOut, uint256 shareOut) { sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI `amount` into `sushiBar` xSUSHI ICompoundBridge(crXSushiToken).mint(IERC20(sushiBar).safeBalanceOfSelf()); // stake resulting xSUSHI into crXSUSHI (amountOut, shareOut) = bento.deposit(IERC20(crXSushiToken), address(this), to, IERC20(crXSushiToken).safeBalanceOfSelf(), 0); // stake resulting crXSUSHI into BENTO for `to` } /******************************** BENTO -> CREAM -> XSUSHI -> SUSHI ********************************/ /// @notice Unstake crXSUSHI `cTokenAmount` into SUSHI from BENTO for benefit of `to` by batching calls to `bento`, `crXSushiToken` and `sushiBar`. function unstakeSushiFromCreamFromBento(address to, uint256 cTokenAmount) external { bento.withdraw(IERC20(crXSushiToken), msg.sender, address(this), cTokenAmount, 0); // withdraw `cTokenAmount` of `crXSushiToken` from BENTO into this contract ICompoundBridge(crXSushiToken).redeem(cTokenAmount); // burn deposited `crXSushiToken` `cTokenAmount` into xSUSHI ISushiBarBridge(sushiBar).leave(IERC20(sushiBar).safeBalanceOfSelf()); // burn resulting xSUSHI from `sushiBar` into SUSHI sushiToken.safeTransfer(to, sushiToken.safeBalanceOfSelf()); // transfer resulting SUSHI to `to` } /* β–„β–„β–„β–„β–„ β–„ β–„ β–ˆβ–ˆ β–ˆ β–„β–„ β–ˆ β–€β–„ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–„ β–€β–€β–€β–€β–„ β–ˆ β–„ β–ˆ β–ˆβ–„β–„β–ˆ β–ˆβ–€β–€β–€ β–€β–„β–„β–„β–„β–€ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–ˆ β–€ β–€ β–ˆ β–€ β–€ */ /// @notice Fallback for received ETH - SushiSwap ETH to stake SUSHI into xSUSHI and BENTO for benefit of `to`. receive() external payable { // INARIZUSHI (uint256 reserve0, uint256 reserve1, ) = sushiSwapSushiETHPair.getReserves(); uint256 amountInWithFee = msg.value.mul(997); uint256 out = amountInWithFee.mul(reserve0) / reserve1.mul(1000).add(amountInWithFee); IWETH(wETH).deposit{value: msg.value}(); IERC20(wETH).safeTransfer(address(sushiSwapSushiETHPair), msg.value); sushiSwapSushiETHPair.swap(out, 0, address(this), ""); ISushiBarBridge(sushiBar).enter(sushiToken.safeBalanceOfSelf()); // stake resulting SUSHI into `sushiBar` xSUSHI bento.deposit(IERC20(sushiBar), address(this), msg.sender, IERC20(sushiBar).safeBalanceOfSelf(), 0); // stake resulting xSUSHI into BENTO for `to` } /// @notice SushiSwap ETH to stake SUSHI into xSUSHI and BENTO for benefit of `to`. function inariZushi(address to) external payable returns (uint256 amountOut, uint256 shareOut) { (uint256 reserve0, uint256 reserve1, ) = sushiSwapSushiETHPair.getReserves(); uint256 amountInWithFee = msg.value.mul(997); uint256 out = amountInWithFee.mul(reserve0) / reserve1.mul(1000).add(amountInWithFee); IWETH(wETH).deposit{value: msg.value}(); IERC20(wETH).safeTransfer(address(sushiSwapSushiETHPair), msg.value); sushiSwapSushiETHPair.swap(out, 0, address(this), ""); ISushiBarBridge(sushiBar).enter(sushiToken.safeBalanceOfSelf()); // stake resulting SUSHI into `sushiBar` xSUSHI (amountOut, shareOut) = bento.deposit(IERC20(sushiBar), address(this), to, IERC20(sushiBar).safeBalanceOfSelf(), 0); // stake resulting xSUSHI into BENTO for `to` } /// @notice Simple SushiSwap `fromToken` `amountIn` to `toToken` for benefit of `to`. function swap(address fromToken, address toToken, address to, uint256 amountIn) external returns (uint256 amountOut) { (address token0, address token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken); ISushiSwap pair = ISushiSwap( uint256( keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash)) ) ); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); uint256 amountInWithFee = amountIn.mul(997); IERC20(fromToken).safeTransferFrom(msg.sender, address(pair), amountIn); if (toToken > fromToken) { amountOut = amountInWithFee.mul(reserve1) / reserve0.mul(1000).add(amountInWithFee); pair.swap(0, amountOut, to, ""); } else { amountOut = amountInWithFee.mul(reserve0) / reserve1.mul(1000).add(amountInWithFee); pair.swap(amountOut, 0, to, ""); } } /// @notice Simple SushiSwap local `fromToken` balance in this contract to `toToken` for benefit of `to`. function swapBalance(address fromToken, address toToken, address to) external returns (uint256 amountOut) { (address token0, address token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken); ISushiSwap pair = ISushiSwap( uint256( keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash)) ) ); uint256 amountIn = IERC20(fromToken).safeBalanceOfSelf(); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); uint256 amountInWithFee = amountIn.mul(997); IERC20(fromToken).safeTransfer(address(pair), amountIn); if (toToken > fromToken) { amountOut = amountInWithFee.mul(reserve1) / reserve0.mul(1000).add(amountInWithFee); pair.swap(0, amountOut, to, ""); } else { amountOut = amountInWithFee.mul(reserve0) / reserve1.mul(1000).add(amountInWithFee); pair.swap(amountOut, 0, to, ""); } } }
/// @notice Contract that batches SUSHI staking and DeFi strategies - V1 'iroirona'.
NatSpecSingleLine
swapBalance
function swapBalance(address fromToken, address toToken, address to) external returns (uint256 amountOut) { (address token0, address token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken); ISushiSwap pair = ISushiSwap( uint256( keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash)) ) ); uint256 amountIn = IERC20(fromToken).safeBalanceOfSelf(); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); uint256 amountInWithFee = amountIn.mul(997); IERC20(fromToken).safeTransfer(address(pair), amountIn); if (toToken > fromToken) { amountOut = amountInWithFee.mul(reserve1) / reserve0.mul(1000).add(amountInWithFee); pair.swap(0, amountOut, to, ""); } else { amountOut = amountInWithFee.mul(reserve0) / reserve1.mul(1000).add(amountInWithFee); pair.swap(amountOut, 0, to, ""); } }
/// @notice Simple SushiSwap local `fromToken` balance in this contract to `toToken` for benefit of `to`.
NatSpecSingleLine
v0.7.6+commit.7338295f
GNU GPLv2
ipfs://89a5125d850fb87a89b52e2cb580c7d062e507e61b962188e0983cbea998b8cd
{ "func_code_index": [ 26281, 27437 ] }
11,803
IdolMintContract
contracts/IdolMintContract.sol
0x7b4b02372d8e54c1c0454d97f01d85ef203cdc5e
Solidity
IdolMintContract
contract IdolMintContract is Ownable, ReentrancyGuard { // publicGodsMinted tracks the number of Gods that have been minted by the public through the // mintGods function. uint public publicGodsMinted; // reservedGodsMinted tracks the number of reserved Gods that have been minted through the // mintReservedGods function. uint public reservedGodsMinted; // MAX_GODS_TO_MINT specifies the maximum number of Gods that can be minted (both public and // reserved.) uint public constant MAX_GODS_TO_MINT = 10000; // MAX_GODS_PER_ADDRESS specifies the maximum number of Gods that a single address can mint. uint public constant MAX_GODS_PER_ADDRESS = 20; // NUM_RESERVED_NFTS specifies the maximum number of Gods that can be minted through the // mintReservedGods function. uint public constant NUM_RESERVED_NFTS = 1000; // publicSaleDuration specifies the length of the dutch auction (in seconds) before the minting // price hits publicSaleGodEndingPrice. uint256 public publicSaleDuration; // publicSaleStartTime tracks the time (as a UNIX timestamp) when the public sale was started. uint256 public publicSaleStartTime; // publicSaleGodStartingPrice specifies the price that the dutch auction mint should start at. uint256 public publicSaleGodStartingPrice; // publicSaleGodEndingPrice specifies the minimum price that Gods can be minted at once the // full duration of the dutch auction has elapsed. uint256 public publicSaleGodEndingPrice; // publicSaleStarted specifies whether the minting event has been started. bool public publicSaleStarted = false; // publicSalePaused specifies whether the minting event has been paused. bool public publicSalePaused = false; // publicSalePausedElapsedTime specifies, if the sale was paused, what the elapsed sale // time was at the time of pausing. uint256 public publicSalePausedElapsedTime; // godIdOffset is pseudo-random offset from 0-10000 generated when the contract is constructed // and used to assign god IDs for each mint. uint256 public immutable godIdOffset; // addressReferencesSet is a boolean flag which tracks that the proper setup functions for the // contract have been run. It must be true before startPublicSale is called. bool public addressReferencesSet = false; // CURVE_POOL_ADDRESS holds the address of the curve pool that we use to exchange ETH for stETH. address constant CURVE_POOL_ADDRESS = 0xDC24316b9AE028F1497c275EB9192a3Ea0f67022; // LIDO_STAKING_ADDRESS holds the address of the Lido staking contract that we also can use to // exchange ETH for stETH. address constant LIDO_STAKING_ADDRESS = 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84; IIdolMain public idolMain; IIdolMarketplace public idolMarketplace; ICurvePool public immutable stethPool; ERC20 public immutable steth; OfferingRefundContract public immutable offeringRefundContract; event PublicSaleStart( uint256 indexed _saleDuration, uint256 indexed _saleStartTime ); event PublicSalePaused( uint256 indexed _currentPrice, uint256 indexed _timeElapsed ); event PublicSaleResumed( uint256 indexed _saleResumeTime ); event IdolsMinted( address indexed _minter, uint256 indexed _mintPrice, uint256 indexed _numMinted ); /** @notice IdolMintContract's constructor takes in two hashes, one of which represents the hash of the Idol NFT metadata, and one of which is the hash of some discord-community-generated input. The two hashes are used to calculate the godIdOffset, which specifies which ID from 0-10000 to start minting at. @param _metadataHash The hash of the master metadata file which corresponds to the 10k Idol NFT images that have been uploaded. @param _discordGeneratedHash The hash of some discord-community-generated input which is used to effectively randomize the value of godIdOffset prior to the start of the mint. @param _stethAddress The address of the stETH ERC20 contract. @param _offeringRefundContractAddress The address of the OfferingRefundContract we will be sending refunds to. */ constructor( string memory _metadataHash, string memory _discordGeneratedHash, address _stethAddress, address payable _offeringRefundContractAddress ) { godIdOffset = uint256(keccak256(abi.encodePacked(_metadataHash, _discordGeneratedHash))) % MAX_GODS_TO_MINT; stethPool = ICurvePool(CURVE_POOL_ADDRESS); steth = ERC20(_stethAddress); offeringRefundContract = OfferingRefundContract(_offeringRefundContractAddress); } /** @notice startPublicSale is called to start the dutch auction for minting Gods to the public. @param _saleDuration The duration of the sale, in seconds, before reaching the minimum minting price. @param _saleStartPrice The initial minting price, which progressively lowers as the dutch auction progresses. @param _saleEndPrice Lower bound for the minting price, once the full duration of the dutch auction has elapsed. */ function startPublicSale(uint256 _saleDuration, uint256 _saleStartPrice, uint256 _saleEndPrice) external onlyOwner beforePublicSaleStarted { require(_saleStartPrice > _saleEndPrice, "_saleStartPrice must be greater than _saleEndPrice"); require(addressReferencesSet, "External reference contracts must all be set before public sale starts"); publicSaleDuration = _saleDuration; publicSaleGodStartingPrice = _saleStartPrice; publicSaleGodEndingPrice = _saleEndPrice; publicSaleStartTime = block.timestamp; publicSaleStarted = true; emit PublicSaleStart(_saleDuration, publicSaleStartTime); } /** @notice setAddressReferences sets references to the main, marketplace, and virtueToken addresses so that the contracts all know about each other. This is all done from the mint contract so that the addresses will no longer be updateable once the mint event has started. @param _idolMainAddress The address of IdolMain. @param _idolMarketplaceAddress The address of the marketplace. @param _virtueTokenAddress The address of the VIRTUE token ERC20 contract. */ function setAddressReferences( address _idolMainAddress, address _idolMarketplaceAddress, address _virtueTokenAddress ) external onlyOwner beforePublicSaleStarted { addressReferencesSet = true; idolMain = IIdolMain(_idolMainAddress); require(steth.approve(_idolMainAddress, 2**255-1)); idolMarketplace = IIdolMarketplace(_idolMarketplaceAddress); idolMain.setVirtueTokenAddr(_virtueTokenAddress); idolMain.setIdolMarketplaceAddr(_idolMarketplaceAddress); idolMarketplace.setVirtueTokenAddr(_virtueTokenAddress); } /** @notice pausePublicSale is called to pause the progression of the mint event. In happy-path circumstances we shouldn't need to call this, but it is included as a precaution in case something goes wrong during the mint. */ function pausePublicSale() external onlyOwner whenPublicSaleActive { uint256 currentSalePrice = getMintPrice(); uint256 elapsedTime = getElapsedSaleTime(); publicSalePausedElapsedTime = elapsedTime; publicSalePaused = true; emit PublicSalePaused(currentSalePrice, elapsedTime); } function resumePublicSale() external onlyOwner { require(publicSalePaused, "Can only resume when the sale is paused"); publicSalePaused = false; publicSaleStartTime = block.timestamp - publicSalePausedElapsedTime; emit PublicSaleResumed(block.timestamp); } /** @notice getElaspedSaleTime is a view function that tells us how many seconds have elapsed since the public sale was started. */ function getElapsedSaleTime() internal view returns (uint256) { if (publicSalePaused) { return publicSalePausedElapsedTime; } return publicSaleStartTime > 0 ? block.timestamp - publicSaleStartTime : 0; } /** @notice getRemainingSaleTime is a view function that tells us how many seconds are remaining before the dutch auction hits the minimum price. */ function getRemainingSaleTime() external view returns (uint256) { if (publicSaleStartTime == 0) { // If the public sale has not been started, we just return 1 week as a placeholder. return 604800; } if (publicSalePaused) { return publicSaleDuration - publicSalePausedElapsedTime; } if (getElapsedSaleTime() >= publicSaleDuration) { return 0; } return (publicSaleStartTime + publicSaleDuration) - block.timestamp; } /** @notice getMintPrice returns the price to mint a God at the current time in the dutch auction. */ function getMintPrice() public view returns (uint256) { if (!publicSaleStarted) { return 0; } uint256 elapsed = getElapsedSaleTime(); if (elapsed >= publicSaleDuration) { return publicSaleGodEndingPrice; } else { int256 tempPrice = int256(publicSaleGodStartingPrice) + ((int256(publicSaleGodEndingPrice) - int256(publicSaleGodStartingPrice)) / int256(publicSaleDuration)) * int256(elapsed); uint256 currentPrice = uint256(tempPrice); return currentPrice > publicSaleGodEndingPrice ? currentPrice : publicSaleGodEndingPrice; } } /** @notice mintGods is a payable function which allows the sender to pay ETH to mint God NFTs at the current price specified by getMintPrice. @param _numGodsToMint The number of gods to be minted, which is capped at a maximum of 5 Gods per transaction. */ function mintGods(uint256 _numGodsToMint) external payable whenPublicSaleActive nonReentrant { require( publicGodsMinted + _numGodsToMint <= MAX_GODS_TO_MINT - NUM_RESERVED_NFTS, "Minting would exceed max supply" ); require(_numGodsToMint > 0, "Must mint at least one god"); require( idolMain.balanceOf(msg.sender) + _numGodsToMint <= MAX_GODS_PER_ADDRESS, "Requested number would exceed the maximum number of gods allowed to be minted for this address." ); uint256 individualCostToMint = getMintPrice(); uint256 costToMint = individualCostToMint * _numGodsToMint; require(costToMint <= msg.value, "Ether value sent is not correct"); for (uint256 i = 0; i < _numGodsToMint; i++) { uint idToMint = (publicGodsMinted + i + godIdOffset) % MAX_GODS_TO_MINT; idolMain.mint(msg.sender, idToMint, false); } publicGodsMinted += _numGodsToMint; if (msg.value > costToMint) { Address.sendValue(payable(msg.sender), msg.value - costToMint); } emit IdolsMinted(msg.sender, individualCostToMint, _numGodsToMint); } /** @notice mintReservedGods is used by the contract owner to mint a reserved pool of 1000 Gods for owners and supporters of the protocol. @param _numGodsToMint The number of Gods to mint in this transaction. @param _mintAddress The address to mint the reserved Gods for. @param _lock If true, specifies that the minted reserved Gods cannot be sold or transferred for the first year of the protocol's existence. */ function mintReservedGods(uint256 _numGodsToMint, address _mintAddress, bool _lock) external onlyOwner nonReentrant { require( reservedGodsMinted + _numGodsToMint < NUM_RESERVED_NFTS, "Minting would exceed max reserved supply" ); require(_numGodsToMint > 0, "Must mint at least one god"); for (uint256 i = 0; i < _numGodsToMint; i++) { uint idToMint = (reservedGodsMinted + i + godIdOffset + MAX_GODS_TO_MINT - NUM_RESERVED_NFTS) % MAX_GODS_TO_MINT; idolMain.mint(_mintAddress, idToMint, _lock); } reservedGodsMinted += _numGodsToMint; } /** @notice sendToOfferingRefundContract sends ETH to the OfferingRefundContract so that it can be distributed to the addresses that are eligible for a refund. */ function sendToOfferingRefundContract(uint _totalRefundAmount) onlyOwner external nonReentrant { Address.sendValue(payable(address(offeringRefundContract)), _totalRefundAmount); } /** @notice swap is used to swap the contract's ETH into stETH via Curve. @param _slippageBps The acceptable slippage percent, in basis points. */ function swap(uint _slippageBps) onlyOwner external returns(uint result) { return stethPool.exchange{ value: address(this).balance }(0, 1, address(this).balance, address(this).balance * _slippageBps / 10000); } function swapLido(uint _slippageBps) onlyOwner external { uint minSteth = steth.balanceOf(address(this)) + address(this).balance * _slippageBps / 10000; Address.sendValue(payable(LIDO_STAKING_ADDRESS), address(this).balance); require(steth.balanceOf(address(this)) >= minSteth, "steth balance not high enough after sending to LIDO_STAKING_ADDRESS"); } /** @notice depositStethIdolMain deposits all of this contract's stETH into the IdolMain contract. */ function depositStethIdolMain() onlyOwner external { idolMain.depositSteth(steth.balanceOf(address(this))); } /** @notice getTotalMinted returns the total number of public + reserved God NFTs minted. */ function getTotalMinted() external view returns (uint) { return reservedGodsMinted + publicGodsMinted; } /** @notice setBaseURI sets the baseURI for the God NFTs. */ function setBaseURI(string memory uri) external onlyOwner { idolMain.setBaseURI(uri); } /** @notice Tears down the contract and allocates any remaining funds to the original contract owner. Should only be called after the mint completes and the contract's balance has been converted to Steth and deposited into IdolMain, or in a disaster scenario where we need to tear down the contract and refund minting fees. */ function tearDown() external onlyOwner { selfdestruct(payable(owner())); } modifier beforePublicSaleStarted { require(!publicSaleStarted, "Public sale has already started"); _; } modifier whenPublicSaleActive { require(publicSaleStarted && !publicSalePaused, "Public sale is not active"); _; } }
/** @notice IdolMintContract is a contract used for the initial mint of the God NFTs. It allocates 90% of the Gods for public minting through a dutch auction protocol, and reserves 10% of the Gods for the creators of the protocol as well as other supporters and stakeholders. IdolMintContract is intended to be torn down once the mint event has completed and once its balance has been deposited into the IdolMain rewards protocol. */
NatSpecMultiLine
startPublicSale
function startPublicSale(uint256 _saleDuration, uint256 _saleStartPrice, uint256 _saleEndPrice) external onlyOwner beforePublicSaleStarted { require(_saleStartPrice > _saleEndPrice, "_saleStartPrice must be greater than _saleEndPrice"); require(addressReferencesSet, "External reference contracts must all be set before public sale starts"); publicSaleDuration = _saleDuration; publicSaleGodStartingPrice = _saleStartPrice; publicSaleGodEndingPrice = _saleEndPrice; publicSaleStartTime = block.timestamp; publicSaleStarted = true; emit PublicSaleStart(_saleDuration, publicSaleStartTime); }
/** @notice startPublicSale is called to start the dutch auction for minting Gods to the public. @param _saleDuration The duration of the sale, in seconds, before reaching the minimum minting price. @param _saleStartPrice The initial minting price, which progressively lowers as the dutch auction progresses. @param _saleEndPrice Lower bound for the minting price, once the full duration of the dutch auction has elapsed. */
NatSpecMultiLine
v0.8.9+commit.e5eed63a
{ "func_code_index": [ 5081, 5721 ] }
11,804
IdolMintContract
contracts/IdolMintContract.sol
0x7b4b02372d8e54c1c0454d97f01d85ef203cdc5e
Solidity
IdolMintContract
contract IdolMintContract is Ownable, ReentrancyGuard { // publicGodsMinted tracks the number of Gods that have been minted by the public through the // mintGods function. uint public publicGodsMinted; // reservedGodsMinted tracks the number of reserved Gods that have been minted through the // mintReservedGods function. uint public reservedGodsMinted; // MAX_GODS_TO_MINT specifies the maximum number of Gods that can be minted (both public and // reserved.) uint public constant MAX_GODS_TO_MINT = 10000; // MAX_GODS_PER_ADDRESS specifies the maximum number of Gods that a single address can mint. uint public constant MAX_GODS_PER_ADDRESS = 20; // NUM_RESERVED_NFTS specifies the maximum number of Gods that can be minted through the // mintReservedGods function. uint public constant NUM_RESERVED_NFTS = 1000; // publicSaleDuration specifies the length of the dutch auction (in seconds) before the minting // price hits publicSaleGodEndingPrice. uint256 public publicSaleDuration; // publicSaleStartTime tracks the time (as a UNIX timestamp) when the public sale was started. uint256 public publicSaleStartTime; // publicSaleGodStartingPrice specifies the price that the dutch auction mint should start at. uint256 public publicSaleGodStartingPrice; // publicSaleGodEndingPrice specifies the minimum price that Gods can be minted at once the // full duration of the dutch auction has elapsed. uint256 public publicSaleGodEndingPrice; // publicSaleStarted specifies whether the minting event has been started. bool public publicSaleStarted = false; // publicSalePaused specifies whether the minting event has been paused. bool public publicSalePaused = false; // publicSalePausedElapsedTime specifies, if the sale was paused, what the elapsed sale // time was at the time of pausing. uint256 public publicSalePausedElapsedTime; // godIdOffset is pseudo-random offset from 0-10000 generated when the contract is constructed // and used to assign god IDs for each mint. uint256 public immutable godIdOffset; // addressReferencesSet is a boolean flag which tracks that the proper setup functions for the // contract have been run. It must be true before startPublicSale is called. bool public addressReferencesSet = false; // CURVE_POOL_ADDRESS holds the address of the curve pool that we use to exchange ETH for stETH. address constant CURVE_POOL_ADDRESS = 0xDC24316b9AE028F1497c275EB9192a3Ea0f67022; // LIDO_STAKING_ADDRESS holds the address of the Lido staking contract that we also can use to // exchange ETH for stETH. address constant LIDO_STAKING_ADDRESS = 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84; IIdolMain public idolMain; IIdolMarketplace public idolMarketplace; ICurvePool public immutable stethPool; ERC20 public immutable steth; OfferingRefundContract public immutable offeringRefundContract; event PublicSaleStart( uint256 indexed _saleDuration, uint256 indexed _saleStartTime ); event PublicSalePaused( uint256 indexed _currentPrice, uint256 indexed _timeElapsed ); event PublicSaleResumed( uint256 indexed _saleResumeTime ); event IdolsMinted( address indexed _minter, uint256 indexed _mintPrice, uint256 indexed _numMinted ); /** @notice IdolMintContract's constructor takes in two hashes, one of which represents the hash of the Idol NFT metadata, and one of which is the hash of some discord-community-generated input. The two hashes are used to calculate the godIdOffset, which specifies which ID from 0-10000 to start minting at. @param _metadataHash The hash of the master metadata file which corresponds to the 10k Idol NFT images that have been uploaded. @param _discordGeneratedHash The hash of some discord-community-generated input which is used to effectively randomize the value of godIdOffset prior to the start of the mint. @param _stethAddress The address of the stETH ERC20 contract. @param _offeringRefundContractAddress The address of the OfferingRefundContract we will be sending refunds to. */ constructor( string memory _metadataHash, string memory _discordGeneratedHash, address _stethAddress, address payable _offeringRefundContractAddress ) { godIdOffset = uint256(keccak256(abi.encodePacked(_metadataHash, _discordGeneratedHash))) % MAX_GODS_TO_MINT; stethPool = ICurvePool(CURVE_POOL_ADDRESS); steth = ERC20(_stethAddress); offeringRefundContract = OfferingRefundContract(_offeringRefundContractAddress); } /** @notice startPublicSale is called to start the dutch auction for minting Gods to the public. @param _saleDuration The duration of the sale, in seconds, before reaching the minimum minting price. @param _saleStartPrice The initial minting price, which progressively lowers as the dutch auction progresses. @param _saleEndPrice Lower bound for the minting price, once the full duration of the dutch auction has elapsed. */ function startPublicSale(uint256 _saleDuration, uint256 _saleStartPrice, uint256 _saleEndPrice) external onlyOwner beforePublicSaleStarted { require(_saleStartPrice > _saleEndPrice, "_saleStartPrice must be greater than _saleEndPrice"); require(addressReferencesSet, "External reference contracts must all be set before public sale starts"); publicSaleDuration = _saleDuration; publicSaleGodStartingPrice = _saleStartPrice; publicSaleGodEndingPrice = _saleEndPrice; publicSaleStartTime = block.timestamp; publicSaleStarted = true; emit PublicSaleStart(_saleDuration, publicSaleStartTime); } /** @notice setAddressReferences sets references to the main, marketplace, and virtueToken addresses so that the contracts all know about each other. This is all done from the mint contract so that the addresses will no longer be updateable once the mint event has started. @param _idolMainAddress The address of IdolMain. @param _idolMarketplaceAddress The address of the marketplace. @param _virtueTokenAddress The address of the VIRTUE token ERC20 contract. */ function setAddressReferences( address _idolMainAddress, address _idolMarketplaceAddress, address _virtueTokenAddress ) external onlyOwner beforePublicSaleStarted { addressReferencesSet = true; idolMain = IIdolMain(_idolMainAddress); require(steth.approve(_idolMainAddress, 2**255-1)); idolMarketplace = IIdolMarketplace(_idolMarketplaceAddress); idolMain.setVirtueTokenAddr(_virtueTokenAddress); idolMain.setIdolMarketplaceAddr(_idolMarketplaceAddress); idolMarketplace.setVirtueTokenAddr(_virtueTokenAddress); } /** @notice pausePublicSale is called to pause the progression of the mint event. In happy-path circumstances we shouldn't need to call this, but it is included as a precaution in case something goes wrong during the mint. */ function pausePublicSale() external onlyOwner whenPublicSaleActive { uint256 currentSalePrice = getMintPrice(); uint256 elapsedTime = getElapsedSaleTime(); publicSalePausedElapsedTime = elapsedTime; publicSalePaused = true; emit PublicSalePaused(currentSalePrice, elapsedTime); } function resumePublicSale() external onlyOwner { require(publicSalePaused, "Can only resume when the sale is paused"); publicSalePaused = false; publicSaleStartTime = block.timestamp - publicSalePausedElapsedTime; emit PublicSaleResumed(block.timestamp); } /** @notice getElaspedSaleTime is a view function that tells us how many seconds have elapsed since the public sale was started. */ function getElapsedSaleTime() internal view returns (uint256) { if (publicSalePaused) { return publicSalePausedElapsedTime; } return publicSaleStartTime > 0 ? block.timestamp - publicSaleStartTime : 0; } /** @notice getRemainingSaleTime is a view function that tells us how many seconds are remaining before the dutch auction hits the minimum price. */ function getRemainingSaleTime() external view returns (uint256) { if (publicSaleStartTime == 0) { // If the public sale has not been started, we just return 1 week as a placeholder. return 604800; } if (publicSalePaused) { return publicSaleDuration - publicSalePausedElapsedTime; } if (getElapsedSaleTime() >= publicSaleDuration) { return 0; } return (publicSaleStartTime + publicSaleDuration) - block.timestamp; } /** @notice getMintPrice returns the price to mint a God at the current time in the dutch auction. */ function getMintPrice() public view returns (uint256) { if (!publicSaleStarted) { return 0; } uint256 elapsed = getElapsedSaleTime(); if (elapsed >= publicSaleDuration) { return publicSaleGodEndingPrice; } else { int256 tempPrice = int256(publicSaleGodStartingPrice) + ((int256(publicSaleGodEndingPrice) - int256(publicSaleGodStartingPrice)) / int256(publicSaleDuration)) * int256(elapsed); uint256 currentPrice = uint256(tempPrice); return currentPrice > publicSaleGodEndingPrice ? currentPrice : publicSaleGodEndingPrice; } } /** @notice mintGods is a payable function which allows the sender to pay ETH to mint God NFTs at the current price specified by getMintPrice. @param _numGodsToMint The number of gods to be minted, which is capped at a maximum of 5 Gods per transaction. */ function mintGods(uint256 _numGodsToMint) external payable whenPublicSaleActive nonReentrant { require( publicGodsMinted + _numGodsToMint <= MAX_GODS_TO_MINT - NUM_RESERVED_NFTS, "Minting would exceed max supply" ); require(_numGodsToMint > 0, "Must mint at least one god"); require( idolMain.balanceOf(msg.sender) + _numGodsToMint <= MAX_GODS_PER_ADDRESS, "Requested number would exceed the maximum number of gods allowed to be minted for this address." ); uint256 individualCostToMint = getMintPrice(); uint256 costToMint = individualCostToMint * _numGodsToMint; require(costToMint <= msg.value, "Ether value sent is not correct"); for (uint256 i = 0; i < _numGodsToMint; i++) { uint idToMint = (publicGodsMinted + i + godIdOffset) % MAX_GODS_TO_MINT; idolMain.mint(msg.sender, idToMint, false); } publicGodsMinted += _numGodsToMint; if (msg.value > costToMint) { Address.sendValue(payable(msg.sender), msg.value - costToMint); } emit IdolsMinted(msg.sender, individualCostToMint, _numGodsToMint); } /** @notice mintReservedGods is used by the contract owner to mint a reserved pool of 1000 Gods for owners and supporters of the protocol. @param _numGodsToMint The number of Gods to mint in this transaction. @param _mintAddress The address to mint the reserved Gods for. @param _lock If true, specifies that the minted reserved Gods cannot be sold or transferred for the first year of the protocol's existence. */ function mintReservedGods(uint256 _numGodsToMint, address _mintAddress, bool _lock) external onlyOwner nonReentrant { require( reservedGodsMinted + _numGodsToMint < NUM_RESERVED_NFTS, "Minting would exceed max reserved supply" ); require(_numGodsToMint > 0, "Must mint at least one god"); for (uint256 i = 0; i < _numGodsToMint; i++) { uint idToMint = (reservedGodsMinted + i + godIdOffset + MAX_GODS_TO_MINT - NUM_RESERVED_NFTS) % MAX_GODS_TO_MINT; idolMain.mint(_mintAddress, idToMint, _lock); } reservedGodsMinted += _numGodsToMint; } /** @notice sendToOfferingRefundContract sends ETH to the OfferingRefundContract so that it can be distributed to the addresses that are eligible for a refund. */ function sendToOfferingRefundContract(uint _totalRefundAmount) onlyOwner external nonReentrant { Address.sendValue(payable(address(offeringRefundContract)), _totalRefundAmount); } /** @notice swap is used to swap the contract's ETH into stETH via Curve. @param _slippageBps The acceptable slippage percent, in basis points. */ function swap(uint _slippageBps) onlyOwner external returns(uint result) { return stethPool.exchange{ value: address(this).balance }(0, 1, address(this).balance, address(this).balance * _slippageBps / 10000); } function swapLido(uint _slippageBps) onlyOwner external { uint minSteth = steth.balanceOf(address(this)) + address(this).balance * _slippageBps / 10000; Address.sendValue(payable(LIDO_STAKING_ADDRESS), address(this).balance); require(steth.balanceOf(address(this)) >= minSteth, "steth balance not high enough after sending to LIDO_STAKING_ADDRESS"); } /** @notice depositStethIdolMain deposits all of this contract's stETH into the IdolMain contract. */ function depositStethIdolMain() onlyOwner external { idolMain.depositSteth(steth.balanceOf(address(this))); } /** @notice getTotalMinted returns the total number of public + reserved God NFTs minted. */ function getTotalMinted() external view returns (uint) { return reservedGodsMinted + publicGodsMinted; } /** @notice setBaseURI sets the baseURI for the God NFTs. */ function setBaseURI(string memory uri) external onlyOwner { idolMain.setBaseURI(uri); } /** @notice Tears down the contract and allocates any remaining funds to the original contract owner. Should only be called after the mint completes and the contract's balance has been converted to Steth and deposited into IdolMain, or in a disaster scenario where we need to tear down the contract and refund minting fees. */ function tearDown() external onlyOwner { selfdestruct(payable(owner())); } modifier beforePublicSaleStarted { require(!publicSaleStarted, "Public sale has already started"); _; } modifier whenPublicSaleActive { require(publicSaleStarted && !publicSalePaused, "Public sale is not active"); _; } }
/** @notice IdolMintContract is a contract used for the initial mint of the God NFTs. It allocates 90% of the Gods for public minting through a dutch auction protocol, and reserves 10% of the Gods for the creators of the protocol as well as other supporters and stakeholders. IdolMintContract is intended to be torn down once the mint event has completed and once its balance has been deposited into the IdolMain rewards protocol. */
NatSpecMultiLine
setAddressReferences
function setAddressReferences( address _idolMainAddress, address _idolMarketplaceAddress, address _virtueTokenAddress ) external onlyOwner beforePublicSaleStarted { addressReferencesSet = true; idolMain = IIdolMain(_idolMainAddress); require(steth.approve(_idolMainAddress, 2**255-1)); idolMarketplace = IIdolMarketplace(_idolMarketplaceAddress); idolMain.setVirtueTokenAddr(_virtueTokenAddress); idolMain.setIdolMarketplaceAddr(_idolMarketplaceAddress); idolMarketplace.setVirtueTokenAddr(_virtueTokenAddress); }
/** @notice setAddressReferences sets references to the main, marketplace, and virtueToken addresses so that the contracts all know about each other. This is all done from the mint contract so that the addresses will no longer be updateable once the mint event has started. @param _idolMainAddress The address of IdolMain. @param _idolMarketplaceAddress The address of the marketplace. @param _virtueTokenAddress The address of the VIRTUE token ERC20 contract. */
NatSpecMultiLine
v0.8.9+commit.e5eed63a
{ "func_code_index": [ 6220, 6796 ] }
11,805
IdolMintContract
contracts/IdolMintContract.sol
0x7b4b02372d8e54c1c0454d97f01d85ef203cdc5e
Solidity
IdolMintContract
contract IdolMintContract is Ownable, ReentrancyGuard { // publicGodsMinted tracks the number of Gods that have been minted by the public through the // mintGods function. uint public publicGodsMinted; // reservedGodsMinted tracks the number of reserved Gods that have been minted through the // mintReservedGods function. uint public reservedGodsMinted; // MAX_GODS_TO_MINT specifies the maximum number of Gods that can be minted (both public and // reserved.) uint public constant MAX_GODS_TO_MINT = 10000; // MAX_GODS_PER_ADDRESS specifies the maximum number of Gods that a single address can mint. uint public constant MAX_GODS_PER_ADDRESS = 20; // NUM_RESERVED_NFTS specifies the maximum number of Gods that can be minted through the // mintReservedGods function. uint public constant NUM_RESERVED_NFTS = 1000; // publicSaleDuration specifies the length of the dutch auction (in seconds) before the minting // price hits publicSaleGodEndingPrice. uint256 public publicSaleDuration; // publicSaleStartTime tracks the time (as a UNIX timestamp) when the public sale was started. uint256 public publicSaleStartTime; // publicSaleGodStartingPrice specifies the price that the dutch auction mint should start at. uint256 public publicSaleGodStartingPrice; // publicSaleGodEndingPrice specifies the minimum price that Gods can be minted at once the // full duration of the dutch auction has elapsed. uint256 public publicSaleGodEndingPrice; // publicSaleStarted specifies whether the minting event has been started. bool public publicSaleStarted = false; // publicSalePaused specifies whether the minting event has been paused. bool public publicSalePaused = false; // publicSalePausedElapsedTime specifies, if the sale was paused, what the elapsed sale // time was at the time of pausing. uint256 public publicSalePausedElapsedTime; // godIdOffset is pseudo-random offset from 0-10000 generated when the contract is constructed // and used to assign god IDs for each mint. uint256 public immutable godIdOffset; // addressReferencesSet is a boolean flag which tracks that the proper setup functions for the // contract have been run. It must be true before startPublicSale is called. bool public addressReferencesSet = false; // CURVE_POOL_ADDRESS holds the address of the curve pool that we use to exchange ETH for stETH. address constant CURVE_POOL_ADDRESS = 0xDC24316b9AE028F1497c275EB9192a3Ea0f67022; // LIDO_STAKING_ADDRESS holds the address of the Lido staking contract that we also can use to // exchange ETH for stETH. address constant LIDO_STAKING_ADDRESS = 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84; IIdolMain public idolMain; IIdolMarketplace public idolMarketplace; ICurvePool public immutable stethPool; ERC20 public immutable steth; OfferingRefundContract public immutable offeringRefundContract; event PublicSaleStart( uint256 indexed _saleDuration, uint256 indexed _saleStartTime ); event PublicSalePaused( uint256 indexed _currentPrice, uint256 indexed _timeElapsed ); event PublicSaleResumed( uint256 indexed _saleResumeTime ); event IdolsMinted( address indexed _minter, uint256 indexed _mintPrice, uint256 indexed _numMinted ); /** @notice IdolMintContract's constructor takes in two hashes, one of which represents the hash of the Idol NFT metadata, and one of which is the hash of some discord-community-generated input. The two hashes are used to calculate the godIdOffset, which specifies which ID from 0-10000 to start minting at. @param _metadataHash The hash of the master metadata file which corresponds to the 10k Idol NFT images that have been uploaded. @param _discordGeneratedHash The hash of some discord-community-generated input which is used to effectively randomize the value of godIdOffset prior to the start of the mint. @param _stethAddress The address of the stETH ERC20 contract. @param _offeringRefundContractAddress The address of the OfferingRefundContract we will be sending refunds to. */ constructor( string memory _metadataHash, string memory _discordGeneratedHash, address _stethAddress, address payable _offeringRefundContractAddress ) { godIdOffset = uint256(keccak256(abi.encodePacked(_metadataHash, _discordGeneratedHash))) % MAX_GODS_TO_MINT; stethPool = ICurvePool(CURVE_POOL_ADDRESS); steth = ERC20(_stethAddress); offeringRefundContract = OfferingRefundContract(_offeringRefundContractAddress); } /** @notice startPublicSale is called to start the dutch auction for minting Gods to the public. @param _saleDuration The duration of the sale, in seconds, before reaching the minimum minting price. @param _saleStartPrice The initial minting price, which progressively lowers as the dutch auction progresses. @param _saleEndPrice Lower bound for the minting price, once the full duration of the dutch auction has elapsed. */ function startPublicSale(uint256 _saleDuration, uint256 _saleStartPrice, uint256 _saleEndPrice) external onlyOwner beforePublicSaleStarted { require(_saleStartPrice > _saleEndPrice, "_saleStartPrice must be greater than _saleEndPrice"); require(addressReferencesSet, "External reference contracts must all be set before public sale starts"); publicSaleDuration = _saleDuration; publicSaleGodStartingPrice = _saleStartPrice; publicSaleGodEndingPrice = _saleEndPrice; publicSaleStartTime = block.timestamp; publicSaleStarted = true; emit PublicSaleStart(_saleDuration, publicSaleStartTime); } /** @notice setAddressReferences sets references to the main, marketplace, and virtueToken addresses so that the contracts all know about each other. This is all done from the mint contract so that the addresses will no longer be updateable once the mint event has started. @param _idolMainAddress The address of IdolMain. @param _idolMarketplaceAddress The address of the marketplace. @param _virtueTokenAddress The address of the VIRTUE token ERC20 contract. */ function setAddressReferences( address _idolMainAddress, address _idolMarketplaceAddress, address _virtueTokenAddress ) external onlyOwner beforePublicSaleStarted { addressReferencesSet = true; idolMain = IIdolMain(_idolMainAddress); require(steth.approve(_idolMainAddress, 2**255-1)); idolMarketplace = IIdolMarketplace(_idolMarketplaceAddress); idolMain.setVirtueTokenAddr(_virtueTokenAddress); idolMain.setIdolMarketplaceAddr(_idolMarketplaceAddress); idolMarketplace.setVirtueTokenAddr(_virtueTokenAddress); } /** @notice pausePublicSale is called to pause the progression of the mint event. In happy-path circumstances we shouldn't need to call this, but it is included as a precaution in case something goes wrong during the mint. */ function pausePublicSale() external onlyOwner whenPublicSaleActive { uint256 currentSalePrice = getMintPrice(); uint256 elapsedTime = getElapsedSaleTime(); publicSalePausedElapsedTime = elapsedTime; publicSalePaused = true; emit PublicSalePaused(currentSalePrice, elapsedTime); } function resumePublicSale() external onlyOwner { require(publicSalePaused, "Can only resume when the sale is paused"); publicSalePaused = false; publicSaleStartTime = block.timestamp - publicSalePausedElapsedTime; emit PublicSaleResumed(block.timestamp); } /** @notice getElaspedSaleTime is a view function that tells us how many seconds have elapsed since the public sale was started. */ function getElapsedSaleTime() internal view returns (uint256) { if (publicSalePaused) { return publicSalePausedElapsedTime; } return publicSaleStartTime > 0 ? block.timestamp - publicSaleStartTime : 0; } /** @notice getRemainingSaleTime is a view function that tells us how many seconds are remaining before the dutch auction hits the minimum price. */ function getRemainingSaleTime() external view returns (uint256) { if (publicSaleStartTime == 0) { // If the public sale has not been started, we just return 1 week as a placeholder. return 604800; } if (publicSalePaused) { return publicSaleDuration - publicSalePausedElapsedTime; } if (getElapsedSaleTime() >= publicSaleDuration) { return 0; } return (publicSaleStartTime + publicSaleDuration) - block.timestamp; } /** @notice getMintPrice returns the price to mint a God at the current time in the dutch auction. */ function getMintPrice() public view returns (uint256) { if (!publicSaleStarted) { return 0; } uint256 elapsed = getElapsedSaleTime(); if (elapsed >= publicSaleDuration) { return publicSaleGodEndingPrice; } else { int256 tempPrice = int256(publicSaleGodStartingPrice) + ((int256(publicSaleGodEndingPrice) - int256(publicSaleGodStartingPrice)) / int256(publicSaleDuration)) * int256(elapsed); uint256 currentPrice = uint256(tempPrice); return currentPrice > publicSaleGodEndingPrice ? currentPrice : publicSaleGodEndingPrice; } } /** @notice mintGods is a payable function which allows the sender to pay ETH to mint God NFTs at the current price specified by getMintPrice. @param _numGodsToMint The number of gods to be minted, which is capped at a maximum of 5 Gods per transaction. */ function mintGods(uint256 _numGodsToMint) external payable whenPublicSaleActive nonReentrant { require( publicGodsMinted + _numGodsToMint <= MAX_GODS_TO_MINT - NUM_RESERVED_NFTS, "Minting would exceed max supply" ); require(_numGodsToMint > 0, "Must mint at least one god"); require( idolMain.balanceOf(msg.sender) + _numGodsToMint <= MAX_GODS_PER_ADDRESS, "Requested number would exceed the maximum number of gods allowed to be minted for this address." ); uint256 individualCostToMint = getMintPrice(); uint256 costToMint = individualCostToMint * _numGodsToMint; require(costToMint <= msg.value, "Ether value sent is not correct"); for (uint256 i = 0; i < _numGodsToMint; i++) { uint idToMint = (publicGodsMinted + i + godIdOffset) % MAX_GODS_TO_MINT; idolMain.mint(msg.sender, idToMint, false); } publicGodsMinted += _numGodsToMint; if (msg.value > costToMint) { Address.sendValue(payable(msg.sender), msg.value - costToMint); } emit IdolsMinted(msg.sender, individualCostToMint, _numGodsToMint); } /** @notice mintReservedGods is used by the contract owner to mint a reserved pool of 1000 Gods for owners and supporters of the protocol. @param _numGodsToMint The number of Gods to mint in this transaction. @param _mintAddress The address to mint the reserved Gods for. @param _lock If true, specifies that the minted reserved Gods cannot be sold or transferred for the first year of the protocol's existence. */ function mintReservedGods(uint256 _numGodsToMint, address _mintAddress, bool _lock) external onlyOwner nonReentrant { require( reservedGodsMinted + _numGodsToMint < NUM_RESERVED_NFTS, "Minting would exceed max reserved supply" ); require(_numGodsToMint > 0, "Must mint at least one god"); for (uint256 i = 0; i < _numGodsToMint; i++) { uint idToMint = (reservedGodsMinted + i + godIdOffset + MAX_GODS_TO_MINT - NUM_RESERVED_NFTS) % MAX_GODS_TO_MINT; idolMain.mint(_mintAddress, idToMint, _lock); } reservedGodsMinted += _numGodsToMint; } /** @notice sendToOfferingRefundContract sends ETH to the OfferingRefundContract so that it can be distributed to the addresses that are eligible for a refund. */ function sendToOfferingRefundContract(uint _totalRefundAmount) onlyOwner external nonReentrant { Address.sendValue(payable(address(offeringRefundContract)), _totalRefundAmount); } /** @notice swap is used to swap the contract's ETH into stETH via Curve. @param _slippageBps The acceptable slippage percent, in basis points. */ function swap(uint _slippageBps) onlyOwner external returns(uint result) { return stethPool.exchange{ value: address(this).balance }(0, 1, address(this).balance, address(this).balance * _slippageBps / 10000); } function swapLido(uint _slippageBps) onlyOwner external { uint minSteth = steth.balanceOf(address(this)) + address(this).balance * _slippageBps / 10000; Address.sendValue(payable(LIDO_STAKING_ADDRESS), address(this).balance); require(steth.balanceOf(address(this)) >= minSteth, "steth balance not high enough after sending to LIDO_STAKING_ADDRESS"); } /** @notice depositStethIdolMain deposits all of this contract's stETH into the IdolMain contract. */ function depositStethIdolMain() onlyOwner external { idolMain.depositSteth(steth.balanceOf(address(this))); } /** @notice getTotalMinted returns the total number of public + reserved God NFTs minted. */ function getTotalMinted() external view returns (uint) { return reservedGodsMinted + publicGodsMinted; } /** @notice setBaseURI sets the baseURI for the God NFTs. */ function setBaseURI(string memory uri) external onlyOwner { idolMain.setBaseURI(uri); } /** @notice Tears down the contract and allocates any remaining funds to the original contract owner. Should only be called after the mint completes and the contract's balance has been converted to Steth and deposited into IdolMain, or in a disaster scenario where we need to tear down the contract and refund minting fees. */ function tearDown() external onlyOwner { selfdestruct(payable(owner())); } modifier beforePublicSaleStarted { require(!publicSaleStarted, "Public sale has already started"); _; } modifier whenPublicSaleActive { require(publicSaleStarted && !publicSalePaused, "Public sale is not active"); _; } }
/** @notice IdolMintContract is a contract used for the initial mint of the God NFTs. It allocates 90% of the Gods for public minting through a dutch auction protocol, and reserves 10% of the Gods for the creators of the protocol as well as other supporters and stakeholders. IdolMintContract is intended to be torn down once the mint event has completed and once its balance has been deposited into the IdolMain rewards protocol. */
NatSpecMultiLine
pausePublicSale
function pausePublicSale() external onlyOwner whenPublicSaleActive { uint256 currentSalePrice = getMintPrice(); uint256 elapsedTime = getElapsedSaleTime(); publicSalePausedElapsedTime = elapsedTime; publicSalePaused = true; emit PublicSalePaused(currentSalePrice, elapsedTime); }
/** @notice pausePublicSale is called to pause the progression of the mint event. In happy-path circumstances we shouldn't need to call this, but it is included as a precaution in case something goes wrong during the mint. */
NatSpecMultiLine
v0.8.9+commit.e5eed63a
{ "func_code_index": [ 7044, 7363 ] }
11,806
IdolMintContract
contracts/IdolMintContract.sol
0x7b4b02372d8e54c1c0454d97f01d85ef203cdc5e
Solidity
IdolMintContract
contract IdolMintContract is Ownable, ReentrancyGuard { // publicGodsMinted tracks the number of Gods that have been minted by the public through the // mintGods function. uint public publicGodsMinted; // reservedGodsMinted tracks the number of reserved Gods that have been minted through the // mintReservedGods function. uint public reservedGodsMinted; // MAX_GODS_TO_MINT specifies the maximum number of Gods that can be minted (both public and // reserved.) uint public constant MAX_GODS_TO_MINT = 10000; // MAX_GODS_PER_ADDRESS specifies the maximum number of Gods that a single address can mint. uint public constant MAX_GODS_PER_ADDRESS = 20; // NUM_RESERVED_NFTS specifies the maximum number of Gods that can be minted through the // mintReservedGods function. uint public constant NUM_RESERVED_NFTS = 1000; // publicSaleDuration specifies the length of the dutch auction (in seconds) before the minting // price hits publicSaleGodEndingPrice. uint256 public publicSaleDuration; // publicSaleStartTime tracks the time (as a UNIX timestamp) when the public sale was started. uint256 public publicSaleStartTime; // publicSaleGodStartingPrice specifies the price that the dutch auction mint should start at. uint256 public publicSaleGodStartingPrice; // publicSaleGodEndingPrice specifies the minimum price that Gods can be minted at once the // full duration of the dutch auction has elapsed. uint256 public publicSaleGodEndingPrice; // publicSaleStarted specifies whether the minting event has been started. bool public publicSaleStarted = false; // publicSalePaused specifies whether the minting event has been paused. bool public publicSalePaused = false; // publicSalePausedElapsedTime specifies, if the sale was paused, what the elapsed sale // time was at the time of pausing. uint256 public publicSalePausedElapsedTime; // godIdOffset is pseudo-random offset from 0-10000 generated when the contract is constructed // and used to assign god IDs for each mint. uint256 public immutable godIdOffset; // addressReferencesSet is a boolean flag which tracks that the proper setup functions for the // contract have been run. It must be true before startPublicSale is called. bool public addressReferencesSet = false; // CURVE_POOL_ADDRESS holds the address of the curve pool that we use to exchange ETH for stETH. address constant CURVE_POOL_ADDRESS = 0xDC24316b9AE028F1497c275EB9192a3Ea0f67022; // LIDO_STAKING_ADDRESS holds the address of the Lido staking contract that we also can use to // exchange ETH for stETH. address constant LIDO_STAKING_ADDRESS = 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84; IIdolMain public idolMain; IIdolMarketplace public idolMarketplace; ICurvePool public immutable stethPool; ERC20 public immutable steth; OfferingRefundContract public immutable offeringRefundContract; event PublicSaleStart( uint256 indexed _saleDuration, uint256 indexed _saleStartTime ); event PublicSalePaused( uint256 indexed _currentPrice, uint256 indexed _timeElapsed ); event PublicSaleResumed( uint256 indexed _saleResumeTime ); event IdolsMinted( address indexed _minter, uint256 indexed _mintPrice, uint256 indexed _numMinted ); /** @notice IdolMintContract's constructor takes in two hashes, one of which represents the hash of the Idol NFT metadata, and one of which is the hash of some discord-community-generated input. The two hashes are used to calculate the godIdOffset, which specifies which ID from 0-10000 to start minting at. @param _metadataHash The hash of the master metadata file which corresponds to the 10k Idol NFT images that have been uploaded. @param _discordGeneratedHash The hash of some discord-community-generated input which is used to effectively randomize the value of godIdOffset prior to the start of the mint. @param _stethAddress The address of the stETH ERC20 contract. @param _offeringRefundContractAddress The address of the OfferingRefundContract we will be sending refunds to. */ constructor( string memory _metadataHash, string memory _discordGeneratedHash, address _stethAddress, address payable _offeringRefundContractAddress ) { godIdOffset = uint256(keccak256(abi.encodePacked(_metadataHash, _discordGeneratedHash))) % MAX_GODS_TO_MINT; stethPool = ICurvePool(CURVE_POOL_ADDRESS); steth = ERC20(_stethAddress); offeringRefundContract = OfferingRefundContract(_offeringRefundContractAddress); } /** @notice startPublicSale is called to start the dutch auction for minting Gods to the public. @param _saleDuration The duration of the sale, in seconds, before reaching the minimum minting price. @param _saleStartPrice The initial minting price, which progressively lowers as the dutch auction progresses. @param _saleEndPrice Lower bound for the minting price, once the full duration of the dutch auction has elapsed. */ function startPublicSale(uint256 _saleDuration, uint256 _saleStartPrice, uint256 _saleEndPrice) external onlyOwner beforePublicSaleStarted { require(_saleStartPrice > _saleEndPrice, "_saleStartPrice must be greater than _saleEndPrice"); require(addressReferencesSet, "External reference contracts must all be set before public sale starts"); publicSaleDuration = _saleDuration; publicSaleGodStartingPrice = _saleStartPrice; publicSaleGodEndingPrice = _saleEndPrice; publicSaleStartTime = block.timestamp; publicSaleStarted = true; emit PublicSaleStart(_saleDuration, publicSaleStartTime); } /** @notice setAddressReferences sets references to the main, marketplace, and virtueToken addresses so that the contracts all know about each other. This is all done from the mint contract so that the addresses will no longer be updateable once the mint event has started. @param _idolMainAddress The address of IdolMain. @param _idolMarketplaceAddress The address of the marketplace. @param _virtueTokenAddress The address of the VIRTUE token ERC20 contract. */ function setAddressReferences( address _idolMainAddress, address _idolMarketplaceAddress, address _virtueTokenAddress ) external onlyOwner beforePublicSaleStarted { addressReferencesSet = true; idolMain = IIdolMain(_idolMainAddress); require(steth.approve(_idolMainAddress, 2**255-1)); idolMarketplace = IIdolMarketplace(_idolMarketplaceAddress); idolMain.setVirtueTokenAddr(_virtueTokenAddress); idolMain.setIdolMarketplaceAddr(_idolMarketplaceAddress); idolMarketplace.setVirtueTokenAddr(_virtueTokenAddress); } /** @notice pausePublicSale is called to pause the progression of the mint event. In happy-path circumstances we shouldn't need to call this, but it is included as a precaution in case something goes wrong during the mint. */ function pausePublicSale() external onlyOwner whenPublicSaleActive { uint256 currentSalePrice = getMintPrice(); uint256 elapsedTime = getElapsedSaleTime(); publicSalePausedElapsedTime = elapsedTime; publicSalePaused = true; emit PublicSalePaused(currentSalePrice, elapsedTime); } function resumePublicSale() external onlyOwner { require(publicSalePaused, "Can only resume when the sale is paused"); publicSalePaused = false; publicSaleStartTime = block.timestamp - publicSalePausedElapsedTime; emit PublicSaleResumed(block.timestamp); } /** @notice getElaspedSaleTime is a view function that tells us how many seconds have elapsed since the public sale was started. */ function getElapsedSaleTime() internal view returns (uint256) { if (publicSalePaused) { return publicSalePausedElapsedTime; } return publicSaleStartTime > 0 ? block.timestamp - publicSaleStartTime : 0; } /** @notice getRemainingSaleTime is a view function that tells us how many seconds are remaining before the dutch auction hits the minimum price. */ function getRemainingSaleTime() external view returns (uint256) { if (publicSaleStartTime == 0) { // If the public sale has not been started, we just return 1 week as a placeholder. return 604800; } if (publicSalePaused) { return publicSaleDuration - publicSalePausedElapsedTime; } if (getElapsedSaleTime() >= publicSaleDuration) { return 0; } return (publicSaleStartTime + publicSaleDuration) - block.timestamp; } /** @notice getMintPrice returns the price to mint a God at the current time in the dutch auction. */ function getMintPrice() public view returns (uint256) { if (!publicSaleStarted) { return 0; } uint256 elapsed = getElapsedSaleTime(); if (elapsed >= publicSaleDuration) { return publicSaleGodEndingPrice; } else { int256 tempPrice = int256(publicSaleGodStartingPrice) + ((int256(publicSaleGodEndingPrice) - int256(publicSaleGodStartingPrice)) / int256(publicSaleDuration)) * int256(elapsed); uint256 currentPrice = uint256(tempPrice); return currentPrice > publicSaleGodEndingPrice ? currentPrice : publicSaleGodEndingPrice; } } /** @notice mintGods is a payable function which allows the sender to pay ETH to mint God NFTs at the current price specified by getMintPrice. @param _numGodsToMint The number of gods to be minted, which is capped at a maximum of 5 Gods per transaction. */ function mintGods(uint256 _numGodsToMint) external payable whenPublicSaleActive nonReentrant { require( publicGodsMinted + _numGodsToMint <= MAX_GODS_TO_MINT - NUM_RESERVED_NFTS, "Minting would exceed max supply" ); require(_numGodsToMint > 0, "Must mint at least one god"); require( idolMain.balanceOf(msg.sender) + _numGodsToMint <= MAX_GODS_PER_ADDRESS, "Requested number would exceed the maximum number of gods allowed to be minted for this address." ); uint256 individualCostToMint = getMintPrice(); uint256 costToMint = individualCostToMint * _numGodsToMint; require(costToMint <= msg.value, "Ether value sent is not correct"); for (uint256 i = 0; i < _numGodsToMint; i++) { uint idToMint = (publicGodsMinted + i + godIdOffset) % MAX_GODS_TO_MINT; idolMain.mint(msg.sender, idToMint, false); } publicGodsMinted += _numGodsToMint; if (msg.value > costToMint) { Address.sendValue(payable(msg.sender), msg.value - costToMint); } emit IdolsMinted(msg.sender, individualCostToMint, _numGodsToMint); } /** @notice mintReservedGods is used by the contract owner to mint a reserved pool of 1000 Gods for owners and supporters of the protocol. @param _numGodsToMint The number of Gods to mint in this transaction. @param _mintAddress The address to mint the reserved Gods for. @param _lock If true, specifies that the minted reserved Gods cannot be sold or transferred for the first year of the protocol's existence. */ function mintReservedGods(uint256 _numGodsToMint, address _mintAddress, bool _lock) external onlyOwner nonReentrant { require( reservedGodsMinted + _numGodsToMint < NUM_RESERVED_NFTS, "Minting would exceed max reserved supply" ); require(_numGodsToMint > 0, "Must mint at least one god"); for (uint256 i = 0; i < _numGodsToMint; i++) { uint idToMint = (reservedGodsMinted + i + godIdOffset + MAX_GODS_TO_MINT - NUM_RESERVED_NFTS) % MAX_GODS_TO_MINT; idolMain.mint(_mintAddress, idToMint, _lock); } reservedGodsMinted += _numGodsToMint; } /** @notice sendToOfferingRefundContract sends ETH to the OfferingRefundContract so that it can be distributed to the addresses that are eligible for a refund. */ function sendToOfferingRefundContract(uint _totalRefundAmount) onlyOwner external nonReentrant { Address.sendValue(payable(address(offeringRefundContract)), _totalRefundAmount); } /** @notice swap is used to swap the contract's ETH into stETH via Curve. @param _slippageBps The acceptable slippage percent, in basis points. */ function swap(uint _slippageBps) onlyOwner external returns(uint result) { return stethPool.exchange{ value: address(this).balance }(0, 1, address(this).balance, address(this).balance * _slippageBps / 10000); } function swapLido(uint _slippageBps) onlyOwner external { uint minSteth = steth.balanceOf(address(this)) + address(this).balance * _slippageBps / 10000; Address.sendValue(payable(LIDO_STAKING_ADDRESS), address(this).balance); require(steth.balanceOf(address(this)) >= minSteth, "steth balance not high enough after sending to LIDO_STAKING_ADDRESS"); } /** @notice depositStethIdolMain deposits all of this contract's stETH into the IdolMain contract. */ function depositStethIdolMain() onlyOwner external { idolMain.depositSteth(steth.balanceOf(address(this))); } /** @notice getTotalMinted returns the total number of public + reserved God NFTs minted. */ function getTotalMinted() external view returns (uint) { return reservedGodsMinted + publicGodsMinted; } /** @notice setBaseURI sets the baseURI for the God NFTs. */ function setBaseURI(string memory uri) external onlyOwner { idolMain.setBaseURI(uri); } /** @notice Tears down the contract and allocates any remaining funds to the original contract owner. Should only be called after the mint completes and the contract's balance has been converted to Steth and deposited into IdolMain, or in a disaster scenario where we need to tear down the contract and refund minting fees. */ function tearDown() external onlyOwner { selfdestruct(payable(owner())); } modifier beforePublicSaleStarted { require(!publicSaleStarted, "Public sale has already started"); _; } modifier whenPublicSaleActive { require(publicSaleStarted && !publicSalePaused, "Public sale is not active"); _; } }
/** @notice IdolMintContract is a contract used for the initial mint of the God NFTs. It allocates 90% of the Gods for public minting through a dutch auction protocol, and reserves 10% of the Gods for the creators of the protocol as well as other supporters and stakeholders. IdolMintContract is intended to be torn down once the mint event has completed and once its balance has been deposited into the IdolMain rewards protocol. */
NatSpecMultiLine
getElapsedSaleTime
function getElapsedSaleTime() internal view returns (uint256) { if (publicSalePaused) { return publicSalePausedElapsedTime; } return publicSaleStartTime > 0 ? block.timestamp - publicSaleStartTime : 0; }
/** @notice getElaspedSaleTime is a view function that tells us how many seconds have elapsed since the public sale was started. */
NatSpecMultiLine
v0.8.9+commit.e5eed63a
{ "func_code_index": [ 7801, 8026 ] }
11,807
IdolMintContract
contracts/IdolMintContract.sol
0x7b4b02372d8e54c1c0454d97f01d85ef203cdc5e
Solidity
IdolMintContract
contract IdolMintContract is Ownable, ReentrancyGuard { // publicGodsMinted tracks the number of Gods that have been minted by the public through the // mintGods function. uint public publicGodsMinted; // reservedGodsMinted tracks the number of reserved Gods that have been minted through the // mintReservedGods function. uint public reservedGodsMinted; // MAX_GODS_TO_MINT specifies the maximum number of Gods that can be minted (both public and // reserved.) uint public constant MAX_GODS_TO_MINT = 10000; // MAX_GODS_PER_ADDRESS specifies the maximum number of Gods that a single address can mint. uint public constant MAX_GODS_PER_ADDRESS = 20; // NUM_RESERVED_NFTS specifies the maximum number of Gods that can be minted through the // mintReservedGods function. uint public constant NUM_RESERVED_NFTS = 1000; // publicSaleDuration specifies the length of the dutch auction (in seconds) before the minting // price hits publicSaleGodEndingPrice. uint256 public publicSaleDuration; // publicSaleStartTime tracks the time (as a UNIX timestamp) when the public sale was started. uint256 public publicSaleStartTime; // publicSaleGodStartingPrice specifies the price that the dutch auction mint should start at. uint256 public publicSaleGodStartingPrice; // publicSaleGodEndingPrice specifies the minimum price that Gods can be minted at once the // full duration of the dutch auction has elapsed. uint256 public publicSaleGodEndingPrice; // publicSaleStarted specifies whether the minting event has been started. bool public publicSaleStarted = false; // publicSalePaused specifies whether the minting event has been paused. bool public publicSalePaused = false; // publicSalePausedElapsedTime specifies, if the sale was paused, what the elapsed sale // time was at the time of pausing. uint256 public publicSalePausedElapsedTime; // godIdOffset is pseudo-random offset from 0-10000 generated when the contract is constructed // and used to assign god IDs for each mint. uint256 public immutable godIdOffset; // addressReferencesSet is a boolean flag which tracks that the proper setup functions for the // contract have been run. It must be true before startPublicSale is called. bool public addressReferencesSet = false; // CURVE_POOL_ADDRESS holds the address of the curve pool that we use to exchange ETH for stETH. address constant CURVE_POOL_ADDRESS = 0xDC24316b9AE028F1497c275EB9192a3Ea0f67022; // LIDO_STAKING_ADDRESS holds the address of the Lido staking contract that we also can use to // exchange ETH for stETH. address constant LIDO_STAKING_ADDRESS = 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84; IIdolMain public idolMain; IIdolMarketplace public idolMarketplace; ICurvePool public immutable stethPool; ERC20 public immutable steth; OfferingRefundContract public immutable offeringRefundContract; event PublicSaleStart( uint256 indexed _saleDuration, uint256 indexed _saleStartTime ); event PublicSalePaused( uint256 indexed _currentPrice, uint256 indexed _timeElapsed ); event PublicSaleResumed( uint256 indexed _saleResumeTime ); event IdolsMinted( address indexed _minter, uint256 indexed _mintPrice, uint256 indexed _numMinted ); /** @notice IdolMintContract's constructor takes in two hashes, one of which represents the hash of the Idol NFT metadata, and one of which is the hash of some discord-community-generated input. The two hashes are used to calculate the godIdOffset, which specifies which ID from 0-10000 to start minting at. @param _metadataHash The hash of the master metadata file which corresponds to the 10k Idol NFT images that have been uploaded. @param _discordGeneratedHash The hash of some discord-community-generated input which is used to effectively randomize the value of godIdOffset prior to the start of the mint. @param _stethAddress The address of the stETH ERC20 contract. @param _offeringRefundContractAddress The address of the OfferingRefundContract we will be sending refunds to. */ constructor( string memory _metadataHash, string memory _discordGeneratedHash, address _stethAddress, address payable _offeringRefundContractAddress ) { godIdOffset = uint256(keccak256(abi.encodePacked(_metadataHash, _discordGeneratedHash))) % MAX_GODS_TO_MINT; stethPool = ICurvePool(CURVE_POOL_ADDRESS); steth = ERC20(_stethAddress); offeringRefundContract = OfferingRefundContract(_offeringRefundContractAddress); } /** @notice startPublicSale is called to start the dutch auction for minting Gods to the public. @param _saleDuration The duration of the sale, in seconds, before reaching the minimum minting price. @param _saleStartPrice The initial minting price, which progressively lowers as the dutch auction progresses. @param _saleEndPrice Lower bound for the minting price, once the full duration of the dutch auction has elapsed. */ function startPublicSale(uint256 _saleDuration, uint256 _saleStartPrice, uint256 _saleEndPrice) external onlyOwner beforePublicSaleStarted { require(_saleStartPrice > _saleEndPrice, "_saleStartPrice must be greater than _saleEndPrice"); require(addressReferencesSet, "External reference contracts must all be set before public sale starts"); publicSaleDuration = _saleDuration; publicSaleGodStartingPrice = _saleStartPrice; publicSaleGodEndingPrice = _saleEndPrice; publicSaleStartTime = block.timestamp; publicSaleStarted = true; emit PublicSaleStart(_saleDuration, publicSaleStartTime); } /** @notice setAddressReferences sets references to the main, marketplace, and virtueToken addresses so that the contracts all know about each other. This is all done from the mint contract so that the addresses will no longer be updateable once the mint event has started. @param _idolMainAddress The address of IdolMain. @param _idolMarketplaceAddress The address of the marketplace. @param _virtueTokenAddress The address of the VIRTUE token ERC20 contract. */ function setAddressReferences( address _idolMainAddress, address _idolMarketplaceAddress, address _virtueTokenAddress ) external onlyOwner beforePublicSaleStarted { addressReferencesSet = true; idolMain = IIdolMain(_idolMainAddress); require(steth.approve(_idolMainAddress, 2**255-1)); idolMarketplace = IIdolMarketplace(_idolMarketplaceAddress); idolMain.setVirtueTokenAddr(_virtueTokenAddress); idolMain.setIdolMarketplaceAddr(_idolMarketplaceAddress); idolMarketplace.setVirtueTokenAddr(_virtueTokenAddress); } /** @notice pausePublicSale is called to pause the progression of the mint event. In happy-path circumstances we shouldn't need to call this, but it is included as a precaution in case something goes wrong during the mint. */ function pausePublicSale() external onlyOwner whenPublicSaleActive { uint256 currentSalePrice = getMintPrice(); uint256 elapsedTime = getElapsedSaleTime(); publicSalePausedElapsedTime = elapsedTime; publicSalePaused = true; emit PublicSalePaused(currentSalePrice, elapsedTime); } function resumePublicSale() external onlyOwner { require(publicSalePaused, "Can only resume when the sale is paused"); publicSalePaused = false; publicSaleStartTime = block.timestamp - publicSalePausedElapsedTime; emit PublicSaleResumed(block.timestamp); } /** @notice getElaspedSaleTime is a view function that tells us how many seconds have elapsed since the public sale was started. */ function getElapsedSaleTime() internal view returns (uint256) { if (publicSalePaused) { return publicSalePausedElapsedTime; } return publicSaleStartTime > 0 ? block.timestamp - publicSaleStartTime : 0; } /** @notice getRemainingSaleTime is a view function that tells us how many seconds are remaining before the dutch auction hits the minimum price. */ function getRemainingSaleTime() external view returns (uint256) { if (publicSaleStartTime == 0) { // If the public sale has not been started, we just return 1 week as a placeholder. return 604800; } if (publicSalePaused) { return publicSaleDuration - publicSalePausedElapsedTime; } if (getElapsedSaleTime() >= publicSaleDuration) { return 0; } return (publicSaleStartTime + publicSaleDuration) - block.timestamp; } /** @notice getMintPrice returns the price to mint a God at the current time in the dutch auction. */ function getMintPrice() public view returns (uint256) { if (!publicSaleStarted) { return 0; } uint256 elapsed = getElapsedSaleTime(); if (elapsed >= publicSaleDuration) { return publicSaleGodEndingPrice; } else { int256 tempPrice = int256(publicSaleGodStartingPrice) + ((int256(publicSaleGodEndingPrice) - int256(publicSaleGodStartingPrice)) / int256(publicSaleDuration)) * int256(elapsed); uint256 currentPrice = uint256(tempPrice); return currentPrice > publicSaleGodEndingPrice ? currentPrice : publicSaleGodEndingPrice; } } /** @notice mintGods is a payable function which allows the sender to pay ETH to mint God NFTs at the current price specified by getMintPrice. @param _numGodsToMint The number of gods to be minted, which is capped at a maximum of 5 Gods per transaction. */ function mintGods(uint256 _numGodsToMint) external payable whenPublicSaleActive nonReentrant { require( publicGodsMinted + _numGodsToMint <= MAX_GODS_TO_MINT - NUM_RESERVED_NFTS, "Minting would exceed max supply" ); require(_numGodsToMint > 0, "Must mint at least one god"); require( idolMain.balanceOf(msg.sender) + _numGodsToMint <= MAX_GODS_PER_ADDRESS, "Requested number would exceed the maximum number of gods allowed to be minted for this address." ); uint256 individualCostToMint = getMintPrice(); uint256 costToMint = individualCostToMint * _numGodsToMint; require(costToMint <= msg.value, "Ether value sent is not correct"); for (uint256 i = 0; i < _numGodsToMint; i++) { uint idToMint = (publicGodsMinted + i + godIdOffset) % MAX_GODS_TO_MINT; idolMain.mint(msg.sender, idToMint, false); } publicGodsMinted += _numGodsToMint; if (msg.value > costToMint) { Address.sendValue(payable(msg.sender), msg.value - costToMint); } emit IdolsMinted(msg.sender, individualCostToMint, _numGodsToMint); } /** @notice mintReservedGods is used by the contract owner to mint a reserved pool of 1000 Gods for owners and supporters of the protocol. @param _numGodsToMint The number of Gods to mint in this transaction. @param _mintAddress The address to mint the reserved Gods for. @param _lock If true, specifies that the minted reserved Gods cannot be sold or transferred for the first year of the protocol's existence. */ function mintReservedGods(uint256 _numGodsToMint, address _mintAddress, bool _lock) external onlyOwner nonReentrant { require( reservedGodsMinted + _numGodsToMint < NUM_RESERVED_NFTS, "Minting would exceed max reserved supply" ); require(_numGodsToMint > 0, "Must mint at least one god"); for (uint256 i = 0; i < _numGodsToMint; i++) { uint idToMint = (reservedGodsMinted + i + godIdOffset + MAX_GODS_TO_MINT - NUM_RESERVED_NFTS) % MAX_GODS_TO_MINT; idolMain.mint(_mintAddress, idToMint, _lock); } reservedGodsMinted += _numGodsToMint; } /** @notice sendToOfferingRefundContract sends ETH to the OfferingRefundContract so that it can be distributed to the addresses that are eligible for a refund. */ function sendToOfferingRefundContract(uint _totalRefundAmount) onlyOwner external nonReentrant { Address.sendValue(payable(address(offeringRefundContract)), _totalRefundAmount); } /** @notice swap is used to swap the contract's ETH into stETH via Curve. @param _slippageBps The acceptable slippage percent, in basis points. */ function swap(uint _slippageBps) onlyOwner external returns(uint result) { return stethPool.exchange{ value: address(this).balance }(0, 1, address(this).balance, address(this).balance * _slippageBps / 10000); } function swapLido(uint _slippageBps) onlyOwner external { uint minSteth = steth.balanceOf(address(this)) + address(this).balance * _slippageBps / 10000; Address.sendValue(payable(LIDO_STAKING_ADDRESS), address(this).balance); require(steth.balanceOf(address(this)) >= minSteth, "steth balance not high enough after sending to LIDO_STAKING_ADDRESS"); } /** @notice depositStethIdolMain deposits all of this contract's stETH into the IdolMain contract. */ function depositStethIdolMain() onlyOwner external { idolMain.depositSteth(steth.balanceOf(address(this))); } /** @notice getTotalMinted returns the total number of public + reserved God NFTs minted. */ function getTotalMinted() external view returns (uint) { return reservedGodsMinted + publicGodsMinted; } /** @notice setBaseURI sets the baseURI for the God NFTs. */ function setBaseURI(string memory uri) external onlyOwner { idolMain.setBaseURI(uri); } /** @notice Tears down the contract and allocates any remaining funds to the original contract owner. Should only be called after the mint completes and the contract's balance has been converted to Steth and deposited into IdolMain, or in a disaster scenario where we need to tear down the contract and refund minting fees. */ function tearDown() external onlyOwner { selfdestruct(payable(owner())); } modifier beforePublicSaleStarted { require(!publicSaleStarted, "Public sale has already started"); _; } modifier whenPublicSaleActive { require(publicSaleStarted && !publicSalePaused, "Public sale is not active"); _; } }
/** @notice IdolMintContract is a contract used for the initial mint of the God NFTs. It allocates 90% of the Gods for public minting through a dutch auction protocol, and reserves 10% of the Gods for the creators of the protocol as well as other supporters and stakeholders. IdolMintContract is intended to be torn down once the mint event has completed and once its balance has been deposited into the IdolMain rewards protocol. */
NatSpecMultiLine
getRemainingSaleTime
function getRemainingSaleTime() external view returns (uint256) { if (publicSaleStartTime == 0) { // If the public sale has not been started, we just return 1 week as a placeholder. return 604800; } if (publicSalePaused) { return publicSaleDuration - publicSalePausedElapsedTime; } if (getElapsedSaleTime() >= publicSaleDuration) { return 0; } return (publicSaleStartTime + publicSaleDuration) - block.timestamp; }
/** @notice getRemainingSaleTime is a view function that tells us how many seconds are remaining before the dutch auction hits the minimum price. */
NatSpecMultiLine
v0.8.9+commit.e5eed63a
{ "func_code_index": [ 8191, 8664 ] }
11,808
IdolMintContract
contracts/IdolMintContract.sol
0x7b4b02372d8e54c1c0454d97f01d85ef203cdc5e
Solidity
IdolMintContract
contract IdolMintContract is Ownable, ReentrancyGuard { // publicGodsMinted tracks the number of Gods that have been minted by the public through the // mintGods function. uint public publicGodsMinted; // reservedGodsMinted tracks the number of reserved Gods that have been minted through the // mintReservedGods function. uint public reservedGodsMinted; // MAX_GODS_TO_MINT specifies the maximum number of Gods that can be minted (both public and // reserved.) uint public constant MAX_GODS_TO_MINT = 10000; // MAX_GODS_PER_ADDRESS specifies the maximum number of Gods that a single address can mint. uint public constant MAX_GODS_PER_ADDRESS = 20; // NUM_RESERVED_NFTS specifies the maximum number of Gods that can be minted through the // mintReservedGods function. uint public constant NUM_RESERVED_NFTS = 1000; // publicSaleDuration specifies the length of the dutch auction (in seconds) before the minting // price hits publicSaleGodEndingPrice. uint256 public publicSaleDuration; // publicSaleStartTime tracks the time (as a UNIX timestamp) when the public sale was started. uint256 public publicSaleStartTime; // publicSaleGodStartingPrice specifies the price that the dutch auction mint should start at. uint256 public publicSaleGodStartingPrice; // publicSaleGodEndingPrice specifies the minimum price that Gods can be minted at once the // full duration of the dutch auction has elapsed. uint256 public publicSaleGodEndingPrice; // publicSaleStarted specifies whether the minting event has been started. bool public publicSaleStarted = false; // publicSalePaused specifies whether the minting event has been paused. bool public publicSalePaused = false; // publicSalePausedElapsedTime specifies, if the sale was paused, what the elapsed sale // time was at the time of pausing. uint256 public publicSalePausedElapsedTime; // godIdOffset is pseudo-random offset from 0-10000 generated when the contract is constructed // and used to assign god IDs for each mint. uint256 public immutable godIdOffset; // addressReferencesSet is a boolean flag which tracks that the proper setup functions for the // contract have been run. It must be true before startPublicSale is called. bool public addressReferencesSet = false; // CURVE_POOL_ADDRESS holds the address of the curve pool that we use to exchange ETH for stETH. address constant CURVE_POOL_ADDRESS = 0xDC24316b9AE028F1497c275EB9192a3Ea0f67022; // LIDO_STAKING_ADDRESS holds the address of the Lido staking contract that we also can use to // exchange ETH for stETH. address constant LIDO_STAKING_ADDRESS = 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84; IIdolMain public idolMain; IIdolMarketplace public idolMarketplace; ICurvePool public immutable stethPool; ERC20 public immutable steth; OfferingRefundContract public immutable offeringRefundContract; event PublicSaleStart( uint256 indexed _saleDuration, uint256 indexed _saleStartTime ); event PublicSalePaused( uint256 indexed _currentPrice, uint256 indexed _timeElapsed ); event PublicSaleResumed( uint256 indexed _saleResumeTime ); event IdolsMinted( address indexed _minter, uint256 indexed _mintPrice, uint256 indexed _numMinted ); /** @notice IdolMintContract's constructor takes in two hashes, one of which represents the hash of the Idol NFT metadata, and one of which is the hash of some discord-community-generated input. The two hashes are used to calculate the godIdOffset, which specifies which ID from 0-10000 to start minting at. @param _metadataHash The hash of the master metadata file which corresponds to the 10k Idol NFT images that have been uploaded. @param _discordGeneratedHash The hash of some discord-community-generated input which is used to effectively randomize the value of godIdOffset prior to the start of the mint. @param _stethAddress The address of the stETH ERC20 contract. @param _offeringRefundContractAddress The address of the OfferingRefundContract we will be sending refunds to. */ constructor( string memory _metadataHash, string memory _discordGeneratedHash, address _stethAddress, address payable _offeringRefundContractAddress ) { godIdOffset = uint256(keccak256(abi.encodePacked(_metadataHash, _discordGeneratedHash))) % MAX_GODS_TO_MINT; stethPool = ICurvePool(CURVE_POOL_ADDRESS); steth = ERC20(_stethAddress); offeringRefundContract = OfferingRefundContract(_offeringRefundContractAddress); } /** @notice startPublicSale is called to start the dutch auction for minting Gods to the public. @param _saleDuration The duration of the sale, in seconds, before reaching the minimum minting price. @param _saleStartPrice The initial minting price, which progressively lowers as the dutch auction progresses. @param _saleEndPrice Lower bound for the minting price, once the full duration of the dutch auction has elapsed. */ function startPublicSale(uint256 _saleDuration, uint256 _saleStartPrice, uint256 _saleEndPrice) external onlyOwner beforePublicSaleStarted { require(_saleStartPrice > _saleEndPrice, "_saleStartPrice must be greater than _saleEndPrice"); require(addressReferencesSet, "External reference contracts must all be set before public sale starts"); publicSaleDuration = _saleDuration; publicSaleGodStartingPrice = _saleStartPrice; publicSaleGodEndingPrice = _saleEndPrice; publicSaleStartTime = block.timestamp; publicSaleStarted = true; emit PublicSaleStart(_saleDuration, publicSaleStartTime); } /** @notice setAddressReferences sets references to the main, marketplace, and virtueToken addresses so that the contracts all know about each other. This is all done from the mint contract so that the addresses will no longer be updateable once the mint event has started. @param _idolMainAddress The address of IdolMain. @param _idolMarketplaceAddress The address of the marketplace. @param _virtueTokenAddress The address of the VIRTUE token ERC20 contract. */ function setAddressReferences( address _idolMainAddress, address _idolMarketplaceAddress, address _virtueTokenAddress ) external onlyOwner beforePublicSaleStarted { addressReferencesSet = true; idolMain = IIdolMain(_idolMainAddress); require(steth.approve(_idolMainAddress, 2**255-1)); idolMarketplace = IIdolMarketplace(_idolMarketplaceAddress); idolMain.setVirtueTokenAddr(_virtueTokenAddress); idolMain.setIdolMarketplaceAddr(_idolMarketplaceAddress); idolMarketplace.setVirtueTokenAddr(_virtueTokenAddress); } /** @notice pausePublicSale is called to pause the progression of the mint event. In happy-path circumstances we shouldn't need to call this, but it is included as a precaution in case something goes wrong during the mint. */ function pausePublicSale() external onlyOwner whenPublicSaleActive { uint256 currentSalePrice = getMintPrice(); uint256 elapsedTime = getElapsedSaleTime(); publicSalePausedElapsedTime = elapsedTime; publicSalePaused = true; emit PublicSalePaused(currentSalePrice, elapsedTime); } function resumePublicSale() external onlyOwner { require(publicSalePaused, "Can only resume when the sale is paused"); publicSalePaused = false; publicSaleStartTime = block.timestamp - publicSalePausedElapsedTime; emit PublicSaleResumed(block.timestamp); } /** @notice getElaspedSaleTime is a view function that tells us how many seconds have elapsed since the public sale was started. */ function getElapsedSaleTime() internal view returns (uint256) { if (publicSalePaused) { return publicSalePausedElapsedTime; } return publicSaleStartTime > 0 ? block.timestamp - publicSaleStartTime : 0; } /** @notice getRemainingSaleTime is a view function that tells us how many seconds are remaining before the dutch auction hits the minimum price. */ function getRemainingSaleTime() external view returns (uint256) { if (publicSaleStartTime == 0) { // If the public sale has not been started, we just return 1 week as a placeholder. return 604800; } if (publicSalePaused) { return publicSaleDuration - publicSalePausedElapsedTime; } if (getElapsedSaleTime() >= publicSaleDuration) { return 0; } return (publicSaleStartTime + publicSaleDuration) - block.timestamp; } /** @notice getMintPrice returns the price to mint a God at the current time in the dutch auction. */ function getMintPrice() public view returns (uint256) { if (!publicSaleStarted) { return 0; } uint256 elapsed = getElapsedSaleTime(); if (elapsed >= publicSaleDuration) { return publicSaleGodEndingPrice; } else { int256 tempPrice = int256(publicSaleGodStartingPrice) + ((int256(publicSaleGodEndingPrice) - int256(publicSaleGodStartingPrice)) / int256(publicSaleDuration)) * int256(elapsed); uint256 currentPrice = uint256(tempPrice); return currentPrice > publicSaleGodEndingPrice ? currentPrice : publicSaleGodEndingPrice; } } /** @notice mintGods is a payable function which allows the sender to pay ETH to mint God NFTs at the current price specified by getMintPrice. @param _numGodsToMint The number of gods to be minted, which is capped at a maximum of 5 Gods per transaction. */ function mintGods(uint256 _numGodsToMint) external payable whenPublicSaleActive nonReentrant { require( publicGodsMinted + _numGodsToMint <= MAX_GODS_TO_MINT - NUM_RESERVED_NFTS, "Minting would exceed max supply" ); require(_numGodsToMint > 0, "Must mint at least one god"); require( idolMain.balanceOf(msg.sender) + _numGodsToMint <= MAX_GODS_PER_ADDRESS, "Requested number would exceed the maximum number of gods allowed to be minted for this address." ); uint256 individualCostToMint = getMintPrice(); uint256 costToMint = individualCostToMint * _numGodsToMint; require(costToMint <= msg.value, "Ether value sent is not correct"); for (uint256 i = 0; i < _numGodsToMint; i++) { uint idToMint = (publicGodsMinted + i + godIdOffset) % MAX_GODS_TO_MINT; idolMain.mint(msg.sender, idToMint, false); } publicGodsMinted += _numGodsToMint; if (msg.value > costToMint) { Address.sendValue(payable(msg.sender), msg.value - costToMint); } emit IdolsMinted(msg.sender, individualCostToMint, _numGodsToMint); } /** @notice mintReservedGods is used by the contract owner to mint a reserved pool of 1000 Gods for owners and supporters of the protocol. @param _numGodsToMint The number of Gods to mint in this transaction. @param _mintAddress The address to mint the reserved Gods for. @param _lock If true, specifies that the minted reserved Gods cannot be sold or transferred for the first year of the protocol's existence. */ function mintReservedGods(uint256 _numGodsToMint, address _mintAddress, bool _lock) external onlyOwner nonReentrant { require( reservedGodsMinted + _numGodsToMint < NUM_RESERVED_NFTS, "Minting would exceed max reserved supply" ); require(_numGodsToMint > 0, "Must mint at least one god"); for (uint256 i = 0; i < _numGodsToMint; i++) { uint idToMint = (reservedGodsMinted + i + godIdOffset + MAX_GODS_TO_MINT - NUM_RESERVED_NFTS) % MAX_GODS_TO_MINT; idolMain.mint(_mintAddress, idToMint, _lock); } reservedGodsMinted += _numGodsToMint; } /** @notice sendToOfferingRefundContract sends ETH to the OfferingRefundContract so that it can be distributed to the addresses that are eligible for a refund. */ function sendToOfferingRefundContract(uint _totalRefundAmount) onlyOwner external nonReentrant { Address.sendValue(payable(address(offeringRefundContract)), _totalRefundAmount); } /** @notice swap is used to swap the contract's ETH into stETH via Curve. @param _slippageBps The acceptable slippage percent, in basis points. */ function swap(uint _slippageBps) onlyOwner external returns(uint result) { return stethPool.exchange{ value: address(this).balance }(0, 1, address(this).balance, address(this).balance * _slippageBps / 10000); } function swapLido(uint _slippageBps) onlyOwner external { uint minSteth = steth.balanceOf(address(this)) + address(this).balance * _slippageBps / 10000; Address.sendValue(payable(LIDO_STAKING_ADDRESS), address(this).balance); require(steth.balanceOf(address(this)) >= minSteth, "steth balance not high enough after sending to LIDO_STAKING_ADDRESS"); } /** @notice depositStethIdolMain deposits all of this contract's stETH into the IdolMain contract. */ function depositStethIdolMain() onlyOwner external { idolMain.depositSteth(steth.balanceOf(address(this))); } /** @notice getTotalMinted returns the total number of public + reserved God NFTs minted. */ function getTotalMinted() external view returns (uint) { return reservedGodsMinted + publicGodsMinted; } /** @notice setBaseURI sets the baseURI for the God NFTs. */ function setBaseURI(string memory uri) external onlyOwner { idolMain.setBaseURI(uri); } /** @notice Tears down the contract and allocates any remaining funds to the original contract owner. Should only be called after the mint completes and the contract's balance has been converted to Steth and deposited into IdolMain, or in a disaster scenario where we need to tear down the contract and refund minting fees. */ function tearDown() external onlyOwner { selfdestruct(payable(owner())); } modifier beforePublicSaleStarted { require(!publicSaleStarted, "Public sale has already started"); _; } modifier whenPublicSaleActive { require(publicSaleStarted && !publicSalePaused, "Public sale is not active"); _; } }
/** @notice IdolMintContract is a contract used for the initial mint of the God NFTs. It allocates 90% of the Gods for public minting through a dutch auction protocol, and reserves 10% of the Gods for the creators of the protocol as well as other supporters and stakeholders. IdolMintContract is intended to be torn down once the mint event has completed and once its balance has been deposited into the IdolMain rewards protocol. */
NatSpecMultiLine
getMintPrice
function getMintPrice() public view returns (uint256) { if (!publicSaleStarted) { return 0; } uint256 elapsed = getElapsedSaleTime(); if (elapsed >= publicSaleDuration) { return publicSaleGodEndingPrice; } else { int256 tempPrice = int256(publicSaleGodStartingPrice) + ((int256(publicSaleGodEndingPrice) - int256(publicSaleGodStartingPrice)) / int256(publicSaleDuration)) * int256(elapsed); uint256 currentPrice = uint256(tempPrice); return currentPrice > publicSaleGodEndingPrice ? currentPrice : publicSaleGodEndingPrice; } }
/** @notice getMintPrice returns the price to mint a God at the current time in the dutch auction. */
NatSpecMultiLine
v0.8.9+commit.e5eed63a
{ "func_code_index": [ 8776, 9425 ] }
11,809
IdolMintContract
contracts/IdolMintContract.sol
0x7b4b02372d8e54c1c0454d97f01d85ef203cdc5e
Solidity
IdolMintContract
contract IdolMintContract is Ownable, ReentrancyGuard { // publicGodsMinted tracks the number of Gods that have been minted by the public through the // mintGods function. uint public publicGodsMinted; // reservedGodsMinted tracks the number of reserved Gods that have been minted through the // mintReservedGods function. uint public reservedGodsMinted; // MAX_GODS_TO_MINT specifies the maximum number of Gods that can be minted (both public and // reserved.) uint public constant MAX_GODS_TO_MINT = 10000; // MAX_GODS_PER_ADDRESS specifies the maximum number of Gods that a single address can mint. uint public constant MAX_GODS_PER_ADDRESS = 20; // NUM_RESERVED_NFTS specifies the maximum number of Gods that can be minted through the // mintReservedGods function. uint public constant NUM_RESERVED_NFTS = 1000; // publicSaleDuration specifies the length of the dutch auction (in seconds) before the minting // price hits publicSaleGodEndingPrice. uint256 public publicSaleDuration; // publicSaleStartTime tracks the time (as a UNIX timestamp) when the public sale was started. uint256 public publicSaleStartTime; // publicSaleGodStartingPrice specifies the price that the dutch auction mint should start at. uint256 public publicSaleGodStartingPrice; // publicSaleGodEndingPrice specifies the minimum price that Gods can be minted at once the // full duration of the dutch auction has elapsed. uint256 public publicSaleGodEndingPrice; // publicSaleStarted specifies whether the minting event has been started. bool public publicSaleStarted = false; // publicSalePaused specifies whether the minting event has been paused. bool public publicSalePaused = false; // publicSalePausedElapsedTime specifies, if the sale was paused, what the elapsed sale // time was at the time of pausing. uint256 public publicSalePausedElapsedTime; // godIdOffset is pseudo-random offset from 0-10000 generated when the contract is constructed // and used to assign god IDs for each mint. uint256 public immutable godIdOffset; // addressReferencesSet is a boolean flag which tracks that the proper setup functions for the // contract have been run. It must be true before startPublicSale is called. bool public addressReferencesSet = false; // CURVE_POOL_ADDRESS holds the address of the curve pool that we use to exchange ETH for stETH. address constant CURVE_POOL_ADDRESS = 0xDC24316b9AE028F1497c275EB9192a3Ea0f67022; // LIDO_STAKING_ADDRESS holds the address of the Lido staking contract that we also can use to // exchange ETH for stETH. address constant LIDO_STAKING_ADDRESS = 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84; IIdolMain public idolMain; IIdolMarketplace public idolMarketplace; ICurvePool public immutable stethPool; ERC20 public immutable steth; OfferingRefundContract public immutable offeringRefundContract; event PublicSaleStart( uint256 indexed _saleDuration, uint256 indexed _saleStartTime ); event PublicSalePaused( uint256 indexed _currentPrice, uint256 indexed _timeElapsed ); event PublicSaleResumed( uint256 indexed _saleResumeTime ); event IdolsMinted( address indexed _minter, uint256 indexed _mintPrice, uint256 indexed _numMinted ); /** @notice IdolMintContract's constructor takes in two hashes, one of which represents the hash of the Idol NFT metadata, and one of which is the hash of some discord-community-generated input. The two hashes are used to calculate the godIdOffset, which specifies which ID from 0-10000 to start minting at. @param _metadataHash The hash of the master metadata file which corresponds to the 10k Idol NFT images that have been uploaded. @param _discordGeneratedHash The hash of some discord-community-generated input which is used to effectively randomize the value of godIdOffset prior to the start of the mint. @param _stethAddress The address of the stETH ERC20 contract. @param _offeringRefundContractAddress The address of the OfferingRefundContract we will be sending refunds to. */ constructor( string memory _metadataHash, string memory _discordGeneratedHash, address _stethAddress, address payable _offeringRefundContractAddress ) { godIdOffset = uint256(keccak256(abi.encodePacked(_metadataHash, _discordGeneratedHash))) % MAX_GODS_TO_MINT; stethPool = ICurvePool(CURVE_POOL_ADDRESS); steth = ERC20(_stethAddress); offeringRefundContract = OfferingRefundContract(_offeringRefundContractAddress); } /** @notice startPublicSale is called to start the dutch auction for minting Gods to the public. @param _saleDuration The duration of the sale, in seconds, before reaching the minimum minting price. @param _saleStartPrice The initial minting price, which progressively lowers as the dutch auction progresses. @param _saleEndPrice Lower bound for the minting price, once the full duration of the dutch auction has elapsed. */ function startPublicSale(uint256 _saleDuration, uint256 _saleStartPrice, uint256 _saleEndPrice) external onlyOwner beforePublicSaleStarted { require(_saleStartPrice > _saleEndPrice, "_saleStartPrice must be greater than _saleEndPrice"); require(addressReferencesSet, "External reference contracts must all be set before public sale starts"); publicSaleDuration = _saleDuration; publicSaleGodStartingPrice = _saleStartPrice; publicSaleGodEndingPrice = _saleEndPrice; publicSaleStartTime = block.timestamp; publicSaleStarted = true; emit PublicSaleStart(_saleDuration, publicSaleStartTime); } /** @notice setAddressReferences sets references to the main, marketplace, and virtueToken addresses so that the contracts all know about each other. This is all done from the mint contract so that the addresses will no longer be updateable once the mint event has started. @param _idolMainAddress The address of IdolMain. @param _idolMarketplaceAddress The address of the marketplace. @param _virtueTokenAddress The address of the VIRTUE token ERC20 contract. */ function setAddressReferences( address _idolMainAddress, address _idolMarketplaceAddress, address _virtueTokenAddress ) external onlyOwner beforePublicSaleStarted { addressReferencesSet = true; idolMain = IIdolMain(_idolMainAddress); require(steth.approve(_idolMainAddress, 2**255-1)); idolMarketplace = IIdolMarketplace(_idolMarketplaceAddress); idolMain.setVirtueTokenAddr(_virtueTokenAddress); idolMain.setIdolMarketplaceAddr(_idolMarketplaceAddress); idolMarketplace.setVirtueTokenAddr(_virtueTokenAddress); } /** @notice pausePublicSale is called to pause the progression of the mint event. In happy-path circumstances we shouldn't need to call this, but it is included as a precaution in case something goes wrong during the mint. */ function pausePublicSale() external onlyOwner whenPublicSaleActive { uint256 currentSalePrice = getMintPrice(); uint256 elapsedTime = getElapsedSaleTime(); publicSalePausedElapsedTime = elapsedTime; publicSalePaused = true; emit PublicSalePaused(currentSalePrice, elapsedTime); } function resumePublicSale() external onlyOwner { require(publicSalePaused, "Can only resume when the sale is paused"); publicSalePaused = false; publicSaleStartTime = block.timestamp - publicSalePausedElapsedTime; emit PublicSaleResumed(block.timestamp); } /** @notice getElaspedSaleTime is a view function that tells us how many seconds have elapsed since the public sale was started. */ function getElapsedSaleTime() internal view returns (uint256) { if (publicSalePaused) { return publicSalePausedElapsedTime; } return publicSaleStartTime > 0 ? block.timestamp - publicSaleStartTime : 0; } /** @notice getRemainingSaleTime is a view function that tells us how many seconds are remaining before the dutch auction hits the minimum price. */ function getRemainingSaleTime() external view returns (uint256) { if (publicSaleStartTime == 0) { // If the public sale has not been started, we just return 1 week as a placeholder. return 604800; } if (publicSalePaused) { return publicSaleDuration - publicSalePausedElapsedTime; } if (getElapsedSaleTime() >= publicSaleDuration) { return 0; } return (publicSaleStartTime + publicSaleDuration) - block.timestamp; } /** @notice getMintPrice returns the price to mint a God at the current time in the dutch auction. */ function getMintPrice() public view returns (uint256) { if (!publicSaleStarted) { return 0; } uint256 elapsed = getElapsedSaleTime(); if (elapsed >= publicSaleDuration) { return publicSaleGodEndingPrice; } else { int256 tempPrice = int256(publicSaleGodStartingPrice) + ((int256(publicSaleGodEndingPrice) - int256(publicSaleGodStartingPrice)) / int256(publicSaleDuration)) * int256(elapsed); uint256 currentPrice = uint256(tempPrice); return currentPrice > publicSaleGodEndingPrice ? currentPrice : publicSaleGodEndingPrice; } } /** @notice mintGods is a payable function which allows the sender to pay ETH to mint God NFTs at the current price specified by getMintPrice. @param _numGodsToMint The number of gods to be minted, which is capped at a maximum of 5 Gods per transaction. */ function mintGods(uint256 _numGodsToMint) external payable whenPublicSaleActive nonReentrant { require( publicGodsMinted + _numGodsToMint <= MAX_GODS_TO_MINT - NUM_RESERVED_NFTS, "Minting would exceed max supply" ); require(_numGodsToMint > 0, "Must mint at least one god"); require( idolMain.balanceOf(msg.sender) + _numGodsToMint <= MAX_GODS_PER_ADDRESS, "Requested number would exceed the maximum number of gods allowed to be minted for this address." ); uint256 individualCostToMint = getMintPrice(); uint256 costToMint = individualCostToMint * _numGodsToMint; require(costToMint <= msg.value, "Ether value sent is not correct"); for (uint256 i = 0; i < _numGodsToMint; i++) { uint idToMint = (publicGodsMinted + i + godIdOffset) % MAX_GODS_TO_MINT; idolMain.mint(msg.sender, idToMint, false); } publicGodsMinted += _numGodsToMint; if (msg.value > costToMint) { Address.sendValue(payable(msg.sender), msg.value - costToMint); } emit IdolsMinted(msg.sender, individualCostToMint, _numGodsToMint); } /** @notice mintReservedGods is used by the contract owner to mint a reserved pool of 1000 Gods for owners and supporters of the protocol. @param _numGodsToMint The number of Gods to mint in this transaction. @param _mintAddress The address to mint the reserved Gods for. @param _lock If true, specifies that the minted reserved Gods cannot be sold or transferred for the first year of the protocol's existence. */ function mintReservedGods(uint256 _numGodsToMint, address _mintAddress, bool _lock) external onlyOwner nonReentrant { require( reservedGodsMinted + _numGodsToMint < NUM_RESERVED_NFTS, "Minting would exceed max reserved supply" ); require(_numGodsToMint > 0, "Must mint at least one god"); for (uint256 i = 0; i < _numGodsToMint; i++) { uint idToMint = (reservedGodsMinted + i + godIdOffset + MAX_GODS_TO_MINT - NUM_RESERVED_NFTS) % MAX_GODS_TO_MINT; idolMain.mint(_mintAddress, idToMint, _lock); } reservedGodsMinted += _numGodsToMint; } /** @notice sendToOfferingRefundContract sends ETH to the OfferingRefundContract so that it can be distributed to the addresses that are eligible for a refund. */ function sendToOfferingRefundContract(uint _totalRefundAmount) onlyOwner external nonReentrant { Address.sendValue(payable(address(offeringRefundContract)), _totalRefundAmount); } /** @notice swap is used to swap the contract's ETH into stETH via Curve. @param _slippageBps The acceptable slippage percent, in basis points. */ function swap(uint _slippageBps) onlyOwner external returns(uint result) { return stethPool.exchange{ value: address(this).balance }(0, 1, address(this).balance, address(this).balance * _slippageBps / 10000); } function swapLido(uint _slippageBps) onlyOwner external { uint minSteth = steth.balanceOf(address(this)) + address(this).balance * _slippageBps / 10000; Address.sendValue(payable(LIDO_STAKING_ADDRESS), address(this).balance); require(steth.balanceOf(address(this)) >= minSteth, "steth balance not high enough after sending to LIDO_STAKING_ADDRESS"); } /** @notice depositStethIdolMain deposits all of this contract's stETH into the IdolMain contract. */ function depositStethIdolMain() onlyOwner external { idolMain.depositSteth(steth.balanceOf(address(this))); } /** @notice getTotalMinted returns the total number of public + reserved God NFTs minted. */ function getTotalMinted() external view returns (uint) { return reservedGodsMinted + publicGodsMinted; } /** @notice setBaseURI sets the baseURI for the God NFTs. */ function setBaseURI(string memory uri) external onlyOwner { idolMain.setBaseURI(uri); } /** @notice Tears down the contract and allocates any remaining funds to the original contract owner. Should only be called after the mint completes and the contract's balance has been converted to Steth and deposited into IdolMain, or in a disaster scenario where we need to tear down the contract and refund minting fees. */ function tearDown() external onlyOwner { selfdestruct(payable(owner())); } modifier beforePublicSaleStarted { require(!publicSaleStarted, "Public sale has already started"); _; } modifier whenPublicSaleActive { require(publicSaleStarted && !publicSalePaused, "Public sale is not active"); _; } }
/** @notice IdolMintContract is a contract used for the initial mint of the God NFTs. It allocates 90% of the Gods for public minting through a dutch auction protocol, and reserves 10% of the Gods for the creators of the protocol as well as other supporters and stakeholders. IdolMintContract is intended to be torn down once the mint event has completed and once its balance has been deposited into the IdolMain rewards protocol. */
NatSpecMultiLine
mintGods
function mintGods(uint256 _numGodsToMint) external payable whenPublicSaleActive nonReentrant { require( publicGodsMinted + _numGodsToMint <= MAX_GODS_TO_MINT - NUM_RESERVED_NFTS, "Minting would exceed max supply" ); require(_numGodsToMint > 0, "Must mint at least one god"); require( idolMain.balanceOf(msg.sender) + _numGodsToMint <= MAX_GODS_PER_ADDRESS, "Requested number would exceed the maximum number of gods allowed to be minted for this address." ); uint256 individualCostToMint = getMintPrice(); uint256 costToMint = individualCostToMint * _numGodsToMint; require(costToMint <= msg.value, "Ether value sent is not correct"); for (uint256 i = 0; i < _numGodsToMint; i++) { uint idToMint = (publicGodsMinted + i + godIdOffset) % MAX_GODS_TO_MINT; idolMain.mint(msg.sender, idToMint, false); } publicGodsMinted += _numGodsToMint; if (msg.value > costToMint) { Address.sendValue(payable(msg.sender), msg.value - costToMint); } emit IdolsMinted(msg.sender, individualCostToMint, _numGodsToMint); }
/** @notice mintGods is a payable function which allows the sender to pay ETH to mint God NFTs at the current price specified by getMintPrice. @param _numGodsToMint The number of gods to be minted, which is capped at a maximum of 5 Gods per transaction. */
NatSpecMultiLine
v0.8.9+commit.e5eed63a
{ "func_code_index": [ 9708, 10833 ] }
11,810
IdolMintContract
contracts/IdolMintContract.sol
0x7b4b02372d8e54c1c0454d97f01d85ef203cdc5e
Solidity
IdolMintContract
contract IdolMintContract is Ownable, ReentrancyGuard { // publicGodsMinted tracks the number of Gods that have been minted by the public through the // mintGods function. uint public publicGodsMinted; // reservedGodsMinted tracks the number of reserved Gods that have been minted through the // mintReservedGods function. uint public reservedGodsMinted; // MAX_GODS_TO_MINT specifies the maximum number of Gods that can be minted (both public and // reserved.) uint public constant MAX_GODS_TO_MINT = 10000; // MAX_GODS_PER_ADDRESS specifies the maximum number of Gods that a single address can mint. uint public constant MAX_GODS_PER_ADDRESS = 20; // NUM_RESERVED_NFTS specifies the maximum number of Gods that can be minted through the // mintReservedGods function. uint public constant NUM_RESERVED_NFTS = 1000; // publicSaleDuration specifies the length of the dutch auction (in seconds) before the minting // price hits publicSaleGodEndingPrice. uint256 public publicSaleDuration; // publicSaleStartTime tracks the time (as a UNIX timestamp) when the public sale was started. uint256 public publicSaleStartTime; // publicSaleGodStartingPrice specifies the price that the dutch auction mint should start at. uint256 public publicSaleGodStartingPrice; // publicSaleGodEndingPrice specifies the minimum price that Gods can be minted at once the // full duration of the dutch auction has elapsed. uint256 public publicSaleGodEndingPrice; // publicSaleStarted specifies whether the minting event has been started. bool public publicSaleStarted = false; // publicSalePaused specifies whether the minting event has been paused. bool public publicSalePaused = false; // publicSalePausedElapsedTime specifies, if the sale was paused, what the elapsed sale // time was at the time of pausing. uint256 public publicSalePausedElapsedTime; // godIdOffset is pseudo-random offset from 0-10000 generated when the contract is constructed // and used to assign god IDs for each mint. uint256 public immutable godIdOffset; // addressReferencesSet is a boolean flag which tracks that the proper setup functions for the // contract have been run. It must be true before startPublicSale is called. bool public addressReferencesSet = false; // CURVE_POOL_ADDRESS holds the address of the curve pool that we use to exchange ETH for stETH. address constant CURVE_POOL_ADDRESS = 0xDC24316b9AE028F1497c275EB9192a3Ea0f67022; // LIDO_STAKING_ADDRESS holds the address of the Lido staking contract that we also can use to // exchange ETH for stETH. address constant LIDO_STAKING_ADDRESS = 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84; IIdolMain public idolMain; IIdolMarketplace public idolMarketplace; ICurvePool public immutable stethPool; ERC20 public immutable steth; OfferingRefundContract public immutable offeringRefundContract; event PublicSaleStart( uint256 indexed _saleDuration, uint256 indexed _saleStartTime ); event PublicSalePaused( uint256 indexed _currentPrice, uint256 indexed _timeElapsed ); event PublicSaleResumed( uint256 indexed _saleResumeTime ); event IdolsMinted( address indexed _minter, uint256 indexed _mintPrice, uint256 indexed _numMinted ); /** @notice IdolMintContract's constructor takes in two hashes, one of which represents the hash of the Idol NFT metadata, and one of which is the hash of some discord-community-generated input. The two hashes are used to calculate the godIdOffset, which specifies which ID from 0-10000 to start minting at. @param _metadataHash The hash of the master metadata file which corresponds to the 10k Idol NFT images that have been uploaded. @param _discordGeneratedHash The hash of some discord-community-generated input which is used to effectively randomize the value of godIdOffset prior to the start of the mint. @param _stethAddress The address of the stETH ERC20 contract. @param _offeringRefundContractAddress The address of the OfferingRefundContract we will be sending refunds to. */ constructor( string memory _metadataHash, string memory _discordGeneratedHash, address _stethAddress, address payable _offeringRefundContractAddress ) { godIdOffset = uint256(keccak256(abi.encodePacked(_metadataHash, _discordGeneratedHash))) % MAX_GODS_TO_MINT; stethPool = ICurvePool(CURVE_POOL_ADDRESS); steth = ERC20(_stethAddress); offeringRefundContract = OfferingRefundContract(_offeringRefundContractAddress); } /** @notice startPublicSale is called to start the dutch auction for minting Gods to the public. @param _saleDuration The duration of the sale, in seconds, before reaching the minimum minting price. @param _saleStartPrice The initial minting price, which progressively lowers as the dutch auction progresses. @param _saleEndPrice Lower bound for the minting price, once the full duration of the dutch auction has elapsed. */ function startPublicSale(uint256 _saleDuration, uint256 _saleStartPrice, uint256 _saleEndPrice) external onlyOwner beforePublicSaleStarted { require(_saleStartPrice > _saleEndPrice, "_saleStartPrice must be greater than _saleEndPrice"); require(addressReferencesSet, "External reference contracts must all be set before public sale starts"); publicSaleDuration = _saleDuration; publicSaleGodStartingPrice = _saleStartPrice; publicSaleGodEndingPrice = _saleEndPrice; publicSaleStartTime = block.timestamp; publicSaleStarted = true; emit PublicSaleStart(_saleDuration, publicSaleStartTime); } /** @notice setAddressReferences sets references to the main, marketplace, and virtueToken addresses so that the contracts all know about each other. This is all done from the mint contract so that the addresses will no longer be updateable once the mint event has started. @param _idolMainAddress The address of IdolMain. @param _idolMarketplaceAddress The address of the marketplace. @param _virtueTokenAddress The address of the VIRTUE token ERC20 contract. */ function setAddressReferences( address _idolMainAddress, address _idolMarketplaceAddress, address _virtueTokenAddress ) external onlyOwner beforePublicSaleStarted { addressReferencesSet = true; idolMain = IIdolMain(_idolMainAddress); require(steth.approve(_idolMainAddress, 2**255-1)); idolMarketplace = IIdolMarketplace(_idolMarketplaceAddress); idolMain.setVirtueTokenAddr(_virtueTokenAddress); idolMain.setIdolMarketplaceAddr(_idolMarketplaceAddress); idolMarketplace.setVirtueTokenAddr(_virtueTokenAddress); } /** @notice pausePublicSale is called to pause the progression of the mint event. In happy-path circumstances we shouldn't need to call this, but it is included as a precaution in case something goes wrong during the mint. */ function pausePublicSale() external onlyOwner whenPublicSaleActive { uint256 currentSalePrice = getMintPrice(); uint256 elapsedTime = getElapsedSaleTime(); publicSalePausedElapsedTime = elapsedTime; publicSalePaused = true; emit PublicSalePaused(currentSalePrice, elapsedTime); } function resumePublicSale() external onlyOwner { require(publicSalePaused, "Can only resume when the sale is paused"); publicSalePaused = false; publicSaleStartTime = block.timestamp - publicSalePausedElapsedTime; emit PublicSaleResumed(block.timestamp); } /** @notice getElaspedSaleTime is a view function that tells us how many seconds have elapsed since the public sale was started. */ function getElapsedSaleTime() internal view returns (uint256) { if (publicSalePaused) { return publicSalePausedElapsedTime; } return publicSaleStartTime > 0 ? block.timestamp - publicSaleStartTime : 0; } /** @notice getRemainingSaleTime is a view function that tells us how many seconds are remaining before the dutch auction hits the minimum price. */ function getRemainingSaleTime() external view returns (uint256) { if (publicSaleStartTime == 0) { // If the public sale has not been started, we just return 1 week as a placeholder. return 604800; } if (publicSalePaused) { return publicSaleDuration - publicSalePausedElapsedTime; } if (getElapsedSaleTime() >= publicSaleDuration) { return 0; } return (publicSaleStartTime + publicSaleDuration) - block.timestamp; } /** @notice getMintPrice returns the price to mint a God at the current time in the dutch auction. */ function getMintPrice() public view returns (uint256) { if (!publicSaleStarted) { return 0; } uint256 elapsed = getElapsedSaleTime(); if (elapsed >= publicSaleDuration) { return publicSaleGodEndingPrice; } else { int256 tempPrice = int256(publicSaleGodStartingPrice) + ((int256(publicSaleGodEndingPrice) - int256(publicSaleGodStartingPrice)) / int256(publicSaleDuration)) * int256(elapsed); uint256 currentPrice = uint256(tempPrice); return currentPrice > publicSaleGodEndingPrice ? currentPrice : publicSaleGodEndingPrice; } } /** @notice mintGods is a payable function which allows the sender to pay ETH to mint God NFTs at the current price specified by getMintPrice. @param _numGodsToMint The number of gods to be minted, which is capped at a maximum of 5 Gods per transaction. */ function mintGods(uint256 _numGodsToMint) external payable whenPublicSaleActive nonReentrant { require( publicGodsMinted + _numGodsToMint <= MAX_GODS_TO_MINT - NUM_RESERVED_NFTS, "Minting would exceed max supply" ); require(_numGodsToMint > 0, "Must mint at least one god"); require( idolMain.balanceOf(msg.sender) + _numGodsToMint <= MAX_GODS_PER_ADDRESS, "Requested number would exceed the maximum number of gods allowed to be minted for this address." ); uint256 individualCostToMint = getMintPrice(); uint256 costToMint = individualCostToMint * _numGodsToMint; require(costToMint <= msg.value, "Ether value sent is not correct"); for (uint256 i = 0; i < _numGodsToMint; i++) { uint idToMint = (publicGodsMinted + i + godIdOffset) % MAX_GODS_TO_MINT; idolMain.mint(msg.sender, idToMint, false); } publicGodsMinted += _numGodsToMint; if (msg.value > costToMint) { Address.sendValue(payable(msg.sender), msg.value - costToMint); } emit IdolsMinted(msg.sender, individualCostToMint, _numGodsToMint); } /** @notice mintReservedGods is used by the contract owner to mint a reserved pool of 1000 Gods for owners and supporters of the protocol. @param _numGodsToMint The number of Gods to mint in this transaction. @param _mintAddress The address to mint the reserved Gods for. @param _lock If true, specifies that the minted reserved Gods cannot be sold or transferred for the first year of the protocol's existence. */ function mintReservedGods(uint256 _numGodsToMint, address _mintAddress, bool _lock) external onlyOwner nonReentrant { require( reservedGodsMinted + _numGodsToMint < NUM_RESERVED_NFTS, "Minting would exceed max reserved supply" ); require(_numGodsToMint > 0, "Must mint at least one god"); for (uint256 i = 0; i < _numGodsToMint; i++) { uint idToMint = (reservedGodsMinted + i + godIdOffset + MAX_GODS_TO_MINT - NUM_RESERVED_NFTS) % MAX_GODS_TO_MINT; idolMain.mint(_mintAddress, idToMint, _lock); } reservedGodsMinted += _numGodsToMint; } /** @notice sendToOfferingRefundContract sends ETH to the OfferingRefundContract so that it can be distributed to the addresses that are eligible for a refund. */ function sendToOfferingRefundContract(uint _totalRefundAmount) onlyOwner external nonReentrant { Address.sendValue(payable(address(offeringRefundContract)), _totalRefundAmount); } /** @notice swap is used to swap the contract's ETH into stETH via Curve. @param _slippageBps The acceptable slippage percent, in basis points. */ function swap(uint _slippageBps) onlyOwner external returns(uint result) { return stethPool.exchange{ value: address(this).balance }(0, 1, address(this).balance, address(this).balance * _slippageBps / 10000); } function swapLido(uint _slippageBps) onlyOwner external { uint minSteth = steth.balanceOf(address(this)) + address(this).balance * _slippageBps / 10000; Address.sendValue(payable(LIDO_STAKING_ADDRESS), address(this).balance); require(steth.balanceOf(address(this)) >= minSteth, "steth balance not high enough after sending to LIDO_STAKING_ADDRESS"); } /** @notice depositStethIdolMain deposits all of this contract's stETH into the IdolMain contract. */ function depositStethIdolMain() onlyOwner external { idolMain.depositSteth(steth.balanceOf(address(this))); } /** @notice getTotalMinted returns the total number of public + reserved God NFTs minted. */ function getTotalMinted() external view returns (uint) { return reservedGodsMinted + publicGodsMinted; } /** @notice setBaseURI sets the baseURI for the God NFTs. */ function setBaseURI(string memory uri) external onlyOwner { idolMain.setBaseURI(uri); } /** @notice Tears down the contract and allocates any remaining funds to the original contract owner. Should only be called after the mint completes and the contract's balance has been converted to Steth and deposited into IdolMain, or in a disaster scenario where we need to tear down the contract and refund minting fees. */ function tearDown() external onlyOwner { selfdestruct(payable(owner())); } modifier beforePublicSaleStarted { require(!publicSaleStarted, "Public sale has already started"); _; } modifier whenPublicSaleActive { require(publicSaleStarted && !publicSalePaused, "Public sale is not active"); _; } }
/** @notice IdolMintContract is a contract used for the initial mint of the God NFTs. It allocates 90% of the Gods for public minting through a dutch auction protocol, and reserves 10% of the Gods for the creators of the protocol as well as other supporters and stakeholders. IdolMintContract is intended to be torn down once the mint event has completed and once its balance has been deposited into the IdolMain rewards protocol. */
NatSpecMultiLine
mintReservedGods
function mintReservedGods(uint256 _numGodsToMint, address _mintAddress, bool _lock) external onlyOwner nonReentrant { require( reservedGodsMinted + _numGodsToMint < NUM_RESERVED_NFTS, "Minting would exceed max reserved supply" ); require(_numGodsToMint > 0, "Must mint at least one god"); for (uint256 i = 0; i < _numGodsToMint; i++) { uint idToMint = (reservedGodsMinted + i + godIdOffset + MAX_GODS_TO_MINT - NUM_RESERVED_NFTS) % MAX_GODS_TO_MINT; idolMain.mint(_mintAddress, idToMint, _lock); } reservedGodsMinted += _numGodsToMint; }
/** @notice mintReservedGods is used by the contract owner to mint a reserved pool of 1000 Gods for owners and supporters of the protocol. @param _numGodsToMint The number of Gods to mint in this transaction. @param _mintAddress The address to mint the reserved Gods for. @param _lock If true, specifies that the minted reserved Gods cannot be sold or transferred for the first year of the protocol's existence. */
NatSpecMultiLine
v0.8.9+commit.e5eed63a
{ "func_code_index": [ 11282, 11886 ] }
11,811
IdolMintContract
contracts/IdolMintContract.sol
0x7b4b02372d8e54c1c0454d97f01d85ef203cdc5e
Solidity
IdolMintContract
contract IdolMintContract is Ownable, ReentrancyGuard { // publicGodsMinted tracks the number of Gods that have been minted by the public through the // mintGods function. uint public publicGodsMinted; // reservedGodsMinted tracks the number of reserved Gods that have been minted through the // mintReservedGods function. uint public reservedGodsMinted; // MAX_GODS_TO_MINT specifies the maximum number of Gods that can be minted (both public and // reserved.) uint public constant MAX_GODS_TO_MINT = 10000; // MAX_GODS_PER_ADDRESS specifies the maximum number of Gods that a single address can mint. uint public constant MAX_GODS_PER_ADDRESS = 20; // NUM_RESERVED_NFTS specifies the maximum number of Gods that can be minted through the // mintReservedGods function. uint public constant NUM_RESERVED_NFTS = 1000; // publicSaleDuration specifies the length of the dutch auction (in seconds) before the minting // price hits publicSaleGodEndingPrice. uint256 public publicSaleDuration; // publicSaleStartTime tracks the time (as a UNIX timestamp) when the public sale was started. uint256 public publicSaleStartTime; // publicSaleGodStartingPrice specifies the price that the dutch auction mint should start at. uint256 public publicSaleGodStartingPrice; // publicSaleGodEndingPrice specifies the minimum price that Gods can be minted at once the // full duration of the dutch auction has elapsed. uint256 public publicSaleGodEndingPrice; // publicSaleStarted specifies whether the minting event has been started. bool public publicSaleStarted = false; // publicSalePaused specifies whether the minting event has been paused. bool public publicSalePaused = false; // publicSalePausedElapsedTime specifies, if the sale was paused, what the elapsed sale // time was at the time of pausing. uint256 public publicSalePausedElapsedTime; // godIdOffset is pseudo-random offset from 0-10000 generated when the contract is constructed // and used to assign god IDs for each mint. uint256 public immutable godIdOffset; // addressReferencesSet is a boolean flag which tracks that the proper setup functions for the // contract have been run. It must be true before startPublicSale is called. bool public addressReferencesSet = false; // CURVE_POOL_ADDRESS holds the address of the curve pool that we use to exchange ETH for stETH. address constant CURVE_POOL_ADDRESS = 0xDC24316b9AE028F1497c275EB9192a3Ea0f67022; // LIDO_STAKING_ADDRESS holds the address of the Lido staking contract that we also can use to // exchange ETH for stETH. address constant LIDO_STAKING_ADDRESS = 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84; IIdolMain public idolMain; IIdolMarketplace public idolMarketplace; ICurvePool public immutable stethPool; ERC20 public immutable steth; OfferingRefundContract public immutable offeringRefundContract; event PublicSaleStart( uint256 indexed _saleDuration, uint256 indexed _saleStartTime ); event PublicSalePaused( uint256 indexed _currentPrice, uint256 indexed _timeElapsed ); event PublicSaleResumed( uint256 indexed _saleResumeTime ); event IdolsMinted( address indexed _minter, uint256 indexed _mintPrice, uint256 indexed _numMinted ); /** @notice IdolMintContract's constructor takes in two hashes, one of which represents the hash of the Idol NFT metadata, and one of which is the hash of some discord-community-generated input. The two hashes are used to calculate the godIdOffset, which specifies which ID from 0-10000 to start minting at. @param _metadataHash The hash of the master metadata file which corresponds to the 10k Idol NFT images that have been uploaded. @param _discordGeneratedHash The hash of some discord-community-generated input which is used to effectively randomize the value of godIdOffset prior to the start of the mint. @param _stethAddress The address of the stETH ERC20 contract. @param _offeringRefundContractAddress The address of the OfferingRefundContract we will be sending refunds to. */ constructor( string memory _metadataHash, string memory _discordGeneratedHash, address _stethAddress, address payable _offeringRefundContractAddress ) { godIdOffset = uint256(keccak256(abi.encodePacked(_metadataHash, _discordGeneratedHash))) % MAX_GODS_TO_MINT; stethPool = ICurvePool(CURVE_POOL_ADDRESS); steth = ERC20(_stethAddress); offeringRefundContract = OfferingRefundContract(_offeringRefundContractAddress); } /** @notice startPublicSale is called to start the dutch auction for minting Gods to the public. @param _saleDuration The duration of the sale, in seconds, before reaching the minimum minting price. @param _saleStartPrice The initial minting price, which progressively lowers as the dutch auction progresses. @param _saleEndPrice Lower bound for the minting price, once the full duration of the dutch auction has elapsed. */ function startPublicSale(uint256 _saleDuration, uint256 _saleStartPrice, uint256 _saleEndPrice) external onlyOwner beforePublicSaleStarted { require(_saleStartPrice > _saleEndPrice, "_saleStartPrice must be greater than _saleEndPrice"); require(addressReferencesSet, "External reference contracts must all be set before public sale starts"); publicSaleDuration = _saleDuration; publicSaleGodStartingPrice = _saleStartPrice; publicSaleGodEndingPrice = _saleEndPrice; publicSaleStartTime = block.timestamp; publicSaleStarted = true; emit PublicSaleStart(_saleDuration, publicSaleStartTime); } /** @notice setAddressReferences sets references to the main, marketplace, and virtueToken addresses so that the contracts all know about each other. This is all done from the mint contract so that the addresses will no longer be updateable once the mint event has started. @param _idolMainAddress The address of IdolMain. @param _idolMarketplaceAddress The address of the marketplace. @param _virtueTokenAddress The address of the VIRTUE token ERC20 contract. */ function setAddressReferences( address _idolMainAddress, address _idolMarketplaceAddress, address _virtueTokenAddress ) external onlyOwner beforePublicSaleStarted { addressReferencesSet = true; idolMain = IIdolMain(_idolMainAddress); require(steth.approve(_idolMainAddress, 2**255-1)); idolMarketplace = IIdolMarketplace(_idolMarketplaceAddress); idolMain.setVirtueTokenAddr(_virtueTokenAddress); idolMain.setIdolMarketplaceAddr(_idolMarketplaceAddress); idolMarketplace.setVirtueTokenAddr(_virtueTokenAddress); } /** @notice pausePublicSale is called to pause the progression of the mint event. In happy-path circumstances we shouldn't need to call this, but it is included as a precaution in case something goes wrong during the mint. */ function pausePublicSale() external onlyOwner whenPublicSaleActive { uint256 currentSalePrice = getMintPrice(); uint256 elapsedTime = getElapsedSaleTime(); publicSalePausedElapsedTime = elapsedTime; publicSalePaused = true; emit PublicSalePaused(currentSalePrice, elapsedTime); } function resumePublicSale() external onlyOwner { require(publicSalePaused, "Can only resume when the sale is paused"); publicSalePaused = false; publicSaleStartTime = block.timestamp - publicSalePausedElapsedTime; emit PublicSaleResumed(block.timestamp); } /** @notice getElaspedSaleTime is a view function that tells us how many seconds have elapsed since the public sale was started. */ function getElapsedSaleTime() internal view returns (uint256) { if (publicSalePaused) { return publicSalePausedElapsedTime; } return publicSaleStartTime > 0 ? block.timestamp - publicSaleStartTime : 0; } /** @notice getRemainingSaleTime is a view function that tells us how many seconds are remaining before the dutch auction hits the minimum price. */ function getRemainingSaleTime() external view returns (uint256) { if (publicSaleStartTime == 0) { // If the public sale has not been started, we just return 1 week as a placeholder. return 604800; } if (publicSalePaused) { return publicSaleDuration - publicSalePausedElapsedTime; } if (getElapsedSaleTime() >= publicSaleDuration) { return 0; } return (publicSaleStartTime + publicSaleDuration) - block.timestamp; } /** @notice getMintPrice returns the price to mint a God at the current time in the dutch auction. */ function getMintPrice() public view returns (uint256) { if (!publicSaleStarted) { return 0; } uint256 elapsed = getElapsedSaleTime(); if (elapsed >= publicSaleDuration) { return publicSaleGodEndingPrice; } else { int256 tempPrice = int256(publicSaleGodStartingPrice) + ((int256(publicSaleGodEndingPrice) - int256(publicSaleGodStartingPrice)) / int256(publicSaleDuration)) * int256(elapsed); uint256 currentPrice = uint256(tempPrice); return currentPrice > publicSaleGodEndingPrice ? currentPrice : publicSaleGodEndingPrice; } } /** @notice mintGods is a payable function which allows the sender to pay ETH to mint God NFTs at the current price specified by getMintPrice. @param _numGodsToMint The number of gods to be minted, which is capped at a maximum of 5 Gods per transaction. */ function mintGods(uint256 _numGodsToMint) external payable whenPublicSaleActive nonReentrant { require( publicGodsMinted + _numGodsToMint <= MAX_GODS_TO_MINT - NUM_RESERVED_NFTS, "Minting would exceed max supply" ); require(_numGodsToMint > 0, "Must mint at least one god"); require( idolMain.balanceOf(msg.sender) + _numGodsToMint <= MAX_GODS_PER_ADDRESS, "Requested number would exceed the maximum number of gods allowed to be minted for this address." ); uint256 individualCostToMint = getMintPrice(); uint256 costToMint = individualCostToMint * _numGodsToMint; require(costToMint <= msg.value, "Ether value sent is not correct"); for (uint256 i = 0; i < _numGodsToMint; i++) { uint idToMint = (publicGodsMinted + i + godIdOffset) % MAX_GODS_TO_MINT; idolMain.mint(msg.sender, idToMint, false); } publicGodsMinted += _numGodsToMint; if (msg.value > costToMint) { Address.sendValue(payable(msg.sender), msg.value - costToMint); } emit IdolsMinted(msg.sender, individualCostToMint, _numGodsToMint); } /** @notice mintReservedGods is used by the contract owner to mint a reserved pool of 1000 Gods for owners and supporters of the protocol. @param _numGodsToMint The number of Gods to mint in this transaction. @param _mintAddress The address to mint the reserved Gods for. @param _lock If true, specifies that the minted reserved Gods cannot be sold or transferred for the first year of the protocol's existence. */ function mintReservedGods(uint256 _numGodsToMint, address _mintAddress, bool _lock) external onlyOwner nonReentrant { require( reservedGodsMinted + _numGodsToMint < NUM_RESERVED_NFTS, "Minting would exceed max reserved supply" ); require(_numGodsToMint > 0, "Must mint at least one god"); for (uint256 i = 0; i < _numGodsToMint; i++) { uint idToMint = (reservedGodsMinted + i + godIdOffset + MAX_GODS_TO_MINT - NUM_RESERVED_NFTS) % MAX_GODS_TO_MINT; idolMain.mint(_mintAddress, idToMint, _lock); } reservedGodsMinted += _numGodsToMint; } /** @notice sendToOfferingRefundContract sends ETH to the OfferingRefundContract so that it can be distributed to the addresses that are eligible for a refund. */ function sendToOfferingRefundContract(uint _totalRefundAmount) onlyOwner external nonReentrant { Address.sendValue(payable(address(offeringRefundContract)), _totalRefundAmount); } /** @notice swap is used to swap the contract's ETH into stETH via Curve. @param _slippageBps The acceptable slippage percent, in basis points. */ function swap(uint _slippageBps) onlyOwner external returns(uint result) { return stethPool.exchange{ value: address(this).balance }(0, 1, address(this).balance, address(this).balance * _slippageBps / 10000); } function swapLido(uint _slippageBps) onlyOwner external { uint minSteth = steth.balanceOf(address(this)) + address(this).balance * _slippageBps / 10000; Address.sendValue(payable(LIDO_STAKING_ADDRESS), address(this).balance); require(steth.balanceOf(address(this)) >= minSteth, "steth balance not high enough after sending to LIDO_STAKING_ADDRESS"); } /** @notice depositStethIdolMain deposits all of this contract's stETH into the IdolMain contract. */ function depositStethIdolMain() onlyOwner external { idolMain.depositSteth(steth.balanceOf(address(this))); } /** @notice getTotalMinted returns the total number of public + reserved God NFTs minted. */ function getTotalMinted() external view returns (uint) { return reservedGodsMinted + publicGodsMinted; } /** @notice setBaseURI sets the baseURI for the God NFTs. */ function setBaseURI(string memory uri) external onlyOwner { idolMain.setBaseURI(uri); } /** @notice Tears down the contract and allocates any remaining funds to the original contract owner. Should only be called after the mint completes and the contract's balance has been converted to Steth and deposited into IdolMain, or in a disaster scenario where we need to tear down the contract and refund minting fees. */ function tearDown() external onlyOwner { selfdestruct(payable(owner())); } modifier beforePublicSaleStarted { require(!publicSaleStarted, "Public sale has already started"); _; } modifier whenPublicSaleActive { require(publicSaleStarted && !publicSalePaused, "Public sale is not active"); _; } }
/** @notice IdolMintContract is a contract used for the initial mint of the God NFTs. It allocates 90% of the Gods for public minting through a dutch auction protocol, and reserves 10% of the Gods for the creators of the protocol as well as other supporters and stakeholders. IdolMintContract is intended to be torn down once the mint event has completed and once its balance has been deposited into the IdolMain rewards protocol. */
NatSpecMultiLine
sendToOfferingRefundContract
function sendToOfferingRefundContract(uint _totalRefundAmount) onlyOwner external nonReentrant { Address.sendValue(payable(address(offeringRefundContract)), _totalRefundAmount); }
/** @notice sendToOfferingRefundContract sends ETH to the OfferingRefundContract so that it can be distributed to the addresses that are eligible for a refund. */
NatSpecMultiLine
v0.8.9+commit.e5eed63a
{ "func_code_index": [ 12065, 12252 ] }
11,812
IdolMintContract
contracts/IdolMintContract.sol
0x7b4b02372d8e54c1c0454d97f01d85ef203cdc5e
Solidity
IdolMintContract
contract IdolMintContract is Ownable, ReentrancyGuard { // publicGodsMinted tracks the number of Gods that have been minted by the public through the // mintGods function. uint public publicGodsMinted; // reservedGodsMinted tracks the number of reserved Gods that have been minted through the // mintReservedGods function. uint public reservedGodsMinted; // MAX_GODS_TO_MINT specifies the maximum number of Gods that can be minted (both public and // reserved.) uint public constant MAX_GODS_TO_MINT = 10000; // MAX_GODS_PER_ADDRESS specifies the maximum number of Gods that a single address can mint. uint public constant MAX_GODS_PER_ADDRESS = 20; // NUM_RESERVED_NFTS specifies the maximum number of Gods that can be minted through the // mintReservedGods function. uint public constant NUM_RESERVED_NFTS = 1000; // publicSaleDuration specifies the length of the dutch auction (in seconds) before the minting // price hits publicSaleGodEndingPrice. uint256 public publicSaleDuration; // publicSaleStartTime tracks the time (as a UNIX timestamp) when the public sale was started. uint256 public publicSaleStartTime; // publicSaleGodStartingPrice specifies the price that the dutch auction mint should start at. uint256 public publicSaleGodStartingPrice; // publicSaleGodEndingPrice specifies the minimum price that Gods can be minted at once the // full duration of the dutch auction has elapsed. uint256 public publicSaleGodEndingPrice; // publicSaleStarted specifies whether the minting event has been started. bool public publicSaleStarted = false; // publicSalePaused specifies whether the minting event has been paused. bool public publicSalePaused = false; // publicSalePausedElapsedTime specifies, if the sale was paused, what the elapsed sale // time was at the time of pausing. uint256 public publicSalePausedElapsedTime; // godIdOffset is pseudo-random offset from 0-10000 generated when the contract is constructed // and used to assign god IDs for each mint. uint256 public immutable godIdOffset; // addressReferencesSet is a boolean flag which tracks that the proper setup functions for the // contract have been run. It must be true before startPublicSale is called. bool public addressReferencesSet = false; // CURVE_POOL_ADDRESS holds the address of the curve pool that we use to exchange ETH for stETH. address constant CURVE_POOL_ADDRESS = 0xDC24316b9AE028F1497c275EB9192a3Ea0f67022; // LIDO_STAKING_ADDRESS holds the address of the Lido staking contract that we also can use to // exchange ETH for stETH. address constant LIDO_STAKING_ADDRESS = 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84; IIdolMain public idolMain; IIdolMarketplace public idolMarketplace; ICurvePool public immutable stethPool; ERC20 public immutable steth; OfferingRefundContract public immutable offeringRefundContract; event PublicSaleStart( uint256 indexed _saleDuration, uint256 indexed _saleStartTime ); event PublicSalePaused( uint256 indexed _currentPrice, uint256 indexed _timeElapsed ); event PublicSaleResumed( uint256 indexed _saleResumeTime ); event IdolsMinted( address indexed _minter, uint256 indexed _mintPrice, uint256 indexed _numMinted ); /** @notice IdolMintContract's constructor takes in two hashes, one of which represents the hash of the Idol NFT metadata, and one of which is the hash of some discord-community-generated input. The two hashes are used to calculate the godIdOffset, which specifies which ID from 0-10000 to start minting at. @param _metadataHash The hash of the master metadata file which corresponds to the 10k Idol NFT images that have been uploaded. @param _discordGeneratedHash The hash of some discord-community-generated input which is used to effectively randomize the value of godIdOffset prior to the start of the mint. @param _stethAddress The address of the stETH ERC20 contract. @param _offeringRefundContractAddress The address of the OfferingRefundContract we will be sending refunds to. */ constructor( string memory _metadataHash, string memory _discordGeneratedHash, address _stethAddress, address payable _offeringRefundContractAddress ) { godIdOffset = uint256(keccak256(abi.encodePacked(_metadataHash, _discordGeneratedHash))) % MAX_GODS_TO_MINT; stethPool = ICurvePool(CURVE_POOL_ADDRESS); steth = ERC20(_stethAddress); offeringRefundContract = OfferingRefundContract(_offeringRefundContractAddress); } /** @notice startPublicSale is called to start the dutch auction for minting Gods to the public. @param _saleDuration The duration of the sale, in seconds, before reaching the minimum minting price. @param _saleStartPrice The initial minting price, which progressively lowers as the dutch auction progresses. @param _saleEndPrice Lower bound for the minting price, once the full duration of the dutch auction has elapsed. */ function startPublicSale(uint256 _saleDuration, uint256 _saleStartPrice, uint256 _saleEndPrice) external onlyOwner beforePublicSaleStarted { require(_saleStartPrice > _saleEndPrice, "_saleStartPrice must be greater than _saleEndPrice"); require(addressReferencesSet, "External reference contracts must all be set before public sale starts"); publicSaleDuration = _saleDuration; publicSaleGodStartingPrice = _saleStartPrice; publicSaleGodEndingPrice = _saleEndPrice; publicSaleStartTime = block.timestamp; publicSaleStarted = true; emit PublicSaleStart(_saleDuration, publicSaleStartTime); } /** @notice setAddressReferences sets references to the main, marketplace, and virtueToken addresses so that the contracts all know about each other. This is all done from the mint contract so that the addresses will no longer be updateable once the mint event has started. @param _idolMainAddress The address of IdolMain. @param _idolMarketplaceAddress The address of the marketplace. @param _virtueTokenAddress The address of the VIRTUE token ERC20 contract. */ function setAddressReferences( address _idolMainAddress, address _idolMarketplaceAddress, address _virtueTokenAddress ) external onlyOwner beforePublicSaleStarted { addressReferencesSet = true; idolMain = IIdolMain(_idolMainAddress); require(steth.approve(_idolMainAddress, 2**255-1)); idolMarketplace = IIdolMarketplace(_idolMarketplaceAddress); idolMain.setVirtueTokenAddr(_virtueTokenAddress); idolMain.setIdolMarketplaceAddr(_idolMarketplaceAddress); idolMarketplace.setVirtueTokenAddr(_virtueTokenAddress); } /** @notice pausePublicSale is called to pause the progression of the mint event. In happy-path circumstances we shouldn't need to call this, but it is included as a precaution in case something goes wrong during the mint. */ function pausePublicSale() external onlyOwner whenPublicSaleActive { uint256 currentSalePrice = getMintPrice(); uint256 elapsedTime = getElapsedSaleTime(); publicSalePausedElapsedTime = elapsedTime; publicSalePaused = true; emit PublicSalePaused(currentSalePrice, elapsedTime); } function resumePublicSale() external onlyOwner { require(publicSalePaused, "Can only resume when the sale is paused"); publicSalePaused = false; publicSaleStartTime = block.timestamp - publicSalePausedElapsedTime; emit PublicSaleResumed(block.timestamp); } /** @notice getElaspedSaleTime is a view function that tells us how many seconds have elapsed since the public sale was started. */ function getElapsedSaleTime() internal view returns (uint256) { if (publicSalePaused) { return publicSalePausedElapsedTime; } return publicSaleStartTime > 0 ? block.timestamp - publicSaleStartTime : 0; } /** @notice getRemainingSaleTime is a view function that tells us how many seconds are remaining before the dutch auction hits the minimum price. */ function getRemainingSaleTime() external view returns (uint256) { if (publicSaleStartTime == 0) { // If the public sale has not been started, we just return 1 week as a placeholder. return 604800; } if (publicSalePaused) { return publicSaleDuration - publicSalePausedElapsedTime; } if (getElapsedSaleTime() >= publicSaleDuration) { return 0; } return (publicSaleStartTime + publicSaleDuration) - block.timestamp; } /** @notice getMintPrice returns the price to mint a God at the current time in the dutch auction. */ function getMintPrice() public view returns (uint256) { if (!publicSaleStarted) { return 0; } uint256 elapsed = getElapsedSaleTime(); if (elapsed >= publicSaleDuration) { return publicSaleGodEndingPrice; } else { int256 tempPrice = int256(publicSaleGodStartingPrice) + ((int256(publicSaleGodEndingPrice) - int256(publicSaleGodStartingPrice)) / int256(publicSaleDuration)) * int256(elapsed); uint256 currentPrice = uint256(tempPrice); return currentPrice > publicSaleGodEndingPrice ? currentPrice : publicSaleGodEndingPrice; } } /** @notice mintGods is a payable function which allows the sender to pay ETH to mint God NFTs at the current price specified by getMintPrice. @param _numGodsToMint The number of gods to be minted, which is capped at a maximum of 5 Gods per transaction. */ function mintGods(uint256 _numGodsToMint) external payable whenPublicSaleActive nonReentrant { require( publicGodsMinted + _numGodsToMint <= MAX_GODS_TO_MINT - NUM_RESERVED_NFTS, "Minting would exceed max supply" ); require(_numGodsToMint > 0, "Must mint at least one god"); require( idolMain.balanceOf(msg.sender) + _numGodsToMint <= MAX_GODS_PER_ADDRESS, "Requested number would exceed the maximum number of gods allowed to be minted for this address." ); uint256 individualCostToMint = getMintPrice(); uint256 costToMint = individualCostToMint * _numGodsToMint; require(costToMint <= msg.value, "Ether value sent is not correct"); for (uint256 i = 0; i < _numGodsToMint; i++) { uint idToMint = (publicGodsMinted + i + godIdOffset) % MAX_GODS_TO_MINT; idolMain.mint(msg.sender, idToMint, false); } publicGodsMinted += _numGodsToMint; if (msg.value > costToMint) { Address.sendValue(payable(msg.sender), msg.value - costToMint); } emit IdolsMinted(msg.sender, individualCostToMint, _numGodsToMint); } /** @notice mintReservedGods is used by the contract owner to mint a reserved pool of 1000 Gods for owners and supporters of the protocol. @param _numGodsToMint The number of Gods to mint in this transaction. @param _mintAddress The address to mint the reserved Gods for. @param _lock If true, specifies that the minted reserved Gods cannot be sold or transferred for the first year of the protocol's existence. */ function mintReservedGods(uint256 _numGodsToMint, address _mintAddress, bool _lock) external onlyOwner nonReentrant { require( reservedGodsMinted + _numGodsToMint < NUM_RESERVED_NFTS, "Minting would exceed max reserved supply" ); require(_numGodsToMint > 0, "Must mint at least one god"); for (uint256 i = 0; i < _numGodsToMint; i++) { uint idToMint = (reservedGodsMinted + i + godIdOffset + MAX_GODS_TO_MINT - NUM_RESERVED_NFTS) % MAX_GODS_TO_MINT; idolMain.mint(_mintAddress, idToMint, _lock); } reservedGodsMinted += _numGodsToMint; } /** @notice sendToOfferingRefundContract sends ETH to the OfferingRefundContract so that it can be distributed to the addresses that are eligible for a refund. */ function sendToOfferingRefundContract(uint _totalRefundAmount) onlyOwner external nonReentrant { Address.sendValue(payable(address(offeringRefundContract)), _totalRefundAmount); } /** @notice swap is used to swap the contract's ETH into stETH via Curve. @param _slippageBps The acceptable slippage percent, in basis points. */ function swap(uint _slippageBps) onlyOwner external returns(uint result) { return stethPool.exchange{ value: address(this).balance }(0, 1, address(this).balance, address(this).balance * _slippageBps / 10000); } function swapLido(uint _slippageBps) onlyOwner external { uint minSteth = steth.balanceOf(address(this)) + address(this).balance * _slippageBps / 10000; Address.sendValue(payable(LIDO_STAKING_ADDRESS), address(this).balance); require(steth.balanceOf(address(this)) >= minSteth, "steth balance not high enough after sending to LIDO_STAKING_ADDRESS"); } /** @notice depositStethIdolMain deposits all of this contract's stETH into the IdolMain contract. */ function depositStethIdolMain() onlyOwner external { idolMain.depositSteth(steth.balanceOf(address(this))); } /** @notice getTotalMinted returns the total number of public + reserved God NFTs minted. */ function getTotalMinted() external view returns (uint) { return reservedGodsMinted + publicGodsMinted; } /** @notice setBaseURI sets the baseURI for the God NFTs. */ function setBaseURI(string memory uri) external onlyOwner { idolMain.setBaseURI(uri); } /** @notice Tears down the contract and allocates any remaining funds to the original contract owner. Should only be called after the mint completes and the contract's balance has been converted to Steth and deposited into IdolMain, or in a disaster scenario where we need to tear down the contract and refund minting fees. */ function tearDown() external onlyOwner { selfdestruct(payable(owner())); } modifier beforePublicSaleStarted { require(!publicSaleStarted, "Public sale has already started"); _; } modifier whenPublicSaleActive { require(publicSaleStarted && !publicSalePaused, "Public sale is not active"); _; } }
/** @notice IdolMintContract is a contract used for the initial mint of the God NFTs. It allocates 90% of the Gods for public minting through a dutch auction protocol, and reserves 10% of the Gods for the creators of the protocol as well as other supporters and stakeholders. IdolMintContract is intended to be torn down once the mint event has completed and once its balance has been deposited into the IdolMain rewards protocol. */
NatSpecMultiLine
swap
function swap(uint _slippageBps) onlyOwner external returns(uint result) { return stethPool.exchange{ value: address(this).balance }(0, 1, address(this).balance, address(this).balance * _slippageBps / 10000); }
/** @notice swap is used to swap the contract's ETH into stETH via Curve. @param _slippageBps The acceptable slippage percent, in basis points. */
NatSpecMultiLine
v0.8.9+commit.e5eed63a
{ "func_code_index": [ 12414, 12646 ] }
11,813
IdolMintContract
contracts/IdolMintContract.sol
0x7b4b02372d8e54c1c0454d97f01d85ef203cdc5e
Solidity
IdolMintContract
contract IdolMintContract is Ownable, ReentrancyGuard { // publicGodsMinted tracks the number of Gods that have been minted by the public through the // mintGods function. uint public publicGodsMinted; // reservedGodsMinted tracks the number of reserved Gods that have been minted through the // mintReservedGods function. uint public reservedGodsMinted; // MAX_GODS_TO_MINT specifies the maximum number of Gods that can be minted (both public and // reserved.) uint public constant MAX_GODS_TO_MINT = 10000; // MAX_GODS_PER_ADDRESS specifies the maximum number of Gods that a single address can mint. uint public constant MAX_GODS_PER_ADDRESS = 20; // NUM_RESERVED_NFTS specifies the maximum number of Gods that can be minted through the // mintReservedGods function. uint public constant NUM_RESERVED_NFTS = 1000; // publicSaleDuration specifies the length of the dutch auction (in seconds) before the minting // price hits publicSaleGodEndingPrice. uint256 public publicSaleDuration; // publicSaleStartTime tracks the time (as a UNIX timestamp) when the public sale was started. uint256 public publicSaleStartTime; // publicSaleGodStartingPrice specifies the price that the dutch auction mint should start at. uint256 public publicSaleGodStartingPrice; // publicSaleGodEndingPrice specifies the minimum price that Gods can be minted at once the // full duration of the dutch auction has elapsed. uint256 public publicSaleGodEndingPrice; // publicSaleStarted specifies whether the minting event has been started. bool public publicSaleStarted = false; // publicSalePaused specifies whether the minting event has been paused. bool public publicSalePaused = false; // publicSalePausedElapsedTime specifies, if the sale was paused, what the elapsed sale // time was at the time of pausing. uint256 public publicSalePausedElapsedTime; // godIdOffset is pseudo-random offset from 0-10000 generated when the contract is constructed // and used to assign god IDs for each mint. uint256 public immutable godIdOffset; // addressReferencesSet is a boolean flag which tracks that the proper setup functions for the // contract have been run. It must be true before startPublicSale is called. bool public addressReferencesSet = false; // CURVE_POOL_ADDRESS holds the address of the curve pool that we use to exchange ETH for stETH. address constant CURVE_POOL_ADDRESS = 0xDC24316b9AE028F1497c275EB9192a3Ea0f67022; // LIDO_STAKING_ADDRESS holds the address of the Lido staking contract that we also can use to // exchange ETH for stETH. address constant LIDO_STAKING_ADDRESS = 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84; IIdolMain public idolMain; IIdolMarketplace public idolMarketplace; ICurvePool public immutable stethPool; ERC20 public immutable steth; OfferingRefundContract public immutable offeringRefundContract; event PublicSaleStart( uint256 indexed _saleDuration, uint256 indexed _saleStartTime ); event PublicSalePaused( uint256 indexed _currentPrice, uint256 indexed _timeElapsed ); event PublicSaleResumed( uint256 indexed _saleResumeTime ); event IdolsMinted( address indexed _minter, uint256 indexed _mintPrice, uint256 indexed _numMinted ); /** @notice IdolMintContract's constructor takes in two hashes, one of which represents the hash of the Idol NFT metadata, and one of which is the hash of some discord-community-generated input. The two hashes are used to calculate the godIdOffset, which specifies which ID from 0-10000 to start minting at. @param _metadataHash The hash of the master metadata file which corresponds to the 10k Idol NFT images that have been uploaded. @param _discordGeneratedHash The hash of some discord-community-generated input which is used to effectively randomize the value of godIdOffset prior to the start of the mint. @param _stethAddress The address of the stETH ERC20 contract. @param _offeringRefundContractAddress The address of the OfferingRefundContract we will be sending refunds to. */ constructor( string memory _metadataHash, string memory _discordGeneratedHash, address _stethAddress, address payable _offeringRefundContractAddress ) { godIdOffset = uint256(keccak256(abi.encodePacked(_metadataHash, _discordGeneratedHash))) % MAX_GODS_TO_MINT; stethPool = ICurvePool(CURVE_POOL_ADDRESS); steth = ERC20(_stethAddress); offeringRefundContract = OfferingRefundContract(_offeringRefundContractAddress); } /** @notice startPublicSale is called to start the dutch auction for minting Gods to the public. @param _saleDuration The duration of the sale, in seconds, before reaching the minimum minting price. @param _saleStartPrice The initial minting price, which progressively lowers as the dutch auction progresses. @param _saleEndPrice Lower bound for the minting price, once the full duration of the dutch auction has elapsed. */ function startPublicSale(uint256 _saleDuration, uint256 _saleStartPrice, uint256 _saleEndPrice) external onlyOwner beforePublicSaleStarted { require(_saleStartPrice > _saleEndPrice, "_saleStartPrice must be greater than _saleEndPrice"); require(addressReferencesSet, "External reference contracts must all be set before public sale starts"); publicSaleDuration = _saleDuration; publicSaleGodStartingPrice = _saleStartPrice; publicSaleGodEndingPrice = _saleEndPrice; publicSaleStartTime = block.timestamp; publicSaleStarted = true; emit PublicSaleStart(_saleDuration, publicSaleStartTime); } /** @notice setAddressReferences sets references to the main, marketplace, and virtueToken addresses so that the contracts all know about each other. This is all done from the mint contract so that the addresses will no longer be updateable once the mint event has started. @param _idolMainAddress The address of IdolMain. @param _idolMarketplaceAddress The address of the marketplace. @param _virtueTokenAddress The address of the VIRTUE token ERC20 contract. */ function setAddressReferences( address _idolMainAddress, address _idolMarketplaceAddress, address _virtueTokenAddress ) external onlyOwner beforePublicSaleStarted { addressReferencesSet = true; idolMain = IIdolMain(_idolMainAddress); require(steth.approve(_idolMainAddress, 2**255-1)); idolMarketplace = IIdolMarketplace(_idolMarketplaceAddress); idolMain.setVirtueTokenAddr(_virtueTokenAddress); idolMain.setIdolMarketplaceAddr(_idolMarketplaceAddress); idolMarketplace.setVirtueTokenAddr(_virtueTokenAddress); } /** @notice pausePublicSale is called to pause the progression of the mint event. In happy-path circumstances we shouldn't need to call this, but it is included as a precaution in case something goes wrong during the mint. */ function pausePublicSale() external onlyOwner whenPublicSaleActive { uint256 currentSalePrice = getMintPrice(); uint256 elapsedTime = getElapsedSaleTime(); publicSalePausedElapsedTime = elapsedTime; publicSalePaused = true; emit PublicSalePaused(currentSalePrice, elapsedTime); } function resumePublicSale() external onlyOwner { require(publicSalePaused, "Can only resume when the sale is paused"); publicSalePaused = false; publicSaleStartTime = block.timestamp - publicSalePausedElapsedTime; emit PublicSaleResumed(block.timestamp); } /** @notice getElaspedSaleTime is a view function that tells us how many seconds have elapsed since the public sale was started. */ function getElapsedSaleTime() internal view returns (uint256) { if (publicSalePaused) { return publicSalePausedElapsedTime; } return publicSaleStartTime > 0 ? block.timestamp - publicSaleStartTime : 0; } /** @notice getRemainingSaleTime is a view function that tells us how many seconds are remaining before the dutch auction hits the minimum price. */ function getRemainingSaleTime() external view returns (uint256) { if (publicSaleStartTime == 0) { // If the public sale has not been started, we just return 1 week as a placeholder. return 604800; } if (publicSalePaused) { return publicSaleDuration - publicSalePausedElapsedTime; } if (getElapsedSaleTime() >= publicSaleDuration) { return 0; } return (publicSaleStartTime + publicSaleDuration) - block.timestamp; } /** @notice getMintPrice returns the price to mint a God at the current time in the dutch auction. */ function getMintPrice() public view returns (uint256) { if (!publicSaleStarted) { return 0; } uint256 elapsed = getElapsedSaleTime(); if (elapsed >= publicSaleDuration) { return publicSaleGodEndingPrice; } else { int256 tempPrice = int256(publicSaleGodStartingPrice) + ((int256(publicSaleGodEndingPrice) - int256(publicSaleGodStartingPrice)) / int256(publicSaleDuration)) * int256(elapsed); uint256 currentPrice = uint256(tempPrice); return currentPrice > publicSaleGodEndingPrice ? currentPrice : publicSaleGodEndingPrice; } } /** @notice mintGods is a payable function which allows the sender to pay ETH to mint God NFTs at the current price specified by getMintPrice. @param _numGodsToMint The number of gods to be minted, which is capped at a maximum of 5 Gods per transaction. */ function mintGods(uint256 _numGodsToMint) external payable whenPublicSaleActive nonReentrant { require( publicGodsMinted + _numGodsToMint <= MAX_GODS_TO_MINT - NUM_RESERVED_NFTS, "Minting would exceed max supply" ); require(_numGodsToMint > 0, "Must mint at least one god"); require( idolMain.balanceOf(msg.sender) + _numGodsToMint <= MAX_GODS_PER_ADDRESS, "Requested number would exceed the maximum number of gods allowed to be minted for this address." ); uint256 individualCostToMint = getMintPrice(); uint256 costToMint = individualCostToMint * _numGodsToMint; require(costToMint <= msg.value, "Ether value sent is not correct"); for (uint256 i = 0; i < _numGodsToMint; i++) { uint idToMint = (publicGodsMinted + i + godIdOffset) % MAX_GODS_TO_MINT; idolMain.mint(msg.sender, idToMint, false); } publicGodsMinted += _numGodsToMint; if (msg.value > costToMint) { Address.sendValue(payable(msg.sender), msg.value - costToMint); } emit IdolsMinted(msg.sender, individualCostToMint, _numGodsToMint); } /** @notice mintReservedGods is used by the contract owner to mint a reserved pool of 1000 Gods for owners and supporters of the protocol. @param _numGodsToMint The number of Gods to mint in this transaction. @param _mintAddress The address to mint the reserved Gods for. @param _lock If true, specifies that the minted reserved Gods cannot be sold or transferred for the first year of the protocol's existence. */ function mintReservedGods(uint256 _numGodsToMint, address _mintAddress, bool _lock) external onlyOwner nonReentrant { require( reservedGodsMinted + _numGodsToMint < NUM_RESERVED_NFTS, "Minting would exceed max reserved supply" ); require(_numGodsToMint > 0, "Must mint at least one god"); for (uint256 i = 0; i < _numGodsToMint; i++) { uint idToMint = (reservedGodsMinted + i + godIdOffset + MAX_GODS_TO_MINT - NUM_RESERVED_NFTS) % MAX_GODS_TO_MINT; idolMain.mint(_mintAddress, idToMint, _lock); } reservedGodsMinted += _numGodsToMint; } /** @notice sendToOfferingRefundContract sends ETH to the OfferingRefundContract so that it can be distributed to the addresses that are eligible for a refund. */ function sendToOfferingRefundContract(uint _totalRefundAmount) onlyOwner external nonReentrant { Address.sendValue(payable(address(offeringRefundContract)), _totalRefundAmount); } /** @notice swap is used to swap the contract's ETH into stETH via Curve. @param _slippageBps The acceptable slippage percent, in basis points. */ function swap(uint _slippageBps) onlyOwner external returns(uint result) { return stethPool.exchange{ value: address(this).balance }(0, 1, address(this).balance, address(this).balance * _slippageBps / 10000); } function swapLido(uint _slippageBps) onlyOwner external { uint minSteth = steth.balanceOf(address(this)) + address(this).balance * _slippageBps / 10000; Address.sendValue(payable(LIDO_STAKING_ADDRESS), address(this).balance); require(steth.balanceOf(address(this)) >= minSteth, "steth balance not high enough after sending to LIDO_STAKING_ADDRESS"); } /** @notice depositStethIdolMain deposits all of this contract's stETH into the IdolMain contract. */ function depositStethIdolMain() onlyOwner external { idolMain.depositSteth(steth.balanceOf(address(this))); } /** @notice getTotalMinted returns the total number of public + reserved God NFTs minted. */ function getTotalMinted() external view returns (uint) { return reservedGodsMinted + publicGodsMinted; } /** @notice setBaseURI sets the baseURI for the God NFTs. */ function setBaseURI(string memory uri) external onlyOwner { idolMain.setBaseURI(uri); } /** @notice Tears down the contract and allocates any remaining funds to the original contract owner. Should only be called after the mint completes and the contract's balance has been converted to Steth and deposited into IdolMain, or in a disaster scenario where we need to tear down the contract and refund minting fees. */ function tearDown() external onlyOwner { selfdestruct(payable(owner())); } modifier beforePublicSaleStarted { require(!publicSaleStarted, "Public sale has already started"); _; } modifier whenPublicSaleActive { require(publicSaleStarted && !publicSalePaused, "Public sale is not active"); _; } }
/** @notice IdolMintContract is a contract used for the initial mint of the God NFTs. It allocates 90% of the Gods for public minting through a dutch auction protocol, and reserves 10% of the Gods for the creators of the protocol as well as other supporters and stakeholders. IdolMintContract is intended to be torn down once the mint event has completed and once its balance has been deposited into the IdolMain rewards protocol. */
NatSpecMultiLine
depositStethIdolMain
function depositStethIdolMain() onlyOwner external { idolMain.depositSteth(steth.balanceOf(address(this))); }
/** @notice depositStethIdolMain deposits all of this contract's stETH into the IdolMain contract. */
NatSpecMultiLine
v0.8.9+commit.e5eed63a
{ "func_code_index": [ 13137, 13264 ] }
11,814
IdolMintContract
contracts/IdolMintContract.sol
0x7b4b02372d8e54c1c0454d97f01d85ef203cdc5e
Solidity
IdolMintContract
contract IdolMintContract is Ownable, ReentrancyGuard { // publicGodsMinted tracks the number of Gods that have been minted by the public through the // mintGods function. uint public publicGodsMinted; // reservedGodsMinted tracks the number of reserved Gods that have been minted through the // mintReservedGods function. uint public reservedGodsMinted; // MAX_GODS_TO_MINT specifies the maximum number of Gods that can be minted (both public and // reserved.) uint public constant MAX_GODS_TO_MINT = 10000; // MAX_GODS_PER_ADDRESS specifies the maximum number of Gods that a single address can mint. uint public constant MAX_GODS_PER_ADDRESS = 20; // NUM_RESERVED_NFTS specifies the maximum number of Gods that can be minted through the // mintReservedGods function. uint public constant NUM_RESERVED_NFTS = 1000; // publicSaleDuration specifies the length of the dutch auction (in seconds) before the minting // price hits publicSaleGodEndingPrice. uint256 public publicSaleDuration; // publicSaleStartTime tracks the time (as a UNIX timestamp) when the public sale was started. uint256 public publicSaleStartTime; // publicSaleGodStartingPrice specifies the price that the dutch auction mint should start at. uint256 public publicSaleGodStartingPrice; // publicSaleGodEndingPrice specifies the minimum price that Gods can be minted at once the // full duration of the dutch auction has elapsed. uint256 public publicSaleGodEndingPrice; // publicSaleStarted specifies whether the minting event has been started. bool public publicSaleStarted = false; // publicSalePaused specifies whether the minting event has been paused. bool public publicSalePaused = false; // publicSalePausedElapsedTime specifies, if the sale was paused, what the elapsed sale // time was at the time of pausing. uint256 public publicSalePausedElapsedTime; // godIdOffset is pseudo-random offset from 0-10000 generated when the contract is constructed // and used to assign god IDs for each mint. uint256 public immutable godIdOffset; // addressReferencesSet is a boolean flag which tracks that the proper setup functions for the // contract have been run. It must be true before startPublicSale is called. bool public addressReferencesSet = false; // CURVE_POOL_ADDRESS holds the address of the curve pool that we use to exchange ETH for stETH. address constant CURVE_POOL_ADDRESS = 0xDC24316b9AE028F1497c275EB9192a3Ea0f67022; // LIDO_STAKING_ADDRESS holds the address of the Lido staking contract that we also can use to // exchange ETH for stETH. address constant LIDO_STAKING_ADDRESS = 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84; IIdolMain public idolMain; IIdolMarketplace public idolMarketplace; ICurvePool public immutable stethPool; ERC20 public immutable steth; OfferingRefundContract public immutable offeringRefundContract; event PublicSaleStart( uint256 indexed _saleDuration, uint256 indexed _saleStartTime ); event PublicSalePaused( uint256 indexed _currentPrice, uint256 indexed _timeElapsed ); event PublicSaleResumed( uint256 indexed _saleResumeTime ); event IdolsMinted( address indexed _minter, uint256 indexed _mintPrice, uint256 indexed _numMinted ); /** @notice IdolMintContract's constructor takes in two hashes, one of which represents the hash of the Idol NFT metadata, and one of which is the hash of some discord-community-generated input. The two hashes are used to calculate the godIdOffset, which specifies which ID from 0-10000 to start minting at. @param _metadataHash The hash of the master metadata file which corresponds to the 10k Idol NFT images that have been uploaded. @param _discordGeneratedHash The hash of some discord-community-generated input which is used to effectively randomize the value of godIdOffset prior to the start of the mint. @param _stethAddress The address of the stETH ERC20 contract. @param _offeringRefundContractAddress The address of the OfferingRefundContract we will be sending refunds to. */ constructor( string memory _metadataHash, string memory _discordGeneratedHash, address _stethAddress, address payable _offeringRefundContractAddress ) { godIdOffset = uint256(keccak256(abi.encodePacked(_metadataHash, _discordGeneratedHash))) % MAX_GODS_TO_MINT; stethPool = ICurvePool(CURVE_POOL_ADDRESS); steth = ERC20(_stethAddress); offeringRefundContract = OfferingRefundContract(_offeringRefundContractAddress); } /** @notice startPublicSale is called to start the dutch auction for minting Gods to the public. @param _saleDuration The duration of the sale, in seconds, before reaching the minimum minting price. @param _saleStartPrice The initial minting price, which progressively lowers as the dutch auction progresses. @param _saleEndPrice Lower bound for the minting price, once the full duration of the dutch auction has elapsed. */ function startPublicSale(uint256 _saleDuration, uint256 _saleStartPrice, uint256 _saleEndPrice) external onlyOwner beforePublicSaleStarted { require(_saleStartPrice > _saleEndPrice, "_saleStartPrice must be greater than _saleEndPrice"); require(addressReferencesSet, "External reference contracts must all be set before public sale starts"); publicSaleDuration = _saleDuration; publicSaleGodStartingPrice = _saleStartPrice; publicSaleGodEndingPrice = _saleEndPrice; publicSaleStartTime = block.timestamp; publicSaleStarted = true; emit PublicSaleStart(_saleDuration, publicSaleStartTime); } /** @notice setAddressReferences sets references to the main, marketplace, and virtueToken addresses so that the contracts all know about each other. This is all done from the mint contract so that the addresses will no longer be updateable once the mint event has started. @param _idolMainAddress The address of IdolMain. @param _idolMarketplaceAddress The address of the marketplace. @param _virtueTokenAddress The address of the VIRTUE token ERC20 contract. */ function setAddressReferences( address _idolMainAddress, address _idolMarketplaceAddress, address _virtueTokenAddress ) external onlyOwner beforePublicSaleStarted { addressReferencesSet = true; idolMain = IIdolMain(_idolMainAddress); require(steth.approve(_idolMainAddress, 2**255-1)); idolMarketplace = IIdolMarketplace(_idolMarketplaceAddress); idolMain.setVirtueTokenAddr(_virtueTokenAddress); idolMain.setIdolMarketplaceAddr(_idolMarketplaceAddress); idolMarketplace.setVirtueTokenAddr(_virtueTokenAddress); } /** @notice pausePublicSale is called to pause the progression of the mint event. In happy-path circumstances we shouldn't need to call this, but it is included as a precaution in case something goes wrong during the mint. */ function pausePublicSale() external onlyOwner whenPublicSaleActive { uint256 currentSalePrice = getMintPrice(); uint256 elapsedTime = getElapsedSaleTime(); publicSalePausedElapsedTime = elapsedTime; publicSalePaused = true; emit PublicSalePaused(currentSalePrice, elapsedTime); } function resumePublicSale() external onlyOwner { require(publicSalePaused, "Can only resume when the sale is paused"); publicSalePaused = false; publicSaleStartTime = block.timestamp - publicSalePausedElapsedTime; emit PublicSaleResumed(block.timestamp); } /** @notice getElaspedSaleTime is a view function that tells us how many seconds have elapsed since the public sale was started. */ function getElapsedSaleTime() internal view returns (uint256) { if (publicSalePaused) { return publicSalePausedElapsedTime; } return publicSaleStartTime > 0 ? block.timestamp - publicSaleStartTime : 0; } /** @notice getRemainingSaleTime is a view function that tells us how many seconds are remaining before the dutch auction hits the minimum price. */ function getRemainingSaleTime() external view returns (uint256) { if (publicSaleStartTime == 0) { // If the public sale has not been started, we just return 1 week as a placeholder. return 604800; } if (publicSalePaused) { return publicSaleDuration - publicSalePausedElapsedTime; } if (getElapsedSaleTime() >= publicSaleDuration) { return 0; } return (publicSaleStartTime + publicSaleDuration) - block.timestamp; } /** @notice getMintPrice returns the price to mint a God at the current time in the dutch auction. */ function getMintPrice() public view returns (uint256) { if (!publicSaleStarted) { return 0; } uint256 elapsed = getElapsedSaleTime(); if (elapsed >= publicSaleDuration) { return publicSaleGodEndingPrice; } else { int256 tempPrice = int256(publicSaleGodStartingPrice) + ((int256(publicSaleGodEndingPrice) - int256(publicSaleGodStartingPrice)) / int256(publicSaleDuration)) * int256(elapsed); uint256 currentPrice = uint256(tempPrice); return currentPrice > publicSaleGodEndingPrice ? currentPrice : publicSaleGodEndingPrice; } } /** @notice mintGods is a payable function which allows the sender to pay ETH to mint God NFTs at the current price specified by getMintPrice. @param _numGodsToMint The number of gods to be minted, which is capped at a maximum of 5 Gods per transaction. */ function mintGods(uint256 _numGodsToMint) external payable whenPublicSaleActive nonReentrant { require( publicGodsMinted + _numGodsToMint <= MAX_GODS_TO_MINT - NUM_RESERVED_NFTS, "Minting would exceed max supply" ); require(_numGodsToMint > 0, "Must mint at least one god"); require( idolMain.balanceOf(msg.sender) + _numGodsToMint <= MAX_GODS_PER_ADDRESS, "Requested number would exceed the maximum number of gods allowed to be minted for this address." ); uint256 individualCostToMint = getMintPrice(); uint256 costToMint = individualCostToMint * _numGodsToMint; require(costToMint <= msg.value, "Ether value sent is not correct"); for (uint256 i = 0; i < _numGodsToMint; i++) { uint idToMint = (publicGodsMinted + i + godIdOffset) % MAX_GODS_TO_MINT; idolMain.mint(msg.sender, idToMint, false); } publicGodsMinted += _numGodsToMint; if (msg.value > costToMint) { Address.sendValue(payable(msg.sender), msg.value - costToMint); } emit IdolsMinted(msg.sender, individualCostToMint, _numGodsToMint); } /** @notice mintReservedGods is used by the contract owner to mint a reserved pool of 1000 Gods for owners and supporters of the protocol. @param _numGodsToMint The number of Gods to mint in this transaction. @param _mintAddress The address to mint the reserved Gods for. @param _lock If true, specifies that the minted reserved Gods cannot be sold or transferred for the first year of the protocol's existence. */ function mintReservedGods(uint256 _numGodsToMint, address _mintAddress, bool _lock) external onlyOwner nonReentrant { require( reservedGodsMinted + _numGodsToMint < NUM_RESERVED_NFTS, "Minting would exceed max reserved supply" ); require(_numGodsToMint > 0, "Must mint at least one god"); for (uint256 i = 0; i < _numGodsToMint; i++) { uint idToMint = (reservedGodsMinted + i + godIdOffset + MAX_GODS_TO_MINT - NUM_RESERVED_NFTS) % MAX_GODS_TO_MINT; idolMain.mint(_mintAddress, idToMint, _lock); } reservedGodsMinted += _numGodsToMint; } /** @notice sendToOfferingRefundContract sends ETH to the OfferingRefundContract so that it can be distributed to the addresses that are eligible for a refund. */ function sendToOfferingRefundContract(uint _totalRefundAmount) onlyOwner external nonReentrant { Address.sendValue(payable(address(offeringRefundContract)), _totalRefundAmount); } /** @notice swap is used to swap the contract's ETH into stETH via Curve. @param _slippageBps The acceptable slippage percent, in basis points. */ function swap(uint _slippageBps) onlyOwner external returns(uint result) { return stethPool.exchange{ value: address(this).balance }(0, 1, address(this).balance, address(this).balance * _slippageBps / 10000); } function swapLido(uint _slippageBps) onlyOwner external { uint minSteth = steth.balanceOf(address(this)) + address(this).balance * _slippageBps / 10000; Address.sendValue(payable(LIDO_STAKING_ADDRESS), address(this).balance); require(steth.balanceOf(address(this)) >= minSteth, "steth balance not high enough after sending to LIDO_STAKING_ADDRESS"); } /** @notice depositStethIdolMain deposits all of this contract's stETH into the IdolMain contract. */ function depositStethIdolMain() onlyOwner external { idolMain.depositSteth(steth.balanceOf(address(this))); } /** @notice getTotalMinted returns the total number of public + reserved God NFTs minted. */ function getTotalMinted() external view returns (uint) { return reservedGodsMinted + publicGodsMinted; } /** @notice setBaseURI sets the baseURI for the God NFTs. */ function setBaseURI(string memory uri) external onlyOwner { idolMain.setBaseURI(uri); } /** @notice Tears down the contract and allocates any remaining funds to the original contract owner. Should only be called after the mint completes and the contract's balance has been converted to Steth and deposited into IdolMain, or in a disaster scenario where we need to tear down the contract and refund minting fees. */ function tearDown() external onlyOwner { selfdestruct(payable(owner())); } modifier beforePublicSaleStarted { require(!publicSaleStarted, "Public sale has already started"); _; } modifier whenPublicSaleActive { require(publicSaleStarted && !publicSalePaused, "Public sale is not active"); _; } }
/** @notice IdolMintContract is a contract used for the initial mint of the God NFTs. It allocates 90% of the Gods for public minting through a dutch auction protocol, and reserves 10% of the Gods for the creators of the protocol as well as other supporters and stakeholders. IdolMintContract is intended to be torn down once the mint event has completed and once its balance has been deposited into the IdolMain rewards protocol. */
NatSpecMultiLine
getTotalMinted
function getTotalMinted() external view returns (uint) { return reservedGodsMinted + publicGodsMinted; }
/** @notice getTotalMinted returns the total number of public + reserved God NFTs minted. */
NatSpecMultiLine
v0.8.9+commit.e5eed63a
{ "func_code_index": [ 13367, 13479 ] }
11,815
IdolMintContract
contracts/IdolMintContract.sol
0x7b4b02372d8e54c1c0454d97f01d85ef203cdc5e
Solidity
IdolMintContract
contract IdolMintContract is Ownable, ReentrancyGuard { // publicGodsMinted tracks the number of Gods that have been minted by the public through the // mintGods function. uint public publicGodsMinted; // reservedGodsMinted tracks the number of reserved Gods that have been minted through the // mintReservedGods function. uint public reservedGodsMinted; // MAX_GODS_TO_MINT specifies the maximum number of Gods that can be minted (both public and // reserved.) uint public constant MAX_GODS_TO_MINT = 10000; // MAX_GODS_PER_ADDRESS specifies the maximum number of Gods that a single address can mint. uint public constant MAX_GODS_PER_ADDRESS = 20; // NUM_RESERVED_NFTS specifies the maximum number of Gods that can be minted through the // mintReservedGods function. uint public constant NUM_RESERVED_NFTS = 1000; // publicSaleDuration specifies the length of the dutch auction (in seconds) before the minting // price hits publicSaleGodEndingPrice. uint256 public publicSaleDuration; // publicSaleStartTime tracks the time (as a UNIX timestamp) when the public sale was started. uint256 public publicSaleStartTime; // publicSaleGodStartingPrice specifies the price that the dutch auction mint should start at. uint256 public publicSaleGodStartingPrice; // publicSaleGodEndingPrice specifies the minimum price that Gods can be minted at once the // full duration of the dutch auction has elapsed. uint256 public publicSaleGodEndingPrice; // publicSaleStarted specifies whether the minting event has been started. bool public publicSaleStarted = false; // publicSalePaused specifies whether the minting event has been paused. bool public publicSalePaused = false; // publicSalePausedElapsedTime specifies, if the sale was paused, what the elapsed sale // time was at the time of pausing. uint256 public publicSalePausedElapsedTime; // godIdOffset is pseudo-random offset from 0-10000 generated when the contract is constructed // and used to assign god IDs for each mint. uint256 public immutable godIdOffset; // addressReferencesSet is a boolean flag which tracks that the proper setup functions for the // contract have been run. It must be true before startPublicSale is called. bool public addressReferencesSet = false; // CURVE_POOL_ADDRESS holds the address of the curve pool that we use to exchange ETH for stETH. address constant CURVE_POOL_ADDRESS = 0xDC24316b9AE028F1497c275EB9192a3Ea0f67022; // LIDO_STAKING_ADDRESS holds the address of the Lido staking contract that we also can use to // exchange ETH for stETH. address constant LIDO_STAKING_ADDRESS = 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84; IIdolMain public idolMain; IIdolMarketplace public idolMarketplace; ICurvePool public immutable stethPool; ERC20 public immutable steth; OfferingRefundContract public immutable offeringRefundContract; event PublicSaleStart( uint256 indexed _saleDuration, uint256 indexed _saleStartTime ); event PublicSalePaused( uint256 indexed _currentPrice, uint256 indexed _timeElapsed ); event PublicSaleResumed( uint256 indexed _saleResumeTime ); event IdolsMinted( address indexed _minter, uint256 indexed _mintPrice, uint256 indexed _numMinted ); /** @notice IdolMintContract's constructor takes in two hashes, one of which represents the hash of the Idol NFT metadata, and one of which is the hash of some discord-community-generated input. The two hashes are used to calculate the godIdOffset, which specifies which ID from 0-10000 to start minting at. @param _metadataHash The hash of the master metadata file which corresponds to the 10k Idol NFT images that have been uploaded. @param _discordGeneratedHash The hash of some discord-community-generated input which is used to effectively randomize the value of godIdOffset prior to the start of the mint. @param _stethAddress The address of the stETH ERC20 contract. @param _offeringRefundContractAddress The address of the OfferingRefundContract we will be sending refunds to. */ constructor( string memory _metadataHash, string memory _discordGeneratedHash, address _stethAddress, address payable _offeringRefundContractAddress ) { godIdOffset = uint256(keccak256(abi.encodePacked(_metadataHash, _discordGeneratedHash))) % MAX_GODS_TO_MINT; stethPool = ICurvePool(CURVE_POOL_ADDRESS); steth = ERC20(_stethAddress); offeringRefundContract = OfferingRefundContract(_offeringRefundContractAddress); } /** @notice startPublicSale is called to start the dutch auction for minting Gods to the public. @param _saleDuration The duration of the sale, in seconds, before reaching the minimum minting price. @param _saleStartPrice The initial minting price, which progressively lowers as the dutch auction progresses. @param _saleEndPrice Lower bound for the minting price, once the full duration of the dutch auction has elapsed. */ function startPublicSale(uint256 _saleDuration, uint256 _saleStartPrice, uint256 _saleEndPrice) external onlyOwner beforePublicSaleStarted { require(_saleStartPrice > _saleEndPrice, "_saleStartPrice must be greater than _saleEndPrice"); require(addressReferencesSet, "External reference contracts must all be set before public sale starts"); publicSaleDuration = _saleDuration; publicSaleGodStartingPrice = _saleStartPrice; publicSaleGodEndingPrice = _saleEndPrice; publicSaleStartTime = block.timestamp; publicSaleStarted = true; emit PublicSaleStart(_saleDuration, publicSaleStartTime); } /** @notice setAddressReferences sets references to the main, marketplace, and virtueToken addresses so that the contracts all know about each other. This is all done from the mint contract so that the addresses will no longer be updateable once the mint event has started. @param _idolMainAddress The address of IdolMain. @param _idolMarketplaceAddress The address of the marketplace. @param _virtueTokenAddress The address of the VIRTUE token ERC20 contract. */ function setAddressReferences( address _idolMainAddress, address _idolMarketplaceAddress, address _virtueTokenAddress ) external onlyOwner beforePublicSaleStarted { addressReferencesSet = true; idolMain = IIdolMain(_idolMainAddress); require(steth.approve(_idolMainAddress, 2**255-1)); idolMarketplace = IIdolMarketplace(_idolMarketplaceAddress); idolMain.setVirtueTokenAddr(_virtueTokenAddress); idolMain.setIdolMarketplaceAddr(_idolMarketplaceAddress); idolMarketplace.setVirtueTokenAddr(_virtueTokenAddress); } /** @notice pausePublicSale is called to pause the progression of the mint event. In happy-path circumstances we shouldn't need to call this, but it is included as a precaution in case something goes wrong during the mint. */ function pausePublicSale() external onlyOwner whenPublicSaleActive { uint256 currentSalePrice = getMintPrice(); uint256 elapsedTime = getElapsedSaleTime(); publicSalePausedElapsedTime = elapsedTime; publicSalePaused = true; emit PublicSalePaused(currentSalePrice, elapsedTime); } function resumePublicSale() external onlyOwner { require(publicSalePaused, "Can only resume when the sale is paused"); publicSalePaused = false; publicSaleStartTime = block.timestamp - publicSalePausedElapsedTime; emit PublicSaleResumed(block.timestamp); } /** @notice getElaspedSaleTime is a view function that tells us how many seconds have elapsed since the public sale was started. */ function getElapsedSaleTime() internal view returns (uint256) { if (publicSalePaused) { return publicSalePausedElapsedTime; } return publicSaleStartTime > 0 ? block.timestamp - publicSaleStartTime : 0; } /** @notice getRemainingSaleTime is a view function that tells us how many seconds are remaining before the dutch auction hits the minimum price. */ function getRemainingSaleTime() external view returns (uint256) { if (publicSaleStartTime == 0) { // If the public sale has not been started, we just return 1 week as a placeholder. return 604800; } if (publicSalePaused) { return publicSaleDuration - publicSalePausedElapsedTime; } if (getElapsedSaleTime() >= publicSaleDuration) { return 0; } return (publicSaleStartTime + publicSaleDuration) - block.timestamp; } /** @notice getMintPrice returns the price to mint a God at the current time in the dutch auction. */ function getMintPrice() public view returns (uint256) { if (!publicSaleStarted) { return 0; } uint256 elapsed = getElapsedSaleTime(); if (elapsed >= publicSaleDuration) { return publicSaleGodEndingPrice; } else { int256 tempPrice = int256(publicSaleGodStartingPrice) + ((int256(publicSaleGodEndingPrice) - int256(publicSaleGodStartingPrice)) / int256(publicSaleDuration)) * int256(elapsed); uint256 currentPrice = uint256(tempPrice); return currentPrice > publicSaleGodEndingPrice ? currentPrice : publicSaleGodEndingPrice; } } /** @notice mintGods is a payable function which allows the sender to pay ETH to mint God NFTs at the current price specified by getMintPrice. @param _numGodsToMint The number of gods to be minted, which is capped at a maximum of 5 Gods per transaction. */ function mintGods(uint256 _numGodsToMint) external payable whenPublicSaleActive nonReentrant { require( publicGodsMinted + _numGodsToMint <= MAX_GODS_TO_MINT - NUM_RESERVED_NFTS, "Minting would exceed max supply" ); require(_numGodsToMint > 0, "Must mint at least one god"); require( idolMain.balanceOf(msg.sender) + _numGodsToMint <= MAX_GODS_PER_ADDRESS, "Requested number would exceed the maximum number of gods allowed to be minted for this address." ); uint256 individualCostToMint = getMintPrice(); uint256 costToMint = individualCostToMint * _numGodsToMint; require(costToMint <= msg.value, "Ether value sent is not correct"); for (uint256 i = 0; i < _numGodsToMint; i++) { uint idToMint = (publicGodsMinted + i + godIdOffset) % MAX_GODS_TO_MINT; idolMain.mint(msg.sender, idToMint, false); } publicGodsMinted += _numGodsToMint; if (msg.value > costToMint) { Address.sendValue(payable(msg.sender), msg.value - costToMint); } emit IdolsMinted(msg.sender, individualCostToMint, _numGodsToMint); } /** @notice mintReservedGods is used by the contract owner to mint a reserved pool of 1000 Gods for owners and supporters of the protocol. @param _numGodsToMint The number of Gods to mint in this transaction. @param _mintAddress The address to mint the reserved Gods for. @param _lock If true, specifies that the minted reserved Gods cannot be sold or transferred for the first year of the protocol's existence. */ function mintReservedGods(uint256 _numGodsToMint, address _mintAddress, bool _lock) external onlyOwner nonReentrant { require( reservedGodsMinted + _numGodsToMint < NUM_RESERVED_NFTS, "Minting would exceed max reserved supply" ); require(_numGodsToMint > 0, "Must mint at least one god"); for (uint256 i = 0; i < _numGodsToMint; i++) { uint idToMint = (reservedGodsMinted + i + godIdOffset + MAX_GODS_TO_MINT - NUM_RESERVED_NFTS) % MAX_GODS_TO_MINT; idolMain.mint(_mintAddress, idToMint, _lock); } reservedGodsMinted += _numGodsToMint; } /** @notice sendToOfferingRefundContract sends ETH to the OfferingRefundContract so that it can be distributed to the addresses that are eligible for a refund. */ function sendToOfferingRefundContract(uint _totalRefundAmount) onlyOwner external nonReentrant { Address.sendValue(payable(address(offeringRefundContract)), _totalRefundAmount); } /** @notice swap is used to swap the contract's ETH into stETH via Curve. @param _slippageBps The acceptable slippage percent, in basis points. */ function swap(uint _slippageBps) onlyOwner external returns(uint result) { return stethPool.exchange{ value: address(this).balance }(0, 1, address(this).balance, address(this).balance * _slippageBps / 10000); } function swapLido(uint _slippageBps) onlyOwner external { uint minSteth = steth.balanceOf(address(this)) + address(this).balance * _slippageBps / 10000; Address.sendValue(payable(LIDO_STAKING_ADDRESS), address(this).balance); require(steth.balanceOf(address(this)) >= minSteth, "steth balance not high enough after sending to LIDO_STAKING_ADDRESS"); } /** @notice depositStethIdolMain deposits all of this contract's stETH into the IdolMain contract. */ function depositStethIdolMain() onlyOwner external { idolMain.depositSteth(steth.balanceOf(address(this))); } /** @notice getTotalMinted returns the total number of public + reserved God NFTs minted. */ function getTotalMinted() external view returns (uint) { return reservedGodsMinted + publicGodsMinted; } /** @notice setBaseURI sets the baseURI for the God NFTs. */ function setBaseURI(string memory uri) external onlyOwner { idolMain.setBaseURI(uri); } /** @notice Tears down the contract and allocates any remaining funds to the original contract owner. Should only be called after the mint completes and the contract's balance has been converted to Steth and deposited into IdolMain, or in a disaster scenario where we need to tear down the contract and refund minting fees. */ function tearDown() external onlyOwner { selfdestruct(payable(owner())); } modifier beforePublicSaleStarted { require(!publicSaleStarted, "Public sale has already started"); _; } modifier whenPublicSaleActive { require(publicSaleStarted && !publicSalePaused, "Public sale is not active"); _; } }
/** @notice IdolMintContract is a contract used for the initial mint of the God NFTs. It allocates 90% of the Gods for public minting through a dutch auction protocol, and reserves 10% of the Gods for the creators of the protocol as well as other supporters and stakeholders. IdolMintContract is intended to be torn down once the mint event has completed and once its balance has been deposited into the IdolMain rewards protocol. */
NatSpecMultiLine
setBaseURI
function setBaseURI(string memory uri) external onlyOwner { idolMain.setBaseURI(uri); }
/** @notice setBaseURI sets the baseURI for the God NFTs. */
NatSpecMultiLine
v0.8.9+commit.e5eed63a
{ "func_code_index": [ 13550, 13645 ] }
11,816
IdolMintContract
contracts/IdolMintContract.sol
0x7b4b02372d8e54c1c0454d97f01d85ef203cdc5e
Solidity
IdolMintContract
contract IdolMintContract is Ownable, ReentrancyGuard { // publicGodsMinted tracks the number of Gods that have been minted by the public through the // mintGods function. uint public publicGodsMinted; // reservedGodsMinted tracks the number of reserved Gods that have been minted through the // mintReservedGods function. uint public reservedGodsMinted; // MAX_GODS_TO_MINT specifies the maximum number of Gods that can be minted (both public and // reserved.) uint public constant MAX_GODS_TO_MINT = 10000; // MAX_GODS_PER_ADDRESS specifies the maximum number of Gods that a single address can mint. uint public constant MAX_GODS_PER_ADDRESS = 20; // NUM_RESERVED_NFTS specifies the maximum number of Gods that can be minted through the // mintReservedGods function. uint public constant NUM_RESERVED_NFTS = 1000; // publicSaleDuration specifies the length of the dutch auction (in seconds) before the minting // price hits publicSaleGodEndingPrice. uint256 public publicSaleDuration; // publicSaleStartTime tracks the time (as a UNIX timestamp) when the public sale was started. uint256 public publicSaleStartTime; // publicSaleGodStartingPrice specifies the price that the dutch auction mint should start at. uint256 public publicSaleGodStartingPrice; // publicSaleGodEndingPrice specifies the minimum price that Gods can be minted at once the // full duration of the dutch auction has elapsed. uint256 public publicSaleGodEndingPrice; // publicSaleStarted specifies whether the minting event has been started. bool public publicSaleStarted = false; // publicSalePaused specifies whether the minting event has been paused. bool public publicSalePaused = false; // publicSalePausedElapsedTime specifies, if the sale was paused, what the elapsed sale // time was at the time of pausing. uint256 public publicSalePausedElapsedTime; // godIdOffset is pseudo-random offset from 0-10000 generated when the contract is constructed // and used to assign god IDs for each mint. uint256 public immutable godIdOffset; // addressReferencesSet is a boolean flag which tracks that the proper setup functions for the // contract have been run. It must be true before startPublicSale is called. bool public addressReferencesSet = false; // CURVE_POOL_ADDRESS holds the address of the curve pool that we use to exchange ETH for stETH. address constant CURVE_POOL_ADDRESS = 0xDC24316b9AE028F1497c275EB9192a3Ea0f67022; // LIDO_STAKING_ADDRESS holds the address of the Lido staking contract that we also can use to // exchange ETH for stETH. address constant LIDO_STAKING_ADDRESS = 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84; IIdolMain public idolMain; IIdolMarketplace public idolMarketplace; ICurvePool public immutable stethPool; ERC20 public immutable steth; OfferingRefundContract public immutable offeringRefundContract; event PublicSaleStart( uint256 indexed _saleDuration, uint256 indexed _saleStartTime ); event PublicSalePaused( uint256 indexed _currentPrice, uint256 indexed _timeElapsed ); event PublicSaleResumed( uint256 indexed _saleResumeTime ); event IdolsMinted( address indexed _minter, uint256 indexed _mintPrice, uint256 indexed _numMinted ); /** @notice IdolMintContract's constructor takes in two hashes, one of which represents the hash of the Idol NFT metadata, and one of which is the hash of some discord-community-generated input. The two hashes are used to calculate the godIdOffset, which specifies which ID from 0-10000 to start minting at. @param _metadataHash The hash of the master metadata file which corresponds to the 10k Idol NFT images that have been uploaded. @param _discordGeneratedHash The hash of some discord-community-generated input which is used to effectively randomize the value of godIdOffset prior to the start of the mint. @param _stethAddress The address of the stETH ERC20 contract. @param _offeringRefundContractAddress The address of the OfferingRefundContract we will be sending refunds to. */ constructor( string memory _metadataHash, string memory _discordGeneratedHash, address _stethAddress, address payable _offeringRefundContractAddress ) { godIdOffset = uint256(keccak256(abi.encodePacked(_metadataHash, _discordGeneratedHash))) % MAX_GODS_TO_MINT; stethPool = ICurvePool(CURVE_POOL_ADDRESS); steth = ERC20(_stethAddress); offeringRefundContract = OfferingRefundContract(_offeringRefundContractAddress); } /** @notice startPublicSale is called to start the dutch auction for minting Gods to the public. @param _saleDuration The duration of the sale, in seconds, before reaching the minimum minting price. @param _saleStartPrice The initial minting price, which progressively lowers as the dutch auction progresses. @param _saleEndPrice Lower bound for the minting price, once the full duration of the dutch auction has elapsed. */ function startPublicSale(uint256 _saleDuration, uint256 _saleStartPrice, uint256 _saleEndPrice) external onlyOwner beforePublicSaleStarted { require(_saleStartPrice > _saleEndPrice, "_saleStartPrice must be greater than _saleEndPrice"); require(addressReferencesSet, "External reference contracts must all be set before public sale starts"); publicSaleDuration = _saleDuration; publicSaleGodStartingPrice = _saleStartPrice; publicSaleGodEndingPrice = _saleEndPrice; publicSaleStartTime = block.timestamp; publicSaleStarted = true; emit PublicSaleStart(_saleDuration, publicSaleStartTime); } /** @notice setAddressReferences sets references to the main, marketplace, and virtueToken addresses so that the contracts all know about each other. This is all done from the mint contract so that the addresses will no longer be updateable once the mint event has started. @param _idolMainAddress The address of IdolMain. @param _idolMarketplaceAddress The address of the marketplace. @param _virtueTokenAddress The address of the VIRTUE token ERC20 contract. */ function setAddressReferences( address _idolMainAddress, address _idolMarketplaceAddress, address _virtueTokenAddress ) external onlyOwner beforePublicSaleStarted { addressReferencesSet = true; idolMain = IIdolMain(_idolMainAddress); require(steth.approve(_idolMainAddress, 2**255-1)); idolMarketplace = IIdolMarketplace(_idolMarketplaceAddress); idolMain.setVirtueTokenAddr(_virtueTokenAddress); idolMain.setIdolMarketplaceAddr(_idolMarketplaceAddress); idolMarketplace.setVirtueTokenAddr(_virtueTokenAddress); } /** @notice pausePublicSale is called to pause the progression of the mint event. In happy-path circumstances we shouldn't need to call this, but it is included as a precaution in case something goes wrong during the mint. */ function pausePublicSale() external onlyOwner whenPublicSaleActive { uint256 currentSalePrice = getMintPrice(); uint256 elapsedTime = getElapsedSaleTime(); publicSalePausedElapsedTime = elapsedTime; publicSalePaused = true; emit PublicSalePaused(currentSalePrice, elapsedTime); } function resumePublicSale() external onlyOwner { require(publicSalePaused, "Can only resume when the sale is paused"); publicSalePaused = false; publicSaleStartTime = block.timestamp - publicSalePausedElapsedTime; emit PublicSaleResumed(block.timestamp); } /** @notice getElaspedSaleTime is a view function that tells us how many seconds have elapsed since the public sale was started. */ function getElapsedSaleTime() internal view returns (uint256) { if (publicSalePaused) { return publicSalePausedElapsedTime; } return publicSaleStartTime > 0 ? block.timestamp - publicSaleStartTime : 0; } /** @notice getRemainingSaleTime is a view function that tells us how many seconds are remaining before the dutch auction hits the minimum price. */ function getRemainingSaleTime() external view returns (uint256) { if (publicSaleStartTime == 0) { // If the public sale has not been started, we just return 1 week as a placeholder. return 604800; } if (publicSalePaused) { return publicSaleDuration - publicSalePausedElapsedTime; } if (getElapsedSaleTime() >= publicSaleDuration) { return 0; } return (publicSaleStartTime + publicSaleDuration) - block.timestamp; } /** @notice getMintPrice returns the price to mint a God at the current time in the dutch auction. */ function getMintPrice() public view returns (uint256) { if (!publicSaleStarted) { return 0; } uint256 elapsed = getElapsedSaleTime(); if (elapsed >= publicSaleDuration) { return publicSaleGodEndingPrice; } else { int256 tempPrice = int256(publicSaleGodStartingPrice) + ((int256(publicSaleGodEndingPrice) - int256(publicSaleGodStartingPrice)) / int256(publicSaleDuration)) * int256(elapsed); uint256 currentPrice = uint256(tempPrice); return currentPrice > publicSaleGodEndingPrice ? currentPrice : publicSaleGodEndingPrice; } } /** @notice mintGods is a payable function which allows the sender to pay ETH to mint God NFTs at the current price specified by getMintPrice. @param _numGodsToMint The number of gods to be minted, which is capped at a maximum of 5 Gods per transaction. */ function mintGods(uint256 _numGodsToMint) external payable whenPublicSaleActive nonReentrant { require( publicGodsMinted + _numGodsToMint <= MAX_GODS_TO_MINT - NUM_RESERVED_NFTS, "Minting would exceed max supply" ); require(_numGodsToMint > 0, "Must mint at least one god"); require( idolMain.balanceOf(msg.sender) + _numGodsToMint <= MAX_GODS_PER_ADDRESS, "Requested number would exceed the maximum number of gods allowed to be minted for this address." ); uint256 individualCostToMint = getMintPrice(); uint256 costToMint = individualCostToMint * _numGodsToMint; require(costToMint <= msg.value, "Ether value sent is not correct"); for (uint256 i = 0; i < _numGodsToMint; i++) { uint idToMint = (publicGodsMinted + i + godIdOffset) % MAX_GODS_TO_MINT; idolMain.mint(msg.sender, idToMint, false); } publicGodsMinted += _numGodsToMint; if (msg.value > costToMint) { Address.sendValue(payable(msg.sender), msg.value - costToMint); } emit IdolsMinted(msg.sender, individualCostToMint, _numGodsToMint); } /** @notice mintReservedGods is used by the contract owner to mint a reserved pool of 1000 Gods for owners and supporters of the protocol. @param _numGodsToMint The number of Gods to mint in this transaction. @param _mintAddress The address to mint the reserved Gods for. @param _lock If true, specifies that the minted reserved Gods cannot be sold or transferred for the first year of the protocol's existence. */ function mintReservedGods(uint256 _numGodsToMint, address _mintAddress, bool _lock) external onlyOwner nonReentrant { require( reservedGodsMinted + _numGodsToMint < NUM_RESERVED_NFTS, "Minting would exceed max reserved supply" ); require(_numGodsToMint > 0, "Must mint at least one god"); for (uint256 i = 0; i < _numGodsToMint; i++) { uint idToMint = (reservedGodsMinted + i + godIdOffset + MAX_GODS_TO_MINT - NUM_RESERVED_NFTS) % MAX_GODS_TO_MINT; idolMain.mint(_mintAddress, idToMint, _lock); } reservedGodsMinted += _numGodsToMint; } /** @notice sendToOfferingRefundContract sends ETH to the OfferingRefundContract so that it can be distributed to the addresses that are eligible for a refund. */ function sendToOfferingRefundContract(uint _totalRefundAmount) onlyOwner external nonReentrant { Address.sendValue(payable(address(offeringRefundContract)), _totalRefundAmount); } /** @notice swap is used to swap the contract's ETH into stETH via Curve. @param _slippageBps The acceptable slippage percent, in basis points. */ function swap(uint _slippageBps) onlyOwner external returns(uint result) { return stethPool.exchange{ value: address(this).balance }(0, 1, address(this).balance, address(this).balance * _slippageBps / 10000); } function swapLido(uint _slippageBps) onlyOwner external { uint minSteth = steth.balanceOf(address(this)) + address(this).balance * _slippageBps / 10000; Address.sendValue(payable(LIDO_STAKING_ADDRESS), address(this).balance); require(steth.balanceOf(address(this)) >= minSteth, "steth balance not high enough after sending to LIDO_STAKING_ADDRESS"); } /** @notice depositStethIdolMain deposits all of this contract's stETH into the IdolMain contract. */ function depositStethIdolMain() onlyOwner external { idolMain.depositSteth(steth.balanceOf(address(this))); } /** @notice getTotalMinted returns the total number of public + reserved God NFTs minted. */ function getTotalMinted() external view returns (uint) { return reservedGodsMinted + publicGodsMinted; } /** @notice setBaseURI sets the baseURI for the God NFTs. */ function setBaseURI(string memory uri) external onlyOwner { idolMain.setBaseURI(uri); } /** @notice Tears down the contract and allocates any remaining funds to the original contract owner. Should only be called after the mint completes and the contract's balance has been converted to Steth and deposited into IdolMain, or in a disaster scenario where we need to tear down the contract and refund minting fees. */ function tearDown() external onlyOwner { selfdestruct(payable(owner())); } modifier beforePublicSaleStarted { require(!publicSaleStarted, "Public sale has already started"); _; } modifier whenPublicSaleActive { require(publicSaleStarted && !publicSalePaused, "Public sale is not active"); _; } }
/** @notice IdolMintContract is a contract used for the initial mint of the God NFTs. It allocates 90% of the Gods for public minting through a dutch auction protocol, and reserves 10% of the Gods for the creators of the protocol as well as other supporters and stakeholders. IdolMintContract is intended to be torn down once the mint event has completed and once its balance has been deposited into the IdolMain rewards protocol. */
NatSpecMultiLine
tearDown
function tearDown() external onlyOwner { selfdestruct(payable(owner())); }
/** @notice Tears down the contract and allocates any remaining funds to the original contract owner. Should only be called after the mint completes and the contract's balance has been converted to Steth and deposited into IdolMain, or in a disaster scenario where we need to tear down the contract and refund minting fees. */
NatSpecMultiLine
v0.8.9+commit.e5eed63a
{ "func_code_index": [ 14000, 14082 ] }
11,817
BITRNXFFF
BITRNXFFF.sol
0x20e830d29b184c08a8facc73d4603e8a0d3a2bfa
Solidity
Ownable
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } }
/** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */
NatSpecMultiLine
transferOwnership
function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; }
/** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://0ca4c6357aeba1a021af42dbb7644db29538cf828d8d66cc17f2b68929b3e009
{ "func_code_index": [ 635, 816 ] }
11,818
BITRNXFFF
BITRNXFFF.sol
0x20e830d29b184c08a8facc73d4603e8a0d3a2bfa
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } }
/** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */
NatSpecMultiLine
totalSupply
function totalSupply() public view returns (uint256) { return totalSupply_; }
/** * @dev total number of tokens in existence */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://0ca4c6357aeba1a021af42dbb7644db29538cf828d8d66cc17f2b68929b3e009
{ "func_code_index": [ 199, 287 ] }
11,819
BITRNXFFF
BITRNXFFF.sol
0x20e830d29b184c08a8facc73d4603e8a0d3a2bfa
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } }
/** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */
NatSpecMultiLine
transfer
function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; }
/** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://0ca4c6357aeba1a021af42dbb7644db29538cf828d8d66cc17f2b68929b3e009
{ "func_code_index": [ 445, 777 ] }
11,820
BITRNXFFF
BITRNXFFF.sol
0x20e830d29b184c08a8facc73d4603e8a0d3a2bfa
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } }
/** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */
NatSpecMultiLine
balanceOf
function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; }
/** * @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. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://0ca4c6357aeba1a021af42dbb7644db29538cf828d8d66cc17f2b68929b3e009
{ "func_code_index": [ 983, 1087 ] }
11,821
BITRNXFFF
BITRNXFFF.sol
0x20e830d29b184c08a8facc73d4603e8a0d3a2bfa
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
transferFrom
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; }
/** * @dev 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 */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://0ca4c6357aeba1a021af42dbb7644db29538cf828d8d66cc17f2b68929b3e009
{ "func_code_index": [ 401, 858 ] }
11,822
BITRNXFFF
BITRNXFFF.sol
0x20e830d29b184c08a8facc73d4603e8a0d3a2bfa
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
approve
function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _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. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://0ca4c6357aeba1a021af42dbb7644db29538cf828d8d66cc17f2b68929b3e009
{ "func_code_index": [ 1490, 1685 ] }
11,823
BITRNXFFF
BITRNXFFF.sol
0x20e830d29b184c08a8facc73d4603e8a0d3a2bfa
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
allowance
function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; }
/** * @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. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://0ca4c6357aeba1a021af42dbb7644db29538cf828d8d66cc17f2b68929b3e009
{ "func_code_index": [ 2009, 2140 ] }
11,824
BITRNXFFF
BITRNXFFF.sol
0x20e830d29b184c08a8facc73d4603e8a0d3a2bfa
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
increaseApproval
function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
/** * @dev 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. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://0ca4c6357aeba1a021af42dbb7644db29538cf828d8d66cc17f2b68929b3e009
{ "func_code_index": [ 2606, 2875 ] }
11,825
BITRNXFFF
BITRNXFFF.sol
0x20e830d29b184c08a8facc73d4603e8a0d3a2bfa
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
decreaseApproval
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
/** * @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. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://0ca4c6357aeba1a021af42dbb7644db29538cf828d8d66cc17f2b68929b3e009
{ "func_code_index": [ 3346, 3761 ] }
11,826
BITRNXFFF
BITRNXFFF.sol
0x20e830d29b184c08a8facc73d4603e8a0d3a2bfa
Solidity
BITRNXFFF
contract BITRNXFFF is StandardToken, Ownable { string public constant name = "BITRNXFFF"; string public constant symbol = "BIT-FFF"; uint8 public constant decimals = 8; uint256 public constant INITIAL_SUPPLY = 200000000 * (10 ** uint256(decimals)); //prevent duplicate distributions mapping (address => bool) distributionLocks; /** * @dev Constructor that gives msg.sender all of existing tokens. */ constructor() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; } /** * @dev Distribute tokens to multiple addresses in a single transaction * * @param addresses A list of addresses to distribute to * @param values A corresponding list of amounts to distribute to each address */ function anailNathrachOrthaBhaisIsBeathaDoChealDeanaimh(address[] addresses, uint256[] values) onlyOwner public returns (bool success) { require(addresses.length == values.length); for (uint i = 0; i < addresses.length; i++) { require(!distributionLocks[addresses[i]]); transfer(addresses[i], values[i]); distributionLocks[addresses[i]] = true; } return true; } }
/** * @title Eternal Token * @dev DistributableToken contract is based on a simple initial supply token, with an API for the owner to perform bulk distributions. * transactions to the distributeTokens function should be paginated to avoid gas limits or computational time restrictions. */
NatSpecMultiLine
anailNathrachOrthaBhaisIsBeathaDoChealDeanaimh
function anailNathrachOrthaBhaisIsBeathaDoChealDeanaimh(address[] addresses, uint256[] values) onlyOwner public returns (bool success) { require(addresses.length == values.length); for (uint i = 0; i < addresses.length; i++) { require(!distributionLocks[addresses[i]]); transfer(addresses[i], values[i]); distributionLocks[addresses[i]] = true; } return true; }
/** * @dev Distribute tokens to multiple addresses in a single transaction * * @param addresses A list of addresses to distribute to * @param values A corresponding list of amounts to distribute to each address */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://0ca4c6357aeba1a021af42dbb7644db29538cf828d8d66cc17f2b68929b3e009
{ "func_code_index": [ 829, 1275 ] }
11,827
AIB2020
ERC20.sol
0x4b63ce7e179d1db5ddac5d9d54e48356cf3e8b7d
Solidity
ERC20
contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } //转账 function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ // function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
totalSupply
function totalSupply() public view returns (uint256) { return _totalSupply; }
/** * @dev See {IERC20-totalSupply}. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
MIT
bzzr://0d1d7faa6754d74b7a40e0489566283646cecb89c0c24a0a887d31b108d4a230
{ "func_code_index": [ 299, 395 ] }
11,828
AIB2020
ERC20.sol
0x4b63ce7e179d1db5ddac5d9d54e48356cf3e8b7d
Solidity
ERC20
contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } //转账 function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ // function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
balanceOf
function balanceOf(address account) public view returns (uint256) { return _balances[account]; }
/** * @dev See {IERC20-balanceOf}. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
MIT
bzzr://0d1d7faa6754d74b7a40e0489566283646cecb89c0c24a0a887d31b108d4a230
{ "func_code_index": [ 453, 568 ] }
11,829
AIB2020
ERC20.sol
0x4b63ce7e179d1db5ddac5d9d54e48356cf3e8b7d
Solidity
ERC20
contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } //转账 function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ // function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
transfer
function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; }
//转账
LineComment
v0.5.17+commit.d19bba13
MIT
bzzr://0d1d7faa6754d74b7a40e0489566283646cecb89c0c24a0a887d31b108d4a230
{ "func_code_index": [ 583, 746 ] }
11,830
AIB2020
ERC20.sol
0x4b63ce7e179d1db5ddac5d9d54e48356cf3e8b7d
Solidity
ERC20
contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } //转账 function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ // function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
allowance
function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; }
/** * @dev See {IERC20-allowance}. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
MIT
bzzr://0d1d7faa6754d74b7a40e0489566283646cecb89c0c24a0a887d31b108d4a230
{ "func_code_index": [ 804, 943 ] }
11,831
AIB2020
ERC20.sol
0x4b63ce7e179d1db5ddac5d9d54e48356cf3e8b7d
Solidity
ERC20
contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } //转账 function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ // function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
approve
function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; }
/** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
MIT
bzzr://0d1d7faa6754d74b7a40e0489566283646cecb89c0c24a0a887d31b108d4a230
{ "func_code_index": [ 1085, 1242 ] }
11,832
AIB2020
ERC20.sol
0x4b63ce7e179d1db5ddac5d9d54e48356cf3e8b7d
Solidity
ERC20
contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } //转账 function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ // function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
transferFrom
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; }
/** * @dev 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`. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
MIT
bzzr://0d1d7faa6754d74b7a40e0489566283646cecb89c0c24a0a887d31b108d4a230
{ "func_code_index": [ 1709, 2018 ] }
11,833
AIB2020
ERC20.sol
0x4b63ce7e179d1db5ddac5d9d54e48356cf3e8b7d
Solidity
ERC20
contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } //转账 function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ // function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
increaseAllowance
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); 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. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
MIT
bzzr://0d1d7faa6754d74b7a40e0489566283646cecb89c0c24a0a887d31b108d4a230
{ "func_code_index": [ 2422, 2637 ] }
11,834
AIB2020
ERC20.sol
0x4b63ce7e179d1db5ddac5d9d54e48356cf3e8b7d
Solidity
ERC20
contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } //转账 function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ // function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
decreaseAllowance
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; }
/** * @dev 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`. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
MIT
bzzr://0d1d7faa6754d74b7a40e0489566283646cecb89c0c24a0a887d31b108d4a230
{ "func_code_index": [ 3135, 3401 ] }
11,835
AIB2020
ERC20.sol
0x4b63ce7e179d1db5ddac5d9d54e48356cf3e8b7d
Solidity
ERC20
contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } //转账 function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ // function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
_transfer
function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); }
/** * @dev 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`. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
MIT
bzzr://0d1d7faa6754d74b7a40e0489566283646cecb89c0c24a0a887d31b108d4a230
{ "func_code_index": [ 3886, 4362 ] }
11,836
AIB2020
ERC20.sol
0x4b63ce7e179d1db5ddac5d9d54e48356cf3e8b7d
Solidity
ERC20
contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } //转账 function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ // function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
_mint
function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); }
//
LineComment
v0.5.17+commit.d19bba13
MIT
bzzr://0d1d7faa6754d74b7a40e0489566283646cecb89c0c24a0a887d31b108d4a230
{ "func_code_index": [ 4646, 4959 ] }
11,837
AIB2020
ERC20.sol
0x4b63ce7e179d1db5ddac5d9d54e48356cf3e8b7d
Solidity
ERC20
contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } //转账 function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ // function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
_burn
function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); }
/** * @dev 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. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
MIT
bzzr://0d1d7faa6754d74b7a40e0489566283646cecb89c0c24a0a887d31b108d4a230
{ "func_code_index": [ 5286, 5639 ] }
11,838
AIB2020
ERC20.sol
0x4b63ce7e179d1db5ddac5d9d54e48356cf3e8b7d
Solidity
ERC20
contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } //转账 function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ // function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
_approve
function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); }
/** * @dev 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. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
MIT
bzzr://0d1d7faa6754d74b7a40e0489566283646cecb89c0c24a0a887d31b108d4a230
{ "func_code_index": [ 6074, 6417 ] }
11,839
AIB2020
ERC20.sol
0x4b63ce7e179d1db5ddac5d9d54e48356cf3e8b7d
Solidity
ERC20
contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } //转账 function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ // function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
_burnFrom
function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); }
/** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
MIT
bzzr://0d1d7faa6754d74b7a40e0489566283646cecb89c0c24a0a887d31b108d4a230
{ "func_code_index": [ 6598, 6835 ] }
11,840
SocialBMIZapper
SocialBMIZapper.sol
0xd2a1c50601df0e0a37f2f915608098022d12eb92
Solidity
SocialBMIZapper
contract SocialBMIZapper is ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; address public governance; address public bmi; address public bmiZapper; // **** ERC20 **** // // Token => Id mapping(address => uint256) public curId; // Token => User Address => Id => Amount deposited mapping(address => mapping(address => mapping(uint256 => uint256))) public deposits; // Token => User Address => Id => Claimed mapping(address => mapping(address => mapping(uint256 => bool))) public claimed; // Token => Id => Amount deposited mapping(address => mapping(uint256 => uint256)) public totalDeposited; // Token => Basket minted per weaveId mapping(address => mapping(uint256 => uint256)) public minted; // Approved users to call weave // This is v important as invalid inputs will // be basically a "fat finger" mapping(address => bool) public approvedWeavers; // **** Constructor and modifiers **** constructor( address _governance, address _bmi, address _bmiZapper ) { governance = _governance; bmi = _bmi; bmiZapper = _bmiZapper; } modifier onlyGov() { require(msg.sender == governance, "!governance"); _; } modifier onlyWeavers { require(msg.sender == governance || approvedWeavers[msg.sender], "!weaver"); _; } receive() external payable {} // **** Protected functions **** function approveWeaver(address _weaver) public onlyGov { approvedWeavers[_weaver] = true; } function revokeWeaver(address _weaver) public onlyGov { approvedWeavers[_weaver] = false; } function setGov(address _governance) public onlyGov { governance = _governance; } // Emergency function recoverERC20(address _token) public onlyGov { IERC20(_token).safeTransfer(governance, IERC20(_token).balanceOf(address(this))); } function socialZap( address _from, address _fromUnderlying, uint256 _fromUnderlyingAmount, uint256 _minBMIRecv, address[] memory _bmiConstituents, uint256[] memory _bmiConstituentsWeightings, address _aggregator, bytes memory _aggregatorData, uint256 deadline ) public onlyWeavers { require(block.timestamp <= deadline, "expired"); uint256 _fromAmount = IERC20(_from).balanceOf(address(this)); IERC20(_from).safeApprove(bmiZapper, 0); IERC20(_from).safeApprove(bmiZapper, _fromAmount); uint256 bmiMinted = BMIZapper(bmiZapper).zapToBMI( _from, _fromAmount, _fromUnderlying, _fromUnderlyingAmount, _minBMIRecv, _bmiConstituents, _bmiConstituentsWeightings, _aggregator, _aggregatorData, true ); minted[_from][curId[_from]] = bmiMinted; curId[_from]++; } // **** Public functions **** /// @notice Deposits ERC20 to be later converted into the Basket by some kind soul function deposit(address _token, uint256 _amount) public nonReentrant { IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); deposits[_token][msg.sender][curId[_token]] = deposits[_token][msg.sender][curId[_token]].add(_amount); totalDeposited[_token][curId[_token]] = totalDeposited[_token][curId[_token]].add(_amount); } /// @notice User doesn't want to wait anymore and just wants their ERC20 back function withdraw(address _token, uint256 _amount) public nonReentrant { // Reverts if withdrawing too many deposits[_token][msg.sender][curId[_token]] = deposits[_token][msg.sender][curId[_token]].sub(_amount); totalDeposited[_token][curId[_token]] = totalDeposited[_token][curId[_token]].sub(_amount); IERC20(_token).safeTransfer(msg.sender, _amount); } /// @notice User withdraws converted Basket token function withdrawBMI(address _token, uint256 _id) public nonReentrant { require(_id < curId[_token], "!weaved"); require(!claimed[_token][msg.sender][_id], "already-claimed"); uint256 userDeposited = deposits[_token][msg.sender][_id]; require(userDeposited > 0, "!deposit"); uint256 ratio = userDeposited.mul(1e18).div(totalDeposited[_token][_id]); uint256 userBasketAmount = minted[_token][_id].mul(ratio).div(1e18); claimed[_token][msg.sender][_id] = true; IERC20(address(bmi)).safeTransfer(msg.sender, userBasketAmount); } /// @notice User withdraws converted Basket token function withdrawBMIMany(address[] memory _tokens, uint256[] memory _ids) public { assert(_tokens.length == _ids.length); for (uint256 i = 0; i < _tokens.length; i++) { withdrawBMI(_tokens[i], _ids[i]); } } }
// Basket Weaver is a way to socialize gas costs related to minting baskets tokens
LineComment
approveWeaver
function approveWeaver(address _weaver) public onlyGov { approvedWeavers[_weaver] = true; }
// **** Protected functions ****
LineComment
v0.7.3+commit.9bfce1f6
MIT
ipfs://9ae22c2252c81517044b9f8249e2c888c45c2c3b61e6eddabf4f8d13dd7a54d8
{ "func_code_index": [ 1511, 1618 ] }
11,841
SocialBMIZapper
SocialBMIZapper.sol
0xd2a1c50601df0e0a37f2f915608098022d12eb92
Solidity
SocialBMIZapper
contract SocialBMIZapper is ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; address public governance; address public bmi; address public bmiZapper; // **** ERC20 **** // // Token => Id mapping(address => uint256) public curId; // Token => User Address => Id => Amount deposited mapping(address => mapping(address => mapping(uint256 => uint256))) public deposits; // Token => User Address => Id => Claimed mapping(address => mapping(address => mapping(uint256 => bool))) public claimed; // Token => Id => Amount deposited mapping(address => mapping(uint256 => uint256)) public totalDeposited; // Token => Basket minted per weaveId mapping(address => mapping(uint256 => uint256)) public minted; // Approved users to call weave // This is v important as invalid inputs will // be basically a "fat finger" mapping(address => bool) public approvedWeavers; // **** Constructor and modifiers **** constructor( address _governance, address _bmi, address _bmiZapper ) { governance = _governance; bmi = _bmi; bmiZapper = _bmiZapper; } modifier onlyGov() { require(msg.sender == governance, "!governance"); _; } modifier onlyWeavers { require(msg.sender == governance || approvedWeavers[msg.sender], "!weaver"); _; } receive() external payable {} // **** Protected functions **** function approveWeaver(address _weaver) public onlyGov { approvedWeavers[_weaver] = true; } function revokeWeaver(address _weaver) public onlyGov { approvedWeavers[_weaver] = false; } function setGov(address _governance) public onlyGov { governance = _governance; } // Emergency function recoverERC20(address _token) public onlyGov { IERC20(_token).safeTransfer(governance, IERC20(_token).balanceOf(address(this))); } function socialZap( address _from, address _fromUnderlying, uint256 _fromUnderlyingAmount, uint256 _minBMIRecv, address[] memory _bmiConstituents, uint256[] memory _bmiConstituentsWeightings, address _aggregator, bytes memory _aggregatorData, uint256 deadline ) public onlyWeavers { require(block.timestamp <= deadline, "expired"); uint256 _fromAmount = IERC20(_from).balanceOf(address(this)); IERC20(_from).safeApprove(bmiZapper, 0); IERC20(_from).safeApprove(bmiZapper, _fromAmount); uint256 bmiMinted = BMIZapper(bmiZapper).zapToBMI( _from, _fromAmount, _fromUnderlying, _fromUnderlyingAmount, _minBMIRecv, _bmiConstituents, _bmiConstituentsWeightings, _aggregator, _aggregatorData, true ); minted[_from][curId[_from]] = bmiMinted; curId[_from]++; } // **** Public functions **** /// @notice Deposits ERC20 to be later converted into the Basket by some kind soul function deposit(address _token, uint256 _amount) public nonReentrant { IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); deposits[_token][msg.sender][curId[_token]] = deposits[_token][msg.sender][curId[_token]].add(_amount); totalDeposited[_token][curId[_token]] = totalDeposited[_token][curId[_token]].add(_amount); } /// @notice User doesn't want to wait anymore and just wants their ERC20 back function withdraw(address _token, uint256 _amount) public nonReentrant { // Reverts if withdrawing too many deposits[_token][msg.sender][curId[_token]] = deposits[_token][msg.sender][curId[_token]].sub(_amount); totalDeposited[_token][curId[_token]] = totalDeposited[_token][curId[_token]].sub(_amount); IERC20(_token).safeTransfer(msg.sender, _amount); } /// @notice User withdraws converted Basket token function withdrawBMI(address _token, uint256 _id) public nonReentrant { require(_id < curId[_token], "!weaved"); require(!claimed[_token][msg.sender][_id], "already-claimed"); uint256 userDeposited = deposits[_token][msg.sender][_id]; require(userDeposited > 0, "!deposit"); uint256 ratio = userDeposited.mul(1e18).div(totalDeposited[_token][_id]); uint256 userBasketAmount = minted[_token][_id].mul(ratio).div(1e18); claimed[_token][msg.sender][_id] = true; IERC20(address(bmi)).safeTransfer(msg.sender, userBasketAmount); } /// @notice User withdraws converted Basket token function withdrawBMIMany(address[] memory _tokens, uint256[] memory _ids) public { assert(_tokens.length == _ids.length); for (uint256 i = 0; i < _tokens.length; i++) { withdrawBMI(_tokens[i], _ids[i]); } } }
// Basket Weaver is a way to socialize gas costs related to minting baskets tokens
LineComment
recoverERC20
function recoverERC20(address _token) public onlyGov { IERC20(_token).safeTransfer(governance, IERC20(_token).balanceOf(address(this))); }
// Emergency
LineComment
v0.7.3+commit.9bfce1f6
MIT
ipfs://9ae22c2252c81517044b9f8249e2c888c45c2c3b61e6eddabf4f8d13dd7a54d8
{ "func_code_index": [ 1845, 1999 ] }
11,842
SocialBMIZapper
SocialBMIZapper.sol
0xd2a1c50601df0e0a37f2f915608098022d12eb92
Solidity
SocialBMIZapper
contract SocialBMIZapper is ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; address public governance; address public bmi; address public bmiZapper; // **** ERC20 **** // // Token => Id mapping(address => uint256) public curId; // Token => User Address => Id => Amount deposited mapping(address => mapping(address => mapping(uint256 => uint256))) public deposits; // Token => User Address => Id => Claimed mapping(address => mapping(address => mapping(uint256 => bool))) public claimed; // Token => Id => Amount deposited mapping(address => mapping(uint256 => uint256)) public totalDeposited; // Token => Basket minted per weaveId mapping(address => mapping(uint256 => uint256)) public minted; // Approved users to call weave // This is v important as invalid inputs will // be basically a "fat finger" mapping(address => bool) public approvedWeavers; // **** Constructor and modifiers **** constructor( address _governance, address _bmi, address _bmiZapper ) { governance = _governance; bmi = _bmi; bmiZapper = _bmiZapper; } modifier onlyGov() { require(msg.sender == governance, "!governance"); _; } modifier onlyWeavers { require(msg.sender == governance || approvedWeavers[msg.sender], "!weaver"); _; } receive() external payable {} // **** Protected functions **** function approveWeaver(address _weaver) public onlyGov { approvedWeavers[_weaver] = true; } function revokeWeaver(address _weaver) public onlyGov { approvedWeavers[_weaver] = false; } function setGov(address _governance) public onlyGov { governance = _governance; } // Emergency function recoverERC20(address _token) public onlyGov { IERC20(_token).safeTransfer(governance, IERC20(_token).balanceOf(address(this))); } function socialZap( address _from, address _fromUnderlying, uint256 _fromUnderlyingAmount, uint256 _minBMIRecv, address[] memory _bmiConstituents, uint256[] memory _bmiConstituentsWeightings, address _aggregator, bytes memory _aggregatorData, uint256 deadline ) public onlyWeavers { require(block.timestamp <= deadline, "expired"); uint256 _fromAmount = IERC20(_from).balanceOf(address(this)); IERC20(_from).safeApprove(bmiZapper, 0); IERC20(_from).safeApprove(bmiZapper, _fromAmount); uint256 bmiMinted = BMIZapper(bmiZapper).zapToBMI( _from, _fromAmount, _fromUnderlying, _fromUnderlyingAmount, _minBMIRecv, _bmiConstituents, _bmiConstituentsWeightings, _aggregator, _aggregatorData, true ); minted[_from][curId[_from]] = bmiMinted; curId[_from]++; } // **** Public functions **** /// @notice Deposits ERC20 to be later converted into the Basket by some kind soul function deposit(address _token, uint256 _amount) public nonReentrant { IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); deposits[_token][msg.sender][curId[_token]] = deposits[_token][msg.sender][curId[_token]].add(_amount); totalDeposited[_token][curId[_token]] = totalDeposited[_token][curId[_token]].add(_amount); } /// @notice User doesn't want to wait anymore and just wants their ERC20 back function withdraw(address _token, uint256 _amount) public nonReentrant { // Reverts if withdrawing too many deposits[_token][msg.sender][curId[_token]] = deposits[_token][msg.sender][curId[_token]].sub(_amount); totalDeposited[_token][curId[_token]] = totalDeposited[_token][curId[_token]].sub(_amount); IERC20(_token).safeTransfer(msg.sender, _amount); } /// @notice User withdraws converted Basket token function withdrawBMI(address _token, uint256 _id) public nonReentrant { require(_id < curId[_token], "!weaved"); require(!claimed[_token][msg.sender][_id], "already-claimed"); uint256 userDeposited = deposits[_token][msg.sender][_id]; require(userDeposited > 0, "!deposit"); uint256 ratio = userDeposited.mul(1e18).div(totalDeposited[_token][_id]); uint256 userBasketAmount = minted[_token][_id].mul(ratio).div(1e18); claimed[_token][msg.sender][_id] = true; IERC20(address(bmi)).safeTransfer(msg.sender, userBasketAmount); } /// @notice User withdraws converted Basket token function withdrawBMIMany(address[] memory _tokens, uint256[] memory _ids) public { assert(_tokens.length == _ids.length); for (uint256 i = 0; i < _tokens.length; i++) { withdrawBMI(_tokens[i], _ids[i]); } } }
// Basket Weaver is a way to socialize gas costs related to minting baskets tokens
LineComment
deposit
function deposit(address _token, uint256 _amount) public nonReentrant { IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); deposits[_token][msg.sender][curId[_token]] = deposits[_token][msg.sender][curId[_token]].add(_amount); totalDeposited[_token][curId[_token]] = totalDeposited[_token][curId[_token]].add(_amount); }
/// @notice Deposits ERC20 to be later converted into the Basket by some kind soul
NatSpecSingleLine
v0.7.3+commit.9bfce1f6
MIT
ipfs://9ae22c2252c81517044b9f8249e2c888c45c2c3b61e6eddabf4f8d13dd7a54d8
{ "func_code_index": [ 3206, 3577 ] }
11,843
SocialBMIZapper
SocialBMIZapper.sol
0xd2a1c50601df0e0a37f2f915608098022d12eb92
Solidity
SocialBMIZapper
contract SocialBMIZapper is ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; address public governance; address public bmi; address public bmiZapper; // **** ERC20 **** // // Token => Id mapping(address => uint256) public curId; // Token => User Address => Id => Amount deposited mapping(address => mapping(address => mapping(uint256 => uint256))) public deposits; // Token => User Address => Id => Claimed mapping(address => mapping(address => mapping(uint256 => bool))) public claimed; // Token => Id => Amount deposited mapping(address => mapping(uint256 => uint256)) public totalDeposited; // Token => Basket minted per weaveId mapping(address => mapping(uint256 => uint256)) public minted; // Approved users to call weave // This is v important as invalid inputs will // be basically a "fat finger" mapping(address => bool) public approvedWeavers; // **** Constructor and modifiers **** constructor( address _governance, address _bmi, address _bmiZapper ) { governance = _governance; bmi = _bmi; bmiZapper = _bmiZapper; } modifier onlyGov() { require(msg.sender == governance, "!governance"); _; } modifier onlyWeavers { require(msg.sender == governance || approvedWeavers[msg.sender], "!weaver"); _; } receive() external payable {} // **** Protected functions **** function approveWeaver(address _weaver) public onlyGov { approvedWeavers[_weaver] = true; } function revokeWeaver(address _weaver) public onlyGov { approvedWeavers[_weaver] = false; } function setGov(address _governance) public onlyGov { governance = _governance; } // Emergency function recoverERC20(address _token) public onlyGov { IERC20(_token).safeTransfer(governance, IERC20(_token).balanceOf(address(this))); } function socialZap( address _from, address _fromUnderlying, uint256 _fromUnderlyingAmount, uint256 _minBMIRecv, address[] memory _bmiConstituents, uint256[] memory _bmiConstituentsWeightings, address _aggregator, bytes memory _aggregatorData, uint256 deadline ) public onlyWeavers { require(block.timestamp <= deadline, "expired"); uint256 _fromAmount = IERC20(_from).balanceOf(address(this)); IERC20(_from).safeApprove(bmiZapper, 0); IERC20(_from).safeApprove(bmiZapper, _fromAmount); uint256 bmiMinted = BMIZapper(bmiZapper).zapToBMI( _from, _fromAmount, _fromUnderlying, _fromUnderlyingAmount, _minBMIRecv, _bmiConstituents, _bmiConstituentsWeightings, _aggregator, _aggregatorData, true ); minted[_from][curId[_from]] = bmiMinted; curId[_from]++; } // **** Public functions **** /// @notice Deposits ERC20 to be later converted into the Basket by some kind soul function deposit(address _token, uint256 _amount) public nonReentrant { IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); deposits[_token][msg.sender][curId[_token]] = deposits[_token][msg.sender][curId[_token]].add(_amount); totalDeposited[_token][curId[_token]] = totalDeposited[_token][curId[_token]].add(_amount); } /// @notice User doesn't want to wait anymore and just wants their ERC20 back function withdraw(address _token, uint256 _amount) public nonReentrant { // Reverts if withdrawing too many deposits[_token][msg.sender][curId[_token]] = deposits[_token][msg.sender][curId[_token]].sub(_amount); totalDeposited[_token][curId[_token]] = totalDeposited[_token][curId[_token]].sub(_amount); IERC20(_token).safeTransfer(msg.sender, _amount); } /// @notice User withdraws converted Basket token function withdrawBMI(address _token, uint256 _id) public nonReentrant { require(_id < curId[_token], "!weaved"); require(!claimed[_token][msg.sender][_id], "already-claimed"); uint256 userDeposited = deposits[_token][msg.sender][_id]; require(userDeposited > 0, "!deposit"); uint256 ratio = userDeposited.mul(1e18).div(totalDeposited[_token][_id]); uint256 userBasketAmount = minted[_token][_id].mul(ratio).div(1e18); claimed[_token][msg.sender][_id] = true; IERC20(address(bmi)).safeTransfer(msg.sender, userBasketAmount); } /// @notice User withdraws converted Basket token function withdrawBMIMany(address[] memory _tokens, uint256[] memory _ids) public { assert(_tokens.length == _ids.length); for (uint256 i = 0; i < _tokens.length; i++) { withdrawBMI(_tokens[i], _ids[i]); } } }
// Basket Weaver is a way to socialize gas costs related to minting baskets tokens
LineComment
withdraw
function withdraw(address _token, uint256 _amount) public nonReentrant { // Reverts if withdrawing too many deposits[_token][msg.sender][curId[_token]] = deposits[_token][msg.sender][curId[_token]].sub(_amount); totalDeposited[_token][curId[_token]] = totalDeposited[_token][curId[_token]].sub(_amount); IERC20(_token).safeTransfer(msg.sender, _amount); }
/// @notice User doesn't want to wait anymore and just wants their ERC20 back
NatSpecSingleLine
v0.7.3+commit.9bfce1f6
MIT
ipfs://9ae22c2252c81517044b9f8249e2c888c45c2c3b61e6eddabf4f8d13dd7a54d8
{ "func_code_index": [ 3661, 4057 ] }
11,844
SocialBMIZapper
SocialBMIZapper.sol
0xd2a1c50601df0e0a37f2f915608098022d12eb92
Solidity
SocialBMIZapper
contract SocialBMIZapper is ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; address public governance; address public bmi; address public bmiZapper; // **** ERC20 **** // // Token => Id mapping(address => uint256) public curId; // Token => User Address => Id => Amount deposited mapping(address => mapping(address => mapping(uint256 => uint256))) public deposits; // Token => User Address => Id => Claimed mapping(address => mapping(address => mapping(uint256 => bool))) public claimed; // Token => Id => Amount deposited mapping(address => mapping(uint256 => uint256)) public totalDeposited; // Token => Basket minted per weaveId mapping(address => mapping(uint256 => uint256)) public minted; // Approved users to call weave // This is v important as invalid inputs will // be basically a "fat finger" mapping(address => bool) public approvedWeavers; // **** Constructor and modifiers **** constructor( address _governance, address _bmi, address _bmiZapper ) { governance = _governance; bmi = _bmi; bmiZapper = _bmiZapper; } modifier onlyGov() { require(msg.sender == governance, "!governance"); _; } modifier onlyWeavers { require(msg.sender == governance || approvedWeavers[msg.sender], "!weaver"); _; } receive() external payable {} // **** Protected functions **** function approveWeaver(address _weaver) public onlyGov { approvedWeavers[_weaver] = true; } function revokeWeaver(address _weaver) public onlyGov { approvedWeavers[_weaver] = false; } function setGov(address _governance) public onlyGov { governance = _governance; } // Emergency function recoverERC20(address _token) public onlyGov { IERC20(_token).safeTransfer(governance, IERC20(_token).balanceOf(address(this))); } function socialZap( address _from, address _fromUnderlying, uint256 _fromUnderlyingAmount, uint256 _minBMIRecv, address[] memory _bmiConstituents, uint256[] memory _bmiConstituentsWeightings, address _aggregator, bytes memory _aggregatorData, uint256 deadline ) public onlyWeavers { require(block.timestamp <= deadline, "expired"); uint256 _fromAmount = IERC20(_from).balanceOf(address(this)); IERC20(_from).safeApprove(bmiZapper, 0); IERC20(_from).safeApprove(bmiZapper, _fromAmount); uint256 bmiMinted = BMIZapper(bmiZapper).zapToBMI( _from, _fromAmount, _fromUnderlying, _fromUnderlyingAmount, _minBMIRecv, _bmiConstituents, _bmiConstituentsWeightings, _aggregator, _aggregatorData, true ); minted[_from][curId[_from]] = bmiMinted; curId[_from]++; } // **** Public functions **** /// @notice Deposits ERC20 to be later converted into the Basket by some kind soul function deposit(address _token, uint256 _amount) public nonReentrant { IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); deposits[_token][msg.sender][curId[_token]] = deposits[_token][msg.sender][curId[_token]].add(_amount); totalDeposited[_token][curId[_token]] = totalDeposited[_token][curId[_token]].add(_amount); } /// @notice User doesn't want to wait anymore and just wants their ERC20 back function withdraw(address _token, uint256 _amount) public nonReentrant { // Reverts if withdrawing too many deposits[_token][msg.sender][curId[_token]] = deposits[_token][msg.sender][curId[_token]].sub(_amount); totalDeposited[_token][curId[_token]] = totalDeposited[_token][curId[_token]].sub(_amount); IERC20(_token).safeTransfer(msg.sender, _amount); } /// @notice User withdraws converted Basket token function withdrawBMI(address _token, uint256 _id) public nonReentrant { require(_id < curId[_token], "!weaved"); require(!claimed[_token][msg.sender][_id], "already-claimed"); uint256 userDeposited = deposits[_token][msg.sender][_id]; require(userDeposited > 0, "!deposit"); uint256 ratio = userDeposited.mul(1e18).div(totalDeposited[_token][_id]); uint256 userBasketAmount = minted[_token][_id].mul(ratio).div(1e18); claimed[_token][msg.sender][_id] = true; IERC20(address(bmi)).safeTransfer(msg.sender, userBasketAmount); } /// @notice User withdraws converted Basket token function withdrawBMIMany(address[] memory _tokens, uint256[] memory _ids) public { assert(_tokens.length == _ids.length); for (uint256 i = 0; i < _tokens.length; i++) { withdrawBMI(_tokens[i], _ids[i]); } } }
// Basket Weaver is a way to socialize gas costs related to minting baskets tokens
LineComment
withdrawBMI
function withdrawBMI(address _token, uint256 _id) public nonReentrant { require(_id < curId[_token], "!weaved"); require(!claimed[_token][msg.sender][_id], "already-claimed"); uint256 userDeposited = deposits[_token][msg.sender][_id]; require(userDeposited > 0, "!deposit"); uint256 ratio = userDeposited.mul(1e18).div(totalDeposited[_token][_id]); uint256 userBasketAmount = minted[_token][_id].mul(ratio).div(1e18); claimed[_token][msg.sender][_id] = true; IERC20(address(bmi)).safeTransfer(msg.sender, userBasketAmount); }
/// @notice User withdraws converted Basket token
NatSpecSingleLine
v0.7.3+commit.9bfce1f6
MIT
ipfs://9ae22c2252c81517044b9f8249e2c888c45c2c3b61e6eddabf4f8d13dd7a54d8
{ "func_code_index": [ 4113, 4712 ] }
11,845
SocialBMIZapper
SocialBMIZapper.sol
0xd2a1c50601df0e0a37f2f915608098022d12eb92
Solidity
SocialBMIZapper
contract SocialBMIZapper is ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; address public governance; address public bmi; address public bmiZapper; // **** ERC20 **** // // Token => Id mapping(address => uint256) public curId; // Token => User Address => Id => Amount deposited mapping(address => mapping(address => mapping(uint256 => uint256))) public deposits; // Token => User Address => Id => Claimed mapping(address => mapping(address => mapping(uint256 => bool))) public claimed; // Token => Id => Amount deposited mapping(address => mapping(uint256 => uint256)) public totalDeposited; // Token => Basket minted per weaveId mapping(address => mapping(uint256 => uint256)) public minted; // Approved users to call weave // This is v important as invalid inputs will // be basically a "fat finger" mapping(address => bool) public approvedWeavers; // **** Constructor and modifiers **** constructor( address _governance, address _bmi, address _bmiZapper ) { governance = _governance; bmi = _bmi; bmiZapper = _bmiZapper; } modifier onlyGov() { require(msg.sender == governance, "!governance"); _; } modifier onlyWeavers { require(msg.sender == governance || approvedWeavers[msg.sender], "!weaver"); _; } receive() external payable {} // **** Protected functions **** function approveWeaver(address _weaver) public onlyGov { approvedWeavers[_weaver] = true; } function revokeWeaver(address _weaver) public onlyGov { approvedWeavers[_weaver] = false; } function setGov(address _governance) public onlyGov { governance = _governance; } // Emergency function recoverERC20(address _token) public onlyGov { IERC20(_token).safeTransfer(governance, IERC20(_token).balanceOf(address(this))); } function socialZap( address _from, address _fromUnderlying, uint256 _fromUnderlyingAmount, uint256 _minBMIRecv, address[] memory _bmiConstituents, uint256[] memory _bmiConstituentsWeightings, address _aggregator, bytes memory _aggregatorData, uint256 deadline ) public onlyWeavers { require(block.timestamp <= deadline, "expired"); uint256 _fromAmount = IERC20(_from).balanceOf(address(this)); IERC20(_from).safeApprove(bmiZapper, 0); IERC20(_from).safeApprove(bmiZapper, _fromAmount); uint256 bmiMinted = BMIZapper(bmiZapper).zapToBMI( _from, _fromAmount, _fromUnderlying, _fromUnderlyingAmount, _minBMIRecv, _bmiConstituents, _bmiConstituentsWeightings, _aggregator, _aggregatorData, true ); minted[_from][curId[_from]] = bmiMinted; curId[_from]++; } // **** Public functions **** /// @notice Deposits ERC20 to be later converted into the Basket by some kind soul function deposit(address _token, uint256 _amount) public nonReentrant { IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); deposits[_token][msg.sender][curId[_token]] = deposits[_token][msg.sender][curId[_token]].add(_amount); totalDeposited[_token][curId[_token]] = totalDeposited[_token][curId[_token]].add(_amount); } /// @notice User doesn't want to wait anymore and just wants their ERC20 back function withdraw(address _token, uint256 _amount) public nonReentrant { // Reverts if withdrawing too many deposits[_token][msg.sender][curId[_token]] = deposits[_token][msg.sender][curId[_token]].sub(_amount); totalDeposited[_token][curId[_token]] = totalDeposited[_token][curId[_token]].sub(_amount); IERC20(_token).safeTransfer(msg.sender, _amount); } /// @notice User withdraws converted Basket token function withdrawBMI(address _token, uint256 _id) public nonReentrant { require(_id < curId[_token], "!weaved"); require(!claimed[_token][msg.sender][_id], "already-claimed"); uint256 userDeposited = deposits[_token][msg.sender][_id]; require(userDeposited > 0, "!deposit"); uint256 ratio = userDeposited.mul(1e18).div(totalDeposited[_token][_id]); uint256 userBasketAmount = minted[_token][_id].mul(ratio).div(1e18); claimed[_token][msg.sender][_id] = true; IERC20(address(bmi)).safeTransfer(msg.sender, userBasketAmount); } /// @notice User withdraws converted Basket token function withdrawBMIMany(address[] memory _tokens, uint256[] memory _ids) public { assert(_tokens.length == _ids.length); for (uint256 i = 0; i < _tokens.length; i++) { withdrawBMI(_tokens[i], _ids[i]); } } }
// Basket Weaver is a way to socialize gas costs related to minting baskets tokens
LineComment
withdrawBMIMany
function withdrawBMIMany(address[] memory _tokens, uint256[] memory _ids) public { assert(_tokens.length == _ids.length); for (uint256 i = 0; i < _tokens.length; i++) { withdrawBMI(_tokens[i], _ids[i]); } }
/// @notice User withdraws converted Basket token
NatSpecSingleLine
v0.7.3+commit.9bfce1f6
MIT
ipfs://9ae22c2252c81517044b9f8249e2c888c45c2c3b61e6eddabf4f8d13dd7a54d8
{ "func_code_index": [ 4768, 5019 ] }
11,846
MFactory
MMath.sol
0x41c3cec9ae12a29d258cf904dda65f08ff742718
Solidity
MMath
contract MMath is MBronze, MConst, MNum { /********************************************************************************************** // calcSpotPrice // // sP = spotPrice // // bI = tokenBalanceIn ( bI / wI ) 1 // // bO = tokenBalanceOut sP = ----------- * ---------- // // wI = tokenWeightIn ( bO / wO ) ( 1 - sF ) // // wO = tokenWeightOut // // sF = swapFee // **********************************************************************************************/ function calcSpotPrice( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint swapFee ) internal pure returns (uint spotPrice) { uint numer = bdiv(tokenBalanceIn, tokenWeightIn); uint denom = bdiv(tokenBalanceOut, tokenWeightOut); uint ratio = bdiv(numer, denom); uint scale = bdiv(BONE, bsub(BONE, swapFee)); return (spotPrice = bmul(ratio, scale)); } /********************************************************************************************** // calcOutGivenIn // // aO = tokenAmountOut // // bO = tokenBalanceOut // // bI = tokenBalanceIn / / bI \ (wI / wO) \ // // aI = tokenAmountIn aO = bO * | 1 - | -------------------------- | ^ | // // wI = tokenWeightIn \ \ ( bI + ( aI * ( 1 - sF )) / / // // wO = tokenWeightOut // // sF = swapFee // **********************************************************************************************/ function calcOutGivenIn( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint tokenAmountIn, uint swapFee ) public pure returns (uint tokenAmountOut) { uint weightRatio = bdiv(tokenWeightIn, tokenWeightOut); uint adjustedIn = bsub(BONE, swapFee); adjustedIn = bmul(tokenAmountIn, adjustedIn); uint y = bdiv(tokenBalanceIn, badd(tokenBalanceIn, adjustedIn)); uint foo = bpow(y, weightRatio); uint bar = bsub(BONE, foo); tokenAmountOut = bmul(tokenBalanceOut, bar); return tokenAmountOut; } /********************************************************************************************** // calcInGivenOut // // aI = tokenAmountIn // // bO = tokenBalanceOut / / bO \ (wO / wI) \ // // bI = tokenBalanceIn bI * | | ------------ | ^ - 1 | // // aO = tokenAmountOut aI = \ \ ( bO - aO ) / / // // wI = tokenWeightIn -------------------------------------------- // // wO = tokenWeightOut ( 1 - sF ) // // sF = swapFee // **********************************************************************************************/ function calcInGivenOut( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint tokenAmountOut, uint swapFee ) public pure returns (uint tokenAmountIn) { uint weightRatio = bdiv(tokenWeightOut, tokenWeightIn); uint diff = bsub(tokenBalanceOut, tokenAmountOut); uint y = bdiv(tokenBalanceOut, diff); uint foo = bpow(y, weightRatio); foo = bsub(foo, BONE); tokenAmountIn = bsub(BONE, swapFee); tokenAmountIn = bdiv(bmul(tokenBalanceIn, foo), tokenAmountIn); return tokenAmountIn; } /********************************************************************************************** // calcPoolOutGivenSingleIn // // pAo = poolAmountOut / \ // // tAi = tokenAmountIn /// / // wI \ \\ \ wI \ // // wI = tokenWeightIn //| tAi *| 1 - || 1 - -- | * sF || + tBi \ -- \ // // tW = totalWeight pAo=|| \ \ \\ tW / // | ^ tW | * pS - pS // // tBi = tokenBalanceIn \\ ------------------------------------- / / // // pS = poolSupply \\ tBi / / // // sF = swapFee \ / // **********************************************************************************************/ function calcPoolOutGivenSingleIn( uint tokenBalanceIn, uint tokenWeightIn, uint poolSupply, uint totalWeight, uint tokenAmountIn, uint swapFee ) internal pure returns (uint poolAmountOut) { // Charge the trading fee for the proportion of tokenAi /// which is implicitly traded to the other pool tokens. // That proportion is (1- weightTokenIn) // tokenAiAfterFee = tAi * (1 - (1-weightTi) * poolFee); uint normalizedWeight = bdiv(tokenWeightIn, totalWeight); uint zaz = bmul(bsub(BONE, normalizedWeight), swapFee); uint tokenAmountInAfterFee = bmul(tokenAmountIn, bsub(BONE, zaz)); uint newTokenBalanceIn = badd(tokenBalanceIn, tokenAmountInAfterFee); uint tokenInRatio = bdiv(newTokenBalanceIn, tokenBalanceIn); // uint newPoolSupply = (ratioTi ^ weightTi) * poolSupply; uint poolRatio = bpow(tokenInRatio, normalizedWeight); uint newPoolSupply = bmul(poolRatio, poolSupply); poolAmountOut = bsub(newPoolSupply, poolSupply); return poolAmountOut; } /********************************************************************************************** // calcSingleOutGivenPoolIn // // tAo = tokenAmountOut / / \\ // // bO = tokenBalanceOut / // pS - (pAi * (1 - eF)) \ / 1 \ \\ // // pAi = poolAmountIn | bO - || ----------------------- | ^ | --------- | * b0 || // // ps = poolSupply \ \\ pS / \(wO / tW)/ // // // wI = tokenWeightIn tAo = \ \ // // // tW = totalWeight / / wO \ \ // // sF = swapFee * | 1 - | 1 - ---- | * sF | // // eF = exitFee \ \ tW / / // **********************************************************************************************/ function calcSingleOutGivenPoolIn( uint tokenBalanceOut, uint tokenWeightOut, uint poolSupply, uint totalWeight, uint poolAmountIn, uint swapFee ) internal pure returns (uint tokenAmountOut) { uint normalizedWeight = bdiv(tokenWeightOut, totalWeight); // charge exit fee on the pool token side // pAiAfterExitFee = pAi*(1-exitFee) uint poolAmountInAfterExitFee = bmul(poolAmountIn, BONE); uint newPoolSupply = bsub(poolSupply, poolAmountInAfterExitFee); uint poolRatio = bdiv(newPoolSupply, poolSupply); // newBalTo = poolRatio^(1/weightTo) * balTo; uint tokenOutRatio = bpow(poolRatio, bdiv(BONE, normalizedWeight)); uint newTokenBalanceOut = bmul(tokenOutRatio, tokenBalanceOut); uint tokenAmountOutBeforeSwapFee = bsub(tokenBalanceOut, newTokenBalanceOut); // charge swap fee on the output token side //uint tAo = tAoBeforeSwapFee * (1 - (1-weightTo) * swapFee) uint zaz = bmul(bsub(BONE, normalizedWeight), swapFee); tokenAmountOut = bmul(tokenAmountOutBeforeSwapFee, bsub(BONE, zaz)); return tokenAmountOut; } }
calcSpotPrice
function calcSpotPrice( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint swapFee ) internal pure returns (uint spotPrice) { uint numer = bdiv(tokenBalanceIn, tokenWeightIn); uint denom = bdiv(tokenBalanceOut, tokenWeightOut); uint ratio = bdiv(numer, denom); uint scale = bdiv(BONE, bsub(BONE, swapFee)); return (spotPrice = bmul(ratio, scale)); }
/********************************************************************************************** // calcSpotPrice // // sP = spotPrice // // bI = tokenBalanceIn ( bI / wI ) 1 // // bO = tokenBalanceOut sP = ----------- * ---------- // // wI = tokenWeightIn ( bO / wO ) ( 1 - sF ) // // wO = tokenWeightOut // // sF = swapFee // **********************************************************************************************/
NatSpecMultiLine
v0.5.12+commit.7709ece9
Unlicense
bzzr://2a277232a61e32885976daf44d130a763efd4c67a6d4b0254dc6f0647de2e950
{ "func_code_index": [ 942, 1434 ] }
11,847
MFactory
MMath.sol
0x41c3cec9ae12a29d258cf904dda65f08ff742718
Solidity
MMath
contract MMath is MBronze, MConst, MNum { /********************************************************************************************** // calcSpotPrice // // sP = spotPrice // // bI = tokenBalanceIn ( bI / wI ) 1 // // bO = tokenBalanceOut sP = ----------- * ---------- // // wI = tokenWeightIn ( bO / wO ) ( 1 - sF ) // // wO = tokenWeightOut // // sF = swapFee // **********************************************************************************************/ function calcSpotPrice( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint swapFee ) internal pure returns (uint spotPrice) { uint numer = bdiv(tokenBalanceIn, tokenWeightIn); uint denom = bdiv(tokenBalanceOut, tokenWeightOut); uint ratio = bdiv(numer, denom); uint scale = bdiv(BONE, bsub(BONE, swapFee)); return (spotPrice = bmul(ratio, scale)); } /********************************************************************************************** // calcOutGivenIn // // aO = tokenAmountOut // // bO = tokenBalanceOut // // bI = tokenBalanceIn / / bI \ (wI / wO) \ // // aI = tokenAmountIn aO = bO * | 1 - | -------------------------- | ^ | // // wI = tokenWeightIn \ \ ( bI + ( aI * ( 1 - sF )) / / // // wO = tokenWeightOut // // sF = swapFee // **********************************************************************************************/ function calcOutGivenIn( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint tokenAmountIn, uint swapFee ) public pure returns (uint tokenAmountOut) { uint weightRatio = bdiv(tokenWeightIn, tokenWeightOut); uint adjustedIn = bsub(BONE, swapFee); adjustedIn = bmul(tokenAmountIn, adjustedIn); uint y = bdiv(tokenBalanceIn, badd(tokenBalanceIn, adjustedIn)); uint foo = bpow(y, weightRatio); uint bar = bsub(BONE, foo); tokenAmountOut = bmul(tokenBalanceOut, bar); return tokenAmountOut; } /********************************************************************************************** // calcInGivenOut // // aI = tokenAmountIn // // bO = tokenBalanceOut / / bO \ (wO / wI) \ // // bI = tokenBalanceIn bI * | | ------------ | ^ - 1 | // // aO = tokenAmountOut aI = \ \ ( bO - aO ) / / // // wI = tokenWeightIn -------------------------------------------- // // wO = tokenWeightOut ( 1 - sF ) // // sF = swapFee // **********************************************************************************************/ function calcInGivenOut( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint tokenAmountOut, uint swapFee ) public pure returns (uint tokenAmountIn) { uint weightRatio = bdiv(tokenWeightOut, tokenWeightIn); uint diff = bsub(tokenBalanceOut, tokenAmountOut); uint y = bdiv(tokenBalanceOut, diff); uint foo = bpow(y, weightRatio); foo = bsub(foo, BONE); tokenAmountIn = bsub(BONE, swapFee); tokenAmountIn = bdiv(bmul(tokenBalanceIn, foo), tokenAmountIn); return tokenAmountIn; } /********************************************************************************************** // calcPoolOutGivenSingleIn // // pAo = poolAmountOut / \ // // tAi = tokenAmountIn /// / // wI \ \\ \ wI \ // // wI = tokenWeightIn //| tAi *| 1 - || 1 - -- | * sF || + tBi \ -- \ // // tW = totalWeight pAo=|| \ \ \\ tW / // | ^ tW | * pS - pS // // tBi = tokenBalanceIn \\ ------------------------------------- / / // // pS = poolSupply \\ tBi / / // // sF = swapFee \ / // **********************************************************************************************/ function calcPoolOutGivenSingleIn( uint tokenBalanceIn, uint tokenWeightIn, uint poolSupply, uint totalWeight, uint tokenAmountIn, uint swapFee ) internal pure returns (uint poolAmountOut) { // Charge the trading fee for the proportion of tokenAi /// which is implicitly traded to the other pool tokens. // That proportion is (1- weightTokenIn) // tokenAiAfterFee = tAi * (1 - (1-weightTi) * poolFee); uint normalizedWeight = bdiv(tokenWeightIn, totalWeight); uint zaz = bmul(bsub(BONE, normalizedWeight), swapFee); uint tokenAmountInAfterFee = bmul(tokenAmountIn, bsub(BONE, zaz)); uint newTokenBalanceIn = badd(tokenBalanceIn, tokenAmountInAfterFee); uint tokenInRatio = bdiv(newTokenBalanceIn, tokenBalanceIn); // uint newPoolSupply = (ratioTi ^ weightTi) * poolSupply; uint poolRatio = bpow(tokenInRatio, normalizedWeight); uint newPoolSupply = bmul(poolRatio, poolSupply); poolAmountOut = bsub(newPoolSupply, poolSupply); return poolAmountOut; } /********************************************************************************************** // calcSingleOutGivenPoolIn // // tAo = tokenAmountOut / / \\ // // bO = tokenBalanceOut / // pS - (pAi * (1 - eF)) \ / 1 \ \\ // // pAi = poolAmountIn | bO - || ----------------------- | ^ | --------- | * b0 || // // ps = poolSupply \ \\ pS / \(wO / tW)/ // // // wI = tokenWeightIn tAo = \ \ // // // tW = totalWeight / / wO \ \ // // sF = swapFee * | 1 - | 1 - ---- | * sF | // // eF = exitFee \ \ tW / / // **********************************************************************************************/ function calcSingleOutGivenPoolIn( uint tokenBalanceOut, uint tokenWeightOut, uint poolSupply, uint totalWeight, uint poolAmountIn, uint swapFee ) internal pure returns (uint tokenAmountOut) { uint normalizedWeight = bdiv(tokenWeightOut, totalWeight); // charge exit fee on the pool token side // pAiAfterExitFee = pAi*(1-exitFee) uint poolAmountInAfterExitFee = bmul(poolAmountIn, BONE); uint newPoolSupply = bsub(poolSupply, poolAmountInAfterExitFee); uint poolRatio = bdiv(newPoolSupply, poolSupply); // newBalTo = poolRatio^(1/weightTo) * balTo; uint tokenOutRatio = bpow(poolRatio, bdiv(BONE, normalizedWeight)); uint newTokenBalanceOut = bmul(tokenOutRatio, tokenBalanceOut); uint tokenAmountOutBeforeSwapFee = bsub(tokenBalanceOut, newTokenBalanceOut); // charge swap fee on the output token side //uint tAo = tAoBeforeSwapFee * (1 - (1-weightTo) * swapFee) uint zaz = bmul(bsub(BONE, normalizedWeight), swapFee); tokenAmountOut = bmul(tokenAmountOutBeforeSwapFee, bsub(BONE, zaz)); return tokenAmountOut; } }
calcOutGivenIn
function calcOutGivenIn( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint tokenAmountIn, uint swapFee ) public pure returns (uint tokenAmountOut) { uint weightRatio = bdiv(tokenWeightIn, tokenWeightOut); uint adjustedIn = bsub(BONE, swapFee); adjustedIn = bmul(tokenAmountIn, adjustedIn); uint y = bdiv(tokenBalanceIn, badd(tokenBalanceIn, adjustedIn)); uint foo = bpow(y, weightRatio); uint bar = bsub(BONE, foo); tokenAmountOut = bmul(tokenBalanceOut, bar); return tokenAmountOut; }
/********************************************************************************************** // calcOutGivenIn // // aO = tokenAmountOut // // bO = tokenBalanceOut // // bI = tokenBalanceIn / / bI \ (wI / wO) \ // // aI = tokenAmountIn aO = bO * | 1 - | -------------------------- | ^ | // // wI = tokenWeightIn \ \ ( bI + ( aI * ( 1 - sF )) / / // // wO = tokenWeightOut // // sF = swapFee // **********************************************************************************************/
NatSpecMultiLine
v0.5.12+commit.7709ece9
Unlicense
bzzr://2a277232a61e32885976daf44d130a763efd4c67a6d4b0254dc6f0647de2e950
{ "func_code_index": [ 2436, 3096 ] }
11,848
MFactory
MMath.sol
0x41c3cec9ae12a29d258cf904dda65f08ff742718
Solidity
MMath
contract MMath is MBronze, MConst, MNum { /********************************************************************************************** // calcSpotPrice // // sP = spotPrice // // bI = tokenBalanceIn ( bI / wI ) 1 // // bO = tokenBalanceOut sP = ----------- * ---------- // // wI = tokenWeightIn ( bO / wO ) ( 1 - sF ) // // wO = tokenWeightOut // // sF = swapFee // **********************************************************************************************/ function calcSpotPrice( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint swapFee ) internal pure returns (uint spotPrice) { uint numer = bdiv(tokenBalanceIn, tokenWeightIn); uint denom = bdiv(tokenBalanceOut, tokenWeightOut); uint ratio = bdiv(numer, denom); uint scale = bdiv(BONE, bsub(BONE, swapFee)); return (spotPrice = bmul(ratio, scale)); } /********************************************************************************************** // calcOutGivenIn // // aO = tokenAmountOut // // bO = tokenBalanceOut // // bI = tokenBalanceIn / / bI \ (wI / wO) \ // // aI = tokenAmountIn aO = bO * | 1 - | -------------------------- | ^ | // // wI = tokenWeightIn \ \ ( bI + ( aI * ( 1 - sF )) / / // // wO = tokenWeightOut // // sF = swapFee // **********************************************************************************************/ function calcOutGivenIn( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint tokenAmountIn, uint swapFee ) public pure returns (uint tokenAmountOut) { uint weightRatio = bdiv(tokenWeightIn, tokenWeightOut); uint adjustedIn = bsub(BONE, swapFee); adjustedIn = bmul(tokenAmountIn, adjustedIn); uint y = bdiv(tokenBalanceIn, badd(tokenBalanceIn, adjustedIn)); uint foo = bpow(y, weightRatio); uint bar = bsub(BONE, foo); tokenAmountOut = bmul(tokenBalanceOut, bar); return tokenAmountOut; } /********************************************************************************************** // calcInGivenOut // // aI = tokenAmountIn // // bO = tokenBalanceOut / / bO \ (wO / wI) \ // // bI = tokenBalanceIn bI * | | ------------ | ^ - 1 | // // aO = tokenAmountOut aI = \ \ ( bO - aO ) / / // // wI = tokenWeightIn -------------------------------------------- // // wO = tokenWeightOut ( 1 - sF ) // // sF = swapFee // **********************************************************************************************/ function calcInGivenOut( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint tokenAmountOut, uint swapFee ) public pure returns (uint tokenAmountIn) { uint weightRatio = bdiv(tokenWeightOut, tokenWeightIn); uint diff = bsub(tokenBalanceOut, tokenAmountOut); uint y = bdiv(tokenBalanceOut, diff); uint foo = bpow(y, weightRatio); foo = bsub(foo, BONE); tokenAmountIn = bsub(BONE, swapFee); tokenAmountIn = bdiv(bmul(tokenBalanceIn, foo), tokenAmountIn); return tokenAmountIn; } /********************************************************************************************** // calcPoolOutGivenSingleIn // // pAo = poolAmountOut / \ // // tAi = tokenAmountIn /// / // wI \ \\ \ wI \ // // wI = tokenWeightIn //| tAi *| 1 - || 1 - -- | * sF || + tBi \ -- \ // // tW = totalWeight pAo=|| \ \ \\ tW / // | ^ tW | * pS - pS // // tBi = tokenBalanceIn \\ ------------------------------------- / / // // pS = poolSupply \\ tBi / / // // sF = swapFee \ / // **********************************************************************************************/ function calcPoolOutGivenSingleIn( uint tokenBalanceIn, uint tokenWeightIn, uint poolSupply, uint totalWeight, uint tokenAmountIn, uint swapFee ) internal pure returns (uint poolAmountOut) { // Charge the trading fee for the proportion of tokenAi /// which is implicitly traded to the other pool tokens. // That proportion is (1- weightTokenIn) // tokenAiAfterFee = tAi * (1 - (1-weightTi) * poolFee); uint normalizedWeight = bdiv(tokenWeightIn, totalWeight); uint zaz = bmul(bsub(BONE, normalizedWeight), swapFee); uint tokenAmountInAfterFee = bmul(tokenAmountIn, bsub(BONE, zaz)); uint newTokenBalanceIn = badd(tokenBalanceIn, tokenAmountInAfterFee); uint tokenInRatio = bdiv(newTokenBalanceIn, tokenBalanceIn); // uint newPoolSupply = (ratioTi ^ weightTi) * poolSupply; uint poolRatio = bpow(tokenInRatio, normalizedWeight); uint newPoolSupply = bmul(poolRatio, poolSupply); poolAmountOut = bsub(newPoolSupply, poolSupply); return poolAmountOut; } /********************************************************************************************** // calcSingleOutGivenPoolIn // // tAo = tokenAmountOut / / \\ // // bO = tokenBalanceOut / // pS - (pAi * (1 - eF)) \ / 1 \ \\ // // pAi = poolAmountIn | bO - || ----------------------- | ^ | --------- | * b0 || // // ps = poolSupply \ \\ pS / \(wO / tW)/ // // // wI = tokenWeightIn tAo = \ \ // // // tW = totalWeight / / wO \ \ // // sF = swapFee * | 1 - | 1 - ---- | * sF | // // eF = exitFee \ \ tW / / // **********************************************************************************************/ function calcSingleOutGivenPoolIn( uint tokenBalanceOut, uint tokenWeightOut, uint poolSupply, uint totalWeight, uint poolAmountIn, uint swapFee ) internal pure returns (uint tokenAmountOut) { uint normalizedWeight = bdiv(tokenWeightOut, totalWeight); // charge exit fee on the pool token side // pAiAfterExitFee = pAi*(1-exitFee) uint poolAmountInAfterExitFee = bmul(poolAmountIn, BONE); uint newPoolSupply = bsub(poolSupply, poolAmountInAfterExitFee); uint poolRatio = bdiv(newPoolSupply, poolSupply); // newBalTo = poolRatio^(1/weightTo) * balTo; uint tokenOutRatio = bpow(poolRatio, bdiv(BONE, normalizedWeight)); uint newTokenBalanceOut = bmul(tokenOutRatio, tokenBalanceOut); uint tokenAmountOutBeforeSwapFee = bsub(tokenBalanceOut, newTokenBalanceOut); // charge swap fee on the output token side //uint tAo = tAoBeforeSwapFee * (1 - (1-weightTo) * swapFee) uint zaz = bmul(bsub(BONE, normalizedWeight), swapFee); tokenAmountOut = bmul(tokenAmountOutBeforeSwapFee, bsub(BONE, zaz)); return tokenAmountOut; } }
calcInGivenOut
function calcInGivenOut( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint tokenAmountOut, uint swapFee ) public pure returns (uint tokenAmountIn) { uint weightRatio = bdiv(tokenWeightOut, tokenWeightIn); uint diff = bsub(tokenBalanceOut, tokenAmountOut); uint y = bdiv(tokenBalanceOut, diff); uint foo = bpow(y, weightRatio); foo = bsub(foo, BONE); tokenAmountIn = bsub(BONE, swapFee); tokenAmountIn = bdiv(bmul(tokenBalanceIn, foo), tokenAmountIn); return tokenAmountIn; }
/********************************************************************************************** // calcInGivenOut // // aI = tokenAmountIn // // bO = tokenBalanceOut / / bO \ (wO / wI) \ // // bI = tokenBalanceIn bI * | | ------------ | ^ - 1 | // // aO = tokenAmountOut aI = \ \ ( bO - aO ) / / // // wI = tokenWeightIn -------------------------------------------- // // wO = tokenWeightOut ( 1 - sF ) // // sF = swapFee // **********************************************************************************************/
NatSpecMultiLine
v0.5.12+commit.7709ece9
Unlicense
bzzr://2a277232a61e32885976daf44d130a763efd4c67a6d4b0254dc6f0647de2e950
{ "func_code_index": [ 4098, 4747 ] }
11,849
MFactory
MMath.sol
0x41c3cec9ae12a29d258cf904dda65f08ff742718
Solidity
MMath
contract MMath is MBronze, MConst, MNum { /********************************************************************************************** // calcSpotPrice // // sP = spotPrice // // bI = tokenBalanceIn ( bI / wI ) 1 // // bO = tokenBalanceOut sP = ----------- * ---------- // // wI = tokenWeightIn ( bO / wO ) ( 1 - sF ) // // wO = tokenWeightOut // // sF = swapFee // **********************************************************************************************/ function calcSpotPrice( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint swapFee ) internal pure returns (uint spotPrice) { uint numer = bdiv(tokenBalanceIn, tokenWeightIn); uint denom = bdiv(tokenBalanceOut, tokenWeightOut); uint ratio = bdiv(numer, denom); uint scale = bdiv(BONE, bsub(BONE, swapFee)); return (spotPrice = bmul(ratio, scale)); } /********************************************************************************************** // calcOutGivenIn // // aO = tokenAmountOut // // bO = tokenBalanceOut // // bI = tokenBalanceIn / / bI \ (wI / wO) \ // // aI = tokenAmountIn aO = bO * | 1 - | -------------------------- | ^ | // // wI = tokenWeightIn \ \ ( bI + ( aI * ( 1 - sF )) / / // // wO = tokenWeightOut // // sF = swapFee // **********************************************************************************************/ function calcOutGivenIn( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint tokenAmountIn, uint swapFee ) public pure returns (uint tokenAmountOut) { uint weightRatio = bdiv(tokenWeightIn, tokenWeightOut); uint adjustedIn = bsub(BONE, swapFee); adjustedIn = bmul(tokenAmountIn, adjustedIn); uint y = bdiv(tokenBalanceIn, badd(tokenBalanceIn, adjustedIn)); uint foo = bpow(y, weightRatio); uint bar = bsub(BONE, foo); tokenAmountOut = bmul(tokenBalanceOut, bar); return tokenAmountOut; } /********************************************************************************************** // calcInGivenOut // // aI = tokenAmountIn // // bO = tokenBalanceOut / / bO \ (wO / wI) \ // // bI = tokenBalanceIn bI * | | ------------ | ^ - 1 | // // aO = tokenAmountOut aI = \ \ ( bO - aO ) / / // // wI = tokenWeightIn -------------------------------------------- // // wO = tokenWeightOut ( 1 - sF ) // // sF = swapFee // **********************************************************************************************/ function calcInGivenOut( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint tokenAmountOut, uint swapFee ) public pure returns (uint tokenAmountIn) { uint weightRatio = bdiv(tokenWeightOut, tokenWeightIn); uint diff = bsub(tokenBalanceOut, tokenAmountOut); uint y = bdiv(tokenBalanceOut, diff); uint foo = bpow(y, weightRatio); foo = bsub(foo, BONE); tokenAmountIn = bsub(BONE, swapFee); tokenAmountIn = bdiv(bmul(tokenBalanceIn, foo), tokenAmountIn); return tokenAmountIn; } /********************************************************************************************** // calcPoolOutGivenSingleIn // // pAo = poolAmountOut / \ // // tAi = tokenAmountIn /// / // wI \ \\ \ wI \ // // wI = tokenWeightIn //| tAi *| 1 - || 1 - -- | * sF || + tBi \ -- \ // // tW = totalWeight pAo=|| \ \ \\ tW / // | ^ tW | * pS - pS // // tBi = tokenBalanceIn \\ ------------------------------------- / / // // pS = poolSupply \\ tBi / / // // sF = swapFee \ / // **********************************************************************************************/ function calcPoolOutGivenSingleIn( uint tokenBalanceIn, uint tokenWeightIn, uint poolSupply, uint totalWeight, uint tokenAmountIn, uint swapFee ) internal pure returns (uint poolAmountOut) { // Charge the trading fee for the proportion of tokenAi /// which is implicitly traded to the other pool tokens. // That proportion is (1- weightTokenIn) // tokenAiAfterFee = tAi * (1 - (1-weightTi) * poolFee); uint normalizedWeight = bdiv(tokenWeightIn, totalWeight); uint zaz = bmul(bsub(BONE, normalizedWeight), swapFee); uint tokenAmountInAfterFee = bmul(tokenAmountIn, bsub(BONE, zaz)); uint newTokenBalanceIn = badd(tokenBalanceIn, tokenAmountInAfterFee); uint tokenInRatio = bdiv(newTokenBalanceIn, tokenBalanceIn); // uint newPoolSupply = (ratioTi ^ weightTi) * poolSupply; uint poolRatio = bpow(tokenInRatio, normalizedWeight); uint newPoolSupply = bmul(poolRatio, poolSupply); poolAmountOut = bsub(newPoolSupply, poolSupply); return poolAmountOut; } /********************************************************************************************** // calcSingleOutGivenPoolIn // // tAo = tokenAmountOut / / \\ // // bO = tokenBalanceOut / // pS - (pAi * (1 - eF)) \ / 1 \ \\ // // pAi = poolAmountIn | bO - || ----------------------- | ^ | --------- | * b0 || // // ps = poolSupply \ \\ pS / \(wO / tW)/ // // // wI = tokenWeightIn tAo = \ \ // // // tW = totalWeight / / wO \ \ // // sF = swapFee * | 1 - | 1 - ---- | * sF | // // eF = exitFee \ \ tW / / // **********************************************************************************************/ function calcSingleOutGivenPoolIn( uint tokenBalanceOut, uint tokenWeightOut, uint poolSupply, uint totalWeight, uint poolAmountIn, uint swapFee ) internal pure returns (uint tokenAmountOut) { uint normalizedWeight = bdiv(tokenWeightOut, totalWeight); // charge exit fee on the pool token side // pAiAfterExitFee = pAi*(1-exitFee) uint poolAmountInAfterExitFee = bmul(poolAmountIn, BONE); uint newPoolSupply = bsub(poolSupply, poolAmountInAfterExitFee); uint poolRatio = bdiv(newPoolSupply, poolSupply); // newBalTo = poolRatio^(1/weightTo) * balTo; uint tokenOutRatio = bpow(poolRatio, bdiv(BONE, normalizedWeight)); uint newTokenBalanceOut = bmul(tokenOutRatio, tokenBalanceOut); uint tokenAmountOutBeforeSwapFee = bsub(tokenBalanceOut, newTokenBalanceOut); // charge swap fee on the output token side //uint tAo = tAoBeforeSwapFee * (1 - (1-weightTo) * swapFee) uint zaz = bmul(bsub(BONE, normalizedWeight), swapFee); tokenAmountOut = bmul(tokenAmountOutBeforeSwapFee, bsub(BONE, zaz)); return tokenAmountOut; } }
calcPoolOutGivenSingleIn
function calcPoolOutGivenSingleIn( uint tokenBalanceIn, uint tokenWeightIn, uint poolSupply, uint totalWeight, uint tokenAmountIn, uint swapFee ) internal pure returns (uint poolAmountOut) { // Charge the trading fee for the proportion of tokenAi /// which is implicitly traded to the other pool tokens. // That proportion is (1- weightTokenIn) // tokenAiAfterFee = tAi * (1 - (1-weightTi) * poolFee); uint normalizedWeight = bdiv(tokenWeightIn, totalWeight); uint zaz = bmul(bsub(BONE, normalizedWeight), swapFee); uint tokenAmountInAfterFee = bmul(tokenAmountIn, bsub(BONE, zaz)); uint newTokenBalanceIn = badd(tokenBalanceIn, tokenAmountInAfterFee); uint tokenInRatio = bdiv(newTokenBalanceIn, tokenBalanceIn); // uint newPoolSupply = (ratioTi ^ weightTi) * poolSupply; uint poolRatio = bpow(tokenInRatio, normalizedWeight); uint newPoolSupply = bmul(poolRatio, poolSupply); poolAmountOut = bsub(newPoolSupply, poolSupply); return poolAmountOut; }
/********************************************************************************************** // calcPoolOutGivenSingleIn // // pAo = poolAmountOut / \ // // tAi = tokenAmountIn /// / // wI \ \\ \ wI \ // // wI = tokenWeightIn //| tAi *| 1 - || 1 - -- | * sF || + tBi \ -- \ // // tW = totalWeight pAo=|| \ \ \\ tW / // | ^ tW | * pS - pS // // tBi = tokenBalanceIn \\ ------------------------------------- / / // // pS = poolSupply \\ tBi / / // // sF = swapFee \ / // **********************************************************************************************/
NatSpecMultiLine
v0.5.12+commit.7709ece9
Unlicense
bzzr://2a277232a61e32885976daf44d130a763efd4c67a6d4b0254dc6f0647de2e950
{ "func_code_index": [ 5749, 6886 ] }
11,850
MFactory
MMath.sol
0x41c3cec9ae12a29d258cf904dda65f08ff742718
Solidity
MMath
contract MMath is MBronze, MConst, MNum { /********************************************************************************************** // calcSpotPrice // // sP = spotPrice // // bI = tokenBalanceIn ( bI / wI ) 1 // // bO = tokenBalanceOut sP = ----------- * ---------- // // wI = tokenWeightIn ( bO / wO ) ( 1 - sF ) // // wO = tokenWeightOut // // sF = swapFee // **********************************************************************************************/ function calcSpotPrice( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint swapFee ) internal pure returns (uint spotPrice) { uint numer = bdiv(tokenBalanceIn, tokenWeightIn); uint denom = bdiv(tokenBalanceOut, tokenWeightOut); uint ratio = bdiv(numer, denom); uint scale = bdiv(BONE, bsub(BONE, swapFee)); return (spotPrice = bmul(ratio, scale)); } /********************************************************************************************** // calcOutGivenIn // // aO = tokenAmountOut // // bO = tokenBalanceOut // // bI = tokenBalanceIn / / bI \ (wI / wO) \ // // aI = tokenAmountIn aO = bO * | 1 - | -------------------------- | ^ | // // wI = tokenWeightIn \ \ ( bI + ( aI * ( 1 - sF )) / / // // wO = tokenWeightOut // // sF = swapFee // **********************************************************************************************/ function calcOutGivenIn( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint tokenAmountIn, uint swapFee ) public pure returns (uint tokenAmountOut) { uint weightRatio = bdiv(tokenWeightIn, tokenWeightOut); uint adjustedIn = bsub(BONE, swapFee); adjustedIn = bmul(tokenAmountIn, adjustedIn); uint y = bdiv(tokenBalanceIn, badd(tokenBalanceIn, adjustedIn)); uint foo = bpow(y, weightRatio); uint bar = bsub(BONE, foo); tokenAmountOut = bmul(tokenBalanceOut, bar); return tokenAmountOut; } /********************************************************************************************** // calcInGivenOut // // aI = tokenAmountIn // // bO = tokenBalanceOut / / bO \ (wO / wI) \ // // bI = tokenBalanceIn bI * | | ------------ | ^ - 1 | // // aO = tokenAmountOut aI = \ \ ( bO - aO ) / / // // wI = tokenWeightIn -------------------------------------------- // // wO = tokenWeightOut ( 1 - sF ) // // sF = swapFee // **********************************************************************************************/ function calcInGivenOut( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint tokenAmountOut, uint swapFee ) public pure returns (uint tokenAmountIn) { uint weightRatio = bdiv(tokenWeightOut, tokenWeightIn); uint diff = bsub(tokenBalanceOut, tokenAmountOut); uint y = bdiv(tokenBalanceOut, diff); uint foo = bpow(y, weightRatio); foo = bsub(foo, BONE); tokenAmountIn = bsub(BONE, swapFee); tokenAmountIn = bdiv(bmul(tokenBalanceIn, foo), tokenAmountIn); return tokenAmountIn; } /********************************************************************************************** // calcPoolOutGivenSingleIn // // pAo = poolAmountOut / \ // // tAi = tokenAmountIn /// / // wI \ \\ \ wI \ // // wI = tokenWeightIn //| tAi *| 1 - || 1 - -- | * sF || + tBi \ -- \ // // tW = totalWeight pAo=|| \ \ \\ tW / // | ^ tW | * pS - pS // // tBi = tokenBalanceIn \\ ------------------------------------- / / // // pS = poolSupply \\ tBi / / // // sF = swapFee \ / // **********************************************************************************************/ function calcPoolOutGivenSingleIn( uint tokenBalanceIn, uint tokenWeightIn, uint poolSupply, uint totalWeight, uint tokenAmountIn, uint swapFee ) internal pure returns (uint poolAmountOut) { // Charge the trading fee for the proportion of tokenAi /// which is implicitly traded to the other pool tokens. // That proportion is (1- weightTokenIn) // tokenAiAfterFee = tAi * (1 - (1-weightTi) * poolFee); uint normalizedWeight = bdiv(tokenWeightIn, totalWeight); uint zaz = bmul(bsub(BONE, normalizedWeight), swapFee); uint tokenAmountInAfterFee = bmul(tokenAmountIn, bsub(BONE, zaz)); uint newTokenBalanceIn = badd(tokenBalanceIn, tokenAmountInAfterFee); uint tokenInRatio = bdiv(newTokenBalanceIn, tokenBalanceIn); // uint newPoolSupply = (ratioTi ^ weightTi) * poolSupply; uint poolRatio = bpow(tokenInRatio, normalizedWeight); uint newPoolSupply = bmul(poolRatio, poolSupply); poolAmountOut = bsub(newPoolSupply, poolSupply); return poolAmountOut; } /********************************************************************************************** // calcSingleOutGivenPoolIn // // tAo = tokenAmountOut / / \\ // // bO = tokenBalanceOut / // pS - (pAi * (1 - eF)) \ / 1 \ \\ // // pAi = poolAmountIn | bO - || ----------------------- | ^ | --------- | * b0 || // // ps = poolSupply \ \\ pS / \(wO / tW)/ // // // wI = tokenWeightIn tAo = \ \ // // // tW = totalWeight / / wO \ \ // // sF = swapFee * | 1 - | 1 - ---- | * sF | // // eF = exitFee \ \ tW / / // **********************************************************************************************/ function calcSingleOutGivenPoolIn( uint tokenBalanceOut, uint tokenWeightOut, uint poolSupply, uint totalWeight, uint poolAmountIn, uint swapFee ) internal pure returns (uint tokenAmountOut) { uint normalizedWeight = bdiv(tokenWeightOut, totalWeight); // charge exit fee on the pool token side // pAiAfterExitFee = pAi*(1-exitFee) uint poolAmountInAfterExitFee = bmul(poolAmountIn, BONE); uint newPoolSupply = bsub(poolSupply, poolAmountInAfterExitFee); uint poolRatio = bdiv(newPoolSupply, poolSupply); // newBalTo = poolRatio^(1/weightTo) * balTo; uint tokenOutRatio = bpow(poolRatio, bdiv(BONE, normalizedWeight)); uint newTokenBalanceOut = bmul(tokenOutRatio, tokenBalanceOut); uint tokenAmountOutBeforeSwapFee = bsub(tokenBalanceOut, newTokenBalanceOut); // charge swap fee on the output token side //uint tAo = tAoBeforeSwapFee * (1 - (1-weightTo) * swapFee) uint zaz = bmul(bsub(BONE, normalizedWeight), swapFee); tokenAmountOut = bmul(tokenAmountOutBeforeSwapFee, bsub(BONE, zaz)); return tokenAmountOut; } }
calcSingleOutGivenPoolIn
function calcSingleOutGivenPoolIn( uint tokenBalanceOut, uint tokenWeightOut, uint poolSupply, uint totalWeight, uint poolAmountIn, uint swapFee ) internal pure returns (uint tokenAmountOut) { uint normalizedWeight = bdiv(tokenWeightOut, totalWeight); // charge exit fee on the pool token side // pAiAfterExitFee = pAi*(1-exitFee) uint poolAmountInAfterExitFee = bmul(poolAmountIn, BONE); uint newPoolSupply = bsub(poolSupply, poolAmountInAfterExitFee); uint poolRatio = bdiv(newPoolSupply, poolSupply); // newBalTo = poolRatio^(1/weightTo) * balTo; uint tokenOutRatio = bpow(poolRatio, bdiv(BONE, normalizedWeight)); uint newTokenBalanceOut = bmul(tokenOutRatio, tokenBalanceOut); uint tokenAmountOutBeforeSwapFee = bsub(tokenBalanceOut, newTokenBalanceOut); // charge swap fee on the output token side //uint tAo = tAoBeforeSwapFee * (1 - (1-weightTo) * swapFee) uint zaz = bmul(bsub(BONE, normalizedWeight), swapFee); tokenAmountOut = bmul(tokenAmountOutBeforeSwapFee, bsub(BONE, zaz)); return tokenAmountOut; }
/********************************************************************************************** // calcSingleOutGivenPoolIn // // tAo = tokenAmountOut / / \\ // // bO = tokenBalanceOut / // pS - (pAi * (1 - eF)) \ / 1 \ \\ // // pAi = poolAmountIn | bO - || ----------------------- | ^ | --------- | * b0 || // // ps = poolSupply \ \\ pS / \(wO / tW)/ // // // wI = tokenWeightIn tAo = \ \ // // // tW = totalWeight / / wO \ \ // // sF = swapFee * | 1 - | 1 - ---- | * sF | // // eF = exitFee \ \ tW / / // **********************************************************************************************/
NatSpecMultiLine
v0.5.12+commit.7709ece9
Unlicense
bzzr://2a277232a61e32885976daf44d130a763efd4c67a6d4b0254dc6f0647de2e950
{ "func_code_index": [ 7988, 9197 ] }
11,851
KyberConverter
contracts/dex/ITokenConverter.sol
0xb26177640eb73b0ac8d6b7f298e40764eff52bdc
Solidity
ITokenConverter
contract ITokenConverter { using SafeMath for uint256; /** * @dev Makes a simple ERC20 -> ERC20 token trade * @param _srcToken - IERC20 token * @param _destToken - IERC20 token * @param _srcAmount - uint256 amount to be converted * @param _destAmount - uint256 amount to get after conversion * @return uint256 for the change. 0 if there is no change */ function convert( IERC20 _srcToken, IERC20 _destToken, uint256 _srcAmount, uint256 _destAmount ) external returns (uint256); /** * @dev Get exchange rate and slippage rate. * Note that these returned values are in 18 decimals regardless of the destination token's decimals. * @param _srcToken - IERC20 token * @param _destToken - IERC20 token * @param _srcAmount - uint256 amount to be converted * @return uint256 of the expected rate * @return uint256 of the slippage rate */ function getExpectedRate(IERC20 _srcToken, IERC20 _destToken, uint256 _srcAmount) public view returns(uint256 expectedRate, uint256 slippageRate); }
convert
function convert( IERC20 _srcToken, IERC20 _destToken, uint256 _srcAmount, uint256 _destAmount ) external returns (uint256);
/** * @dev Makes a simple ERC20 -> ERC20 token trade * @param _srcToken - IERC20 token * @param _destToken - IERC20 token * @param _srcAmount - uint256 amount to be converted * @param _destAmount - uint256 amount to get after conversion * @return uint256 for the change. 0 if there is no change */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://69ba92e98511c1a8edf6aec2c862f0f4b932d5e4e43562938959c8cfa2c9f86a
{ "func_code_index": [ 406, 580 ] }
11,852
KyberConverter
contracts/dex/ITokenConverter.sol
0xb26177640eb73b0ac8d6b7f298e40764eff52bdc
Solidity
ITokenConverter
contract ITokenConverter { using SafeMath for uint256; /** * @dev Makes a simple ERC20 -> ERC20 token trade * @param _srcToken - IERC20 token * @param _destToken - IERC20 token * @param _srcAmount - uint256 amount to be converted * @param _destAmount - uint256 amount to get after conversion * @return uint256 for the change. 0 if there is no change */ function convert( IERC20 _srcToken, IERC20 _destToken, uint256 _srcAmount, uint256 _destAmount ) external returns (uint256); /** * @dev Get exchange rate and slippage rate. * Note that these returned values are in 18 decimals regardless of the destination token's decimals. * @param _srcToken - IERC20 token * @param _destToken - IERC20 token * @param _srcAmount - uint256 amount to be converted * @return uint256 of the expected rate * @return uint256 of the slippage rate */ function getExpectedRate(IERC20 _srcToken, IERC20 _destToken, uint256 _srcAmount) public view returns(uint256 expectedRate, uint256 slippageRate); }
getExpectedRate
function getExpectedRate(IERC20 _srcToken, IERC20 _destToken, uint256 _srcAmount) public view returns(uint256 expectedRate, uint256 slippageRate);
/** * @dev Get exchange rate and slippage rate. * Note that these returned values are in 18 decimals regardless of the destination token's decimals. * @param _srcToken - IERC20 token * @param _destToken - IERC20 token * @param _srcAmount - uint256 amount to be converted * @return uint256 of the expected rate * @return uint256 of the slippage rate */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://69ba92e98511c1a8edf6aec2c862f0f4b932d5e4e43562938959c8cfa2c9f86a
{ "func_code_index": [ 982, 1143 ] }
11,853
MFactory
MNum.sol
0x41c3cec9ae12a29d258cf904dda65f08ff742718
Solidity
MNum
contract MNum is MConst { function btoi(uint a) internal pure returns (uint) { return a / BONE; } function bfloor(uint a) internal pure returns (uint) { return btoi(a) * BONE; } function badd(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "ERR_ADD_OVERFLOW"); return c; } function bsub(uint a, uint b) internal pure returns (uint) { (uint c, bool flag) = bsubSign(a, b); require(!flag, "ERR_SUB_UNDERFLOW"); return c; } function bsubSign(uint a, uint b) internal pure returns (uint, bool) { if (a >= b) { return (a - b, false); } else { return (b - a, true); } } function bmul(uint a, uint b) internal pure returns (uint) { uint c0 = a * b; require(a == 0 || c0 / a == b, "ERR_MUL_OVERFLOW"); uint c1 = c0 + (BONE / 2); require(c1 >= c0, "ERR_MUL_OVERFLOW"); uint c2 = c1 / BONE; return c2; } function bdiv(uint a, uint b) internal pure returns (uint) { require(b != 0, "ERR_DIV_ZERO"); uint c0 = a * BONE; require(a == 0 || c0 / a == BONE, "ERR_DIV_INTERNAL"); // bmul overflow uint c1 = c0 + (b / 2); require(c1 >= c0, "ERR_DIV_INTERNAL"); // badd require uint c2 = c1 / b; return c2; } // DSMath.wpow function bpowi(uint a, uint n) internal pure returns (uint) { uint z = n % 2 != 0 ? a : BONE; for (n /= 2; n != 0; n /= 2) { a = bmul(a, a); if (n % 2 != 0) { z = bmul(z, a); } } return z; } // Compute b^(e.w) by splitting it into (b^e)*(b^0.w). // Use `bpowi` for `b^e` and `bpowK` for k iterations // of approximation of b^0.w function bpow(uint base, uint exp) internal pure returns (uint) { require(base >= MIN_BPOW_BASE, "ERR_BPOW_BASE_TOO_LOW"); require(base <= MAX_BPOW_BASE, "ERR_BPOW_BASE_TOO_HIGH"); uint whole = bfloor(exp); uint remain = bsub(exp, whole); uint wholePow = bpowi(base, btoi(whole)); if (remain == 0) { return wholePow; } uint partialResult = bpowApprox(base, remain, BPOW_PRECISION); return bmul(wholePow, partialResult); } function bpowApprox(uint base, uint exp, uint precision) internal pure returns (uint) { // term 0: uint a = exp; (uint x, bool xneg) = bsubSign(base, BONE); uint term = BONE; uint sum = term; bool negative = false; // term(k) = numer / denom // = (product(a - i - 1, i=1-->k) * x^k) / (k!) // each iteration, multiply previous term by (a-(k-1)) * x / k // continue until term is less than precision for (uint i = 1; term >= precision; i++) { uint bigK = i * BONE; (uint c, bool cneg) = bsubSign(a, bsub(bigK, BONE)); term = bmul(term, bmul(c, x)); term = bdiv(term, bigK); if (term == 0) break; if (xneg) negative = !negative; if (cneg) negative = !negative; if (negative) { sum = bsub(sum, term); } else { sum = badd(sum, term); } } return sum; } }
bpowi
function bpowi(uint a, uint n) internal pure returns (uint) { uint z = n % 2 != 0 ? a : BONE; for (n /= 2; n != 0; n /= 2) { a = bmul(a, a); if (n % 2 != 0) { z = bmul(z, a); } } return z; }
// DSMath.wpow
LineComment
v0.5.12+commit.7709ece9
Unlicense
bzzr://2a277232a61e32885976daf44d130a763efd4c67a6d4b0254dc6f0647de2e950
{ "func_code_index": [ 1505, 1801 ] }
11,854
MFactory
MNum.sol
0x41c3cec9ae12a29d258cf904dda65f08ff742718
Solidity
MNum
contract MNum is MConst { function btoi(uint a) internal pure returns (uint) { return a / BONE; } function bfloor(uint a) internal pure returns (uint) { return btoi(a) * BONE; } function badd(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "ERR_ADD_OVERFLOW"); return c; } function bsub(uint a, uint b) internal pure returns (uint) { (uint c, bool flag) = bsubSign(a, b); require(!flag, "ERR_SUB_UNDERFLOW"); return c; } function bsubSign(uint a, uint b) internal pure returns (uint, bool) { if (a >= b) { return (a - b, false); } else { return (b - a, true); } } function bmul(uint a, uint b) internal pure returns (uint) { uint c0 = a * b; require(a == 0 || c0 / a == b, "ERR_MUL_OVERFLOW"); uint c1 = c0 + (BONE / 2); require(c1 >= c0, "ERR_MUL_OVERFLOW"); uint c2 = c1 / BONE; return c2; } function bdiv(uint a, uint b) internal pure returns (uint) { require(b != 0, "ERR_DIV_ZERO"); uint c0 = a * BONE; require(a == 0 || c0 / a == BONE, "ERR_DIV_INTERNAL"); // bmul overflow uint c1 = c0 + (b / 2); require(c1 >= c0, "ERR_DIV_INTERNAL"); // badd require uint c2 = c1 / b; return c2; } // DSMath.wpow function bpowi(uint a, uint n) internal pure returns (uint) { uint z = n % 2 != 0 ? a : BONE; for (n /= 2; n != 0; n /= 2) { a = bmul(a, a); if (n % 2 != 0) { z = bmul(z, a); } } return z; } // Compute b^(e.w) by splitting it into (b^e)*(b^0.w). // Use `bpowi` for `b^e` and `bpowK` for k iterations // of approximation of b^0.w function bpow(uint base, uint exp) internal pure returns (uint) { require(base >= MIN_BPOW_BASE, "ERR_BPOW_BASE_TOO_LOW"); require(base <= MAX_BPOW_BASE, "ERR_BPOW_BASE_TOO_HIGH"); uint whole = bfloor(exp); uint remain = bsub(exp, whole); uint wholePow = bpowi(base, btoi(whole)); if (remain == 0) { return wholePow; } uint partialResult = bpowApprox(base, remain, BPOW_PRECISION); return bmul(wholePow, partialResult); } function bpowApprox(uint base, uint exp, uint precision) internal pure returns (uint) { // term 0: uint a = exp; (uint x, bool xneg) = bsubSign(base, BONE); uint term = BONE; uint sum = term; bool negative = false; // term(k) = numer / denom // = (product(a - i - 1, i=1-->k) * x^k) / (k!) // each iteration, multiply previous term by (a-(k-1)) * x / k // continue until term is less than precision for (uint i = 1; term >= precision; i++) { uint bigK = i * BONE; (uint c, bool cneg) = bsubSign(a, bsub(bigK, BONE)); term = bmul(term, bmul(c, x)); term = bdiv(term, bigK); if (term == 0) break; if (xneg) negative = !negative; if (cneg) negative = !negative; if (negative) { sum = bsub(sum, term); } else { sum = badd(sum, term); } } return sum; } }
bpow
function bpow(uint base, uint exp) internal pure returns (uint) { require(base >= MIN_BPOW_BASE, "ERR_BPOW_BASE_TOO_LOW"); require(base <= MAX_BPOW_BASE, "ERR_BPOW_BASE_TOO_HIGH"); uint whole = bfloor(exp); uint remain = bsub(exp, whole); uint wholePow = bpowi(base, btoi(whole)); if (remain == 0) { return wholePow; } uint partialResult = bpowApprox(base, remain, BPOW_PRECISION); return bmul(wholePow, partialResult); }
// Compute b^(e.w) by splitting it into (b^e)*(b^0.w). // Use `bpowi` for `b^e` and `bpowK` for k iterations // of approximation of b^0.w
LineComment
v0.5.12+commit.7709ece9
Unlicense
bzzr://2a277232a61e32885976daf44d130a763efd4c67a6d4b0254dc6f0647de2e950
{ "func_code_index": [ 1953, 2483 ] }
11,855
DragonCrowdsaleCore
DragonCrowdsaleCore.sol
0xd275b50f71badf4fa2f911e80e1e420730ab403e
Solidity
Ownable
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 Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */
NatSpecMultiLine
Ownable
function Ownable() public { owner = msg.sender; }
/** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://29509a214ff9474aa8c7265bfcb60b8c49cd1f1b36989de6157cc035ebf8e0ee
{ "func_code_index": [ 261, 321 ] }
11,856
DragonCrowdsaleCore
DragonCrowdsaleCore.sol
0xd275b50f71badf4fa2f911e80e1e420730ab403e
Solidity
Ownable
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 Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */
NatSpecMultiLine
transferOwnership
function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; }
/** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://29509a214ff9474aa8c7265bfcb60b8c49cd1f1b36989de6157cc035ebf8e0ee
{ "func_code_index": [ 644, 820 ] }
11,857
DragonCrowdsaleCore
DragonCrowdsaleCore.sol
0xd275b50f71badf4fa2f911e80e1e420730ab403e
Solidity
DragonCrowdsaleCore
contract DragonCrowdsaleCore is Ownable, DragonPricing { using SafeMath for uint; // address public owner; address public beneficiary; address public charity; address public advisor; address public front; bool public advisorset; uint public tokensSold; uint public etherRaised; uint public presold; uint public presoldMax; uint public crowdsaleCounter; uint public advisorTotal; uint public advisorCut; Dragon public tokenReward; mapping ( address => bool ) public alreadyParticipated; modifier onlyFront() { require (msg.sender == front ); _; } function DragonCrowdsaleCore(){ tokenReward = Dragon( 0x814f67fa286f7572b041d041b1d99b432c9155ee ); // Dragon Token Address owner = msg.sender; beneficiary = msg.sender; charity = msg.sender; advisor = msg.sender; advisorset = false; presold = 0; presoldMax = 3500000000000000; crowdsaleCounter = 0; advisorCut = 0; advisorTotal = 1667 ether; } // runs during precrowdsale - can only be called by main crowdsale contract function precrowdsale ( address tokenholder ) onlyFront payable { require ( presold < presoldMax ); uint award; // amount of dragons to credit to tokenholder uint donation; // donation to charity require ( alreadyParticipated[ tokenholder ] != true ) ; alreadyParticipated[ tokenholder ] = true; DragonPricing pricingstructure = new DragonPricing(); ( award, donation ) = pricingstructure.precrowdsalepricing( tokenholder , msg.value ); tokenReward.transfer ( charity , donation ); // send dragons to charity presold = presold.add( award ); //add number of tokens sold in presale presold = presold.add( donation ); //add number of tokens sent via charity tokensSold = tokensSold.add(donation); //add charity donation to total number of tokens sold tokenReward.transfer ( tokenholder , award ); // immediate transfer of dragons to token buyer if ( advisorCut < advisorTotal ) { advisorSiphon();} else { beneficiary.transfer ( msg.value ); } //send ether to beneficiary etherRaised = etherRaised.add( msg.value ); // tallies ether raised tokensSold = tokensSold.add(award); // tallies total dragons sold } // runs when crowdsale is active - can only be called by main crowdsale contract function crowdsale ( address tokenholder ) onlyFront payable { uint award; // amount of dragons to send to tokenholder uint donation; // donation to charity DragonPricing pricingstructure = new DragonPricing(); ( award , donation ) = pricingstructure.crowdsalepricing( tokenholder, msg.value, crowdsaleCounter ); crowdsaleCounter += award; tokenReward.transfer ( tokenholder , award ); // immediate transfer to token holders if ( advisorCut < advisorTotal ) { advisorSiphon();} // send advisor his share else { beneficiary.transfer ( msg.value ); } //send all ether to beneficiary etherRaised = etherRaised.add( msg.value ); //etherRaised += msg.value; // tallies ether raised tokensSold = tokensSold.add(award); //tokensSold += award; // tallies total dragons sold } // pays the advisor part of the incoming ether function advisorSiphon() internal { uint share = msg.value/10; uint foradvisor = share; if ( (advisorCut + share) > advisorTotal ) foradvisor = advisorTotal.sub( advisorCut ); advisor.transfer ( foradvisor ); // advisor gets 10% of the incoming ether advisorCut = advisorCut.add( foradvisor ); beneficiary.transfer( share * 9 ); // the ether balance goes to the benfeciary if ( foradvisor != share ) beneficiary.transfer( share.sub(foradvisor) ); // if 10% of the incoming ether exceeds the total advisor is supposed to get , then this gives them a smaller share to not exceed max } // use this to set the crowdsale beneficiary address function transferBeneficiary ( address _newbeneficiary ) onlyOwner { require ( _newbeneficiary != 0x00 ); beneficiary = _newbeneficiary; } // use this to set the charity address function transferCharity ( address _charity ) onlyOwner { require ( _charity != 0x00 ); charity = _charity; } // sets crowdsale address function setFront ( address _front ) onlyOwner { require ( _front != 0x00 ); front = _front; } // sets advisors address function setAdvisor ( address _advisor ) onlyOwner { require ( _advisor != 0x00 ); require ( advisorset == false ); advisorset = true; advisor = _advisor; } //empty the crowdsale contract of Dragons and forward balance to beneficiary function withdrawCrowdsaleDragons() onlyOwner{ uint256 balance = tokenReward.balanceOf( address( this ) ); tokenReward.transfer( beneficiary, balance ); } //manually send different dragon packages function manualSend ( address tokenholder, uint packagenumber ) onlyOwner { require ( tokenholder != 0x00 ); if ( packagenumber != 1 && packagenumber != 2 && packagenumber != 3 ) revert(); uint award; uint donation; if ( packagenumber == 1 ) { award = 10800000000; donation = 800000000; } if ( packagenumber == 2 ) { award = 108800000000; donation = 8800000000; } if ( packagenumber == 3 ) { award = 1088800000000; donation = 88800000000; } tokenReward.transfer ( tokenholder , award ); tokenReward.transfer ( charity , donation ); presold = presold.add( award ); //add number of tokens sold in presale presold = presold.add( donation ); //add number of tokens sent via charity tokensSold = tokensSold.add(award); // tallies total dragons sold tokensSold = tokensSold.add(donation); // tallies total dragons sold } }
precrowdsale
function precrowdsale ( address tokenholder ) onlyFront payable { require ( presold < presoldMax ); uint award; // amount of dragons to credit to tokenholder uint donation; // donation to charity require ( alreadyParticipated[ tokenholder ] != true ) ; alreadyParticipated[ tokenholder ] = true; DragonPricing pricingstructure = new DragonPricing(); ( award, donation ) = pricingstructure.precrowdsalepricing( tokenholder , msg.value ); tokenReward.transfer ( charity , donation ); // send dragons to charity presold = presold.add( award ); //add number of tokens sold in presale presold = presold.add( donation ); //add number of tokens sent via charity tokensSold = tokensSold.add(donation); //add charity donation to total number of tokens sold tokenReward.transfer ( tokenholder , award ); // immediate transfer of dragons to token buyer if ( advisorCut < advisorTotal ) { advisorSiphon();} else { beneficiary.transfer ( msg.value ); } //send ether to beneficiary etherRaised = etherRaised.add( msg.value ); // tallies ether raised tokensSold = tokensSold.add(award); // tallies total dragons sold }
// runs during precrowdsale - can only be called by main crowdsale contract
LineComment
v0.4.18+commit.9cf6e910
bzzr://29509a214ff9474aa8c7265bfcb60b8c49cd1f1b36989de6157cc035ebf8e0ee
{ "func_code_index": [ 1365, 2742 ] }
11,858
DragonCrowdsaleCore
DragonCrowdsaleCore.sol
0xd275b50f71badf4fa2f911e80e1e420730ab403e
Solidity
DragonCrowdsaleCore
contract DragonCrowdsaleCore is Ownable, DragonPricing { using SafeMath for uint; // address public owner; address public beneficiary; address public charity; address public advisor; address public front; bool public advisorset; uint public tokensSold; uint public etherRaised; uint public presold; uint public presoldMax; uint public crowdsaleCounter; uint public advisorTotal; uint public advisorCut; Dragon public tokenReward; mapping ( address => bool ) public alreadyParticipated; modifier onlyFront() { require (msg.sender == front ); _; } function DragonCrowdsaleCore(){ tokenReward = Dragon( 0x814f67fa286f7572b041d041b1d99b432c9155ee ); // Dragon Token Address owner = msg.sender; beneficiary = msg.sender; charity = msg.sender; advisor = msg.sender; advisorset = false; presold = 0; presoldMax = 3500000000000000; crowdsaleCounter = 0; advisorCut = 0; advisorTotal = 1667 ether; } // runs during precrowdsale - can only be called by main crowdsale contract function precrowdsale ( address tokenholder ) onlyFront payable { require ( presold < presoldMax ); uint award; // amount of dragons to credit to tokenholder uint donation; // donation to charity require ( alreadyParticipated[ tokenholder ] != true ) ; alreadyParticipated[ tokenholder ] = true; DragonPricing pricingstructure = new DragonPricing(); ( award, donation ) = pricingstructure.precrowdsalepricing( tokenholder , msg.value ); tokenReward.transfer ( charity , donation ); // send dragons to charity presold = presold.add( award ); //add number of tokens sold in presale presold = presold.add( donation ); //add number of tokens sent via charity tokensSold = tokensSold.add(donation); //add charity donation to total number of tokens sold tokenReward.transfer ( tokenholder , award ); // immediate transfer of dragons to token buyer if ( advisorCut < advisorTotal ) { advisorSiphon();} else { beneficiary.transfer ( msg.value ); } //send ether to beneficiary etherRaised = etherRaised.add( msg.value ); // tallies ether raised tokensSold = tokensSold.add(award); // tallies total dragons sold } // runs when crowdsale is active - can only be called by main crowdsale contract function crowdsale ( address tokenholder ) onlyFront payable { uint award; // amount of dragons to send to tokenholder uint donation; // donation to charity DragonPricing pricingstructure = new DragonPricing(); ( award , donation ) = pricingstructure.crowdsalepricing( tokenholder, msg.value, crowdsaleCounter ); crowdsaleCounter += award; tokenReward.transfer ( tokenholder , award ); // immediate transfer to token holders if ( advisorCut < advisorTotal ) { advisorSiphon();} // send advisor his share else { beneficiary.transfer ( msg.value ); } //send all ether to beneficiary etherRaised = etherRaised.add( msg.value ); //etherRaised += msg.value; // tallies ether raised tokensSold = tokensSold.add(award); //tokensSold += award; // tallies total dragons sold } // pays the advisor part of the incoming ether function advisorSiphon() internal { uint share = msg.value/10; uint foradvisor = share; if ( (advisorCut + share) > advisorTotal ) foradvisor = advisorTotal.sub( advisorCut ); advisor.transfer ( foradvisor ); // advisor gets 10% of the incoming ether advisorCut = advisorCut.add( foradvisor ); beneficiary.transfer( share * 9 ); // the ether balance goes to the benfeciary if ( foradvisor != share ) beneficiary.transfer( share.sub(foradvisor) ); // if 10% of the incoming ether exceeds the total advisor is supposed to get , then this gives them a smaller share to not exceed max } // use this to set the crowdsale beneficiary address function transferBeneficiary ( address _newbeneficiary ) onlyOwner { require ( _newbeneficiary != 0x00 ); beneficiary = _newbeneficiary; } // use this to set the charity address function transferCharity ( address _charity ) onlyOwner { require ( _charity != 0x00 ); charity = _charity; } // sets crowdsale address function setFront ( address _front ) onlyOwner { require ( _front != 0x00 ); front = _front; } // sets advisors address function setAdvisor ( address _advisor ) onlyOwner { require ( _advisor != 0x00 ); require ( advisorset == false ); advisorset = true; advisor = _advisor; } //empty the crowdsale contract of Dragons and forward balance to beneficiary function withdrawCrowdsaleDragons() onlyOwner{ uint256 balance = tokenReward.balanceOf( address( this ) ); tokenReward.transfer( beneficiary, balance ); } //manually send different dragon packages function manualSend ( address tokenholder, uint packagenumber ) onlyOwner { require ( tokenholder != 0x00 ); if ( packagenumber != 1 && packagenumber != 2 && packagenumber != 3 ) revert(); uint award; uint donation; if ( packagenumber == 1 ) { award = 10800000000; donation = 800000000; } if ( packagenumber == 2 ) { award = 108800000000; donation = 8800000000; } if ( packagenumber == 3 ) { award = 1088800000000; donation = 88800000000; } tokenReward.transfer ( tokenholder , award ); tokenReward.transfer ( charity , donation ); presold = presold.add( award ); //add number of tokens sold in presale presold = presold.add( donation ); //add number of tokens sent via charity tokensSold = tokensSold.add(award); // tallies total dragons sold tokensSold = tokensSold.add(donation); // tallies total dragons sold } }
crowdsale
function crowdsale ( address tokenholder ) onlyFront payable { uint award; // amount of dragons to send to tokenholder uint donation; // donation to charity DragonPricing pricingstructure = new DragonPricing(); ( award , donation ) = pricingstructure.crowdsalepricing( tokenholder, msg.value, crowdsaleCounter ); crowdsaleCounter += award; tokenReward.transfer ( tokenholder , award ); // immediate transfer to token holders if ( advisorCut < advisorTotal ) { advisorSiphon();} // send advisor his share else { beneficiary.transfer ( msg.value ); } //send all ether to beneficiary etherRaised = etherRaised.add( msg.value ); //etherRaised += msg.value; // tallies ether raised tokensSold = tokensSold.add(award); //tokensSold += award; // tallies total dragons sold }
// runs when crowdsale is active - can only be called by main crowdsale contract
LineComment
v0.4.18+commit.9cf6e910
bzzr://29509a214ff9474aa8c7265bfcb60b8c49cd1f1b36989de6157cc035ebf8e0ee
{ "func_code_index": [ 2835, 3807 ] }
11,859
DragonCrowdsaleCore
DragonCrowdsaleCore.sol
0xd275b50f71badf4fa2f911e80e1e420730ab403e
Solidity
DragonCrowdsaleCore
contract DragonCrowdsaleCore is Ownable, DragonPricing { using SafeMath for uint; // address public owner; address public beneficiary; address public charity; address public advisor; address public front; bool public advisorset; uint public tokensSold; uint public etherRaised; uint public presold; uint public presoldMax; uint public crowdsaleCounter; uint public advisorTotal; uint public advisorCut; Dragon public tokenReward; mapping ( address => bool ) public alreadyParticipated; modifier onlyFront() { require (msg.sender == front ); _; } function DragonCrowdsaleCore(){ tokenReward = Dragon( 0x814f67fa286f7572b041d041b1d99b432c9155ee ); // Dragon Token Address owner = msg.sender; beneficiary = msg.sender; charity = msg.sender; advisor = msg.sender; advisorset = false; presold = 0; presoldMax = 3500000000000000; crowdsaleCounter = 0; advisorCut = 0; advisorTotal = 1667 ether; } // runs during precrowdsale - can only be called by main crowdsale contract function precrowdsale ( address tokenholder ) onlyFront payable { require ( presold < presoldMax ); uint award; // amount of dragons to credit to tokenholder uint donation; // donation to charity require ( alreadyParticipated[ tokenholder ] != true ) ; alreadyParticipated[ tokenholder ] = true; DragonPricing pricingstructure = new DragonPricing(); ( award, donation ) = pricingstructure.precrowdsalepricing( tokenholder , msg.value ); tokenReward.transfer ( charity , donation ); // send dragons to charity presold = presold.add( award ); //add number of tokens sold in presale presold = presold.add( donation ); //add number of tokens sent via charity tokensSold = tokensSold.add(donation); //add charity donation to total number of tokens sold tokenReward.transfer ( tokenholder , award ); // immediate transfer of dragons to token buyer if ( advisorCut < advisorTotal ) { advisorSiphon();} else { beneficiary.transfer ( msg.value ); } //send ether to beneficiary etherRaised = etherRaised.add( msg.value ); // tallies ether raised tokensSold = tokensSold.add(award); // tallies total dragons sold } // runs when crowdsale is active - can only be called by main crowdsale contract function crowdsale ( address tokenholder ) onlyFront payable { uint award; // amount of dragons to send to tokenholder uint donation; // donation to charity DragonPricing pricingstructure = new DragonPricing(); ( award , donation ) = pricingstructure.crowdsalepricing( tokenholder, msg.value, crowdsaleCounter ); crowdsaleCounter += award; tokenReward.transfer ( tokenholder , award ); // immediate transfer to token holders if ( advisorCut < advisorTotal ) { advisorSiphon();} // send advisor his share else { beneficiary.transfer ( msg.value ); } //send all ether to beneficiary etherRaised = etherRaised.add( msg.value ); //etherRaised += msg.value; // tallies ether raised tokensSold = tokensSold.add(award); //tokensSold += award; // tallies total dragons sold } // pays the advisor part of the incoming ether function advisorSiphon() internal { uint share = msg.value/10; uint foradvisor = share; if ( (advisorCut + share) > advisorTotal ) foradvisor = advisorTotal.sub( advisorCut ); advisor.transfer ( foradvisor ); // advisor gets 10% of the incoming ether advisorCut = advisorCut.add( foradvisor ); beneficiary.transfer( share * 9 ); // the ether balance goes to the benfeciary if ( foradvisor != share ) beneficiary.transfer( share.sub(foradvisor) ); // if 10% of the incoming ether exceeds the total advisor is supposed to get , then this gives them a smaller share to not exceed max } // use this to set the crowdsale beneficiary address function transferBeneficiary ( address _newbeneficiary ) onlyOwner { require ( _newbeneficiary != 0x00 ); beneficiary = _newbeneficiary; } // use this to set the charity address function transferCharity ( address _charity ) onlyOwner { require ( _charity != 0x00 ); charity = _charity; } // sets crowdsale address function setFront ( address _front ) onlyOwner { require ( _front != 0x00 ); front = _front; } // sets advisors address function setAdvisor ( address _advisor ) onlyOwner { require ( _advisor != 0x00 ); require ( advisorset == false ); advisorset = true; advisor = _advisor; } //empty the crowdsale contract of Dragons and forward balance to beneficiary function withdrawCrowdsaleDragons() onlyOwner{ uint256 balance = tokenReward.balanceOf( address( this ) ); tokenReward.transfer( beneficiary, balance ); } //manually send different dragon packages function manualSend ( address tokenholder, uint packagenumber ) onlyOwner { require ( tokenholder != 0x00 ); if ( packagenumber != 1 && packagenumber != 2 && packagenumber != 3 ) revert(); uint award; uint donation; if ( packagenumber == 1 ) { award = 10800000000; donation = 800000000; } if ( packagenumber == 2 ) { award = 108800000000; donation = 8800000000; } if ( packagenumber == 3 ) { award = 1088800000000; donation = 88800000000; } tokenReward.transfer ( tokenholder , award ); tokenReward.transfer ( charity , donation ); presold = presold.add( award ); //add number of tokens sold in presale presold = presold.add( donation ); //add number of tokens sent via charity tokensSold = tokensSold.add(award); // tallies total dragons sold tokensSold = tokensSold.add(donation); // tallies total dragons sold } }
advisorSiphon
function advisorSiphon() internal { uint share = msg.value/10; uint foradvisor = share; if ( (advisorCut + share) > advisorTotal ) foradvisor = advisorTotal.sub( advisorCut ); advisor.transfer ( foradvisor ); // advisor gets 10% of the incoming ether advisorCut = advisorCut.add( foradvisor ); beneficiary.transfer( share * 9 ); // the ether balance goes to the benfeciary if ( foradvisor != share ) beneficiary.transfer( share.sub(foradvisor) ); // if 10% of the incoming ether exceeds the total advisor is supposed to get , then this gives them a smaller share to not exceed max }
// pays the advisor part of the incoming ether
LineComment
v0.4.18+commit.9cf6e910
bzzr://29509a214ff9474aa8c7265bfcb60b8c49cd1f1b36989de6157cc035ebf8e0ee
{ "func_code_index": [ 3872, 4630 ] }
11,860
DragonCrowdsaleCore
DragonCrowdsaleCore.sol
0xd275b50f71badf4fa2f911e80e1e420730ab403e
Solidity
DragonCrowdsaleCore
contract DragonCrowdsaleCore is Ownable, DragonPricing { using SafeMath for uint; // address public owner; address public beneficiary; address public charity; address public advisor; address public front; bool public advisorset; uint public tokensSold; uint public etherRaised; uint public presold; uint public presoldMax; uint public crowdsaleCounter; uint public advisorTotal; uint public advisorCut; Dragon public tokenReward; mapping ( address => bool ) public alreadyParticipated; modifier onlyFront() { require (msg.sender == front ); _; } function DragonCrowdsaleCore(){ tokenReward = Dragon( 0x814f67fa286f7572b041d041b1d99b432c9155ee ); // Dragon Token Address owner = msg.sender; beneficiary = msg.sender; charity = msg.sender; advisor = msg.sender; advisorset = false; presold = 0; presoldMax = 3500000000000000; crowdsaleCounter = 0; advisorCut = 0; advisorTotal = 1667 ether; } // runs during precrowdsale - can only be called by main crowdsale contract function precrowdsale ( address tokenholder ) onlyFront payable { require ( presold < presoldMax ); uint award; // amount of dragons to credit to tokenholder uint donation; // donation to charity require ( alreadyParticipated[ tokenholder ] != true ) ; alreadyParticipated[ tokenholder ] = true; DragonPricing pricingstructure = new DragonPricing(); ( award, donation ) = pricingstructure.precrowdsalepricing( tokenholder , msg.value ); tokenReward.transfer ( charity , donation ); // send dragons to charity presold = presold.add( award ); //add number of tokens sold in presale presold = presold.add( donation ); //add number of tokens sent via charity tokensSold = tokensSold.add(donation); //add charity donation to total number of tokens sold tokenReward.transfer ( tokenholder , award ); // immediate transfer of dragons to token buyer if ( advisorCut < advisorTotal ) { advisorSiphon();} else { beneficiary.transfer ( msg.value ); } //send ether to beneficiary etherRaised = etherRaised.add( msg.value ); // tallies ether raised tokensSold = tokensSold.add(award); // tallies total dragons sold } // runs when crowdsale is active - can only be called by main crowdsale contract function crowdsale ( address tokenholder ) onlyFront payable { uint award; // amount of dragons to send to tokenholder uint donation; // donation to charity DragonPricing pricingstructure = new DragonPricing(); ( award , donation ) = pricingstructure.crowdsalepricing( tokenholder, msg.value, crowdsaleCounter ); crowdsaleCounter += award; tokenReward.transfer ( tokenholder , award ); // immediate transfer to token holders if ( advisorCut < advisorTotal ) { advisorSiphon();} // send advisor his share else { beneficiary.transfer ( msg.value ); } //send all ether to beneficiary etherRaised = etherRaised.add( msg.value ); //etherRaised += msg.value; // tallies ether raised tokensSold = tokensSold.add(award); //tokensSold += award; // tallies total dragons sold } // pays the advisor part of the incoming ether function advisorSiphon() internal { uint share = msg.value/10; uint foradvisor = share; if ( (advisorCut + share) > advisorTotal ) foradvisor = advisorTotal.sub( advisorCut ); advisor.transfer ( foradvisor ); // advisor gets 10% of the incoming ether advisorCut = advisorCut.add( foradvisor ); beneficiary.transfer( share * 9 ); // the ether balance goes to the benfeciary if ( foradvisor != share ) beneficiary.transfer( share.sub(foradvisor) ); // if 10% of the incoming ether exceeds the total advisor is supposed to get , then this gives them a smaller share to not exceed max } // use this to set the crowdsale beneficiary address function transferBeneficiary ( address _newbeneficiary ) onlyOwner { require ( _newbeneficiary != 0x00 ); beneficiary = _newbeneficiary; } // use this to set the charity address function transferCharity ( address _charity ) onlyOwner { require ( _charity != 0x00 ); charity = _charity; } // sets crowdsale address function setFront ( address _front ) onlyOwner { require ( _front != 0x00 ); front = _front; } // sets advisors address function setAdvisor ( address _advisor ) onlyOwner { require ( _advisor != 0x00 ); require ( advisorset == false ); advisorset = true; advisor = _advisor; } //empty the crowdsale contract of Dragons and forward balance to beneficiary function withdrawCrowdsaleDragons() onlyOwner{ uint256 balance = tokenReward.balanceOf( address( this ) ); tokenReward.transfer( beneficiary, balance ); } //manually send different dragon packages function manualSend ( address tokenholder, uint packagenumber ) onlyOwner { require ( tokenholder != 0x00 ); if ( packagenumber != 1 && packagenumber != 2 && packagenumber != 3 ) revert(); uint award; uint donation; if ( packagenumber == 1 ) { award = 10800000000; donation = 800000000; } if ( packagenumber == 2 ) { award = 108800000000; donation = 8800000000; } if ( packagenumber == 3 ) { award = 1088800000000; donation = 88800000000; } tokenReward.transfer ( tokenholder , award ); tokenReward.transfer ( charity , donation ); presold = presold.add( award ); //add number of tokens sold in presale presold = presold.add( donation ); //add number of tokens sent via charity tokensSold = tokensSold.add(award); // tallies total dragons sold tokensSold = tokensSold.add(donation); // tallies total dragons sold } }
transferBeneficiary
function transferBeneficiary ( address _newbeneficiary ) onlyOwner { require ( _newbeneficiary != 0x00 ); beneficiary = _newbeneficiary; }
// use this to set the crowdsale beneficiary address
LineComment
v0.4.18+commit.9cf6e910
bzzr://29509a214ff9474aa8c7265bfcb60b8c49cd1f1b36989de6157cc035ebf8e0ee
{ "func_code_index": [ 4708, 4894 ] }
11,861
DragonCrowdsaleCore
DragonCrowdsaleCore.sol
0xd275b50f71badf4fa2f911e80e1e420730ab403e
Solidity
DragonCrowdsaleCore
contract DragonCrowdsaleCore is Ownable, DragonPricing { using SafeMath for uint; // address public owner; address public beneficiary; address public charity; address public advisor; address public front; bool public advisorset; uint public tokensSold; uint public etherRaised; uint public presold; uint public presoldMax; uint public crowdsaleCounter; uint public advisorTotal; uint public advisorCut; Dragon public tokenReward; mapping ( address => bool ) public alreadyParticipated; modifier onlyFront() { require (msg.sender == front ); _; } function DragonCrowdsaleCore(){ tokenReward = Dragon( 0x814f67fa286f7572b041d041b1d99b432c9155ee ); // Dragon Token Address owner = msg.sender; beneficiary = msg.sender; charity = msg.sender; advisor = msg.sender; advisorset = false; presold = 0; presoldMax = 3500000000000000; crowdsaleCounter = 0; advisorCut = 0; advisorTotal = 1667 ether; } // runs during precrowdsale - can only be called by main crowdsale contract function precrowdsale ( address tokenholder ) onlyFront payable { require ( presold < presoldMax ); uint award; // amount of dragons to credit to tokenholder uint donation; // donation to charity require ( alreadyParticipated[ tokenholder ] != true ) ; alreadyParticipated[ tokenholder ] = true; DragonPricing pricingstructure = new DragonPricing(); ( award, donation ) = pricingstructure.precrowdsalepricing( tokenholder , msg.value ); tokenReward.transfer ( charity , donation ); // send dragons to charity presold = presold.add( award ); //add number of tokens sold in presale presold = presold.add( donation ); //add number of tokens sent via charity tokensSold = tokensSold.add(donation); //add charity donation to total number of tokens sold tokenReward.transfer ( tokenholder , award ); // immediate transfer of dragons to token buyer if ( advisorCut < advisorTotal ) { advisorSiphon();} else { beneficiary.transfer ( msg.value ); } //send ether to beneficiary etherRaised = etherRaised.add( msg.value ); // tallies ether raised tokensSold = tokensSold.add(award); // tallies total dragons sold } // runs when crowdsale is active - can only be called by main crowdsale contract function crowdsale ( address tokenholder ) onlyFront payable { uint award; // amount of dragons to send to tokenholder uint donation; // donation to charity DragonPricing pricingstructure = new DragonPricing(); ( award , donation ) = pricingstructure.crowdsalepricing( tokenholder, msg.value, crowdsaleCounter ); crowdsaleCounter += award; tokenReward.transfer ( tokenholder , award ); // immediate transfer to token holders if ( advisorCut < advisorTotal ) { advisorSiphon();} // send advisor his share else { beneficiary.transfer ( msg.value ); } //send all ether to beneficiary etherRaised = etherRaised.add( msg.value ); //etherRaised += msg.value; // tallies ether raised tokensSold = tokensSold.add(award); //tokensSold += award; // tallies total dragons sold } // pays the advisor part of the incoming ether function advisorSiphon() internal { uint share = msg.value/10; uint foradvisor = share; if ( (advisorCut + share) > advisorTotal ) foradvisor = advisorTotal.sub( advisorCut ); advisor.transfer ( foradvisor ); // advisor gets 10% of the incoming ether advisorCut = advisorCut.add( foradvisor ); beneficiary.transfer( share * 9 ); // the ether balance goes to the benfeciary if ( foradvisor != share ) beneficiary.transfer( share.sub(foradvisor) ); // if 10% of the incoming ether exceeds the total advisor is supposed to get , then this gives them a smaller share to not exceed max } // use this to set the crowdsale beneficiary address function transferBeneficiary ( address _newbeneficiary ) onlyOwner { require ( _newbeneficiary != 0x00 ); beneficiary = _newbeneficiary; } // use this to set the charity address function transferCharity ( address _charity ) onlyOwner { require ( _charity != 0x00 ); charity = _charity; } // sets crowdsale address function setFront ( address _front ) onlyOwner { require ( _front != 0x00 ); front = _front; } // sets advisors address function setAdvisor ( address _advisor ) onlyOwner { require ( _advisor != 0x00 ); require ( advisorset == false ); advisorset = true; advisor = _advisor; } //empty the crowdsale contract of Dragons and forward balance to beneficiary function withdrawCrowdsaleDragons() onlyOwner{ uint256 balance = tokenReward.balanceOf( address( this ) ); tokenReward.transfer( beneficiary, balance ); } //manually send different dragon packages function manualSend ( address tokenholder, uint packagenumber ) onlyOwner { require ( tokenholder != 0x00 ); if ( packagenumber != 1 && packagenumber != 2 && packagenumber != 3 ) revert(); uint award; uint donation; if ( packagenumber == 1 ) { award = 10800000000; donation = 800000000; } if ( packagenumber == 2 ) { award = 108800000000; donation = 8800000000; } if ( packagenumber == 3 ) { award = 1088800000000; donation = 88800000000; } tokenReward.transfer ( tokenholder , award ); tokenReward.transfer ( charity , donation ); presold = presold.add( award ); //add number of tokens sold in presale presold = presold.add( donation ); //add number of tokens sent via charity tokensSold = tokensSold.add(award); // tallies total dragons sold tokensSold = tokensSold.add(donation); // tallies total dragons sold } }
transferCharity
function transferCharity ( address _charity ) onlyOwner { require ( _charity != 0x00 ); charity = _charity; }
// use this to set the charity address
LineComment
v0.4.18+commit.9cf6e910
bzzr://29509a214ff9474aa8c7265bfcb60b8c49cd1f1b36989de6157cc035ebf8e0ee
{ "func_code_index": [ 4945, 5102 ] }
11,862
DragonCrowdsaleCore
DragonCrowdsaleCore.sol
0xd275b50f71badf4fa2f911e80e1e420730ab403e
Solidity
DragonCrowdsaleCore
contract DragonCrowdsaleCore is Ownable, DragonPricing { using SafeMath for uint; // address public owner; address public beneficiary; address public charity; address public advisor; address public front; bool public advisorset; uint public tokensSold; uint public etherRaised; uint public presold; uint public presoldMax; uint public crowdsaleCounter; uint public advisorTotal; uint public advisorCut; Dragon public tokenReward; mapping ( address => bool ) public alreadyParticipated; modifier onlyFront() { require (msg.sender == front ); _; } function DragonCrowdsaleCore(){ tokenReward = Dragon( 0x814f67fa286f7572b041d041b1d99b432c9155ee ); // Dragon Token Address owner = msg.sender; beneficiary = msg.sender; charity = msg.sender; advisor = msg.sender; advisorset = false; presold = 0; presoldMax = 3500000000000000; crowdsaleCounter = 0; advisorCut = 0; advisorTotal = 1667 ether; } // runs during precrowdsale - can only be called by main crowdsale contract function precrowdsale ( address tokenholder ) onlyFront payable { require ( presold < presoldMax ); uint award; // amount of dragons to credit to tokenholder uint donation; // donation to charity require ( alreadyParticipated[ tokenholder ] != true ) ; alreadyParticipated[ tokenholder ] = true; DragonPricing pricingstructure = new DragonPricing(); ( award, donation ) = pricingstructure.precrowdsalepricing( tokenholder , msg.value ); tokenReward.transfer ( charity , donation ); // send dragons to charity presold = presold.add( award ); //add number of tokens sold in presale presold = presold.add( donation ); //add number of tokens sent via charity tokensSold = tokensSold.add(donation); //add charity donation to total number of tokens sold tokenReward.transfer ( tokenholder , award ); // immediate transfer of dragons to token buyer if ( advisorCut < advisorTotal ) { advisorSiphon();} else { beneficiary.transfer ( msg.value ); } //send ether to beneficiary etherRaised = etherRaised.add( msg.value ); // tallies ether raised tokensSold = tokensSold.add(award); // tallies total dragons sold } // runs when crowdsale is active - can only be called by main crowdsale contract function crowdsale ( address tokenholder ) onlyFront payable { uint award; // amount of dragons to send to tokenholder uint donation; // donation to charity DragonPricing pricingstructure = new DragonPricing(); ( award , donation ) = pricingstructure.crowdsalepricing( tokenholder, msg.value, crowdsaleCounter ); crowdsaleCounter += award; tokenReward.transfer ( tokenholder , award ); // immediate transfer to token holders if ( advisorCut < advisorTotal ) { advisorSiphon();} // send advisor his share else { beneficiary.transfer ( msg.value ); } //send all ether to beneficiary etherRaised = etherRaised.add( msg.value ); //etherRaised += msg.value; // tallies ether raised tokensSold = tokensSold.add(award); //tokensSold += award; // tallies total dragons sold } // pays the advisor part of the incoming ether function advisorSiphon() internal { uint share = msg.value/10; uint foradvisor = share; if ( (advisorCut + share) > advisorTotal ) foradvisor = advisorTotal.sub( advisorCut ); advisor.transfer ( foradvisor ); // advisor gets 10% of the incoming ether advisorCut = advisorCut.add( foradvisor ); beneficiary.transfer( share * 9 ); // the ether balance goes to the benfeciary if ( foradvisor != share ) beneficiary.transfer( share.sub(foradvisor) ); // if 10% of the incoming ether exceeds the total advisor is supposed to get , then this gives them a smaller share to not exceed max } // use this to set the crowdsale beneficiary address function transferBeneficiary ( address _newbeneficiary ) onlyOwner { require ( _newbeneficiary != 0x00 ); beneficiary = _newbeneficiary; } // use this to set the charity address function transferCharity ( address _charity ) onlyOwner { require ( _charity != 0x00 ); charity = _charity; } // sets crowdsale address function setFront ( address _front ) onlyOwner { require ( _front != 0x00 ); front = _front; } // sets advisors address function setAdvisor ( address _advisor ) onlyOwner { require ( _advisor != 0x00 ); require ( advisorset == false ); advisorset = true; advisor = _advisor; } //empty the crowdsale contract of Dragons and forward balance to beneficiary function withdrawCrowdsaleDragons() onlyOwner{ uint256 balance = tokenReward.balanceOf( address( this ) ); tokenReward.transfer( beneficiary, balance ); } //manually send different dragon packages function manualSend ( address tokenholder, uint packagenumber ) onlyOwner { require ( tokenholder != 0x00 ); if ( packagenumber != 1 && packagenumber != 2 && packagenumber != 3 ) revert(); uint award; uint donation; if ( packagenumber == 1 ) { award = 10800000000; donation = 800000000; } if ( packagenumber == 2 ) { award = 108800000000; donation = 8800000000; } if ( packagenumber == 3 ) { award = 1088800000000; donation = 88800000000; } tokenReward.transfer ( tokenholder , award ); tokenReward.transfer ( charity , donation ); presold = presold.add( award ); //add number of tokens sold in presale presold = presold.add( donation ); //add number of tokens sent via charity tokensSold = tokensSold.add(award); // tallies total dragons sold tokensSold = tokensSold.add(donation); // tallies total dragons sold } }
setFront
function setFront ( address _front ) onlyOwner { require ( _front != 0x00 ); front = _front; }
// sets crowdsale address
LineComment
v0.4.18+commit.9cf6e910
bzzr://29509a214ff9474aa8c7265bfcb60b8c49cd1f1b36989de6157cc035ebf8e0ee
{ "func_code_index": [ 5140, 5282 ] }
11,863
DragonCrowdsaleCore
DragonCrowdsaleCore.sol
0xd275b50f71badf4fa2f911e80e1e420730ab403e
Solidity
DragonCrowdsaleCore
contract DragonCrowdsaleCore is Ownable, DragonPricing { using SafeMath for uint; // address public owner; address public beneficiary; address public charity; address public advisor; address public front; bool public advisorset; uint public tokensSold; uint public etherRaised; uint public presold; uint public presoldMax; uint public crowdsaleCounter; uint public advisorTotal; uint public advisorCut; Dragon public tokenReward; mapping ( address => bool ) public alreadyParticipated; modifier onlyFront() { require (msg.sender == front ); _; } function DragonCrowdsaleCore(){ tokenReward = Dragon( 0x814f67fa286f7572b041d041b1d99b432c9155ee ); // Dragon Token Address owner = msg.sender; beneficiary = msg.sender; charity = msg.sender; advisor = msg.sender; advisorset = false; presold = 0; presoldMax = 3500000000000000; crowdsaleCounter = 0; advisorCut = 0; advisorTotal = 1667 ether; } // runs during precrowdsale - can only be called by main crowdsale contract function precrowdsale ( address tokenholder ) onlyFront payable { require ( presold < presoldMax ); uint award; // amount of dragons to credit to tokenholder uint donation; // donation to charity require ( alreadyParticipated[ tokenholder ] != true ) ; alreadyParticipated[ tokenholder ] = true; DragonPricing pricingstructure = new DragonPricing(); ( award, donation ) = pricingstructure.precrowdsalepricing( tokenholder , msg.value ); tokenReward.transfer ( charity , donation ); // send dragons to charity presold = presold.add( award ); //add number of tokens sold in presale presold = presold.add( donation ); //add number of tokens sent via charity tokensSold = tokensSold.add(donation); //add charity donation to total number of tokens sold tokenReward.transfer ( tokenholder , award ); // immediate transfer of dragons to token buyer if ( advisorCut < advisorTotal ) { advisorSiphon();} else { beneficiary.transfer ( msg.value ); } //send ether to beneficiary etherRaised = etherRaised.add( msg.value ); // tallies ether raised tokensSold = tokensSold.add(award); // tallies total dragons sold } // runs when crowdsale is active - can only be called by main crowdsale contract function crowdsale ( address tokenholder ) onlyFront payable { uint award; // amount of dragons to send to tokenholder uint donation; // donation to charity DragonPricing pricingstructure = new DragonPricing(); ( award , donation ) = pricingstructure.crowdsalepricing( tokenholder, msg.value, crowdsaleCounter ); crowdsaleCounter += award; tokenReward.transfer ( tokenholder , award ); // immediate transfer to token holders if ( advisorCut < advisorTotal ) { advisorSiphon();} // send advisor his share else { beneficiary.transfer ( msg.value ); } //send all ether to beneficiary etherRaised = etherRaised.add( msg.value ); //etherRaised += msg.value; // tallies ether raised tokensSold = tokensSold.add(award); //tokensSold += award; // tallies total dragons sold } // pays the advisor part of the incoming ether function advisorSiphon() internal { uint share = msg.value/10; uint foradvisor = share; if ( (advisorCut + share) > advisorTotal ) foradvisor = advisorTotal.sub( advisorCut ); advisor.transfer ( foradvisor ); // advisor gets 10% of the incoming ether advisorCut = advisorCut.add( foradvisor ); beneficiary.transfer( share * 9 ); // the ether balance goes to the benfeciary if ( foradvisor != share ) beneficiary.transfer( share.sub(foradvisor) ); // if 10% of the incoming ether exceeds the total advisor is supposed to get , then this gives them a smaller share to not exceed max } // use this to set the crowdsale beneficiary address function transferBeneficiary ( address _newbeneficiary ) onlyOwner { require ( _newbeneficiary != 0x00 ); beneficiary = _newbeneficiary; } // use this to set the charity address function transferCharity ( address _charity ) onlyOwner { require ( _charity != 0x00 ); charity = _charity; } // sets crowdsale address function setFront ( address _front ) onlyOwner { require ( _front != 0x00 ); front = _front; } // sets advisors address function setAdvisor ( address _advisor ) onlyOwner { require ( _advisor != 0x00 ); require ( advisorset == false ); advisorset = true; advisor = _advisor; } //empty the crowdsale contract of Dragons and forward balance to beneficiary function withdrawCrowdsaleDragons() onlyOwner{ uint256 balance = tokenReward.balanceOf( address( this ) ); tokenReward.transfer( beneficiary, balance ); } //manually send different dragon packages function manualSend ( address tokenholder, uint packagenumber ) onlyOwner { require ( tokenholder != 0x00 ); if ( packagenumber != 1 && packagenumber != 2 && packagenumber != 3 ) revert(); uint award; uint donation; if ( packagenumber == 1 ) { award = 10800000000; donation = 800000000; } if ( packagenumber == 2 ) { award = 108800000000; donation = 8800000000; } if ( packagenumber == 3 ) { award = 1088800000000; donation = 88800000000; } tokenReward.transfer ( tokenholder , award ); tokenReward.transfer ( charity , donation ); presold = presold.add( award ); //add number of tokens sold in presale presold = presold.add( donation ); //add number of tokens sent via charity tokensSold = tokensSold.add(award); // tallies total dragons sold tokensSold = tokensSold.add(donation); // tallies total dragons sold } }
setAdvisor
function setAdvisor ( address _advisor ) onlyOwner { require ( _advisor != 0x00 ); require ( advisorset == false ); advisorset = true; advisor = _advisor; }
// sets advisors address
LineComment
v0.4.18+commit.9cf6e910
bzzr://29509a214ff9474aa8c7265bfcb60b8c49cd1f1b36989de6157cc035ebf8e0ee
{ "func_code_index": [ 5313, 5535 ] }
11,864
DragonCrowdsaleCore
DragonCrowdsaleCore.sol
0xd275b50f71badf4fa2f911e80e1e420730ab403e
Solidity
DragonCrowdsaleCore
contract DragonCrowdsaleCore is Ownable, DragonPricing { using SafeMath for uint; // address public owner; address public beneficiary; address public charity; address public advisor; address public front; bool public advisorset; uint public tokensSold; uint public etherRaised; uint public presold; uint public presoldMax; uint public crowdsaleCounter; uint public advisorTotal; uint public advisorCut; Dragon public tokenReward; mapping ( address => bool ) public alreadyParticipated; modifier onlyFront() { require (msg.sender == front ); _; } function DragonCrowdsaleCore(){ tokenReward = Dragon( 0x814f67fa286f7572b041d041b1d99b432c9155ee ); // Dragon Token Address owner = msg.sender; beneficiary = msg.sender; charity = msg.sender; advisor = msg.sender; advisorset = false; presold = 0; presoldMax = 3500000000000000; crowdsaleCounter = 0; advisorCut = 0; advisorTotal = 1667 ether; } // runs during precrowdsale - can only be called by main crowdsale contract function precrowdsale ( address tokenholder ) onlyFront payable { require ( presold < presoldMax ); uint award; // amount of dragons to credit to tokenholder uint donation; // donation to charity require ( alreadyParticipated[ tokenholder ] != true ) ; alreadyParticipated[ tokenholder ] = true; DragonPricing pricingstructure = new DragonPricing(); ( award, donation ) = pricingstructure.precrowdsalepricing( tokenholder , msg.value ); tokenReward.transfer ( charity , donation ); // send dragons to charity presold = presold.add( award ); //add number of tokens sold in presale presold = presold.add( donation ); //add number of tokens sent via charity tokensSold = tokensSold.add(donation); //add charity donation to total number of tokens sold tokenReward.transfer ( tokenholder , award ); // immediate transfer of dragons to token buyer if ( advisorCut < advisorTotal ) { advisorSiphon();} else { beneficiary.transfer ( msg.value ); } //send ether to beneficiary etherRaised = etherRaised.add( msg.value ); // tallies ether raised tokensSold = tokensSold.add(award); // tallies total dragons sold } // runs when crowdsale is active - can only be called by main crowdsale contract function crowdsale ( address tokenholder ) onlyFront payable { uint award; // amount of dragons to send to tokenholder uint donation; // donation to charity DragonPricing pricingstructure = new DragonPricing(); ( award , donation ) = pricingstructure.crowdsalepricing( tokenholder, msg.value, crowdsaleCounter ); crowdsaleCounter += award; tokenReward.transfer ( tokenholder , award ); // immediate transfer to token holders if ( advisorCut < advisorTotal ) { advisorSiphon();} // send advisor his share else { beneficiary.transfer ( msg.value ); } //send all ether to beneficiary etherRaised = etherRaised.add( msg.value ); //etherRaised += msg.value; // tallies ether raised tokensSold = tokensSold.add(award); //tokensSold += award; // tallies total dragons sold } // pays the advisor part of the incoming ether function advisorSiphon() internal { uint share = msg.value/10; uint foradvisor = share; if ( (advisorCut + share) > advisorTotal ) foradvisor = advisorTotal.sub( advisorCut ); advisor.transfer ( foradvisor ); // advisor gets 10% of the incoming ether advisorCut = advisorCut.add( foradvisor ); beneficiary.transfer( share * 9 ); // the ether balance goes to the benfeciary if ( foradvisor != share ) beneficiary.transfer( share.sub(foradvisor) ); // if 10% of the incoming ether exceeds the total advisor is supposed to get , then this gives them a smaller share to not exceed max } // use this to set the crowdsale beneficiary address function transferBeneficiary ( address _newbeneficiary ) onlyOwner { require ( _newbeneficiary != 0x00 ); beneficiary = _newbeneficiary; } // use this to set the charity address function transferCharity ( address _charity ) onlyOwner { require ( _charity != 0x00 ); charity = _charity; } // sets crowdsale address function setFront ( address _front ) onlyOwner { require ( _front != 0x00 ); front = _front; } // sets advisors address function setAdvisor ( address _advisor ) onlyOwner { require ( _advisor != 0x00 ); require ( advisorset == false ); advisorset = true; advisor = _advisor; } //empty the crowdsale contract of Dragons and forward balance to beneficiary function withdrawCrowdsaleDragons() onlyOwner{ uint256 balance = tokenReward.balanceOf( address( this ) ); tokenReward.transfer( beneficiary, balance ); } //manually send different dragon packages function manualSend ( address tokenholder, uint packagenumber ) onlyOwner { require ( tokenholder != 0x00 ); if ( packagenumber != 1 && packagenumber != 2 && packagenumber != 3 ) revert(); uint award; uint donation; if ( packagenumber == 1 ) { award = 10800000000; donation = 800000000; } if ( packagenumber == 2 ) { award = 108800000000; donation = 8800000000; } if ( packagenumber == 3 ) { award = 1088800000000; donation = 88800000000; } tokenReward.transfer ( tokenholder , award ); tokenReward.transfer ( charity , donation ); presold = presold.add( award ); //add number of tokens sold in presale presold = presold.add( donation ); //add number of tokens sent via charity tokensSold = tokensSold.add(award); // tallies total dragons sold tokensSold = tokensSold.add(donation); // tallies total dragons sold } }
withdrawCrowdsaleDragons
function withdrawCrowdsaleDragons() onlyOwner{ uint256 balance = tokenReward.balanceOf( address( this ) ); tokenReward.transfer( beneficiary, balance ); }
//empty the crowdsale contract of Dragons and forward balance to beneficiary
LineComment
v0.4.18+commit.9cf6e910
bzzr://29509a214ff9474aa8c7265bfcb60b8c49cd1f1b36989de6157cc035ebf8e0ee
{ "func_code_index": [ 5639, 5851 ] }
11,865
DragonCrowdsaleCore
DragonCrowdsaleCore.sol
0xd275b50f71badf4fa2f911e80e1e420730ab403e
Solidity
DragonCrowdsaleCore
contract DragonCrowdsaleCore is Ownable, DragonPricing { using SafeMath for uint; // address public owner; address public beneficiary; address public charity; address public advisor; address public front; bool public advisorset; uint public tokensSold; uint public etherRaised; uint public presold; uint public presoldMax; uint public crowdsaleCounter; uint public advisorTotal; uint public advisorCut; Dragon public tokenReward; mapping ( address => bool ) public alreadyParticipated; modifier onlyFront() { require (msg.sender == front ); _; } function DragonCrowdsaleCore(){ tokenReward = Dragon( 0x814f67fa286f7572b041d041b1d99b432c9155ee ); // Dragon Token Address owner = msg.sender; beneficiary = msg.sender; charity = msg.sender; advisor = msg.sender; advisorset = false; presold = 0; presoldMax = 3500000000000000; crowdsaleCounter = 0; advisorCut = 0; advisorTotal = 1667 ether; } // runs during precrowdsale - can only be called by main crowdsale contract function precrowdsale ( address tokenholder ) onlyFront payable { require ( presold < presoldMax ); uint award; // amount of dragons to credit to tokenholder uint donation; // donation to charity require ( alreadyParticipated[ tokenholder ] != true ) ; alreadyParticipated[ tokenholder ] = true; DragonPricing pricingstructure = new DragonPricing(); ( award, donation ) = pricingstructure.precrowdsalepricing( tokenholder , msg.value ); tokenReward.transfer ( charity , donation ); // send dragons to charity presold = presold.add( award ); //add number of tokens sold in presale presold = presold.add( donation ); //add number of tokens sent via charity tokensSold = tokensSold.add(donation); //add charity donation to total number of tokens sold tokenReward.transfer ( tokenholder , award ); // immediate transfer of dragons to token buyer if ( advisorCut < advisorTotal ) { advisorSiphon();} else { beneficiary.transfer ( msg.value ); } //send ether to beneficiary etherRaised = etherRaised.add( msg.value ); // tallies ether raised tokensSold = tokensSold.add(award); // tallies total dragons sold } // runs when crowdsale is active - can only be called by main crowdsale contract function crowdsale ( address tokenholder ) onlyFront payable { uint award; // amount of dragons to send to tokenholder uint donation; // donation to charity DragonPricing pricingstructure = new DragonPricing(); ( award , donation ) = pricingstructure.crowdsalepricing( tokenholder, msg.value, crowdsaleCounter ); crowdsaleCounter += award; tokenReward.transfer ( tokenholder , award ); // immediate transfer to token holders if ( advisorCut < advisorTotal ) { advisorSiphon();} // send advisor his share else { beneficiary.transfer ( msg.value ); } //send all ether to beneficiary etherRaised = etherRaised.add( msg.value ); //etherRaised += msg.value; // tallies ether raised tokensSold = tokensSold.add(award); //tokensSold += award; // tallies total dragons sold } // pays the advisor part of the incoming ether function advisorSiphon() internal { uint share = msg.value/10; uint foradvisor = share; if ( (advisorCut + share) > advisorTotal ) foradvisor = advisorTotal.sub( advisorCut ); advisor.transfer ( foradvisor ); // advisor gets 10% of the incoming ether advisorCut = advisorCut.add( foradvisor ); beneficiary.transfer( share * 9 ); // the ether balance goes to the benfeciary if ( foradvisor != share ) beneficiary.transfer( share.sub(foradvisor) ); // if 10% of the incoming ether exceeds the total advisor is supposed to get , then this gives them a smaller share to not exceed max } // use this to set the crowdsale beneficiary address function transferBeneficiary ( address _newbeneficiary ) onlyOwner { require ( _newbeneficiary != 0x00 ); beneficiary = _newbeneficiary; } // use this to set the charity address function transferCharity ( address _charity ) onlyOwner { require ( _charity != 0x00 ); charity = _charity; } // sets crowdsale address function setFront ( address _front ) onlyOwner { require ( _front != 0x00 ); front = _front; } // sets advisors address function setAdvisor ( address _advisor ) onlyOwner { require ( _advisor != 0x00 ); require ( advisorset == false ); advisorset = true; advisor = _advisor; } //empty the crowdsale contract of Dragons and forward balance to beneficiary function withdrawCrowdsaleDragons() onlyOwner{ uint256 balance = tokenReward.balanceOf( address( this ) ); tokenReward.transfer( beneficiary, balance ); } //manually send different dragon packages function manualSend ( address tokenholder, uint packagenumber ) onlyOwner { require ( tokenholder != 0x00 ); if ( packagenumber != 1 && packagenumber != 2 && packagenumber != 3 ) revert(); uint award; uint donation; if ( packagenumber == 1 ) { award = 10800000000; donation = 800000000; } if ( packagenumber == 2 ) { award = 108800000000; donation = 8800000000; } if ( packagenumber == 3 ) { award = 1088800000000; donation = 88800000000; } tokenReward.transfer ( tokenholder , award ); tokenReward.transfer ( charity , donation ); presold = presold.add( award ); //add number of tokens sold in presale presold = presold.add( donation ); //add number of tokens sent via charity tokensSold = tokensSold.add(award); // tallies total dragons sold tokensSold = tokensSold.add(donation); // tallies total dragons sold } }
manualSend
function manualSend ( address tokenholder, uint packagenumber ) onlyOwner { require ( tokenholder != 0x00 ); if ( packagenumber != 1 && packagenumber != 2 && packagenumber != 3 ) revert(); uint award; uint donation; if ( packagenumber == 1 ) { award = 10800000000; donation = 800000000; } if ( packagenumber == 2 ) { award = 108800000000; donation = 8800000000; } if ( packagenumber == 3 ) { award = 1088800000000; donation = 88800000000; } tokenReward.transfer ( tokenholder , award ); tokenReward.transfer ( charity , donation ); presold = presold.add( award ); //add number of tokens sold in presale presold = presold.add( donation ); //add number of tokens sent via charity tokensSold = tokensSold.add(award); // tallies total dragons sold tokensSold = tokensSold.add(donation); // tallies total dragons sold }
//manually send different dragon packages
LineComment
v0.4.18+commit.9cf6e910
bzzr://29509a214ff9474aa8c7265bfcb60b8c49cd1f1b36989de6157cc035ebf8e0ee
{ "func_code_index": [ 5905, 6963 ] }
11,866
HyperLimit
HyperLimit.sol
0x16a893f27fdb30cc05d8fd7a333a5ab841461658
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
/** * @dev 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. */
NatSpecMultiLine
add
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 addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */
NatSpecMultiLine
v0.6.8+commit.0bbfe453
MIT
ipfs://87b25594a09c529edcbca78f8b34edb2270eef34e0e1c6085d9645d3ea74cd05
{ "func_code_index": [ 251, 437 ] }
11,867
HyperLimit
HyperLimit.sol
0x16a893f27fdb30cc05d8fd7a333a5ab841461658
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
/** * @dev 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. */
NatSpecMultiLine
sub
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 on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */
NatSpecMultiLine
v0.6.8+commit.0bbfe453
MIT
ipfs://87b25594a09c529edcbca78f8b34edb2270eef34e0e1c6085d9645d3ea74cd05
{ "func_code_index": [ 707, 848 ] }
11,868
HyperLimit
HyperLimit.sol
0x16a893f27fdb30cc05d8fd7a333a5ab841461658
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
/** * @dev 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. */
NatSpecMultiLine
sub
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 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. */
NatSpecMultiLine
v0.6.8+commit.0bbfe453
MIT
ipfs://87b25594a09c529edcbca78f8b34edb2270eef34e0e1c6085d9645d3ea74cd05
{ "func_code_index": [ 1138, 1335 ] }
11,869
HyperLimit
HyperLimit.sol
0x16a893f27fdb30cc05d8fd7a333a5ab841461658
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
/** * @dev 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. */
NatSpecMultiLine
mul
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 multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */
NatSpecMultiLine
v0.6.8+commit.0bbfe453
MIT
ipfs://87b25594a09c529edcbca78f8b34edb2270eef34e0e1c6085d9645d3ea74cd05
{ "func_code_index": [ 1581, 2057 ] }
11,870
HyperLimit
HyperLimit.sol
0x16a893f27fdb30cc05d8fd7a333a5ab841461658
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
/** * @dev 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. */
NatSpecMultiLine
div
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 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. */
NatSpecMultiLine
v0.6.8+commit.0bbfe453
MIT
ipfs://87b25594a09c529edcbca78f8b34edb2270eef34e0e1c6085d9645d3ea74cd05
{ "func_code_index": [ 2520, 2657 ] }
11,871
HyperLimit
HyperLimit.sol
0x16a893f27fdb30cc05d8fd7a333a5ab841461658
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
/** * @dev 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. */
NatSpecMultiLine
div
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 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. */
NatSpecMultiLine
v0.6.8+commit.0bbfe453
MIT
ipfs://87b25594a09c529edcbca78f8b34edb2270eef34e0e1c6085d9645d3ea74cd05
{ "func_code_index": [ 3140, 3423 ] }
11,872
HyperLimit
HyperLimit.sol
0x16a893f27fdb30cc05d8fd7a333a5ab841461658
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
/** * @dev 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. */
NatSpecMultiLine
mod
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 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. */
NatSpecMultiLine
v0.6.8+commit.0bbfe453
MIT
ipfs://87b25594a09c529edcbca78f8b34edb2270eef34e0e1c6085d9645d3ea74cd05
{ "func_code_index": [ 3875, 4010 ] }
11,873
HyperLimit
HyperLimit.sol
0x16a893f27fdb30cc05d8fd7a333a5ab841461658
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
/** * @dev 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. */
NatSpecMultiLine
mod
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; }
/** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * 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. */
NatSpecMultiLine
v0.6.8+commit.0bbfe453
MIT
ipfs://87b25594a09c529edcbca78f8b34edb2270eef34e0e1c6085d9645d3ea74cd05
{ "func_code_index": [ 4482, 4653 ] }
11,874
HyperLimit
HyperLimit.sol
0x16a893f27fdb30cc05d8fd7a333a5ab841461658
Solidity
ECDSA
library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } }
/** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */
NatSpecMultiLine
recover
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; }
/** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */
NatSpecMultiLine
v0.6.8+commit.0bbfe453
MIT
ipfs://87b25594a09c529edcbca78f8b34edb2270eef34e0e1c6085d9645d3ea74cd05
{ "func_code_index": [ 811, 2923 ] }
11,875
HyperLimit
HyperLimit.sol
0x16a893f27fdb30cc05d8fd7a333a5ab841461658
Solidity
ECDSA
library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } }
/** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */
NatSpecMultiLine
toEthSignedMessageHash
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); }
/** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */
NatSpecMultiLine
v0.6.8+commit.0bbfe453
MIT
ipfs://87b25594a09c529edcbca78f8b34edb2270eef34e0e1c6085d9645d3ea74cd05
{ "func_code_index": [ 3192, 3466 ] }
11,876
HyperLimit
HyperLimit.sol
0x16a893f27fdb30cc05d8fd7a333a5ab841461658
Solidity
IERC20
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 of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */
NatSpecMultiLine
totalSupply
function totalSupply() external view returns (uint256);
/** * @dev Returns the amount of tokens in existence. */
NatSpecMultiLine
v0.6.8+commit.0bbfe453
MIT
ipfs://87b25594a09c529edcbca78f8b34edb2270eef34e0e1c6085d9645d3ea74cd05
{ "func_code_index": [ 94, 154 ] }
11,877
HyperLimit
HyperLimit.sol
0x16a893f27fdb30cc05d8fd7a333a5ab841461658
Solidity
IERC20
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 of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */
NatSpecMultiLine
balanceOf
function balanceOf(address account) external view returns (uint256);
/** * @dev Returns the amount of tokens owned by `account`. */
NatSpecMultiLine
v0.6.8+commit.0bbfe453
MIT
ipfs://87b25594a09c529edcbca78f8b34edb2270eef34e0e1c6085d9645d3ea74cd05
{ "func_code_index": [ 237, 310 ] }
11,878
HyperLimit
HyperLimit.sol
0x16a893f27fdb30cc05d8fd7a333a5ab841461658
Solidity
IERC20
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 of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */
NatSpecMultiLine
transfer
function transfer(address recipient, uint256 amount) external returns (bool);
/** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */
NatSpecMultiLine
v0.6.8+commit.0bbfe453
MIT
ipfs://87b25594a09c529edcbca78f8b34edb2270eef34e0e1c6085d9645d3ea74cd05
{ "func_code_index": [ 534, 616 ] }
11,879
HyperLimit
HyperLimit.sol
0x16a893f27fdb30cc05d8fd7a333a5ab841461658
Solidity
IERC20
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 of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */
NatSpecMultiLine
allowance
function allowance(address owner, address spender) external view returns (uint256);
/** * @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. */
NatSpecMultiLine
v0.6.8+commit.0bbfe453
MIT
ipfs://87b25594a09c529edcbca78f8b34edb2270eef34e0e1c6085d9645d3ea74cd05
{ "func_code_index": [ 895, 983 ] }
11,880
HyperLimit
HyperLimit.sol
0x16a893f27fdb30cc05d8fd7a333a5ab841461658
Solidity
IERC20
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 of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */
NatSpecMultiLine
approve
function approve(address spender, uint256 amount) external returns (bool);
/** * @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. */
NatSpecMultiLine
v0.6.8+commit.0bbfe453
MIT
ipfs://87b25594a09c529edcbca78f8b34edb2270eef34e0e1c6085d9645d3ea74cd05
{ "func_code_index": [ 1647, 1726 ] }
11,881
HyperLimit
HyperLimit.sol
0x16a893f27fdb30cc05d8fd7a333a5ab841461658
Solidity
IERC20
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 of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */
NatSpecMultiLine
transferFrom
function transferFrom(address sender, address recipient, 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. */
NatSpecMultiLine
v0.6.8+commit.0bbfe453
MIT
ipfs://87b25594a09c529edcbca78f8b34edb2270eef34e0e1c6085d9645d3ea74cd05
{ "func_code_index": [ 2039, 2141 ] }
11,882
HyperLimit
HyperLimit.sol
0x16a893f27fdb30cc05d8fd7a333a5ab841461658
Solidity
Fabric
library Fabric { /*Vault bytecode def _fallback() payable: call cd[56] with: funct call.data[0 len 4] gas cd[56] wei args call.data[4 len 64] selfdestruct(tx.origin) // Constructor bytecode 0x6012600081600A8239f3 0x60 12 - PUSH1 12 // Size of the contract to return 0x60 00 - PUSH1 00 // Memory offset to return stored code 0x81 - DUP2 12 // Size of code to copy 0x60 0a - PUSH1 0A // Start of the code to copy 0x82 - DUP3 00 // Dest memory for code copy 0x39 - CODECOPY 00 0A 12 // Code copy to memory 0xf3 - RETURN 00 12 // Return code to store // Deployed contract bytecode 0x60008060448082803781806038355AF132FF 0x60 00 - PUSH1 00 // Size for the call output 0x80 - DUP1 00 // Offset for the call output 0x60 44 - PUSH1 44 // Size for the call input 0x80 - DUP1 44 // Size for copying calldata to memory 0x82 - DUP3 00 // Offset for calldata copy 0x80 - DUP1 00 // Offset for destination of calldata copy 0x37 - CALLDATACOPY 00 00 44 // Execute calldata copy, is going to be used for next call 0x81 - DUP2 00 // Offset for call input 0x80 - DUP1 00 // Amount of ETH to send during call 0x60 38 - PUSH1 38 // calldata pointer to load value into stack 0x35 - CALLDATALOAD 38 (A) // Load value (A), address to call 0x5a - GAS // Remaining gas 0xf1 - CALL (A) (A) 00 00 44 00 00 // Execute call to address (A) with calldata mem[0:64] 0x32 - ORIGIN (B) // Dest funds for selfdestruct 0xff - SELFDESTRUCT (B) // selfdestruct contract, end of execution */ bytes public constant code = hex"6012600081600A8239F360008060448082803781806038355AF132FF"; bytes32 public constant vaultCodeHash = bytes32(0xfa3da1081bc86587310fce8f3a5309785fc567b9b20875900cb289302d6bfa97); /** * @dev Get a deterministics vault. */ function getVault(bytes32 _key) internal view returns (address) { return address( uint256( keccak256( abi.encodePacked( byte(0xff), address(this), _key, vaultCodeHash ) ) ) ); } /** * @dev Create deterministic vault. */ function executeVault(bytes32 _key, IERC20 _token, address _to) internal returns (uint256 value) { address addr; bytes memory slotcode = code; /* solium-disable-next-line */ assembly{ // Create the contract arguments for the constructor addr := create2(0, add(slotcode, 0x20), mload(slotcode), _key) } value = _token.balanceOf(addr); /* solium-disable-next-line */ (bool success, ) = addr.call( abi.encodePacked( abi.encodeWithSelector( _token.transfer.selector, _to, value ), address(_token) ) ); require(success, "Error pulling tokens"); } }
/** * @title Fabric * @dev Create deterministics vaults. */
NatSpecMultiLine
getVault
function getVault(bytes32 _key) internal view returns (address) { return address( uint256( keccak256( abi.encodePacked( byte(0xff), address(this), _key, vaultCodeHash ) ) ) ); }
/** * @dev Get a deterministics vault. */
NatSpecMultiLine
v0.6.8+commit.0bbfe453
MIT
ipfs://87b25594a09c529edcbca78f8b34edb2270eef34e0e1c6085d9645d3ea74cd05
{ "func_code_index": [ 2422, 2829 ] }
11,883
HyperLimit
HyperLimit.sol
0x16a893f27fdb30cc05d8fd7a333a5ab841461658
Solidity
Fabric
library Fabric { /*Vault bytecode def _fallback() payable: call cd[56] with: funct call.data[0 len 4] gas cd[56] wei args call.data[4 len 64] selfdestruct(tx.origin) // Constructor bytecode 0x6012600081600A8239f3 0x60 12 - PUSH1 12 // Size of the contract to return 0x60 00 - PUSH1 00 // Memory offset to return stored code 0x81 - DUP2 12 // Size of code to copy 0x60 0a - PUSH1 0A // Start of the code to copy 0x82 - DUP3 00 // Dest memory for code copy 0x39 - CODECOPY 00 0A 12 // Code copy to memory 0xf3 - RETURN 00 12 // Return code to store // Deployed contract bytecode 0x60008060448082803781806038355AF132FF 0x60 00 - PUSH1 00 // Size for the call output 0x80 - DUP1 00 // Offset for the call output 0x60 44 - PUSH1 44 // Size for the call input 0x80 - DUP1 44 // Size for copying calldata to memory 0x82 - DUP3 00 // Offset for calldata copy 0x80 - DUP1 00 // Offset for destination of calldata copy 0x37 - CALLDATACOPY 00 00 44 // Execute calldata copy, is going to be used for next call 0x81 - DUP2 00 // Offset for call input 0x80 - DUP1 00 // Amount of ETH to send during call 0x60 38 - PUSH1 38 // calldata pointer to load value into stack 0x35 - CALLDATALOAD 38 (A) // Load value (A), address to call 0x5a - GAS // Remaining gas 0xf1 - CALL (A) (A) 00 00 44 00 00 // Execute call to address (A) with calldata mem[0:64] 0x32 - ORIGIN (B) // Dest funds for selfdestruct 0xff - SELFDESTRUCT (B) // selfdestruct contract, end of execution */ bytes public constant code = hex"6012600081600A8239F360008060448082803781806038355AF132FF"; bytes32 public constant vaultCodeHash = bytes32(0xfa3da1081bc86587310fce8f3a5309785fc567b9b20875900cb289302d6bfa97); /** * @dev Get a deterministics vault. */ function getVault(bytes32 _key) internal view returns (address) { return address( uint256( keccak256( abi.encodePacked( byte(0xff), address(this), _key, vaultCodeHash ) ) ) ); } /** * @dev Create deterministic vault. */ function executeVault(bytes32 _key, IERC20 _token, address _to) internal returns (uint256 value) { address addr; bytes memory slotcode = code; /* solium-disable-next-line */ assembly{ // Create the contract arguments for the constructor addr := create2(0, add(slotcode, 0x20), mload(slotcode), _key) } value = _token.balanceOf(addr); /* solium-disable-next-line */ (bool success, ) = addr.call( abi.encodePacked( abi.encodeWithSelector( _token.transfer.selector, _to, value ), address(_token) ) ); require(success, "Error pulling tokens"); } }
/** * @title Fabric * @dev Create deterministics vaults. */
NatSpecMultiLine
executeVault
function executeVault(bytes32 _key, IERC20 _token, address _to) internal returns (uint256 value) { address addr; bytes memory slotcode = code; /* solium-disable-next-line */ assembly{ // Create the contract arguments for the constructor addr := create2(0, add(slotcode, 0x20), mload(slotcode), _key) } value = _token.balanceOf(addr); /* solium-disable-next-line */ (bool success, ) = addr.call( abi.encodePacked( abi.encodeWithSelector( _token.transfer.selector, _to, value ), address(_token) ) ); require(success, "Error pulling tokens"); }
/** * @dev Create deterministic vault. */
NatSpecMultiLine
v0.6.8+commit.0bbfe453
MIT
ipfs://87b25594a09c529edcbca78f8b34edb2270eef34e0e1c6085d9645d3ea74cd05
{ "func_code_index": [ 2889, 3698 ] }
11,884
HyperLimit
HyperLimit.sol
0x16a893f27fdb30cc05d8fd7a333a5ab841461658
Solidity
IModule
interface IModule { /// @notice receive ETH receive() external payable; /** * @notice Executes an order * @param _inputToken - Address of the input token * @param _inputAmount - uint256 of the input token amount (order amount) * @param _owner - Address of the order's owner * @param _data - Bytes of the order's data * @param _auxData - Bytes of the auxiliar data used for the handlers to execute the order * @return bought - amount of output token bought */ function execute( IERC20 _inputToken, uint256 _inputAmount, address payable _owner, bytes calldata _data, bytes calldata _auxData ) external returns (uint256 bought); /** * @notice Check whether an order can be executed or not * @param _inputToken - Address of the input token * @param _inputAmount - uint256 of the input token amount (order amount) * @param _data - Bytes of the order's data * @param _auxData - Bytes of the auxiliar data used for the handlers to execute the order * @return bool - whether the order can be executed or not */ function canExecute( IERC20 _inputToken, uint256 _inputAmount, bytes calldata _data, bytes calldata _auxData ) external view returns (bool); }
/// @notice receive ETH
NatSpecSingleLine
v0.6.8+commit.0bbfe453
MIT
ipfs://87b25594a09c529edcbca78f8b34edb2270eef34e0e1c6085d9645d3ea74cd05
{ "func_code_index": [ 50, 82 ] }
11,885
HyperLimit
HyperLimit.sol
0x16a893f27fdb30cc05d8fd7a333a5ab841461658
Solidity
IModule
interface IModule { /// @notice receive ETH receive() external payable; /** * @notice Executes an order * @param _inputToken - Address of the input token * @param _inputAmount - uint256 of the input token amount (order amount) * @param _owner - Address of the order's owner * @param _data - Bytes of the order's data * @param _auxData - Bytes of the auxiliar data used for the handlers to execute the order * @return bought - amount of output token bought */ function execute( IERC20 _inputToken, uint256 _inputAmount, address payable _owner, bytes calldata _data, bytes calldata _auxData ) external returns (uint256 bought); /** * @notice Check whether an order can be executed or not * @param _inputToken - Address of the input token * @param _inputAmount - uint256 of the input token amount (order amount) * @param _data - Bytes of the order's data * @param _auxData - Bytes of the auxiliar data used for the handlers to execute the order * @return bool - whether the order can be executed or not */ function canExecute( IERC20 _inputToken, uint256 _inputAmount, bytes calldata _data, bytes calldata _auxData ) external view returns (bool); }
execute
function execute( IERC20 _inputToken, uint256 _inputAmount, address payable _owner, bytes calldata _data, bytes calldata _auxData ) external returns (uint256 bought);
/** * @notice Executes an order * @param _inputToken - Address of the input token * @param _inputAmount - uint256 of the input token amount (order amount) * @param _owner - Address of the order's owner * @param _data - Bytes of the order's data * @param _auxData - Bytes of the auxiliar data used for the handlers to execute the order * @return bought - amount of output token bought */
NatSpecMultiLine
v0.6.8+commit.0bbfe453
MIT
ipfs://87b25594a09c529edcbca78f8b34edb2270eef34e0e1c6085d9645d3ea74cd05
{ "func_code_index": [ 525, 746 ] }
11,886
HyperLimit
HyperLimit.sol
0x16a893f27fdb30cc05d8fd7a333a5ab841461658
Solidity
IModule
interface IModule { /// @notice receive ETH receive() external payable; /** * @notice Executes an order * @param _inputToken - Address of the input token * @param _inputAmount - uint256 of the input token amount (order amount) * @param _owner - Address of the order's owner * @param _data - Bytes of the order's data * @param _auxData - Bytes of the auxiliar data used for the handlers to execute the order * @return bought - amount of output token bought */ function execute( IERC20 _inputToken, uint256 _inputAmount, address payable _owner, bytes calldata _data, bytes calldata _auxData ) external returns (uint256 bought); /** * @notice Check whether an order can be executed or not * @param _inputToken - Address of the input token * @param _inputAmount - uint256 of the input token amount (order amount) * @param _data - Bytes of the order's data * @param _auxData - Bytes of the auxiliar data used for the handlers to execute the order * @return bool - whether the order can be executed or not */ function canExecute( IERC20 _inputToken, uint256 _inputAmount, bytes calldata _data, bytes calldata _auxData ) external view returns (bool); }
canExecute
function canExecute( IERC20 _inputToken, uint256 _inputAmount, bytes calldata _data, bytes calldata _auxData ) external view returns (bool);
/** * @notice Check whether an order can be executed or not * @param _inputToken - Address of the input token * @param _inputAmount - uint256 of the input token amount (order amount) * @param _data - Bytes of the order's data * @param _auxData - Bytes of the auxiliar data used for the handlers to execute the order * @return bool - whether the order can be executed or not */
NatSpecMultiLine
v0.6.8+commit.0bbfe453
MIT
ipfs://87b25594a09c529edcbca78f8b34edb2270eef34e0e1c6085d9645d3ea74cd05
{ "func_code_index": [ 1173, 1359 ] }
11,887
HyperLimit
HyperLimit.sol
0x16a893f27fdb30cc05d8fd7a333a5ab841461658
Solidity
HyperLimit
contract HyperLimit is Order { using SafeMath for uint256; using Fabric for bytes32; // ETH orders mapping(bytes32 => uint256) public ethDeposits; // Events event DepositETH( bytes32 indexed _key, address indexed _caller, uint256 _amount, bytes _data ); event OrderExecuted( bytes32 indexed _key, address _inputToken, address _owner, address _witness, bytes _data, bytes _auxData, uint256 _amount, uint256 _bought ); event OrderCancelled( bytes32 indexed _key, address _inputToken, address _owner, address _witness, bytes _data, uint256 _amount ); /** * @dev Prevent users to send Ether directly to this contract */ receive() external payable { require( msg.sender != tx.origin, "HyperLimit#receive: NO_SEND_ETH_PLEASE" ); } /** * @notice Create an ETH to token order * @param _data - Bytes of an ETH to token order. See `encodeEthOrder` for more info */ function depositEth( bytes calldata _data ) external payable { require(msg.value > 0, "HyperLimit#depositEth: VALUE_IS_0"); ( address module, address inputToken, address payable owner, address witness, bytes memory data, ) = decodeOrder(_data); require(inputToken == ETH_ADDRESS, "HyperLimit#depositEth: WRONG_INPUT_TOKEN"); bytes32 key = keyOf( IModule(uint160(module)), IERC20(inputToken), owner, witness, data ); ethDeposits[key] = ethDeposits[key].add(msg.value); emit DepositETH(key, msg.sender, msg.value, _data); } /** * @notice Cancel order * @dev The params should be the same used for the order creation * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data */ function cancelOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data ) external { require(msg.sender == _owner, "HyperLimit#cancelOrder: INVALID_OWNER"); bytes32 key = keyOf( _module, _inputToken, _owner, _witness, _data ); uint256 amount = _pullOrder(_inputToken, key, msg.sender); emit OrderCancelled( key, address(_inputToken), _owner, _witness, _data, amount ); } /** * @notice Get the calldata needed to create a token to token/ETH order * @dev Returns the input data that the user needs to use to create the order * The _secret is used to prevent a front-running at the order execution * The _amount is used as the param `_value` for the ERC20 `transfer` function * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @param _secret - Private key of the _witness * @param _amount - uint256 of the order amount * @return bytes - input data to send the transaction */ function encodeTokenOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data, bytes32 _secret, uint256 _amount ) external view returns (bytes memory) { return abi.encodeWithSelector( _inputToken.transfer.selector, vaultOfOrder( _module, _inputToken, _owner, _witness, _data ), _amount, abi.encode( _module, _inputToken, _owner, _witness, _data, _secret ) ); } /** * @notice Get the calldata needed to create a ETH to token order * @dev Returns the input data that the user needs to use to create the order * The _secret is used to prevent a front-running at the order execution * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @param _secret - Private key of the _witness * @return bytes - input data to send the transaction */ function encodeEthOrder( address _module, address _inputToken, address payable _owner, address _witness, bytes calldata _data, bytes32 _secret ) external pure returns (bytes memory) { return abi.encode( _module, _inputToken, _owner, _witness, _data, _secret ); } /** * @notice Get order's properties * @param _data - Bytes of the order * @return module - Address of the module to use for the order execution * @return inputToken - Address of the input token * @return owner - Address of the order's owner * @return witness - Address of the witness * @return data - Bytes of the order's data * @return secret - Private key of the _witness */ function decodeOrder( bytes memory _data ) public pure returns ( address module, address inputToken, address payable owner, address witness, bytes memory data, bytes32 secret ) { ( module, inputToken, owner, witness, data, secret ) = abi.decode( _data, ( address, address, address, address, bytes, bytes32 ) ); } /** * @notice Get the vault's address of a token to token/ETH order * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @return address - The address of the vault */ function vaultOfOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes memory _data ) public view returns (address) { return keyOf( _module, _inputToken, _owner, _witness, _data ).getVault(); } /** * @notice Executes an order * @dev The sender should use the _secret to sign its own address * to prevent front-runnings * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _data - Bytes of the order's data * @param _signature - Signature to calculate the witness * @param _auxData - Bytes of the auxiliar data used for the handlers to execute the order */ function executeOrder( IModule _module, IERC20 _inputToken, address payable _owner, bytes calldata _data, bytes calldata _signature, bytes calldata _auxData ) external { // Calculate witness using signature address witness = ECDSA.recover( keccak256(abi.encodePacked(msg.sender)), _signature ); bytes32 key = keyOf( _module, _inputToken, _owner, witness, _data ); // Pull amount uint256 amount = _pullOrder(_inputToken, key, address(_module)); require(amount > 0, "HyperLimit#executeOrder: INVALID_ORDER"); uint256 bought = _module.execute( _inputToken, amount, _owner, _data, _auxData ); emit OrderExecuted( key, address(_inputToken), _owner, witness, _data, _auxData, amount, bought ); } /** * @notice Check whether an order exists or not * @dev Check the balance of the order * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @return bool - whether the order exists or not */ function existOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data ) external view returns (bool) { bytes32 key = keyOf( _module, _inputToken, _owner, _witness, _data ); if (address(_inputToken) == ETH_ADDRESS) { return ethDeposits[key] != 0; } else { return _inputToken.balanceOf(key.getVault()) != 0; } } /** * @notice Check whether an order can be executed or not * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @param _auxData - Bytes of the auxiliar data used for the handlers to execute the order * @return bool - whether the order can be executed or not */ function canExecuteOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data, bytes calldata _auxData ) external view returns (bool) { bytes32 key = keyOf( _module, _inputToken, _owner, _witness, _data ); // Pull amount uint256 amount; if (address(_inputToken) == ETH_ADDRESS) { amount = ethDeposits[key]; } else { amount = _inputToken.balanceOf(key.getVault()); } return _module.canExecute( _inputToken, amount, _data, _auxData ); } /** * @notice Transfer the order amount to a recipient. * @dev For an ETH order, the ETH will be transferred from this contract * For a token order, its vault will be executed transferring the amount of tokens to * the recipient * @param _inputToken - Address of the input token * @param _key - Order's key * @param _to - Address of the recipient * @return amount - amount transferred */ function _pullOrder( IERC20 _inputToken, bytes32 _key, address payable _to ) private returns (uint256 amount) { if (address(_inputToken) == ETH_ADDRESS) { amount = ethDeposits[_key]; ethDeposits[_key] = 0; (bool success,) = _to.call{value: amount}(""); require(success, "HyperLimit#_pullOrder: PULL_ETHER_FAILED"); } else { amount = _key.executeVault(_inputToken, _to); } } /** * @notice Get the order's key * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @return bytes32 - order's key */ function keyOf( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes memory _data ) public pure returns (bytes32) { return keccak256( abi.encode( _module, _inputToken, _owner, _witness, _data ) ); } }
/// @notice Core contract used to create, cancel and execute orders.
NatSpecSingleLine
/** * @dev Prevent users to send Ether directly to this contract */
NatSpecMultiLine
v0.6.8+commit.0bbfe453
MIT
ipfs://87b25594a09c529edcbca78f8b34edb2270eef34e0e1c6085d9645d3ea74cd05
{ "func_code_index": [ 861, 1023 ] }
11,888
HyperLimit
HyperLimit.sol
0x16a893f27fdb30cc05d8fd7a333a5ab841461658
Solidity
HyperLimit
contract HyperLimit is Order { using SafeMath for uint256; using Fabric for bytes32; // ETH orders mapping(bytes32 => uint256) public ethDeposits; // Events event DepositETH( bytes32 indexed _key, address indexed _caller, uint256 _amount, bytes _data ); event OrderExecuted( bytes32 indexed _key, address _inputToken, address _owner, address _witness, bytes _data, bytes _auxData, uint256 _amount, uint256 _bought ); event OrderCancelled( bytes32 indexed _key, address _inputToken, address _owner, address _witness, bytes _data, uint256 _amount ); /** * @dev Prevent users to send Ether directly to this contract */ receive() external payable { require( msg.sender != tx.origin, "HyperLimit#receive: NO_SEND_ETH_PLEASE" ); } /** * @notice Create an ETH to token order * @param _data - Bytes of an ETH to token order. See `encodeEthOrder` for more info */ function depositEth( bytes calldata _data ) external payable { require(msg.value > 0, "HyperLimit#depositEth: VALUE_IS_0"); ( address module, address inputToken, address payable owner, address witness, bytes memory data, ) = decodeOrder(_data); require(inputToken == ETH_ADDRESS, "HyperLimit#depositEth: WRONG_INPUT_TOKEN"); bytes32 key = keyOf( IModule(uint160(module)), IERC20(inputToken), owner, witness, data ); ethDeposits[key] = ethDeposits[key].add(msg.value); emit DepositETH(key, msg.sender, msg.value, _data); } /** * @notice Cancel order * @dev The params should be the same used for the order creation * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data */ function cancelOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data ) external { require(msg.sender == _owner, "HyperLimit#cancelOrder: INVALID_OWNER"); bytes32 key = keyOf( _module, _inputToken, _owner, _witness, _data ); uint256 amount = _pullOrder(_inputToken, key, msg.sender); emit OrderCancelled( key, address(_inputToken), _owner, _witness, _data, amount ); } /** * @notice Get the calldata needed to create a token to token/ETH order * @dev Returns the input data that the user needs to use to create the order * The _secret is used to prevent a front-running at the order execution * The _amount is used as the param `_value` for the ERC20 `transfer` function * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @param _secret - Private key of the _witness * @param _amount - uint256 of the order amount * @return bytes - input data to send the transaction */ function encodeTokenOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data, bytes32 _secret, uint256 _amount ) external view returns (bytes memory) { return abi.encodeWithSelector( _inputToken.transfer.selector, vaultOfOrder( _module, _inputToken, _owner, _witness, _data ), _amount, abi.encode( _module, _inputToken, _owner, _witness, _data, _secret ) ); } /** * @notice Get the calldata needed to create a ETH to token order * @dev Returns the input data that the user needs to use to create the order * The _secret is used to prevent a front-running at the order execution * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @param _secret - Private key of the _witness * @return bytes - input data to send the transaction */ function encodeEthOrder( address _module, address _inputToken, address payable _owner, address _witness, bytes calldata _data, bytes32 _secret ) external pure returns (bytes memory) { return abi.encode( _module, _inputToken, _owner, _witness, _data, _secret ); } /** * @notice Get order's properties * @param _data - Bytes of the order * @return module - Address of the module to use for the order execution * @return inputToken - Address of the input token * @return owner - Address of the order's owner * @return witness - Address of the witness * @return data - Bytes of the order's data * @return secret - Private key of the _witness */ function decodeOrder( bytes memory _data ) public pure returns ( address module, address inputToken, address payable owner, address witness, bytes memory data, bytes32 secret ) { ( module, inputToken, owner, witness, data, secret ) = abi.decode( _data, ( address, address, address, address, bytes, bytes32 ) ); } /** * @notice Get the vault's address of a token to token/ETH order * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @return address - The address of the vault */ function vaultOfOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes memory _data ) public view returns (address) { return keyOf( _module, _inputToken, _owner, _witness, _data ).getVault(); } /** * @notice Executes an order * @dev The sender should use the _secret to sign its own address * to prevent front-runnings * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _data - Bytes of the order's data * @param _signature - Signature to calculate the witness * @param _auxData - Bytes of the auxiliar data used for the handlers to execute the order */ function executeOrder( IModule _module, IERC20 _inputToken, address payable _owner, bytes calldata _data, bytes calldata _signature, bytes calldata _auxData ) external { // Calculate witness using signature address witness = ECDSA.recover( keccak256(abi.encodePacked(msg.sender)), _signature ); bytes32 key = keyOf( _module, _inputToken, _owner, witness, _data ); // Pull amount uint256 amount = _pullOrder(_inputToken, key, address(_module)); require(amount > 0, "HyperLimit#executeOrder: INVALID_ORDER"); uint256 bought = _module.execute( _inputToken, amount, _owner, _data, _auxData ); emit OrderExecuted( key, address(_inputToken), _owner, witness, _data, _auxData, amount, bought ); } /** * @notice Check whether an order exists or not * @dev Check the balance of the order * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @return bool - whether the order exists or not */ function existOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data ) external view returns (bool) { bytes32 key = keyOf( _module, _inputToken, _owner, _witness, _data ); if (address(_inputToken) == ETH_ADDRESS) { return ethDeposits[key] != 0; } else { return _inputToken.balanceOf(key.getVault()) != 0; } } /** * @notice Check whether an order can be executed or not * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @param _auxData - Bytes of the auxiliar data used for the handlers to execute the order * @return bool - whether the order can be executed or not */ function canExecuteOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data, bytes calldata _auxData ) external view returns (bool) { bytes32 key = keyOf( _module, _inputToken, _owner, _witness, _data ); // Pull amount uint256 amount; if (address(_inputToken) == ETH_ADDRESS) { amount = ethDeposits[key]; } else { amount = _inputToken.balanceOf(key.getVault()); } return _module.canExecute( _inputToken, amount, _data, _auxData ); } /** * @notice Transfer the order amount to a recipient. * @dev For an ETH order, the ETH will be transferred from this contract * For a token order, its vault will be executed transferring the amount of tokens to * the recipient * @param _inputToken - Address of the input token * @param _key - Order's key * @param _to - Address of the recipient * @return amount - amount transferred */ function _pullOrder( IERC20 _inputToken, bytes32 _key, address payable _to ) private returns (uint256 amount) { if (address(_inputToken) == ETH_ADDRESS) { amount = ethDeposits[_key]; ethDeposits[_key] = 0; (bool success,) = _to.call{value: amount}(""); require(success, "HyperLimit#_pullOrder: PULL_ETHER_FAILED"); } else { amount = _key.executeVault(_inputToken, _to); } } /** * @notice Get the order's key * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @return bytes32 - order's key */ function keyOf( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes memory _data ) public pure returns (bytes32) { return keccak256( abi.encode( _module, _inputToken, _owner, _witness, _data ) ); } }
/// @notice Core contract used to create, cancel and execute orders.
NatSpecSingleLine
depositEth
function depositEth( bytes calldata _data ) external payable { require(msg.value > 0, "HyperLimit#depositEth: VALUE_IS_0"); ( address module, address inputToken, address payable owner, address witness, bytes memory data, ) = decodeOrder(_data); require(inputToken == ETH_ADDRESS, "HyperLimit#depositEth: WRONG_INPUT_TOKEN"); bytes32 key = keyOf( IModule(uint160(module)), IERC20(inputToken), owner, witness, data ); ethDeposits[key] = ethDeposits[key].add(msg.value); emit DepositETH(key, msg.sender, msg.value, _data); }
/** * @notice Create an ETH to token order * @param _data - Bytes of an ETH to token order. See `encodeEthOrder` for more info */
NatSpecMultiLine
v0.6.8+commit.0bbfe453
MIT
ipfs://87b25594a09c529edcbca78f8b34edb2270eef34e0e1c6085d9645d3ea74cd05
{ "func_code_index": [ 1179, 1934 ] }
11,889
HyperLimit
HyperLimit.sol
0x16a893f27fdb30cc05d8fd7a333a5ab841461658
Solidity
HyperLimit
contract HyperLimit is Order { using SafeMath for uint256; using Fabric for bytes32; // ETH orders mapping(bytes32 => uint256) public ethDeposits; // Events event DepositETH( bytes32 indexed _key, address indexed _caller, uint256 _amount, bytes _data ); event OrderExecuted( bytes32 indexed _key, address _inputToken, address _owner, address _witness, bytes _data, bytes _auxData, uint256 _amount, uint256 _bought ); event OrderCancelled( bytes32 indexed _key, address _inputToken, address _owner, address _witness, bytes _data, uint256 _amount ); /** * @dev Prevent users to send Ether directly to this contract */ receive() external payable { require( msg.sender != tx.origin, "HyperLimit#receive: NO_SEND_ETH_PLEASE" ); } /** * @notice Create an ETH to token order * @param _data - Bytes of an ETH to token order. See `encodeEthOrder` for more info */ function depositEth( bytes calldata _data ) external payable { require(msg.value > 0, "HyperLimit#depositEth: VALUE_IS_0"); ( address module, address inputToken, address payable owner, address witness, bytes memory data, ) = decodeOrder(_data); require(inputToken == ETH_ADDRESS, "HyperLimit#depositEth: WRONG_INPUT_TOKEN"); bytes32 key = keyOf( IModule(uint160(module)), IERC20(inputToken), owner, witness, data ); ethDeposits[key] = ethDeposits[key].add(msg.value); emit DepositETH(key, msg.sender, msg.value, _data); } /** * @notice Cancel order * @dev The params should be the same used for the order creation * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data */ function cancelOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data ) external { require(msg.sender == _owner, "HyperLimit#cancelOrder: INVALID_OWNER"); bytes32 key = keyOf( _module, _inputToken, _owner, _witness, _data ); uint256 amount = _pullOrder(_inputToken, key, msg.sender); emit OrderCancelled( key, address(_inputToken), _owner, _witness, _data, amount ); } /** * @notice Get the calldata needed to create a token to token/ETH order * @dev Returns the input data that the user needs to use to create the order * The _secret is used to prevent a front-running at the order execution * The _amount is used as the param `_value` for the ERC20 `transfer` function * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @param _secret - Private key of the _witness * @param _amount - uint256 of the order amount * @return bytes - input data to send the transaction */ function encodeTokenOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data, bytes32 _secret, uint256 _amount ) external view returns (bytes memory) { return abi.encodeWithSelector( _inputToken.transfer.selector, vaultOfOrder( _module, _inputToken, _owner, _witness, _data ), _amount, abi.encode( _module, _inputToken, _owner, _witness, _data, _secret ) ); } /** * @notice Get the calldata needed to create a ETH to token order * @dev Returns the input data that the user needs to use to create the order * The _secret is used to prevent a front-running at the order execution * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @param _secret - Private key of the _witness * @return bytes - input data to send the transaction */ function encodeEthOrder( address _module, address _inputToken, address payable _owner, address _witness, bytes calldata _data, bytes32 _secret ) external pure returns (bytes memory) { return abi.encode( _module, _inputToken, _owner, _witness, _data, _secret ); } /** * @notice Get order's properties * @param _data - Bytes of the order * @return module - Address of the module to use for the order execution * @return inputToken - Address of the input token * @return owner - Address of the order's owner * @return witness - Address of the witness * @return data - Bytes of the order's data * @return secret - Private key of the _witness */ function decodeOrder( bytes memory _data ) public pure returns ( address module, address inputToken, address payable owner, address witness, bytes memory data, bytes32 secret ) { ( module, inputToken, owner, witness, data, secret ) = abi.decode( _data, ( address, address, address, address, bytes, bytes32 ) ); } /** * @notice Get the vault's address of a token to token/ETH order * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @return address - The address of the vault */ function vaultOfOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes memory _data ) public view returns (address) { return keyOf( _module, _inputToken, _owner, _witness, _data ).getVault(); } /** * @notice Executes an order * @dev The sender should use the _secret to sign its own address * to prevent front-runnings * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _data - Bytes of the order's data * @param _signature - Signature to calculate the witness * @param _auxData - Bytes of the auxiliar data used for the handlers to execute the order */ function executeOrder( IModule _module, IERC20 _inputToken, address payable _owner, bytes calldata _data, bytes calldata _signature, bytes calldata _auxData ) external { // Calculate witness using signature address witness = ECDSA.recover( keccak256(abi.encodePacked(msg.sender)), _signature ); bytes32 key = keyOf( _module, _inputToken, _owner, witness, _data ); // Pull amount uint256 amount = _pullOrder(_inputToken, key, address(_module)); require(amount > 0, "HyperLimit#executeOrder: INVALID_ORDER"); uint256 bought = _module.execute( _inputToken, amount, _owner, _data, _auxData ); emit OrderExecuted( key, address(_inputToken), _owner, witness, _data, _auxData, amount, bought ); } /** * @notice Check whether an order exists or not * @dev Check the balance of the order * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @return bool - whether the order exists or not */ function existOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data ) external view returns (bool) { bytes32 key = keyOf( _module, _inputToken, _owner, _witness, _data ); if (address(_inputToken) == ETH_ADDRESS) { return ethDeposits[key] != 0; } else { return _inputToken.balanceOf(key.getVault()) != 0; } } /** * @notice Check whether an order can be executed or not * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @param _auxData - Bytes of the auxiliar data used for the handlers to execute the order * @return bool - whether the order can be executed or not */ function canExecuteOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data, bytes calldata _auxData ) external view returns (bool) { bytes32 key = keyOf( _module, _inputToken, _owner, _witness, _data ); // Pull amount uint256 amount; if (address(_inputToken) == ETH_ADDRESS) { amount = ethDeposits[key]; } else { amount = _inputToken.balanceOf(key.getVault()); } return _module.canExecute( _inputToken, amount, _data, _auxData ); } /** * @notice Transfer the order amount to a recipient. * @dev For an ETH order, the ETH will be transferred from this contract * For a token order, its vault will be executed transferring the amount of tokens to * the recipient * @param _inputToken - Address of the input token * @param _key - Order's key * @param _to - Address of the recipient * @return amount - amount transferred */ function _pullOrder( IERC20 _inputToken, bytes32 _key, address payable _to ) private returns (uint256 amount) { if (address(_inputToken) == ETH_ADDRESS) { amount = ethDeposits[_key]; ethDeposits[_key] = 0; (bool success,) = _to.call{value: amount}(""); require(success, "HyperLimit#_pullOrder: PULL_ETHER_FAILED"); } else { amount = _key.executeVault(_inputToken, _to); } } /** * @notice Get the order's key * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @return bytes32 - order's key */ function keyOf( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes memory _data ) public pure returns (bytes32) { return keccak256( abi.encode( _module, _inputToken, _owner, _witness, _data ) ); } }
/// @notice Core contract used to create, cancel and execute orders.
NatSpecSingleLine
cancelOrder
function cancelOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data ) external { require(msg.sender == _owner, "HyperLimit#cancelOrder: INVALID_OWNER"); bytes32 key = keyOf( _module, _inputToken, _owner, _witness, _data ); uint256 amount = _pullOrder(_inputToken, key, msg.sender); emit OrderCancelled( key, address(_inputToken), _owner, _witness, _data, amount ); }
/** * @notice Cancel order * @dev The params should be the same used for the order creation * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data */
NatSpecMultiLine
v0.6.8+commit.0bbfe453
MIT
ipfs://87b25594a09c529edcbca78f8b34edb2270eef34e0e1c6085d9645d3ea74cd05
{ "func_code_index": [ 2340, 3021 ] }
11,890
HyperLimit
HyperLimit.sol
0x16a893f27fdb30cc05d8fd7a333a5ab841461658
Solidity
HyperLimit
contract HyperLimit is Order { using SafeMath for uint256; using Fabric for bytes32; // ETH orders mapping(bytes32 => uint256) public ethDeposits; // Events event DepositETH( bytes32 indexed _key, address indexed _caller, uint256 _amount, bytes _data ); event OrderExecuted( bytes32 indexed _key, address _inputToken, address _owner, address _witness, bytes _data, bytes _auxData, uint256 _amount, uint256 _bought ); event OrderCancelled( bytes32 indexed _key, address _inputToken, address _owner, address _witness, bytes _data, uint256 _amount ); /** * @dev Prevent users to send Ether directly to this contract */ receive() external payable { require( msg.sender != tx.origin, "HyperLimit#receive: NO_SEND_ETH_PLEASE" ); } /** * @notice Create an ETH to token order * @param _data - Bytes of an ETH to token order. See `encodeEthOrder` for more info */ function depositEth( bytes calldata _data ) external payable { require(msg.value > 0, "HyperLimit#depositEth: VALUE_IS_0"); ( address module, address inputToken, address payable owner, address witness, bytes memory data, ) = decodeOrder(_data); require(inputToken == ETH_ADDRESS, "HyperLimit#depositEth: WRONG_INPUT_TOKEN"); bytes32 key = keyOf( IModule(uint160(module)), IERC20(inputToken), owner, witness, data ); ethDeposits[key] = ethDeposits[key].add(msg.value); emit DepositETH(key, msg.sender, msg.value, _data); } /** * @notice Cancel order * @dev The params should be the same used for the order creation * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data */ function cancelOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data ) external { require(msg.sender == _owner, "HyperLimit#cancelOrder: INVALID_OWNER"); bytes32 key = keyOf( _module, _inputToken, _owner, _witness, _data ); uint256 amount = _pullOrder(_inputToken, key, msg.sender); emit OrderCancelled( key, address(_inputToken), _owner, _witness, _data, amount ); } /** * @notice Get the calldata needed to create a token to token/ETH order * @dev Returns the input data that the user needs to use to create the order * The _secret is used to prevent a front-running at the order execution * The _amount is used as the param `_value` for the ERC20 `transfer` function * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @param _secret - Private key of the _witness * @param _amount - uint256 of the order amount * @return bytes - input data to send the transaction */ function encodeTokenOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data, bytes32 _secret, uint256 _amount ) external view returns (bytes memory) { return abi.encodeWithSelector( _inputToken.transfer.selector, vaultOfOrder( _module, _inputToken, _owner, _witness, _data ), _amount, abi.encode( _module, _inputToken, _owner, _witness, _data, _secret ) ); } /** * @notice Get the calldata needed to create a ETH to token order * @dev Returns the input data that the user needs to use to create the order * The _secret is used to prevent a front-running at the order execution * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @param _secret - Private key of the _witness * @return bytes - input data to send the transaction */ function encodeEthOrder( address _module, address _inputToken, address payable _owner, address _witness, bytes calldata _data, bytes32 _secret ) external pure returns (bytes memory) { return abi.encode( _module, _inputToken, _owner, _witness, _data, _secret ); } /** * @notice Get order's properties * @param _data - Bytes of the order * @return module - Address of the module to use for the order execution * @return inputToken - Address of the input token * @return owner - Address of the order's owner * @return witness - Address of the witness * @return data - Bytes of the order's data * @return secret - Private key of the _witness */ function decodeOrder( bytes memory _data ) public pure returns ( address module, address inputToken, address payable owner, address witness, bytes memory data, bytes32 secret ) { ( module, inputToken, owner, witness, data, secret ) = abi.decode( _data, ( address, address, address, address, bytes, bytes32 ) ); } /** * @notice Get the vault's address of a token to token/ETH order * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @return address - The address of the vault */ function vaultOfOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes memory _data ) public view returns (address) { return keyOf( _module, _inputToken, _owner, _witness, _data ).getVault(); } /** * @notice Executes an order * @dev The sender should use the _secret to sign its own address * to prevent front-runnings * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _data - Bytes of the order's data * @param _signature - Signature to calculate the witness * @param _auxData - Bytes of the auxiliar data used for the handlers to execute the order */ function executeOrder( IModule _module, IERC20 _inputToken, address payable _owner, bytes calldata _data, bytes calldata _signature, bytes calldata _auxData ) external { // Calculate witness using signature address witness = ECDSA.recover( keccak256(abi.encodePacked(msg.sender)), _signature ); bytes32 key = keyOf( _module, _inputToken, _owner, witness, _data ); // Pull amount uint256 amount = _pullOrder(_inputToken, key, address(_module)); require(amount > 0, "HyperLimit#executeOrder: INVALID_ORDER"); uint256 bought = _module.execute( _inputToken, amount, _owner, _data, _auxData ); emit OrderExecuted( key, address(_inputToken), _owner, witness, _data, _auxData, amount, bought ); } /** * @notice Check whether an order exists or not * @dev Check the balance of the order * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @return bool - whether the order exists or not */ function existOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data ) external view returns (bool) { bytes32 key = keyOf( _module, _inputToken, _owner, _witness, _data ); if (address(_inputToken) == ETH_ADDRESS) { return ethDeposits[key] != 0; } else { return _inputToken.balanceOf(key.getVault()) != 0; } } /** * @notice Check whether an order can be executed or not * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @param _auxData - Bytes of the auxiliar data used for the handlers to execute the order * @return bool - whether the order can be executed or not */ function canExecuteOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data, bytes calldata _auxData ) external view returns (bool) { bytes32 key = keyOf( _module, _inputToken, _owner, _witness, _data ); // Pull amount uint256 amount; if (address(_inputToken) == ETH_ADDRESS) { amount = ethDeposits[key]; } else { amount = _inputToken.balanceOf(key.getVault()); } return _module.canExecute( _inputToken, amount, _data, _auxData ); } /** * @notice Transfer the order amount to a recipient. * @dev For an ETH order, the ETH will be transferred from this contract * For a token order, its vault will be executed transferring the amount of tokens to * the recipient * @param _inputToken - Address of the input token * @param _key - Order's key * @param _to - Address of the recipient * @return amount - amount transferred */ function _pullOrder( IERC20 _inputToken, bytes32 _key, address payable _to ) private returns (uint256 amount) { if (address(_inputToken) == ETH_ADDRESS) { amount = ethDeposits[_key]; ethDeposits[_key] = 0; (bool success,) = _to.call{value: amount}(""); require(success, "HyperLimit#_pullOrder: PULL_ETHER_FAILED"); } else { amount = _key.executeVault(_inputToken, _to); } } /** * @notice Get the order's key * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @return bytes32 - order's key */ function keyOf( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes memory _data ) public pure returns (bytes32) { return keccak256( abi.encode( _module, _inputToken, _owner, _witness, _data ) ); } }
/// @notice Core contract used to create, cancel and execute orders.
NatSpecSingleLine
encodeTokenOrder
function encodeTokenOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data, bytes32 _secret, uint256 _amount ) external view returns (bytes memory) { return abi.encodeWithSelector( _inputToken.transfer.selector, vaultOfOrder( _module, _inputToken, _owner, _witness, _data ), _amount, abi.encode( _module, _inputToken, _owner, _witness, _data, _secret ) ); }
/** * @notice Get the calldata needed to create a token to token/ETH order * @dev Returns the input data that the user needs to use to create the order * The _secret is used to prevent a front-running at the order execution * The _amount is used as the param `_value` for the ERC20 `transfer` function * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @param _secret - Private key of the _witness * @param _amount - uint256 of the order amount * @return bytes - input data to send the transaction */
NatSpecMultiLine
v0.6.8+commit.0bbfe453
MIT
ipfs://87b25594a09c529edcbca78f8b34edb2270eef34e0e1c6085d9645d3ea74cd05
{ "func_code_index": [ 3814, 4584 ] }
11,891
HyperLimit
HyperLimit.sol
0x16a893f27fdb30cc05d8fd7a333a5ab841461658
Solidity
HyperLimit
contract HyperLimit is Order { using SafeMath for uint256; using Fabric for bytes32; // ETH orders mapping(bytes32 => uint256) public ethDeposits; // Events event DepositETH( bytes32 indexed _key, address indexed _caller, uint256 _amount, bytes _data ); event OrderExecuted( bytes32 indexed _key, address _inputToken, address _owner, address _witness, bytes _data, bytes _auxData, uint256 _amount, uint256 _bought ); event OrderCancelled( bytes32 indexed _key, address _inputToken, address _owner, address _witness, bytes _data, uint256 _amount ); /** * @dev Prevent users to send Ether directly to this contract */ receive() external payable { require( msg.sender != tx.origin, "HyperLimit#receive: NO_SEND_ETH_PLEASE" ); } /** * @notice Create an ETH to token order * @param _data - Bytes of an ETH to token order. See `encodeEthOrder` for more info */ function depositEth( bytes calldata _data ) external payable { require(msg.value > 0, "HyperLimit#depositEth: VALUE_IS_0"); ( address module, address inputToken, address payable owner, address witness, bytes memory data, ) = decodeOrder(_data); require(inputToken == ETH_ADDRESS, "HyperLimit#depositEth: WRONG_INPUT_TOKEN"); bytes32 key = keyOf( IModule(uint160(module)), IERC20(inputToken), owner, witness, data ); ethDeposits[key] = ethDeposits[key].add(msg.value); emit DepositETH(key, msg.sender, msg.value, _data); } /** * @notice Cancel order * @dev The params should be the same used for the order creation * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data */ function cancelOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data ) external { require(msg.sender == _owner, "HyperLimit#cancelOrder: INVALID_OWNER"); bytes32 key = keyOf( _module, _inputToken, _owner, _witness, _data ); uint256 amount = _pullOrder(_inputToken, key, msg.sender); emit OrderCancelled( key, address(_inputToken), _owner, _witness, _data, amount ); } /** * @notice Get the calldata needed to create a token to token/ETH order * @dev Returns the input data that the user needs to use to create the order * The _secret is used to prevent a front-running at the order execution * The _amount is used as the param `_value` for the ERC20 `transfer` function * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @param _secret - Private key of the _witness * @param _amount - uint256 of the order amount * @return bytes - input data to send the transaction */ function encodeTokenOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data, bytes32 _secret, uint256 _amount ) external view returns (bytes memory) { return abi.encodeWithSelector( _inputToken.transfer.selector, vaultOfOrder( _module, _inputToken, _owner, _witness, _data ), _amount, abi.encode( _module, _inputToken, _owner, _witness, _data, _secret ) ); } /** * @notice Get the calldata needed to create a ETH to token order * @dev Returns the input data that the user needs to use to create the order * The _secret is used to prevent a front-running at the order execution * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @param _secret - Private key of the _witness * @return bytes - input data to send the transaction */ function encodeEthOrder( address _module, address _inputToken, address payable _owner, address _witness, bytes calldata _data, bytes32 _secret ) external pure returns (bytes memory) { return abi.encode( _module, _inputToken, _owner, _witness, _data, _secret ); } /** * @notice Get order's properties * @param _data - Bytes of the order * @return module - Address of the module to use for the order execution * @return inputToken - Address of the input token * @return owner - Address of the order's owner * @return witness - Address of the witness * @return data - Bytes of the order's data * @return secret - Private key of the _witness */ function decodeOrder( bytes memory _data ) public pure returns ( address module, address inputToken, address payable owner, address witness, bytes memory data, bytes32 secret ) { ( module, inputToken, owner, witness, data, secret ) = abi.decode( _data, ( address, address, address, address, bytes, bytes32 ) ); } /** * @notice Get the vault's address of a token to token/ETH order * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @return address - The address of the vault */ function vaultOfOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes memory _data ) public view returns (address) { return keyOf( _module, _inputToken, _owner, _witness, _data ).getVault(); } /** * @notice Executes an order * @dev The sender should use the _secret to sign its own address * to prevent front-runnings * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _data - Bytes of the order's data * @param _signature - Signature to calculate the witness * @param _auxData - Bytes of the auxiliar data used for the handlers to execute the order */ function executeOrder( IModule _module, IERC20 _inputToken, address payable _owner, bytes calldata _data, bytes calldata _signature, bytes calldata _auxData ) external { // Calculate witness using signature address witness = ECDSA.recover( keccak256(abi.encodePacked(msg.sender)), _signature ); bytes32 key = keyOf( _module, _inputToken, _owner, witness, _data ); // Pull amount uint256 amount = _pullOrder(_inputToken, key, address(_module)); require(amount > 0, "HyperLimit#executeOrder: INVALID_ORDER"); uint256 bought = _module.execute( _inputToken, amount, _owner, _data, _auxData ); emit OrderExecuted( key, address(_inputToken), _owner, witness, _data, _auxData, amount, bought ); } /** * @notice Check whether an order exists or not * @dev Check the balance of the order * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @return bool - whether the order exists or not */ function existOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data ) external view returns (bool) { bytes32 key = keyOf( _module, _inputToken, _owner, _witness, _data ); if (address(_inputToken) == ETH_ADDRESS) { return ethDeposits[key] != 0; } else { return _inputToken.balanceOf(key.getVault()) != 0; } } /** * @notice Check whether an order can be executed or not * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @param _auxData - Bytes of the auxiliar data used for the handlers to execute the order * @return bool - whether the order can be executed or not */ function canExecuteOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data, bytes calldata _auxData ) external view returns (bool) { bytes32 key = keyOf( _module, _inputToken, _owner, _witness, _data ); // Pull amount uint256 amount; if (address(_inputToken) == ETH_ADDRESS) { amount = ethDeposits[key]; } else { amount = _inputToken.balanceOf(key.getVault()); } return _module.canExecute( _inputToken, amount, _data, _auxData ); } /** * @notice Transfer the order amount to a recipient. * @dev For an ETH order, the ETH will be transferred from this contract * For a token order, its vault will be executed transferring the amount of tokens to * the recipient * @param _inputToken - Address of the input token * @param _key - Order's key * @param _to - Address of the recipient * @return amount - amount transferred */ function _pullOrder( IERC20 _inputToken, bytes32 _key, address payable _to ) private returns (uint256 amount) { if (address(_inputToken) == ETH_ADDRESS) { amount = ethDeposits[_key]; ethDeposits[_key] = 0; (bool success,) = _to.call{value: amount}(""); require(success, "HyperLimit#_pullOrder: PULL_ETHER_FAILED"); } else { amount = _key.executeVault(_inputToken, _to); } } /** * @notice Get the order's key * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @return bytes32 - order's key */ function keyOf( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes memory _data ) public pure returns (bytes32) { return keccak256( abi.encode( _module, _inputToken, _owner, _witness, _data ) ); } }
/// @notice Core contract used to create, cancel and execute orders.
NatSpecSingleLine
encodeEthOrder
function encodeEthOrder( address _module, address _inputToken, address payable _owner, address _witness, bytes calldata _data, bytes32 _secret ) external pure returns (bytes memory) { return abi.encode( _module, _inputToken, _owner, _witness, _data, _secret ); }
/** * @notice Get the calldata needed to create a ETH to token order * @dev Returns the input data that the user needs to use to create the order * The _secret is used to prevent a front-running at the order execution * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @param _secret - Private key of the _witness * @return bytes - input data to send the transaction */
NatSpecMultiLine
v0.6.8+commit.0bbfe453
MIT
ipfs://87b25594a09c529edcbca78f8b34edb2270eef34e0e1c6085d9645d3ea74cd05
{ "func_code_index": [ 5235, 5662 ] }
11,892
HyperLimit
HyperLimit.sol
0x16a893f27fdb30cc05d8fd7a333a5ab841461658
Solidity
HyperLimit
contract HyperLimit is Order { using SafeMath for uint256; using Fabric for bytes32; // ETH orders mapping(bytes32 => uint256) public ethDeposits; // Events event DepositETH( bytes32 indexed _key, address indexed _caller, uint256 _amount, bytes _data ); event OrderExecuted( bytes32 indexed _key, address _inputToken, address _owner, address _witness, bytes _data, bytes _auxData, uint256 _amount, uint256 _bought ); event OrderCancelled( bytes32 indexed _key, address _inputToken, address _owner, address _witness, bytes _data, uint256 _amount ); /** * @dev Prevent users to send Ether directly to this contract */ receive() external payable { require( msg.sender != tx.origin, "HyperLimit#receive: NO_SEND_ETH_PLEASE" ); } /** * @notice Create an ETH to token order * @param _data - Bytes of an ETH to token order. See `encodeEthOrder` for more info */ function depositEth( bytes calldata _data ) external payable { require(msg.value > 0, "HyperLimit#depositEth: VALUE_IS_0"); ( address module, address inputToken, address payable owner, address witness, bytes memory data, ) = decodeOrder(_data); require(inputToken == ETH_ADDRESS, "HyperLimit#depositEth: WRONG_INPUT_TOKEN"); bytes32 key = keyOf( IModule(uint160(module)), IERC20(inputToken), owner, witness, data ); ethDeposits[key] = ethDeposits[key].add(msg.value); emit DepositETH(key, msg.sender, msg.value, _data); } /** * @notice Cancel order * @dev The params should be the same used for the order creation * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data */ function cancelOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data ) external { require(msg.sender == _owner, "HyperLimit#cancelOrder: INVALID_OWNER"); bytes32 key = keyOf( _module, _inputToken, _owner, _witness, _data ); uint256 amount = _pullOrder(_inputToken, key, msg.sender); emit OrderCancelled( key, address(_inputToken), _owner, _witness, _data, amount ); } /** * @notice Get the calldata needed to create a token to token/ETH order * @dev Returns the input data that the user needs to use to create the order * The _secret is used to prevent a front-running at the order execution * The _amount is used as the param `_value` for the ERC20 `transfer` function * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @param _secret - Private key of the _witness * @param _amount - uint256 of the order amount * @return bytes - input data to send the transaction */ function encodeTokenOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data, bytes32 _secret, uint256 _amount ) external view returns (bytes memory) { return abi.encodeWithSelector( _inputToken.transfer.selector, vaultOfOrder( _module, _inputToken, _owner, _witness, _data ), _amount, abi.encode( _module, _inputToken, _owner, _witness, _data, _secret ) ); } /** * @notice Get the calldata needed to create a ETH to token order * @dev Returns the input data that the user needs to use to create the order * The _secret is used to prevent a front-running at the order execution * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @param _secret - Private key of the _witness * @return bytes - input data to send the transaction */ function encodeEthOrder( address _module, address _inputToken, address payable _owner, address _witness, bytes calldata _data, bytes32 _secret ) external pure returns (bytes memory) { return abi.encode( _module, _inputToken, _owner, _witness, _data, _secret ); } /** * @notice Get order's properties * @param _data - Bytes of the order * @return module - Address of the module to use for the order execution * @return inputToken - Address of the input token * @return owner - Address of the order's owner * @return witness - Address of the witness * @return data - Bytes of the order's data * @return secret - Private key of the _witness */ function decodeOrder( bytes memory _data ) public pure returns ( address module, address inputToken, address payable owner, address witness, bytes memory data, bytes32 secret ) { ( module, inputToken, owner, witness, data, secret ) = abi.decode( _data, ( address, address, address, address, bytes, bytes32 ) ); } /** * @notice Get the vault's address of a token to token/ETH order * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @return address - The address of the vault */ function vaultOfOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes memory _data ) public view returns (address) { return keyOf( _module, _inputToken, _owner, _witness, _data ).getVault(); } /** * @notice Executes an order * @dev The sender should use the _secret to sign its own address * to prevent front-runnings * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _data - Bytes of the order's data * @param _signature - Signature to calculate the witness * @param _auxData - Bytes of the auxiliar data used for the handlers to execute the order */ function executeOrder( IModule _module, IERC20 _inputToken, address payable _owner, bytes calldata _data, bytes calldata _signature, bytes calldata _auxData ) external { // Calculate witness using signature address witness = ECDSA.recover( keccak256(abi.encodePacked(msg.sender)), _signature ); bytes32 key = keyOf( _module, _inputToken, _owner, witness, _data ); // Pull amount uint256 amount = _pullOrder(_inputToken, key, address(_module)); require(amount > 0, "HyperLimit#executeOrder: INVALID_ORDER"); uint256 bought = _module.execute( _inputToken, amount, _owner, _data, _auxData ); emit OrderExecuted( key, address(_inputToken), _owner, witness, _data, _auxData, amount, bought ); } /** * @notice Check whether an order exists or not * @dev Check the balance of the order * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @return bool - whether the order exists or not */ function existOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data ) external view returns (bool) { bytes32 key = keyOf( _module, _inputToken, _owner, _witness, _data ); if (address(_inputToken) == ETH_ADDRESS) { return ethDeposits[key] != 0; } else { return _inputToken.balanceOf(key.getVault()) != 0; } } /** * @notice Check whether an order can be executed or not * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @param _auxData - Bytes of the auxiliar data used for the handlers to execute the order * @return bool - whether the order can be executed or not */ function canExecuteOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data, bytes calldata _auxData ) external view returns (bool) { bytes32 key = keyOf( _module, _inputToken, _owner, _witness, _data ); // Pull amount uint256 amount; if (address(_inputToken) == ETH_ADDRESS) { amount = ethDeposits[key]; } else { amount = _inputToken.balanceOf(key.getVault()); } return _module.canExecute( _inputToken, amount, _data, _auxData ); } /** * @notice Transfer the order amount to a recipient. * @dev For an ETH order, the ETH will be transferred from this contract * For a token order, its vault will be executed transferring the amount of tokens to * the recipient * @param _inputToken - Address of the input token * @param _key - Order's key * @param _to - Address of the recipient * @return amount - amount transferred */ function _pullOrder( IERC20 _inputToken, bytes32 _key, address payable _to ) private returns (uint256 amount) { if (address(_inputToken) == ETH_ADDRESS) { amount = ethDeposits[_key]; ethDeposits[_key] = 0; (bool success,) = _to.call{value: amount}(""); require(success, "HyperLimit#_pullOrder: PULL_ETHER_FAILED"); } else { amount = _key.executeVault(_inputToken, _to); } } /** * @notice Get the order's key * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @return bytes32 - order's key */ function keyOf( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes memory _data ) public pure returns (bytes32) { return keccak256( abi.encode( _module, _inputToken, _owner, _witness, _data ) ); } }
/// @notice Core contract used to create, cancel and execute orders.
NatSpecSingleLine
decodeOrder
function decodeOrder( bytes memory _data ) public pure returns ( address module, address inputToken, address payable owner, address witness, bytes memory data, bytes32 secret ) { ( module, inputToken, owner, witness, data, secret ) = abi.decode( _data, ( address, address, address, address, bytes, bytes32 ) ); }
/** * @notice Get order's properties * @param _data - Bytes of the order * @return module - Address of the module to use for the order execution * @return inputToken - Address of the input token * @return owner - Address of the order's owner * @return witness - Address of the witness * @return data - Bytes of the order's data * @return secret - Private key of the _witness */
NatSpecMultiLine
v0.6.8+commit.0bbfe453
MIT
ipfs://87b25594a09c529edcbca78f8b34edb2270eef34e0e1c6085d9645d3ea74cd05
{ "func_code_index": [ 6103, 6744 ] }
11,893
HyperLimit
HyperLimit.sol
0x16a893f27fdb30cc05d8fd7a333a5ab841461658
Solidity
HyperLimit
contract HyperLimit is Order { using SafeMath for uint256; using Fabric for bytes32; // ETH orders mapping(bytes32 => uint256) public ethDeposits; // Events event DepositETH( bytes32 indexed _key, address indexed _caller, uint256 _amount, bytes _data ); event OrderExecuted( bytes32 indexed _key, address _inputToken, address _owner, address _witness, bytes _data, bytes _auxData, uint256 _amount, uint256 _bought ); event OrderCancelled( bytes32 indexed _key, address _inputToken, address _owner, address _witness, bytes _data, uint256 _amount ); /** * @dev Prevent users to send Ether directly to this contract */ receive() external payable { require( msg.sender != tx.origin, "HyperLimit#receive: NO_SEND_ETH_PLEASE" ); } /** * @notice Create an ETH to token order * @param _data - Bytes of an ETH to token order. See `encodeEthOrder` for more info */ function depositEth( bytes calldata _data ) external payable { require(msg.value > 0, "HyperLimit#depositEth: VALUE_IS_0"); ( address module, address inputToken, address payable owner, address witness, bytes memory data, ) = decodeOrder(_data); require(inputToken == ETH_ADDRESS, "HyperLimit#depositEth: WRONG_INPUT_TOKEN"); bytes32 key = keyOf( IModule(uint160(module)), IERC20(inputToken), owner, witness, data ); ethDeposits[key] = ethDeposits[key].add(msg.value); emit DepositETH(key, msg.sender, msg.value, _data); } /** * @notice Cancel order * @dev The params should be the same used for the order creation * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data */ function cancelOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data ) external { require(msg.sender == _owner, "HyperLimit#cancelOrder: INVALID_OWNER"); bytes32 key = keyOf( _module, _inputToken, _owner, _witness, _data ); uint256 amount = _pullOrder(_inputToken, key, msg.sender); emit OrderCancelled( key, address(_inputToken), _owner, _witness, _data, amount ); } /** * @notice Get the calldata needed to create a token to token/ETH order * @dev Returns the input data that the user needs to use to create the order * The _secret is used to prevent a front-running at the order execution * The _amount is used as the param `_value` for the ERC20 `transfer` function * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @param _secret - Private key of the _witness * @param _amount - uint256 of the order amount * @return bytes - input data to send the transaction */ function encodeTokenOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data, bytes32 _secret, uint256 _amount ) external view returns (bytes memory) { return abi.encodeWithSelector( _inputToken.transfer.selector, vaultOfOrder( _module, _inputToken, _owner, _witness, _data ), _amount, abi.encode( _module, _inputToken, _owner, _witness, _data, _secret ) ); } /** * @notice Get the calldata needed to create a ETH to token order * @dev Returns the input data that the user needs to use to create the order * The _secret is used to prevent a front-running at the order execution * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @param _secret - Private key of the _witness * @return bytes - input data to send the transaction */ function encodeEthOrder( address _module, address _inputToken, address payable _owner, address _witness, bytes calldata _data, bytes32 _secret ) external pure returns (bytes memory) { return abi.encode( _module, _inputToken, _owner, _witness, _data, _secret ); } /** * @notice Get order's properties * @param _data - Bytes of the order * @return module - Address of the module to use for the order execution * @return inputToken - Address of the input token * @return owner - Address of the order's owner * @return witness - Address of the witness * @return data - Bytes of the order's data * @return secret - Private key of the _witness */ function decodeOrder( bytes memory _data ) public pure returns ( address module, address inputToken, address payable owner, address witness, bytes memory data, bytes32 secret ) { ( module, inputToken, owner, witness, data, secret ) = abi.decode( _data, ( address, address, address, address, bytes, bytes32 ) ); } /** * @notice Get the vault's address of a token to token/ETH order * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @return address - The address of the vault */ function vaultOfOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes memory _data ) public view returns (address) { return keyOf( _module, _inputToken, _owner, _witness, _data ).getVault(); } /** * @notice Executes an order * @dev The sender should use the _secret to sign its own address * to prevent front-runnings * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _data - Bytes of the order's data * @param _signature - Signature to calculate the witness * @param _auxData - Bytes of the auxiliar data used for the handlers to execute the order */ function executeOrder( IModule _module, IERC20 _inputToken, address payable _owner, bytes calldata _data, bytes calldata _signature, bytes calldata _auxData ) external { // Calculate witness using signature address witness = ECDSA.recover( keccak256(abi.encodePacked(msg.sender)), _signature ); bytes32 key = keyOf( _module, _inputToken, _owner, witness, _data ); // Pull amount uint256 amount = _pullOrder(_inputToken, key, address(_module)); require(amount > 0, "HyperLimit#executeOrder: INVALID_ORDER"); uint256 bought = _module.execute( _inputToken, amount, _owner, _data, _auxData ); emit OrderExecuted( key, address(_inputToken), _owner, witness, _data, _auxData, amount, bought ); } /** * @notice Check whether an order exists or not * @dev Check the balance of the order * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @return bool - whether the order exists or not */ function existOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data ) external view returns (bool) { bytes32 key = keyOf( _module, _inputToken, _owner, _witness, _data ); if (address(_inputToken) == ETH_ADDRESS) { return ethDeposits[key] != 0; } else { return _inputToken.balanceOf(key.getVault()) != 0; } } /** * @notice Check whether an order can be executed or not * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @param _auxData - Bytes of the auxiliar data used for the handlers to execute the order * @return bool - whether the order can be executed or not */ function canExecuteOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data, bytes calldata _auxData ) external view returns (bool) { bytes32 key = keyOf( _module, _inputToken, _owner, _witness, _data ); // Pull amount uint256 amount; if (address(_inputToken) == ETH_ADDRESS) { amount = ethDeposits[key]; } else { amount = _inputToken.balanceOf(key.getVault()); } return _module.canExecute( _inputToken, amount, _data, _auxData ); } /** * @notice Transfer the order amount to a recipient. * @dev For an ETH order, the ETH will be transferred from this contract * For a token order, its vault will be executed transferring the amount of tokens to * the recipient * @param _inputToken - Address of the input token * @param _key - Order's key * @param _to - Address of the recipient * @return amount - amount transferred */ function _pullOrder( IERC20 _inputToken, bytes32 _key, address payable _to ) private returns (uint256 amount) { if (address(_inputToken) == ETH_ADDRESS) { amount = ethDeposits[_key]; ethDeposits[_key] = 0; (bool success,) = _to.call{value: amount}(""); require(success, "HyperLimit#_pullOrder: PULL_ETHER_FAILED"); } else { amount = _key.executeVault(_inputToken, _to); } } /** * @notice Get the order's key * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @return bytes32 - order's key */ function keyOf( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes memory _data ) public pure returns (bytes32) { return keccak256( abi.encode( _module, _inputToken, _owner, _witness, _data ) ); } }
/// @notice Core contract used to create, cancel and execute orders.
NatSpecSingleLine
vaultOfOrder
function vaultOfOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes memory _data ) public view returns (address) { return keyOf( _module, _inputToken, _owner, _witness, _data ).getVault(); }
/** * @notice Get the vault's address of a token to token/ETH order * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @return address - The address of the vault */
NatSpecMultiLine
v0.6.8+commit.0bbfe453
MIT
ipfs://87b25594a09c529edcbca78f8b34edb2270eef34e0e1c6085d9645d3ea74cd05
{ "func_code_index": [ 7171, 7544 ] }
11,894
HyperLimit
HyperLimit.sol
0x16a893f27fdb30cc05d8fd7a333a5ab841461658
Solidity
HyperLimit
contract HyperLimit is Order { using SafeMath for uint256; using Fabric for bytes32; // ETH orders mapping(bytes32 => uint256) public ethDeposits; // Events event DepositETH( bytes32 indexed _key, address indexed _caller, uint256 _amount, bytes _data ); event OrderExecuted( bytes32 indexed _key, address _inputToken, address _owner, address _witness, bytes _data, bytes _auxData, uint256 _amount, uint256 _bought ); event OrderCancelled( bytes32 indexed _key, address _inputToken, address _owner, address _witness, bytes _data, uint256 _amount ); /** * @dev Prevent users to send Ether directly to this contract */ receive() external payable { require( msg.sender != tx.origin, "HyperLimit#receive: NO_SEND_ETH_PLEASE" ); } /** * @notice Create an ETH to token order * @param _data - Bytes of an ETH to token order. See `encodeEthOrder` for more info */ function depositEth( bytes calldata _data ) external payable { require(msg.value > 0, "HyperLimit#depositEth: VALUE_IS_0"); ( address module, address inputToken, address payable owner, address witness, bytes memory data, ) = decodeOrder(_data); require(inputToken == ETH_ADDRESS, "HyperLimit#depositEth: WRONG_INPUT_TOKEN"); bytes32 key = keyOf( IModule(uint160(module)), IERC20(inputToken), owner, witness, data ); ethDeposits[key] = ethDeposits[key].add(msg.value); emit DepositETH(key, msg.sender, msg.value, _data); } /** * @notice Cancel order * @dev The params should be the same used for the order creation * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data */ function cancelOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data ) external { require(msg.sender == _owner, "HyperLimit#cancelOrder: INVALID_OWNER"); bytes32 key = keyOf( _module, _inputToken, _owner, _witness, _data ); uint256 amount = _pullOrder(_inputToken, key, msg.sender); emit OrderCancelled( key, address(_inputToken), _owner, _witness, _data, amount ); } /** * @notice Get the calldata needed to create a token to token/ETH order * @dev Returns the input data that the user needs to use to create the order * The _secret is used to prevent a front-running at the order execution * The _amount is used as the param `_value` for the ERC20 `transfer` function * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @param _secret - Private key of the _witness * @param _amount - uint256 of the order amount * @return bytes - input data to send the transaction */ function encodeTokenOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data, bytes32 _secret, uint256 _amount ) external view returns (bytes memory) { return abi.encodeWithSelector( _inputToken.transfer.selector, vaultOfOrder( _module, _inputToken, _owner, _witness, _data ), _amount, abi.encode( _module, _inputToken, _owner, _witness, _data, _secret ) ); } /** * @notice Get the calldata needed to create a ETH to token order * @dev Returns the input data that the user needs to use to create the order * The _secret is used to prevent a front-running at the order execution * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @param _secret - Private key of the _witness * @return bytes - input data to send the transaction */ function encodeEthOrder( address _module, address _inputToken, address payable _owner, address _witness, bytes calldata _data, bytes32 _secret ) external pure returns (bytes memory) { return abi.encode( _module, _inputToken, _owner, _witness, _data, _secret ); } /** * @notice Get order's properties * @param _data - Bytes of the order * @return module - Address of the module to use for the order execution * @return inputToken - Address of the input token * @return owner - Address of the order's owner * @return witness - Address of the witness * @return data - Bytes of the order's data * @return secret - Private key of the _witness */ function decodeOrder( bytes memory _data ) public pure returns ( address module, address inputToken, address payable owner, address witness, bytes memory data, bytes32 secret ) { ( module, inputToken, owner, witness, data, secret ) = abi.decode( _data, ( address, address, address, address, bytes, bytes32 ) ); } /** * @notice Get the vault's address of a token to token/ETH order * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @return address - The address of the vault */ function vaultOfOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes memory _data ) public view returns (address) { return keyOf( _module, _inputToken, _owner, _witness, _data ).getVault(); } /** * @notice Executes an order * @dev The sender should use the _secret to sign its own address * to prevent front-runnings * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _data - Bytes of the order's data * @param _signature - Signature to calculate the witness * @param _auxData - Bytes of the auxiliar data used for the handlers to execute the order */ function executeOrder( IModule _module, IERC20 _inputToken, address payable _owner, bytes calldata _data, bytes calldata _signature, bytes calldata _auxData ) external { // Calculate witness using signature address witness = ECDSA.recover( keccak256(abi.encodePacked(msg.sender)), _signature ); bytes32 key = keyOf( _module, _inputToken, _owner, witness, _data ); // Pull amount uint256 amount = _pullOrder(_inputToken, key, address(_module)); require(amount > 0, "HyperLimit#executeOrder: INVALID_ORDER"); uint256 bought = _module.execute( _inputToken, amount, _owner, _data, _auxData ); emit OrderExecuted( key, address(_inputToken), _owner, witness, _data, _auxData, amount, bought ); } /** * @notice Check whether an order exists or not * @dev Check the balance of the order * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @return bool - whether the order exists or not */ function existOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data ) external view returns (bool) { bytes32 key = keyOf( _module, _inputToken, _owner, _witness, _data ); if (address(_inputToken) == ETH_ADDRESS) { return ethDeposits[key] != 0; } else { return _inputToken.balanceOf(key.getVault()) != 0; } } /** * @notice Check whether an order can be executed or not * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @param _auxData - Bytes of the auxiliar data used for the handlers to execute the order * @return bool - whether the order can be executed or not */ function canExecuteOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data, bytes calldata _auxData ) external view returns (bool) { bytes32 key = keyOf( _module, _inputToken, _owner, _witness, _data ); // Pull amount uint256 amount; if (address(_inputToken) == ETH_ADDRESS) { amount = ethDeposits[key]; } else { amount = _inputToken.balanceOf(key.getVault()); } return _module.canExecute( _inputToken, amount, _data, _auxData ); } /** * @notice Transfer the order amount to a recipient. * @dev For an ETH order, the ETH will be transferred from this contract * For a token order, its vault will be executed transferring the amount of tokens to * the recipient * @param _inputToken - Address of the input token * @param _key - Order's key * @param _to - Address of the recipient * @return amount - amount transferred */ function _pullOrder( IERC20 _inputToken, bytes32 _key, address payable _to ) private returns (uint256 amount) { if (address(_inputToken) == ETH_ADDRESS) { amount = ethDeposits[_key]; ethDeposits[_key] = 0; (bool success,) = _to.call{value: amount}(""); require(success, "HyperLimit#_pullOrder: PULL_ETHER_FAILED"); } else { amount = _key.executeVault(_inputToken, _to); } } /** * @notice Get the order's key * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @return bytes32 - order's key */ function keyOf( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes memory _data ) public pure returns (bytes32) { return keccak256( abi.encode( _module, _inputToken, _owner, _witness, _data ) ); } }
/// @notice Core contract used to create, cancel and execute orders.
NatSpecSingleLine
executeOrder
function executeOrder( IModule _module, IERC20 _inputToken, address payable _owner, bytes calldata _data, bytes calldata _signature, bytes calldata _auxData ) external { // Calculate witness using signature address witness = ECDSA.recover( keccak256(abi.encodePacked(msg.sender)), _signature ); bytes32 key = keyOf( _module, _inputToken, _owner, witness, _data ); // Pull amount uint256 amount = _pullOrder(_inputToken, key, address(_module)); require(amount > 0, "HyperLimit#executeOrder: INVALID_ORDER"); uint256 bought = _module.execute( _inputToken, amount, _owner, _data, _auxData ); emit OrderExecuted( key, address(_inputToken), _owner, witness, _data, _auxData, amount, bought ); }
/** * @notice Executes an order * @dev The sender should use the _secret to sign its own address * to prevent front-runnings * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _data - Bytes of the order's data * @param _signature - Signature to calculate the witness * @param _auxData - Bytes of the auxiliar data used for the handlers to execute the order */
NatSpecMultiLine
v0.6.8+commit.0bbfe453
MIT
ipfs://87b25594a09c529edcbca78f8b34edb2270eef34e0e1c6085d9645d3ea74cd05
{ "func_code_index": [ 8100, 9234 ] }
11,895
HyperLimit
HyperLimit.sol
0x16a893f27fdb30cc05d8fd7a333a5ab841461658
Solidity
HyperLimit
contract HyperLimit is Order { using SafeMath for uint256; using Fabric for bytes32; // ETH orders mapping(bytes32 => uint256) public ethDeposits; // Events event DepositETH( bytes32 indexed _key, address indexed _caller, uint256 _amount, bytes _data ); event OrderExecuted( bytes32 indexed _key, address _inputToken, address _owner, address _witness, bytes _data, bytes _auxData, uint256 _amount, uint256 _bought ); event OrderCancelled( bytes32 indexed _key, address _inputToken, address _owner, address _witness, bytes _data, uint256 _amount ); /** * @dev Prevent users to send Ether directly to this contract */ receive() external payable { require( msg.sender != tx.origin, "HyperLimit#receive: NO_SEND_ETH_PLEASE" ); } /** * @notice Create an ETH to token order * @param _data - Bytes of an ETH to token order. See `encodeEthOrder` for more info */ function depositEth( bytes calldata _data ) external payable { require(msg.value > 0, "HyperLimit#depositEth: VALUE_IS_0"); ( address module, address inputToken, address payable owner, address witness, bytes memory data, ) = decodeOrder(_data); require(inputToken == ETH_ADDRESS, "HyperLimit#depositEth: WRONG_INPUT_TOKEN"); bytes32 key = keyOf( IModule(uint160(module)), IERC20(inputToken), owner, witness, data ); ethDeposits[key] = ethDeposits[key].add(msg.value); emit DepositETH(key, msg.sender, msg.value, _data); } /** * @notice Cancel order * @dev The params should be the same used for the order creation * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data */ function cancelOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data ) external { require(msg.sender == _owner, "HyperLimit#cancelOrder: INVALID_OWNER"); bytes32 key = keyOf( _module, _inputToken, _owner, _witness, _data ); uint256 amount = _pullOrder(_inputToken, key, msg.sender); emit OrderCancelled( key, address(_inputToken), _owner, _witness, _data, amount ); } /** * @notice Get the calldata needed to create a token to token/ETH order * @dev Returns the input data that the user needs to use to create the order * The _secret is used to prevent a front-running at the order execution * The _amount is used as the param `_value` for the ERC20 `transfer` function * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @param _secret - Private key of the _witness * @param _amount - uint256 of the order amount * @return bytes - input data to send the transaction */ function encodeTokenOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data, bytes32 _secret, uint256 _amount ) external view returns (bytes memory) { return abi.encodeWithSelector( _inputToken.transfer.selector, vaultOfOrder( _module, _inputToken, _owner, _witness, _data ), _amount, abi.encode( _module, _inputToken, _owner, _witness, _data, _secret ) ); } /** * @notice Get the calldata needed to create a ETH to token order * @dev Returns the input data that the user needs to use to create the order * The _secret is used to prevent a front-running at the order execution * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @param _secret - Private key of the _witness * @return bytes - input data to send the transaction */ function encodeEthOrder( address _module, address _inputToken, address payable _owner, address _witness, bytes calldata _data, bytes32 _secret ) external pure returns (bytes memory) { return abi.encode( _module, _inputToken, _owner, _witness, _data, _secret ); } /** * @notice Get order's properties * @param _data - Bytes of the order * @return module - Address of the module to use for the order execution * @return inputToken - Address of the input token * @return owner - Address of the order's owner * @return witness - Address of the witness * @return data - Bytes of the order's data * @return secret - Private key of the _witness */ function decodeOrder( bytes memory _data ) public pure returns ( address module, address inputToken, address payable owner, address witness, bytes memory data, bytes32 secret ) { ( module, inputToken, owner, witness, data, secret ) = abi.decode( _data, ( address, address, address, address, bytes, bytes32 ) ); } /** * @notice Get the vault's address of a token to token/ETH order * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @return address - The address of the vault */ function vaultOfOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes memory _data ) public view returns (address) { return keyOf( _module, _inputToken, _owner, _witness, _data ).getVault(); } /** * @notice Executes an order * @dev The sender should use the _secret to sign its own address * to prevent front-runnings * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _data - Bytes of the order's data * @param _signature - Signature to calculate the witness * @param _auxData - Bytes of the auxiliar data used for the handlers to execute the order */ function executeOrder( IModule _module, IERC20 _inputToken, address payable _owner, bytes calldata _data, bytes calldata _signature, bytes calldata _auxData ) external { // Calculate witness using signature address witness = ECDSA.recover( keccak256(abi.encodePacked(msg.sender)), _signature ); bytes32 key = keyOf( _module, _inputToken, _owner, witness, _data ); // Pull amount uint256 amount = _pullOrder(_inputToken, key, address(_module)); require(amount > 0, "HyperLimit#executeOrder: INVALID_ORDER"); uint256 bought = _module.execute( _inputToken, amount, _owner, _data, _auxData ); emit OrderExecuted( key, address(_inputToken), _owner, witness, _data, _auxData, amount, bought ); } /** * @notice Check whether an order exists or not * @dev Check the balance of the order * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @return bool - whether the order exists or not */ function existOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data ) external view returns (bool) { bytes32 key = keyOf( _module, _inputToken, _owner, _witness, _data ); if (address(_inputToken) == ETH_ADDRESS) { return ethDeposits[key] != 0; } else { return _inputToken.balanceOf(key.getVault()) != 0; } } /** * @notice Check whether an order can be executed or not * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @param _auxData - Bytes of the auxiliar data used for the handlers to execute the order * @return bool - whether the order can be executed or not */ function canExecuteOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data, bytes calldata _auxData ) external view returns (bool) { bytes32 key = keyOf( _module, _inputToken, _owner, _witness, _data ); // Pull amount uint256 amount; if (address(_inputToken) == ETH_ADDRESS) { amount = ethDeposits[key]; } else { amount = _inputToken.balanceOf(key.getVault()); } return _module.canExecute( _inputToken, amount, _data, _auxData ); } /** * @notice Transfer the order amount to a recipient. * @dev For an ETH order, the ETH will be transferred from this contract * For a token order, its vault will be executed transferring the amount of tokens to * the recipient * @param _inputToken - Address of the input token * @param _key - Order's key * @param _to - Address of the recipient * @return amount - amount transferred */ function _pullOrder( IERC20 _inputToken, bytes32 _key, address payable _to ) private returns (uint256 amount) { if (address(_inputToken) == ETH_ADDRESS) { amount = ethDeposits[_key]; ethDeposits[_key] = 0; (bool success,) = _to.call{value: amount}(""); require(success, "HyperLimit#_pullOrder: PULL_ETHER_FAILED"); } else { amount = _key.executeVault(_inputToken, _to); } } /** * @notice Get the order's key * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @return bytes32 - order's key */ function keyOf( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes memory _data ) public pure returns (bytes32) { return keccak256( abi.encode( _module, _inputToken, _owner, _witness, _data ) ); } }
/// @notice Core contract used to create, cancel and execute orders.
NatSpecSingleLine
existOrder
function existOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data ) external view returns (bool) { bytes32 key = keyOf( _module, _inputToken, _owner, _witness, _data ); if (address(_inputToken) == ETH_ADDRESS) { return ethDeposits[key] != 0; } else { return _inputToken.balanceOf(key.getVault()) != 0; } }
/** * @notice Check whether an order exists or not * @dev Check the balance of the order * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @return bool - whether the order exists or not */
NatSpecMultiLine
v0.6.8+commit.0bbfe453
MIT
ipfs://87b25594a09c529edcbca78f8b34edb2270eef34e0e1c6085d9645d3ea74cd05
{ "func_code_index": [ 9693, 10250 ] }
11,896
HyperLimit
HyperLimit.sol
0x16a893f27fdb30cc05d8fd7a333a5ab841461658
Solidity
HyperLimit
contract HyperLimit is Order { using SafeMath for uint256; using Fabric for bytes32; // ETH orders mapping(bytes32 => uint256) public ethDeposits; // Events event DepositETH( bytes32 indexed _key, address indexed _caller, uint256 _amount, bytes _data ); event OrderExecuted( bytes32 indexed _key, address _inputToken, address _owner, address _witness, bytes _data, bytes _auxData, uint256 _amount, uint256 _bought ); event OrderCancelled( bytes32 indexed _key, address _inputToken, address _owner, address _witness, bytes _data, uint256 _amount ); /** * @dev Prevent users to send Ether directly to this contract */ receive() external payable { require( msg.sender != tx.origin, "HyperLimit#receive: NO_SEND_ETH_PLEASE" ); } /** * @notice Create an ETH to token order * @param _data - Bytes of an ETH to token order. See `encodeEthOrder` for more info */ function depositEth( bytes calldata _data ) external payable { require(msg.value > 0, "HyperLimit#depositEth: VALUE_IS_0"); ( address module, address inputToken, address payable owner, address witness, bytes memory data, ) = decodeOrder(_data); require(inputToken == ETH_ADDRESS, "HyperLimit#depositEth: WRONG_INPUT_TOKEN"); bytes32 key = keyOf( IModule(uint160(module)), IERC20(inputToken), owner, witness, data ); ethDeposits[key] = ethDeposits[key].add(msg.value); emit DepositETH(key, msg.sender, msg.value, _data); } /** * @notice Cancel order * @dev The params should be the same used for the order creation * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data */ function cancelOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data ) external { require(msg.sender == _owner, "HyperLimit#cancelOrder: INVALID_OWNER"); bytes32 key = keyOf( _module, _inputToken, _owner, _witness, _data ); uint256 amount = _pullOrder(_inputToken, key, msg.sender); emit OrderCancelled( key, address(_inputToken), _owner, _witness, _data, amount ); } /** * @notice Get the calldata needed to create a token to token/ETH order * @dev Returns the input data that the user needs to use to create the order * The _secret is used to prevent a front-running at the order execution * The _amount is used as the param `_value` for the ERC20 `transfer` function * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @param _secret - Private key of the _witness * @param _amount - uint256 of the order amount * @return bytes - input data to send the transaction */ function encodeTokenOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data, bytes32 _secret, uint256 _amount ) external view returns (bytes memory) { return abi.encodeWithSelector( _inputToken.transfer.selector, vaultOfOrder( _module, _inputToken, _owner, _witness, _data ), _amount, abi.encode( _module, _inputToken, _owner, _witness, _data, _secret ) ); } /** * @notice Get the calldata needed to create a ETH to token order * @dev Returns the input data that the user needs to use to create the order * The _secret is used to prevent a front-running at the order execution * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @param _secret - Private key of the _witness * @return bytes - input data to send the transaction */ function encodeEthOrder( address _module, address _inputToken, address payable _owner, address _witness, bytes calldata _data, bytes32 _secret ) external pure returns (bytes memory) { return abi.encode( _module, _inputToken, _owner, _witness, _data, _secret ); } /** * @notice Get order's properties * @param _data - Bytes of the order * @return module - Address of the module to use for the order execution * @return inputToken - Address of the input token * @return owner - Address of the order's owner * @return witness - Address of the witness * @return data - Bytes of the order's data * @return secret - Private key of the _witness */ function decodeOrder( bytes memory _data ) public pure returns ( address module, address inputToken, address payable owner, address witness, bytes memory data, bytes32 secret ) { ( module, inputToken, owner, witness, data, secret ) = abi.decode( _data, ( address, address, address, address, bytes, bytes32 ) ); } /** * @notice Get the vault's address of a token to token/ETH order * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @return address - The address of the vault */ function vaultOfOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes memory _data ) public view returns (address) { return keyOf( _module, _inputToken, _owner, _witness, _data ).getVault(); } /** * @notice Executes an order * @dev The sender should use the _secret to sign its own address * to prevent front-runnings * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _data - Bytes of the order's data * @param _signature - Signature to calculate the witness * @param _auxData - Bytes of the auxiliar data used for the handlers to execute the order */ function executeOrder( IModule _module, IERC20 _inputToken, address payable _owner, bytes calldata _data, bytes calldata _signature, bytes calldata _auxData ) external { // Calculate witness using signature address witness = ECDSA.recover( keccak256(abi.encodePacked(msg.sender)), _signature ); bytes32 key = keyOf( _module, _inputToken, _owner, witness, _data ); // Pull amount uint256 amount = _pullOrder(_inputToken, key, address(_module)); require(amount > 0, "HyperLimit#executeOrder: INVALID_ORDER"); uint256 bought = _module.execute( _inputToken, amount, _owner, _data, _auxData ); emit OrderExecuted( key, address(_inputToken), _owner, witness, _data, _auxData, amount, bought ); } /** * @notice Check whether an order exists or not * @dev Check the balance of the order * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @return bool - whether the order exists or not */ function existOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data ) external view returns (bool) { bytes32 key = keyOf( _module, _inputToken, _owner, _witness, _data ); if (address(_inputToken) == ETH_ADDRESS) { return ethDeposits[key] != 0; } else { return _inputToken.balanceOf(key.getVault()) != 0; } } /** * @notice Check whether an order can be executed or not * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @param _auxData - Bytes of the auxiliar data used for the handlers to execute the order * @return bool - whether the order can be executed or not */ function canExecuteOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data, bytes calldata _auxData ) external view returns (bool) { bytes32 key = keyOf( _module, _inputToken, _owner, _witness, _data ); // Pull amount uint256 amount; if (address(_inputToken) == ETH_ADDRESS) { amount = ethDeposits[key]; } else { amount = _inputToken.balanceOf(key.getVault()); } return _module.canExecute( _inputToken, amount, _data, _auxData ); } /** * @notice Transfer the order amount to a recipient. * @dev For an ETH order, the ETH will be transferred from this contract * For a token order, its vault will be executed transferring the amount of tokens to * the recipient * @param _inputToken - Address of the input token * @param _key - Order's key * @param _to - Address of the recipient * @return amount - amount transferred */ function _pullOrder( IERC20 _inputToken, bytes32 _key, address payable _to ) private returns (uint256 amount) { if (address(_inputToken) == ETH_ADDRESS) { amount = ethDeposits[_key]; ethDeposits[_key] = 0; (bool success,) = _to.call{value: amount}(""); require(success, "HyperLimit#_pullOrder: PULL_ETHER_FAILED"); } else { amount = _key.executeVault(_inputToken, _to); } } /** * @notice Get the order's key * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @return bytes32 - order's key */ function keyOf( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes memory _data ) public pure returns (bytes32) { return keccak256( abi.encode( _module, _inputToken, _owner, _witness, _data ) ); } }
/// @notice Core contract used to create, cancel and execute orders.
NatSpecSingleLine
canExecuteOrder
function canExecuteOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data, bytes calldata _auxData ) external view returns (bool) { bytes32 key = keyOf( _module, _inputToken, _owner, _witness, _data ); // Pull amount uint256 amount; if (address(_inputToken) == ETH_ADDRESS) { amount = ethDeposits[key]; } else { amount = _inputToken.balanceOf(key.getVault()); } return _module.canExecute( _inputToken, amount, _data, _auxData ); }
/** * @notice Check whether an order can be executed or not * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @param _auxData - Bytes of the auxiliar data used for the handlers to execute the order * @return bool - whether the order can be executed or not */
NatSpecMultiLine
v0.6.8+commit.0bbfe453
MIT
ipfs://87b25594a09c529edcbca78f8b34edb2270eef34e0e1c6085d9645d3ea74cd05
{ "func_code_index": [ 10778, 11557 ] }
11,897
HyperLimit
HyperLimit.sol
0x16a893f27fdb30cc05d8fd7a333a5ab841461658
Solidity
HyperLimit
contract HyperLimit is Order { using SafeMath for uint256; using Fabric for bytes32; // ETH orders mapping(bytes32 => uint256) public ethDeposits; // Events event DepositETH( bytes32 indexed _key, address indexed _caller, uint256 _amount, bytes _data ); event OrderExecuted( bytes32 indexed _key, address _inputToken, address _owner, address _witness, bytes _data, bytes _auxData, uint256 _amount, uint256 _bought ); event OrderCancelled( bytes32 indexed _key, address _inputToken, address _owner, address _witness, bytes _data, uint256 _amount ); /** * @dev Prevent users to send Ether directly to this contract */ receive() external payable { require( msg.sender != tx.origin, "HyperLimit#receive: NO_SEND_ETH_PLEASE" ); } /** * @notice Create an ETH to token order * @param _data - Bytes of an ETH to token order. See `encodeEthOrder` for more info */ function depositEth( bytes calldata _data ) external payable { require(msg.value > 0, "HyperLimit#depositEth: VALUE_IS_0"); ( address module, address inputToken, address payable owner, address witness, bytes memory data, ) = decodeOrder(_data); require(inputToken == ETH_ADDRESS, "HyperLimit#depositEth: WRONG_INPUT_TOKEN"); bytes32 key = keyOf( IModule(uint160(module)), IERC20(inputToken), owner, witness, data ); ethDeposits[key] = ethDeposits[key].add(msg.value); emit DepositETH(key, msg.sender, msg.value, _data); } /** * @notice Cancel order * @dev The params should be the same used for the order creation * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data */ function cancelOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data ) external { require(msg.sender == _owner, "HyperLimit#cancelOrder: INVALID_OWNER"); bytes32 key = keyOf( _module, _inputToken, _owner, _witness, _data ); uint256 amount = _pullOrder(_inputToken, key, msg.sender); emit OrderCancelled( key, address(_inputToken), _owner, _witness, _data, amount ); } /** * @notice Get the calldata needed to create a token to token/ETH order * @dev Returns the input data that the user needs to use to create the order * The _secret is used to prevent a front-running at the order execution * The _amount is used as the param `_value` for the ERC20 `transfer` function * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @param _secret - Private key of the _witness * @param _amount - uint256 of the order amount * @return bytes - input data to send the transaction */ function encodeTokenOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data, bytes32 _secret, uint256 _amount ) external view returns (bytes memory) { return abi.encodeWithSelector( _inputToken.transfer.selector, vaultOfOrder( _module, _inputToken, _owner, _witness, _data ), _amount, abi.encode( _module, _inputToken, _owner, _witness, _data, _secret ) ); } /** * @notice Get the calldata needed to create a ETH to token order * @dev Returns the input data that the user needs to use to create the order * The _secret is used to prevent a front-running at the order execution * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @param _secret - Private key of the _witness * @return bytes - input data to send the transaction */ function encodeEthOrder( address _module, address _inputToken, address payable _owner, address _witness, bytes calldata _data, bytes32 _secret ) external pure returns (bytes memory) { return abi.encode( _module, _inputToken, _owner, _witness, _data, _secret ); } /** * @notice Get order's properties * @param _data - Bytes of the order * @return module - Address of the module to use for the order execution * @return inputToken - Address of the input token * @return owner - Address of the order's owner * @return witness - Address of the witness * @return data - Bytes of the order's data * @return secret - Private key of the _witness */ function decodeOrder( bytes memory _data ) public pure returns ( address module, address inputToken, address payable owner, address witness, bytes memory data, bytes32 secret ) { ( module, inputToken, owner, witness, data, secret ) = abi.decode( _data, ( address, address, address, address, bytes, bytes32 ) ); } /** * @notice Get the vault's address of a token to token/ETH order * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @return address - The address of the vault */ function vaultOfOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes memory _data ) public view returns (address) { return keyOf( _module, _inputToken, _owner, _witness, _data ).getVault(); } /** * @notice Executes an order * @dev The sender should use the _secret to sign its own address * to prevent front-runnings * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _data - Bytes of the order's data * @param _signature - Signature to calculate the witness * @param _auxData - Bytes of the auxiliar data used for the handlers to execute the order */ function executeOrder( IModule _module, IERC20 _inputToken, address payable _owner, bytes calldata _data, bytes calldata _signature, bytes calldata _auxData ) external { // Calculate witness using signature address witness = ECDSA.recover( keccak256(abi.encodePacked(msg.sender)), _signature ); bytes32 key = keyOf( _module, _inputToken, _owner, witness, _data ); // Pull amount uint256 amount = _pullOrder(_inputToken, key, address(_module)); require(amount > 0, "HyperLimit#executeOrder: INVALID_ORDER"); uint256 bought = _module.execute( _inputToken, amount, _owner, _data, _auxData ); emit OrderExecuted( key, address(_inputToken), _owner, witness, _data, _auxData, amount, bought ); } /** * @notice Check whether an order exists or not * @dev Check the balance of the order * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @return bool - whether the order exists or not */ function existOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data ) external view returns (bool) { bytes32 key = keyOf( _module, _inputToken, _owner, _witness, _data ); if (address(_inputToken) == ETH_ADDRESS) { return ethDeposits[key] != 0; } else { return _inputToken.balanceOf(key.getVault()) != 0; } } /** * @notice Check whether an order can be executed or not * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @param _auxData - Bytes of the auxiliar data used for the handlers to execute the order * @return bool - whether the order can be executed or not */ function canExecuteOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data, bytes calldata _auxData ) external view returns (bool) { bytes32 key = keyOf( _module, _inputToken, _owner, _witness, _data ); // Pull amount uint256 amount; if (address(_inputToken) == ETH_ADDRESS) { amount = ethDeposits[key]; } else { amount = _inputToken.balanceOf(key.getVault()); } return _module.canExecute( _inputToken, amount, _data, _auxData ); } /** * @notice Transfer the order amount to a recipient. * @dev For an ETH order, the ETH will be transferred from this contract * For a token order, its vault will be executed transferring the amount of tokens to * the recipient * @param _inputToken - Address of the input token * @param _key - Order's key * @param _to - Address of the recipient * @return amount - amount transferred */ function _pullOrder( IERC20 _inputToken, bytes32 _key, address payable _to ) private returns (uint256 amount) { if (address(_inputToken) == ETH_ADDRESS) { amount = ethDeposits[_key]; ethDeposits[_key] = 0; (bool success,) = _to.call{value: amount}(""); require(success, "HyperLimit#_pullOrder: PULL_ETHER_FAILED"); } else { amount = _key.executeVault(_inputToken, _to); } } /** * @notice Get the order's key * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @return bytes32 - order's key */ function keyOf( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes memory _data ) public pure returns (bytes32) { return keccak256( abi.encode( _module, _inputToken, _owner, _witness, _data ) ); } }
/// @notice Core contract used to create, cancel and execute orders.
NatSpecSingleLine
_pullOrder
function _pullOrder( IERC20 _inputToken, bytes32 _key, address payable _to ) private returns (uint256 amount) { if (address(_inputToken) == ETH_ADDRESS) { amount = ethDeposits[_key]; ethDeposits[_key] = 0; (bool success,) = _to.call{value: amount}(""); require(success, "HyperLimit#_pullOrder: PULL_ETHER_FAILED"); } else { amount = _key.executeVault(_inputToken, _to); } }
/** * @notice Transfer the order amount to a recipient. * @dev For an ETH order, the ETH will be transferred from this contract * For a token order, its vault will be executed transferring the amount of tokens to * the recipient * @param _inputToken - Address of the input token * @param _key - Order's key * @param _to - Address of the recipient * @return amount - amount transferred */
NatSpecMultiLine
v0.6.8+commit.0bbfe453
MIT
ipfs://87b25594a09c529edcbca78f8b34edb2270eef34e0e1c6085d9645d3ea74cd05
{ "func_code_index": [ 12007, 12514 ] }
11,898
HyperLimit
HyperLimit.sol
0x16a893f27fdb30cc05d8fd7a333a5ab841461658
Solidity
HyperLimit
contract HyperLimit is Order { using SafeMath for uint256; using Fabric for bytes32; // ETH orders mapping(bytes32 => uint256) public ethDeposits; // Events event DepositETH( bytes32 indexed _key, address indexed _caller, uint256 _amount, bytes _data ); event OrderExecuted( bytes32 indexed _key, address _inputToken, address _owner, address _witness, bytes _data, bytes _auxData, uint256 _amount, uint256 _bought ); event OrderCancelled( bytes32 indexed _key, address _inputToken, address _owner, address _witness, bytes _data, uint256 _amount ); /** * @dev Prevent users to send Ether directly to this contract */ receive() external payable { require( msg.sender != tx.origin, "HyperLimit#receive: NO_SEND_ETH_PLEASE" ); } /** * @notice Create an ETH to token order * @param _data - Bytes of an ETH to token order. See `encodeEthOrder` for more info */ function depositEth( bytes calldata _data ) external payable { require(msg.value > 0, "HyperLimit#depositEth: VALUE_IS_0"); ( address module, address inputToken, address payable owner, address witness, bytes memory data, ) = decodeOrder(_data); require(inputToken == ETH_ADDRESS, "HyperLimit#depositEth: WRONG_INPUT_TOKEN"); bytes32 key = keyOf( IModule(uint160(module)), IERC20(inputToken), owner, witness, data ); ethDeposits[key] = ethDeposits[key].add(msg.value); emit DepositETH(key, msg.sender, msg.value, _data); } /** * @notice Cancel order * @dev The params should be the same used for the order creation * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data */ function cancelOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data ) external { require(msg.sender == _owner, "HyperLimit#cancelOrder: INVALID_OWNER"); bytes32 key = keyOf( _module, _inputToken, _owner, _witness, _data ); uint256 amount = _pullOrder(_inputToken, key, msg.sender); emit OrderCancelled( key, address(_inputToken), _owner, _witness, _data, amount ); } /** * @notice Get the calldata needed to create a token to token/ETH order * @dev Returns the input data that the user needs to use to create the order * The _secret is used to prevent a front-running at the order execution * The _amount is used as the param `_value` for the ERC20 `transfer` function * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @param _secret - Private key of the _witness * @param _amount - uint256 of the order amount * @return bytes - input data to send the transaction */ function encodeTokenOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data, bytes32 _secret, uint256 _amount ) external view returns (bytes memory) { return abi.encodeWithSelector( _inputToken.transfer.selector, vaultOfOrder( _module, _inputToken, _owner, _witness, _data ), _amount, abi.encode( _module, _inputToken, _owner, _witness, _data, _secret ) ); } /** * @notice Get the calldata needed to create a ETH to token order * @dev Returns the input data that the user needs to use to create the order * The _secret is used to prevent a front-running at the order execution * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @param _secret - Private key of the _witness * @return bytes - input data to send the transaction */ function encodeEthOrder( address _module, address _inputToken, address payable _owner, address _witness, bytes calldata _data, bytes32 _secret ) external pure returns (bytes memory) { return abi.encode( _module, _inputToken, _owner, _witness, _data, _secret ); } /** * @notice Get order's properties * @param _data - Bytes of the order * @return module - Address of the module to use for the order execution * @return inputToken - Address of the input token * @return owner - Address of the order's owner * @return witness - Address of the witness * @return data - Bytes of the order's data * @return secret - Private key of the _witness */ function decodeOrder( bytes memory _data ) public pure returns ( address module, address inputToken, address payable owner, address witness, bytes memory data, bytes32 secret ) { ( module, inputToken, owner, witness, data, secret ) = abi.decode( _data, ( address, address, address, address, bytes, bytes32 ) ); } /** * @notice Get the vault's address of a token to token/ETH order * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @return address - The address of the vault */ function vaultOfOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes memory _data ) public view returns (address) { return keyOf( _module, _inputToken, _owner, _witness, _data ).getVault(); } /** * @notice Executes an order * @dev The sender should use the _secret to sign its own address * to prevent front-runnings * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _data - Bytes of the order's data * @param _signature - Signature to calculate the witness * @param _auxData - Bytes of the auxiliar data used for the handlers to execute the order */ function executeOrder( IModule _module, IERC20 _inputToken, address payable _owner, bytes calldata _data, bytes calldata _signature, bytes calldata _auxData ) external { // Calculate witness using signature address witness = ECDSA.recover( keccak256(abi.encodePacked(msg.sender)), _signature ); bytes32 key = keyOf( _module, _inputToken, _owner, witness, _data ); // Pull amount uint256 amount = _pullOrder(_inputToken, key, address(_module)); require(amount > 0, "HyperLimit#executeOrder: INVALID_ORDER"); uint256 bought = _module.execute( _inputToken, amount, _owner, _data, _auxData ); emit OrderExecuted( key, address(_inputToken), _owner, witness, _data, _auxData, amount, bought ); } /** * @notice Check whether an order exists or not * @dev Check the balance of the order * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @return bool - whether the order exists or not */ function existOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data ) external view returns (bool) { bytes32 key = keyOf( _module, _inputToken, _owner, _witness, _data ); if (address(_inputToken) == ETH_ADDRESS) { return ethDeposits[key] != 0; } else { return _inputToken.balanceOf(key.getVault()) != 0; } } /** * @notice Check whether an order can be executed or not * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @param _auxData - Bytes of the auxiliar data used for the handlers to execute the order * @return bool - whether the order can be executed or not */ function canExecuteOrder( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes calldata _data, bytes calldata _auxData ) external view returns (bool) { bytes32 key = keyOf( _module, _inputToken, _owner, _witness, _data ); // Pull amount uint256 amount; if (address(_inputToken) == ETH_ADDRESS) { amount = ethDeposits[key]; } else { amount = _inputToken.balanceOf(key.getVault()); } return _module.canExecute( _inputToken, amount, _data, _auxData ); } /** * @notice Transfer the order amount to a recipient. * @dev For an ETH order, the ETH will be transferred from this contract * For a token order, its vault will be executed transferring the amount of tokens to * the recipient * @param _inputToken - Address of the input token * @param _key - Order's key * @param _to - Address of the recipient * @return amount - amount transferred */ function _pullOrder( IERC20 _inputToken, bytes32 _key, address payable _to ) private returns (uint256 amount) { if (address(_inputToken) == ETH_ADDRESS) { amount = ethDeposits[_key]; ethDeposits[_key] = 0; (bool success,) = _to.call{value: amount}(""); require(success, "HyperLimit#_pullOrder: PULL_ETHER_FAILED"); } else { amount = _key.executeVault(_inputToken, _to); } } /** * @notice Get the order's key * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @return bytes32 - order's key */ function keyOf( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes memory _data ) public pure returns (bytes32) { return keccak256( abi.encode( _module, _inputToken, _owner, _witness, _data ) ); } }
/// @notice Core contract used to create, cancel and execute orders.
NatSpecSingleLine
keyOf
function keyOf( IModule _module, IERC20 _inputToken, address payable _owner, address _witness, bytes memory _data ) public pure returns (bytes32) { return keccak256( abi.encode( _module, _inputToken, _owner, _witness, _data ) ); }
/** * @notice Get the order's key * @param _module - Address of the module to use for the order execution * @param _inputToken - Address of the input token * @param _owner - Address of the order's owner * @param _witness - Address of the witness * @param _data - Bytes of the order's data * @return bytes32 - order's key */
NatSpecMultiLine
v0.6.8+commit.0bbfe453
MIT
ipfs://87b25594a09c529edcbca78f8b34edb2270eef34e0e1c6085d9645d3ea74cd05
{ "func_code_index": [ 12894, 13313 ] }
11,899