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
UniV3PairManagerFactory
solidity/contracts/UniV3PairManager.sol
0x005634cfef45e5a19c84aede6f0af17833471852
Solidity
UniV3PairManager
contract UniV3PairManager is IUniV3PairManager, Governable { /// @inheritdoc IERC20Metadata string public override name; /// @inheritdoc IERC20Metadata string public override symbol; /// @inheritdoc IERC20 uint256 public override totalSupply = 0; /// @inheritdoc IPairManager address public immutable override token0; /// @inheritdoc IPairManager address public immutable override token1; /// @inheritdoc IPairManager address public immutable override pool; /// @inheritdoc IUniV3PairManager uint24 public immutable override fee; /// @inheritdoc IUniV3PairManager uint160 public immutable override sqrtRatioAX96; /// @inheritdoc IUniV3PairManager uint160 public immutable override sqrtRatioBX96; /// @notice Lowest possible tick in the Uniswap's curve int24 private constant _TICK_LOWER = -887200; /// @notice Highest possible tick in the Uniswap's curve int24 private constant _TICK_UPPER = 887200; /// @inheritdoc IERC20Metadata //solhint-disable-next-line const-name-snakecase uint8 public constant override decimals = 18; /// @inheritdoc IERC20 mapping(address => mapping(address => uint256)) public override allowance; /// @inheritdoc IERC20 mapping(address => uint256) public override balanceOf; /// @notice Struct that contains token0, token1, and fee of the Uniswap pool PoolAddress.PoolKey private _poolKey; constructor(address _pool, address _governance) Governable(_governance) { pool = _pool; uint24 _fee = IUniswapV3Pool(_pool).fee(); fee = _fee; address _token0 = IUniswapV3Pool(_pool).token0(); address _token1 = IUniswapV3Pool(_pool).token1(); token0 = _token0; token1 = _token1; name = string(abi.encodePacked('Keep3rLP - ', ERC20(_token0).symbol(), '/', ERC20(_token1).symbol())); symbol = string(abi.encodePacked('kLP-', ERC20(_token0).symbol(), '/', ERC20(_token1).symbol())); sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(_TICK_LOWER); sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(_TICK_UPPER); _poolKey = PoolAddress.PoolKey({token0: _token0, token1: _token1, fee: _fee}); } // This low-level function should be called from a contract which performs important safety checks /// @inheritdoc IUniV3PairManager function mint( uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min, address to ) external override returns (uint128 liquidity) { (liquidity, , ) = _addLiquidity(amount0Desired, amount1Desired, amount0Min, amount1Min); _mint(to, liquidity); } /// @inheritdoc IUniV3PairManager function uniswapV3MintCallback( uint256 amount0Owed, uint256 amount1Owed, bytes calldata data ) external override { MintCallbackData memory decoded = abi.decode(data, (MintCallbackData)); if (msg.sender != pool) revert OnlyPool(); if (amount0Owed > 0) _pay(decoded._poolKey.token0, decoded.payer, pool, amount0Owed); if (amount1Owed > 0) _pay(decoded._poolKey.token1, decoded.payer, pool, amount1Owed); } /// @inheritdoc IUniV3PairManager function burn( uint128 liquidity, uint256 amount0Min, uint256 amount1Min, address to ) external override returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = IUniswapV3Pool(pool).burn(_TICK_LOWER, _TICK_UPPER, liquidity); if (amount0 < amount0Min || amount1 < amount1Min) revert ExcessiveSlippage(); IUniswapV3Pool(pool).collect(to, _TICK_LOWER, _TICK_UPPER, uint128(amount0), uint128(amount1)); _burn(msg.sender, liquidity); } /// @inheritdoc IUniV3PairManager function collect() external override onlyGovernance returns (uint256 amount0, uint256 amount1) { (, , , uint128 tokensOwed0, uint128 tokensOwed1) = IUniswapV3Pool(pool).positions( keccak256(abi.encodePacked(address(this), _TICK_LOWER, _TICK_UPPER)) ); (amount0, amount1) = IUniswapV3Pool(pool).collect(governance, _TICK_LOWER, _TICK_UPPER, tokensOwed0, tokensOwed1); } /// @inheritdoc IUniV3PairManager function position() external view override returns ( uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ) { (liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128, tokensOwed0, tokensOwed1) = IUniswapV3Pool(pool).positions( keccak256(abi.encodePacked(address(this), _TICK_LOWER, _TICK_UPPER)) ); } /// @inheritdoc IERC20 function approve(address spender, uint256 amount) external override returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /// @inheritdoc IERC20 function transfer(address to, uint256 amount) external override returns (bool) { _transferTokens(msg.sender, to, amount); return true; } /// @inheritdoc IERC20 function transferFrom( address from, address to, uint256 amount ) external override returns (bool) { address spender = msg.sender; uint256 spenderAllowance = allowance[from][spender]; if (spender != from && spenderAllowance != type(uint256).max) { uint256 newAllowance = spenderAllowance - amount; allowance[from][spender] = newAllowance; emit Approval(from, spender, newAllowance); } _transferTokens(from, to, amount); return true; } /// @notice Adds liquidity to an initialized pool /// @dev Reverts if the returned amount0 is less than amount0Min or if amount1 is less than amount1Min /// @dev This function calls the mint function of the corresponding Uniswap pool, which in turn calls UniswapV3Callback /// @param amount0Desired The amount of token0 we would like to provide /// @param amount1Desired The amount of token1 we would like to provide /// @param amount0Min The minimum amount of token0 we want to provide /// @param amount1Min The minimum amount of token1 we want to provide /// @return liquidity The calculated liquidity we get for the token amounts we provided /// @return amount0 The amount of token0 we ended up providing /// @return amount1 The amount of token1 we ended up providing function _addLiquidity( uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min ) internal returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ) { (uint160 sqrtPriceX96, , , , , , ) = IUniswapV3Pool(pool).slot0(); liquidity = LiquidityAmounts.getLiquidityForAmounts(sqrtPriceX96, sqrtRatioAX96, sqrtRatioBX96, amount0Desired, amount1Desired); (amount0, amount1) = IUniswapV3Pool(pool).mint( address(this), _TICK_LOWER, _TICK_UPPER, liquidity, abi.encode(MintCallbackData({_poolKey: _poolKey, payer: msg.sender})) ); if (amount0 < amount0Min || amount1 < amount1Min) revert ExcessiveSlippage(); } /// @notice Transfers the passed-in token from the payer to the recipient for the corresponding value /// @param token The token to be transferred to the recipient /// @param from The address of the payer /// @param to The address of the passed-in tokens recipient /// @param value How much of that token to be transferred from payer to the recipient function _pay( address token, address from, address to, uint256 value ) internal { _safeTransferFrom(token, from, to, value); } /// @notice Mints Keep3r credits to the passed-in address of recipient and increases total supply of Keep3r credits by the corresponding amount /// @param to The recipient of the Keep3r credits /// @param amount The amount Keep3r credits to be minted to the recipient function _mint(address to, uint256 amount) internal { totalSupply += amount; balanceOf[to] += amount; emit Transfer(address(0), to, amount); } /// @notice Burns Keep3r credits to the passed-in address of recipient and reduces total supply of Keep3r credits by the corresponding amount /// @param to The address that will get its Keep3r credits burned /// @param amount The amount Keep3r credits to be burned from the recipient/recipient function _burn(address to, uint256 amount) internal { totalSupply -= amount; balanceOf[to] -= amount; emit Transfer(to, address(0), amount); } /// @notice Transfers amount of Keep3r credits between two addresses /// @param from The user that transfers the Keep3r credits /// @param to The user that receives the Keep3r credits /// @param amount The amount of Keep3r credits to be transferred function _transferTokens( address from, address to, uint256 amount ) internal { balanceOf[from] -= amount; balanceOf[to] += amount; emit Transfer(from, to, amount); } /// @notice Transfers the passed-in token from the specified "from" to the specified "to" for the corresponding value /// @dev Reverts with IUniV3PairManager#UnsuccessfulTransfer if the transfer was not successful, /// or if the passed data length is different than 0 and the decoded data is not a boolean /// @param token The token to be transferred to the specified "to" /// @param from The address which is going to transfer the tokens /// @param value How much of that token to be transferred from "from" to "to" function _safeTransferFrom( address token, address from, address to, uint256 value ) internal { // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) revert UnsuccessfulTransfer(); } }
position
function position() external view override returns ( uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ) { (liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128, tokensOwed0, tokensOwed1) = IUniswapV3Pool(pool).positions( keccak256(abi.encodePacked(address(this), _TICK_LOWER, _TICK_UPPER)) ); }
/// @inheritdoc IUniV3PairManager
NatSpecSingleLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 4031, 4483 ] }
7,607
UniV3PairManagerFactory
solidity/contracts/UniV3PairManager.sol
0x005634cfef45e5a19c84aede6f0af17833471852
Solidity
UniV3PairManager
contract UniV3PairManager is IUniV3PairManager, Governable { /// @inheritdoc IERC20Metadata string public override name; /// @inheritdoc IERC20Metadata string public override symbol; /// @inheritdoc IERC20 uint256 public override totalSupply = 0; /// @inheritdoc IPairManager address public immutable override token0; /// @inheritdoc IPairManager address public immutable override token1; /// @inheritdoc IPairManager address public immutable override pool; /// @inheritdoc IUniV3PairManager uint24 public immutable override fee; /// @inheritdoc IUniV3PairManager uint160 public immutable override sqrtRatioAX96; /// @inheritdoc IUniV3PairManager uint160 public immutable override sqrtRatioBX96; /// @notice Lowest possible tick in the Uniswap's curve int24 private constant _TICK_LOWER = -887200; /// @notice Highest possible tick in the Uniswap's curve int24 private constant _TICK_UPPER = 887200; /// @inheritdoc IERC20Metadata //solhint-disable-next-line const-name-snakecase uint8 public constant override decimals = 18; /// @inheritdoc IERC20 mapping(address => mapping(address => uint256)) public override allowance; /// @inheritdoc IERC20 mapping(address => uint256) public override balanceOf; /// @notice Struct that contains token0, token1, and fee of the Uniswap pool PoolAddress.PoolKey private _poolKey; constructor(address _pool, address _governance) Governable(_governance) { pool = _pool; uint24 _fee = IUniswapV3Pool(_pool).fee(); fee = _fee; address _token0 = IUniswapV3Pool(_pool).token0(); address _token1 = IUniswapV3Pool(_pool).token1(); token0 = _token0; token1 = _token1; name = string(abi.encodePacked('Keep3rLP - ', ERC20(_token0).symbol(), '/', ERC20(_token1).symbol())); symbol = string(abi.encodePacked('kLP-', ERC20(_token0).symbol(), '/', ERC20(_token1).symbol())); sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(_TICK_LOWER); sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(_TICK_UPPER); _poolKey = PoolAddress.PoolKey({token0: _token0, token1: _token1, fee: _fee}); } // This low-level function should be called from a contract which performs important safety checks /// @inheritdoc IUniV3PairManager function mint( uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min, address to ) external override returns (uint128 liquidity) { (liquidity, , ) = _addLiquidity(amount0Desired, amount1Desired, amount0Min, amount1Min); _mint(to, liquidity); } /// @inheritdoc IUniV3PairManager function uniswapV3MintCallback( uint256 amount0Owed, uint256 amount1Owed, bytes calldata data ) external override { MintCallbackData memory decoded = abi.decode(data, (MintCallbackData)); if (msg.sender != pool) revert OnlyPool(); if (amount0Owed > 0) _pay(decoded._poolKey.token0, decoded.payer, pool, amount0Owed); if (amount1Owed > 0) _pay(decoded._poolKey.token1, decoded.payer, pool, amount1Owed); } /// @inheritdoc IUniV3PairManager function burn( uint128 liquidity, uint256 amount0Min, uint256 amount1Min, address to ) external override returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = IUniswapV3Pool(pool).burn(_TICK_LOWER, _TICK_UPPER, liquidity); if (amount0 < amount0Min || amount1 < amount1Min) revert ExcessiveSlippage(); IUniswapV3Pool(pool).collect(to, _TICK_LOWER, _TICK_UPPER, uint128(amount0), uint128(amount1)); _burn(msg.sender, liquidity); } /// @inheritdoc IUniV3PairManager function collect() external override onlyGovernance returns (uint256 amount0, uint256 amount1) { (, , , uint128 tokensOwed0, uint128 tokensOwed1) = IUniswapV3Pool(pool).positions( keccak256(abi.encodePacked(address(this), _TICK_LOWER, _TICK_UPPER)) ); (amount0, amount1) = IUniswapV3Pool(pool).collect(governance, _TICK_LOWER, _TICK_UPPER, tokensOwed0, tokensOwed1); } /// @inheritdoc IUniV3PairManager function position() external view override returns ( uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ) { (liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128, tokensOwed0, tokensOwed1) = IUniswapV3Pool(pool).positions( keccak256(abi.encodePacked(address(this), _TICK_LOWER, _TICK_UPPER)) ); } /// @inheritdoc IERC20 function approve(address spender, uint256 amount) external override returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /// @inheritdoc IERC20 function transfer(address to, uint256 amount) external override returns (bool) { _transferTokens(msg.sender, to, amount); return true; } /// @inheritdoc IERC20 function transferFrom( address from, address to, uint256 amount ) external override returns (bool) { address spender = msg.sender; uint256 spenderAllowance = allowance[from][spender]; if (spender != from && spenderAllowance != type(uint256).max) { uint256 newAllowance = spenderAllowance - amount; allowance[from][spender] = newAllowance; emit Approval(from, spender, newAllowance); } _transferTokens(from, to, amount); return true; } /// @notice Adds liquidity to an initialized pool /// @dev Reverts if the returned amount0 is less than amount0Min or if amount1 is less than amount1Min /// @dev This function calls the mint function of the corresponding Uniswap pool, which in turn calls UniswapV3Callback /// @param amount0Desired The amount of token0 we would like to provide /// @param amount1Desired The amount of token1 we would like to provide /// @param amount0Min The minimum amount of token0 we want to provide /// @param amount1Min The minimum amount of token1 we want to provide /// @return liquidity The calculated liquidity we get for the token amounts we provided /// @return amount0 The amount of token0 we ended up providing /// @return amount1 The amount of token1 we ended up providing function _addLiquidity( uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min ) internal returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ) { (uint160 sqrtPriceX96, , , , , , ) = IUniswapV3Pool(pool).slot0(); liquidity = LiquidityAmounts.getLiquidityForAmounts(sqrtPriceX96, sqrtRatioAX96, sqrtRatioBX96, amount0Desired, amount1Desired); (amount0, amount1) = IUniswapV3Pool(pool).mint( address(this), _TICK_LOWER, _TICK_UPPER, liquidity, abi.encode(MintCallbackData({_poolKey: _poolKey, payer: msg.sender})) ); if (amount0 < amount0Min || amount1 < amount1Min) revert ExcessiveSlippage(); } /// @notice Transfers the passed-in token from the payer to the recipient for the corresponding value /// @param token The token to be transferred to the recipient /// @param from The address of the payer /// @param to The address of the passed-in tokens recipient /// @param value How much of that token to be transferred from payer to the recipient function _pay( address token, address from, address to, uint256 value ) internal { _safeTransferFrom(token, from, to, value); } /// @notice Mints Keep3r credits to the passed-in address of recipient and increases total supply of Keep3r credits by the corresponding amount /// @param to The recipient of the Keep3r credits /// @param amount The amount Keep3r credits to be minted to the recipient function _mint(address to, uint256 amount) internal { totalSupply += amount; balanceOf[to] += amount; emit Transfer(address(0), to, amount); } /// @notice Burns Keep3r credits to the passed-in address of recipient and reduces total supply of Keep3r credits by the corresponding amount /// @param to The address that will get its Keep3r credits burned /// @param amount The amount Keep3r credits to be burned from the recipient/recipient function _burn(address to, uint256 amount) internal { totalSupply -= amount; balanceOf[to] -= amount; emit Transfer(to, address(0), amount); } /// @notice Transfers amount of Keep3r credits between two addresses /// @param from The user that transfers the Keep3r credits /// @param to The user that receives the Keep3r credits /// @param amount The amount of Keep3r credits to be transferred function _transferTokens( address from, address to, uint256 amount ) internal { balanceOf[from] -= amount; balanceOf[to] += amount; emit Transfer(from, to, amount); } /// @notice Transfers the passed-in token from the specified "from" to the specified "to" for the corresponding value /// @dev Reverts with IUniV3PairManager#UnsuccessfulTransfer if the transfer was not successful, /// or if the passed data length is different than 0 and the decoded data is not a boolean /// @param token The token to be transferred to the specified "to" /// @param from The address which is going to transfer the tokens /// @param value How much of that token to be transferred from "from" to "to" function _safeTransferFrom( address token, address from, address to, uint256 value ) internal { // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) revert UnsuccessfulTransfer(); } }
approve
function approve(address spender, uint256 amount) external override returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; }
/// @inheritdoc IERC20
NatSpecSingleLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 4510, 4711 ] }
7,608
UniV3PairManagerFactory
solidity/contracts/UniV3PairManager.sol
0x005634cfef45e5a19c84aede6f0af17833471852
Solidity
UniV3PairManager
contract UniV3PairManager is IUniV3PairManager, Governable { /// @inheritdoc IERC20Metadata string public override name; /// @inheritdoc IERC20Metadata string public override symbol; /// @inheritdoc IERC20 uint256 public override totalSupply = 0; /// @inheritdoc IPairManager address public immutable override token0; /// @inheritdoc IPairManager address public immutable override token1; /// @inheritdoc IPairManager address public immutable override pool; /// @inheritdoc IUniV3PairManager uint24 public immutable override fee; /// @inheritdoc IUniV3PairManager uint160 public immutable override sqrtRatioAX96; /// @inheritdoc IUniV3PairManager uint160 public immutable override sqrtRatioBX96; /// @notice Lowest possible tick in the Uniswap's curve int24 private constant _TICK_LOWER = -887200; /// @notice Highest possible tick in the Uniswap's curve int24 private constant _TICK_UPPER = 887200; /// @inheritdoc IERC20Metadata //solhint-disable-next-line const-name-snakecase uint8 public constant override decimals = 18; /// @inheritdoc IERC20 mapping(address => mapping(address => uint256)) public override allowance; /// @inheritdoc IERC20 mapping(address => uint256) public override balanceOf; /// @notice Struct that contains token0, token1, and fee of the Uniswap pool PoolAddress.PoolKey private _poolKey; constructor(address _pool, address _governance) Governable(_governance) { pool = _pool; uint24 _fee = IUniswapV3Pool(_pool).fee(); fee = _fee; address _token0 = IUniswapV3Pool(_pool).token0(); address _token1 = IUniswapV3Pool(_pool).token1(); token0 = _token0; token1 = _token1; name = string(abi.encodePacked('Keep3rLP - ', ERC20(_token0).symbol(), '/', ERC20(_token1).symbol())); symbol = string(abi.encodePacked('kLP-', ERC20(_token0).symbol(), '/', ERC20(_token1).symbol())); sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(_TICK_LOWER); sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(_TICK_UPPER); _poolKey = PoolAddress.PoolKey({token0: _token0, token1: _token1, fee: _fee}); } // This low-level function should be called from a contract which performs important safety checks /// @inheritdoc IUniV3PairManager function mint( uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min, address to ) external override returns (uint128 liquidity) { (liquidity, , ) = _addLiquidity(amount0Desired, amount1Desired, amount0Min, amount1Min); _mint(to, liquidity); } /// @inheritdoc IUniV3PairManager function uniswapV3MintCallback( uint256 amount0Owed, uint256 amount1Owed, bytes calldata data ) external override { MintCallbackData memory decoded = abi.decode(data, (MintCallbackData)); if (msg.sender != pool) revert OnlyPool(); if (amount0Owed > 0) _pay(decoded._poolKey.token0, decoded.payer, pool, amount0Owed); if (amount1Owed > 0) _pay(decoded._poolKey.token1, decoded.payer, pool, amount1Owed); } /// @inheritdoc IUniV3PairManager function burn( uint128 liquidity, uint256 amount0Min, uint256 amount1Min, address to ) external override returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = IUniswapV3Pool(pool).burn(_TICK_LOWER, _TICK_UPPER, liquidity); if (amount0 < amount0Min || amount1 < amount1Min) revert ExcessiveSlippage(); IUniswapV3Pool(pool).collect(to, _TICK_LOWER, _TICK_UPPER, uint128(amount0), uint128(amount1)); _burn(msg.sender, liquidity); } /// @inheritdoc IUniV3PairManager function collect() external override onlyGovernance returns (uint256 amount0, uint256 amount1) { (, , , uint128 tokensOwed0, uint128 tokensOwed1) = IUniswapV3Pool(pool).positions( keccak256(abi.encodePacked(address(this), _TICK_LOWER, _TICK_UPPER)) ); (amount0, amount1) = IUniswapV3Pool(pool).collect(governance, _TICK_LOWER, _TICK_UPPER, tokensOwed0, tokensOwed1); } /// @inheritdoc IUniV3PairManager function position() external view override returns ( uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ) { (liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128, tokensOwed0, tokensOwed1) = IUniswapV3Pool(pool).positions( keccak256(abi.encodePacked(address(this), _TICK_LOWER, _TICK_UPPER)) ); } /// @inheritdoc IERC20 function approve(address spender, uint256 amount) external override returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /// @inheritdoc IERC20 function transfer(address to, uint256 amount) external override returns (bool) { _transferTokens(msg.sender, to, amount); return true; } /// @inheritdoc IERC20 function transferFrom( address from, address to, uint256 amount ) external override returns (bool) { address spender = msg.sender; uint256 spenderAllowance = allowance[from][spender]; if (spender != from && spenderAllowance != type(uint256).max) { uint256 newAllowance = spenderAllowance - amount; allowance[from][spender] = newAllowance; emit Approval(from, spender, newAllowance); } _transferTokens(from, to, amount); return true; } /// @notice Adds liquidity to an initialized pool /// @dev Reverts if the returned amount0 is less than amount0Min or if amount1 is less than amount1Min /// @dev This function calls the mint function of the corresponding Uniswap pool, which in turn calls UniswapV3Callback /// @param amount0Desired The amount of token0 we would like to provide /// @param amount1Desired The amount of token1 we would like to provide /// @param amount0Min The minimum amount of token0 we want to provide /// @param amount1Min The minimum amount of token1 we want to provide /// @return liquidity The calculated liquidity we get for the token amounts we provided /// @return amount0 The amount of token0 we ended up providing /// @return amount1 The amount of token1 we ended up providing function _addLiquidity( uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min ) internal returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ) { (uint160 sqrtPriceX96, , , , , , ) = IUniswapV3Pool(pool).slot0(); liquidity = LiquidityAmounts.getLiquidityForAmounts(sqrtPriceX96, sqrtRatioAX96, sqrtRatioBX96, amount0Desired, amount1Desired); (amount0, amount1) = IUniswapV3Pool(pool).mint( address(this), _TICK_LOWER, _TICK_UPPER, liquidity, abi.encode(MintCallbackData({_poolKey: _poolKey, payer: msg.sender})) ); if (amount0 < amount0Min || amount1 < amount1Min) revert ExcessiveSlippage(); } /// @notice Transfers the passed-in token from the payer to the recipient for the corresponding value /// @param token The token to be transferred to the recipient /// @param from The address of the payer /// @param to The address of the passed-in tokens recipient /// @param value How much of that token to be transferred from payer to the recipient function _pay( address token, address from, address to, uint256 value ) internal { _safeTransferFrom(token, from, to, value); } /// @notice Mints Keep3r credits to the passed-in address of recipient and increases total supply of Keep3r credits by the corresponding amount /// @param to The recipient of the Keep3r credits /// @param amount The amount Keep3r credits to be minted to the recipient function _mint(address to, uint256 amount) internal { totalSupply += amount; balanceOf[to] += amount; emit Transfer(address(0), to, amount); } /// @notice Burns Keep3r credits to the passed-in address of recipient and reduces total supply of Keep3r credits by the corresponding amount /// @param to The address that will get its Keep3r credits burned /// @param amount The amount Keep3r credits to be burned from the recipient/recipient function _burn(address to, uint256 amount) internal { totalSupply -= amount; balanceOf[to] -= amount; emit Transfer(to, address(0), amount); } /// @notice Transfers amount of Keep3r credits between two addresses /// @param from The user that transfers the Keep3r credits /// @param to The user that receives the Keep3r credits /// @param amount The amount of Keep3r credits to be transferred function _transferTokens( address from, address to, uint256 amount ) internal { balanceOf[from] -= amount; balanceOf[to] += amount; emit Transfer(from, to, amount); } /// @notice Transfers the passed-in token from the specified "from" to the specified "to" for the corresponding value /// @dev Reverts with IUniV3PairManager#UnsuccessfulTransfer if the transfer was not successful, /// or if the passed data length is different than 0 and the decoded data is not a boolean /// @param token The token to be transferred to the specified "to" /// @param from The address which is going to transfer the tokens /// @param value How much of that token to be transferred from "from" to "to" function _safeTransferFrom( address token, address from, address to, uint256 value ) internal { // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) revert UnsuccessfulTransfer(); } }
transfer
function transfer(address to, uint256 amount) external override returns (bool) { _transferTokens(msg.sender, to, amount); return true; }
/// @inheritdoc IERC20
NatSpecSingleLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 4738, 4886 ] }
7,609
UniV3PairManagerFactory
solidity/contracts/UniV3PairManager.sol
0x005634cfef45e5a19c84aede6f0af17833471852
Solidity
UniV3PairManager
contract UniV3PairManager is IUniV3PairManager, Governable { /// @inheritdoc IERC20Metadata string public override name; /// @inheritdoc IERC20Metadata string public override symbol; /// @inheritdoc IERC20 uint256 public override totalSupply = 0; /// @inheritdoc IPairManager address public immutable override token0; /// @inheritdoc IPairManager address public immutable override token1; /// @inheritdoc IPairManager address public immutable override pool; /// @inheritdoc IUniV3PairManager uint24 public immutable override fee; /// @inheritdoc IUniV3PairManager uint160 public immutable override sqrtRatioAX96; /// @inheritdoc IUniV3PairManager uint160 public immutable override sqrtRatioBX96; /// @notice Lowest possible tick in the Uniswap's curve int24 private constant _TICK_LOWER = -887200; /// @notice Highest possible tick in the Uniswap's curve int24 private constant _TICK_UPPER = 887200; /// @inheritdoc IERC20Metadata //solhint-disable-next-line const-name-snakecase uint8 public constant override decimals = 18; /// @inheritdoc IERC20 mapping(address => mapping(address => uint256)) public override allowance; /// @inheritdoc IERC20 mapping(address => uint256) public override balanceOf; /// @notice Struct that contains token0, token1, and fee of the Uniswap pool PoolAddress.PoolKey private _poolKey; constructor(address _pool, address _governance) Governable(_governance) { pool = _pool; uint24 _fee = IUniswapV3Pool(_pool).fee(); fee = _fee; address _token0 = IUniswapV3Pool(_pool).token0(); address _token1 = IUniswapV3Pool(_pool).token1(); token0 = _token0; token1 = _token1; name = string(abi.encodePacked('Keep3rLP - ', ERC20(_token0).symbol(), '/', ERC20(_token1).symbol())); symbol = string(abi.encodePacked('kLP-', ERC20(_token0).symbol(), '/', ERC20(_token1).symbol())); sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(_TICK_LOWER); sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(_TICK_UPPER); _poolKey = PoolAddress.PoolKey({token0: _token0, token1: _token1, fee: _fee}); } // This low-level function should be called from a contract which performs important safety checks /// @inheritdoc IUniV3PairManager function mint( uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min, address to ) external override returns (uint128 liquidity) { (liquidity, , ) = _addLiquidity(amount0Desired, amount1Desired, amount0Min, amount1Min); _mint(to, liquidity); } /// @inheritdoc IUniV3PairManager function uniswapV3MintCallback( uint256 amount0Owed, uint256 amount1Owed, bytes calldata data ) external override { MintCallbackData memory decoded = abi.decode(data, (MintCallbackData)); if (msg.sender != pool) revert OnlyPool(); if (amount0Owed > 0) _pay(decoded._poolKey.token0, decoded.payer, pool, amount0Owed); if (amount1Owed > 0) _pay(decoded._poolKey.token1, decoded.payer, pool, amount1Owed); } /// @inheritdoc IUniV3PairManager function burn( uint128 liquidity, uint256 amount0Min, uint256 amount1Min, address to ) external override returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = IUniswapV3Pool(pool).burn(_TICK_LOWER, _TICK_UPPER, liquidity); if (amount0 < amount0Min || amount1 < amount1Min) revert ExcessiveSlippage(); IUniswapV3Pool(pool).collect(to, _TICK_LOWER, _TICK_UPPER, uint128(amount0), uint128(amount1)); _burn(msg.sender, liquidity); } /// @inheritdoc IUniV3PairManager function collect() external override onlyGovernance returns (uint256 amount0, uint256 amount1) { (, , , uint128 tokensOwed0, uint128 tokensOwed1) = IUniswapV3Pool(pool).positions( keccak256(abi.encodePacked(address(this), _TICK_LOWER, _TICK_UPPER)) ); (amount0, amount1) = IUniswapV3Pool(pool).collect(governance, _TICK_LOWER, _TICK_UPPER, tokensOwed0, tokensOwed1); } /// @inheritdoc IUniV3PairManager function position() external view override returns ( uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ) { (liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128, tokensOwed0, tokensOwed1) = IUniswapV3Pool(pool).positions( keccak256(abi.encodePacked(address(this), _TICK_LOWER, _TICK_UPPER)) ); } /// @inheritdoc IERC20 function approve(address spender, uint256 amount) external override returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /// @inheritdoc IERC20 function transfer(address to, uint256 amount) external override returns (bool) { _transferTokens(msg.sender, to, amount); return true; } /// @inheritdoc IERC20 function transferFrom( address from, address to, uint256 amount ) external override returns (bool) { address spender = msg.sender; uint256 spenderAllowance = allowance[from][spender]; if (spender != from && spenderAllowance != type(uint256).max) { uint256 newAllowance = spenderAllowance - amount; allowance[from][spender] = newAllowance; emit Approval(from, spender, newAllowance); } _transferTokens(from, to, amount); return true; } /// @notice Adds liquidity to an initialized pool /// @dev Reverts if the returned amount0 is less than amount0Min or if amount1 is less than amount1Min /// @dev This function calls the mint function of the corresponding Uniswap pool, which in turn calls UniswapV3Callback /// @param amount0Desired The amount of token0 we would like to provide /// @param amount1Desired The amount of token1 we would like to provide /// @param amount0Min The minimum amount of token0 we want to provide /// @param amount1Min The minimum amount of token1 we want to provide /// @return liquidity The calculated liquidity we get for the token amounts we provided /// @return amount0 The amount of token0 we ended up providing /// @return amount1 The amount of token1 we ended up providing function _addLiquidity( uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min ) internal returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ) { (uint160 sqrtPriceX96, , , , , , ) = IUniswapV3Pool(pool).slot0(); liquidity = LiquidityAmounts.getLiquidityForAmounts(sqrtPriceX96, sqrtRatioAX96, sqrtRatioBX96, amount0Desired, amount1Desired); (amount0, amount1) = IUniswapV3Pool(pool).mint( address(this), _TICK_LOWER, _TICK_UPPER, liquidity, abi.encode(MintCallbackData({_poolKey: _poolKey, payer: msg.sender})) ); if (amount0 < amount0Min || amount1 < amount1Min) revert ExcessiveSlippage(); } /// @notice Transfers the passed-in token from the payer to the recipient for the corresponding value /// @param token The token to be transferred to the recipient /// @param from The address of the payer /// @param to The address of the passed-in tokens recipient /// @param value How much of that token to be transferred from payer to the recipient function _pay( address token, address from, address to, uint256 value ) internal { _safeTransferFrom(token, from, to, value); } /// @notice Mints Keep3r credits to the passed-in address of recipient and increases total supply of Keep3r credits by the corresponding amount /// @param to The recipient of the Keep3r credits /// @param amount The amount Keep3r credits to be minted to the recipient function _mint(address to, uint256 amount) internal { totalSupply += amount; balanceOf[to] += amount; emit Transfer(address(0), to, amount); } /// @notice Burns Keep3r credits to the passed-in address of recipient and reduces total supply of Keep3r credits by the corresponding amount /// @param to The address that will get its Keep3r credits burned /// @param amount The amount Keep3r credits to be burned from the recipient/recipient function _burn(address to, uint256 amount) internal { totalSupply -= amount; balanceOf[to] -= amount; emit Transfer(to, address(0), amount); } /// @notice Transfers amount of Keep3r credits between two addresses /// @param from The user that transfers the Keep3r credits /// @param to The user that receives the Keep3r credits /// @param amount The amount of Keep3r credits to be transferred function _transferTokens( address from, address to, uint256 amount ) internal { balanceOf[from] -= amount; balanceOf[to] += amount; emit Transfer(from, to, amount); } /// @notice Transfers the passed-in token from the specified "from" to the specified "to" for the corresponding value /// @dev Reverts with IUniV3PairManager#UnsuccessfulTransfer if the transfer was not successful, /// or if the passed data length is different than 0 and the decoded data is not a boolean /// @param token The token to be transferred to the specified "to" /// @param from The address which is going to transfer the tokens /// @param value How much of that token to be transferred from "from" to "to" function _safeTransferFrom( address token, address from, address to, uint256 value ) internal { // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) revert UnsuccessfulTransfer(); } }
transferFrom
function transferFrom( address from, address to, uint256 amount ) external override returns (bool) { address spender = msg.sender; uint256 spenderAllowance = allowance[from][spender]; if (spender != from && spenderAllowance != type(uint256).max) { uint256 newAllowance = spenderAllowance - amount; allowance[from][spender] = newAllowance; emit Approval(from, spender, newAllowance); } _transferTokens(from, to, amount); return true; }
/// @inheritdoc IERC20
NatSpecSingleLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 4913, 5410 ] }
7,610
UniV3PairManagerFactory
solidity/contracts/UniV3PairManager.sol
0x005634cfef45e5a19c84aede6f0af17833471852
Solidity
UniV3PairManager
contract UniV3PairManager is IUniV3PairManager, Governable { /// @inheritdoc IERC20Metadata string public override name; /// @inheritdoc IERC20Metadata string public override symbol; /// @inheritdoc IERC20 uint256 public override totalSupply = 0; /// @inheritdoc IPairManager address public immutable override token0; /// @inheritdoc IPairManager address public immutable override token1; /// @inheritdoc IPairManager address public immutable override pool; /// @inheritdoc IUniV3PairManager uint24 public immutable override fee; /// @inheritdoc IUniV3PairManager uint160 public immutable override sqrtRatioAX96; /// @inheritdoc IUniV3PairManager uint160 public immutable override sqrtRatioBX96; /// @notice Lowest possible tick in the Uniswap's curve int24 private constant _TICK_LOWER = -887200; /// @notice Highest possible tick in the Uniswap's curve int24 private constant _TICK_UPPER = 887200; /// @inheritdoc IERC20Metadata //solhint-disable-next-line const-name-snakecase uint8 public constant override decimals = 18; /// @inheritdoc IERC20 mapping(address => mapping(address => uint256)) public override allowance; /// @inheritdoc IERC20 mapping(address => uint256) public override balanceOf; /// @notice Struct that contains token0, token1, and fee of the Uniswap pool PoolAddress.PoolKey private _poolKey; constructor(address _pool, address _governance) Governable(_governance) { pool = _pool; uint24 _fee = IUniswapV3Pool(_pool).fee(); fee = _fee; address _token0 = IUniswapV3Pool(_pool).token0(); address _token1 = IUniswapV3Pool(_pool).token1(); token0 = _token0; token1 = _token1; name = string(abi.encodePacked('Keep3rLP - ', ERC20(_token0).symbol(), '/', ERC20(_token1).symbol())); symbol = string(abi.encodePacked('kLP-', ERC20(_token0).symbol(), '/', ERC20(_token1).symbol())); sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(_TICK_LOWER); sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(_TICK_UPPER); _poolKey = PoolAddress.PoolKey({token0: _token0, token1: _token1, fee: _fee}); } // This low-level function should be called from a contract which performs important safety checks /// @inheritdoc IUniV3PairManager function mint( uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min, address to ) external override returns (uint128 liquidity) { (liquidity, , ) = _addLiquidity(amount0Desired, amount1Desired, amount0Min, amount1Min); _mint(to, liquidity); } /// @inheritdoc IUniV3PairManager function uniswapV3MintCallback( uint256 amount0Owed, uint256 amount1Owed, bytes calldata data ) external override { MintCallbackData memory decoded = abi.decode(data, (MintCallbackData)); if (msg.sender != pool) revert OnlyPool(); if (amount0Owed > 0) _pay(decoded._poolKey.token0, decoded.payer, pool, amount0Owed); if (amount1Owed > 0) _pay(decoded._poolKey.token1, decoded.payer, pool, amount1Owed); } /// @inheritdoc IUniV3PairManager function burn( uint128 liquidity, uint256 amount0Min, uint256 amount1Min, address to ) external override returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = IUniswapV3Pool(pool).burn(_TICK_LOWER, _TICK_UPPER, liquidity); if (amount0 < amount0Min || amount1 < amount1Min) revert ExcessiveSlippage(); IUniswapV3Pool(pool).collect(to, _TICK_LOWER, _TICK_UPPER, uint128(amount0), uint128(amount1)); _burn(msg.sender, liquidity); } /// @inheritdoc IUniV3PairManager function collect() external override onlyGovernance returns (uint256 amount0, uint256 amount1) { (, , , uint128 tokensOwed0, uint128 tokensOwed1) = IUniswapV3Pool(pool).positions( keccak256(abi.encodePacked(address(this), _TICK_LOWER, _TICK_UPPER)) ); (amount0, amount1) = IUniswapV3Pool(pool).collect(governance, _TICK_LOWER, _TICK_UPPER, tokensOwed0, tokensOwed1); } /// @inheritdoc IUniV3PairManager function position() external view override returns ( uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ) { (liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128, tokensOwed0, tokensOwed1) = IUniswapV3Pool(pool).positions( keccak256(abi.encodePacked(address(this), _TICK_LOWER, _TICK_UPPER)) ); } /// @inheritdoc IERC20 function approve(address spender, uint256 amount) external override returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /// @inheritdoc IERC20 function transfer(address to, uint256 amount) external override returns (bool) { _transferTokens(msg.sender, to, amount); return true; } /// @inheritdoc IERC20 function transferFrom( address from, address to, uint256 amount ) external override returns (bool) { address spender = msg.sender; uint256 spenderAllowance = allowance[from][spender]; if (spender != from && spenderAllowance != type(uint256).max) { uint256 newAllowance = spenderAllowance - amount; allowance[from][spender] = newAllowance; emit Approval(from, spender, newAllowance); } _transferTokens(from, to, amount); return true; } /// @notice Adds liquidity to an initialized pool /// @dev Reverts if the returned amount0 is less than amount0Min or if amount1 is less than amount1Min /// @dev This function calls the mint function of the corresponding Uniswap pool, which in turn calls UniswapV3Callback /// @param amount0Desired The amount of token0 we would like to provide /// @param amount1Desired The amount of token1 we would like to provide /// @param amount0Min The minimum amount of token0 we want to provide /// @param amount1Min The minimum amount of token1 we want to provide /// @return liquidity The calculated liquidity we get for the token amounts we provided /// @return amount0 The amount of token0 we ended up providing /// @return amount1 The amount of token1 we ended up providing function _addLiquidity( uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min ) internal returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ) { (uint160 sqrtPriceX96, , , , , , ) = IUniswapV3Pool(pool).slot0(); liquidity = LiquidityAmounts.getLiquidityForAmounts(sqrtPriceX96, sqrtRatioAX96, sqrtRatioBX96, amount0Desired, amount1Desired); (amount0, amount1) = IUniswapV3Pool(pool).mint( address(this), _TICK_LOWER, _TICK_UPPER, liquidity, abi.encode(MintCallbackData({_poolKey: _poolKey, payer: msg.sender})) ); if (amount0 < amount0Min || amount1 < amount1Min) revert ExcessiveSlippage(); } /// @notice Transfers the passed-in token from the payer to the recipient for the corresponding value /// @param token The token to be transferred to the recipient /// @param from The address of the payer /// @param to The address of the passed-in tokens recipient /// @param value How much of that token to be transferred from payer to the recipient function _pay( address token, address from, address to, uint256 value ) internal { _safeTransferFrom(token, from, to, value); } /// @notice Mints Keep3r credits to the passed-in address of recipient and increases total supply of Keep3r credits by the corresponding amount /// @param to The recipient of the Keep3r credits /// @param amount The amount Keep3r credits to be minted to the recipient function _mint(address to, uint256 amount) internal { totalSupply += amount; balanceOf[to] += amount; emit Transfer(address(0), to, amount); } /// @notice Burns Keep3r credits to the passed-in address of recipient and reduces total supply of Keep3r credits by the corresponding amount /// @param to The address that will get its Keep3r credits burned /// @param amount The amount Keep3r credits to be burned from the recipient/recipient function _burn(address to, uint256 amount) internal { totalSupply -= amount; balanceOf[to] -= amount; emit Transfer(to, address(0), amount); } /// @notice Transfers amount of Keep3r credits between two addresses /// @param from The user that transfers the Keep3r credits /// @param to The user that receives the Keep3r credits /// @param amount The amount of Keep3r credits to be transferred function _transferTokens( address from, address to, uint256 amount ) internal { balanceOf[from] -= amount; balanceOf[to] += amount; emit Transfer(from, to, amount); } /// @notice Transfers the passed-in token from the specified "from" to the specified "to" for the corresponding value /// @dev Reverts with IUniV3PairManager#UnsuccessfulTransfer if the transfer was not successful, /// or if the passed data length is different than 0 and the decoded data is not a boolean /// @param token The token to be transferred to the specified "to" /// @param from The address which is going to transfer the tokens /// @param value How much of that token to be transferred from "from" to "to" function _safeTransferFrom( address token, address from, address to, uint256 value ) internal { // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) revert UnsuccessfulTransfer(); } }
_addLiquidity
function _addLiquidity( uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min ) internal returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ) { (uint160 sqrtPriceX96, , , , , , ) = IUniswapV3Pool(pool).slot0(); liquidity = LiquidityAmounts.getLiquidityForAmounts(sqrtPriceX96, sqrtRatioAX96, sqrtRatioBX96, amount0Desired, amount1Desired); (amount0, amount1) = IUniswapV3Pool(pool).mint( address(this), _TICK_LOWER, _TICK_UPPER, liquidity, abi.encode(MintCallbackData({_poolKey: _poolKey, payer: msg.sender})) ); if (amount0 < amount0Min || amount1 < amount1Min) revert ExcessiveSlippage(); }
/// @notice Adds liquidity to an initialized pool /// @dev Reverts if the returned amount0 is less than amount0Min or if amount1 is less than amount1Min /// @dev This function calls the mint function of the corresponding Uniswap pool, which in turn calls UniswapV3Callback /// @param amount0Desired The amount of token0 we would like to provide /// @param amount1Desired The amount of token1 we would like to provide /// @param amount0Min The minimum amount of token0 we want to provide /// @param amount1Min The minimum amount of token1 we want to provide /// @return liquidity The calculated liquidity we get for the token amounts we provided /// @return amount0 The amount of token0 we ended up providing /// @return amount1 The amount of token1 we ended up providing
NatSpecSingleLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 6203, 6946 ] }
7,611
UniV3PairManagerFactory
solidity/contracts/UniV3PairManager.sol
0x005634cfef45e5a19c84aede6f0af17833471852
Solidity
UniV3PairManager
contract UniV3PairManager is IUniV3PairManager, Governable { /// @inheritdoc IERC20Metadata string public override name; /// @inheritdoc IERC20Metadata string public override symbol; /// @inheritdoc IERC20 uint256 public override totalSupply = 0; /// @inheritdoc IPairManager address public immutable override token0; /// @inheritdoc IPairManager address public immutable override token1; /// @inheritdoc IPairManager address public immutable override pool; /// @inheritdoc IUniV3PairManager uint24 public immutable override fee; /// @inheritdoc IUniV3PairManager uint160 public immutable override sqrtRatioAX96; /// @inheritdoc IUniV3PairManager uint160 public immutable override sqrtRatioBX96; /// @notice Lowest possible tick in the Uniswap's curve int24 private constant _TICK_LOWER = -887200; /// @notice Highest possible tick in the Uniswap's curve int24 private constant _TICK_UPPER = 887200; /// @inheritdoc IERC20Metadata //solhint-disable-next-line const-name-snakecase uint8 public constant override decimals = 18; /// @inheritdoc IERC20 mapping(address => mapping(address => uint256)) public override allowance; /// @inheritdoc IERC20 mapping(address => uint256) public override balanceOf; /// @notice Struct that contains token0, token1, and fee of the Uniswap pool PoolAddress.PoolKey private _poolKey; constructor(address _pool, address _governance) Governable(_governance) { pool = _pool; uint24 _fee = IUniswapV3Pool(_pool).fee(); fee = _fee; address _token0 = IUniswapV3Pool(_pool).token0(); address _token1 = IUniswapV3Pool(_pool).token1(); token0 = _token0; token1 = _token1; name = string(abi.encodePacked('Keep3rLP - ', ERC20(_token0).symbol(), '/', ERC20(_token1).symbol())); symbol = string(abi.encodePacked('kLP-', ERC20(_token0).symbol(), '/', ERC20(_token1).symbol())); sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(_TICK_LOWER); sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(_TICK_UPPER); _poolKey = PoolAddress.PoolKey({token0: _token0, token1: _token1, fee: _fee}); } // This low-level function should be called from a contract which performs important safety checks /// @inheritdoc IUniV3PairManager function mint( uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min, address to ) external override returns (uint128 liquidity) { (liquidity, , ) = _addLiquidity(amount0Desired, amount1Desired, amount0Min, amount1Min); _mint(to, liquidity); } /// @inheritdoc IUniV3PairManager function uniswapV3MintCallback( uint256 amount0Owed, uint256 amount1Owed, bytes calldata data ) external override { MintCallbackData memory decoded = abi.decode(data, (MintCallbackData)); if (msg.sender != pool) revert OnlyPool(); if (amount0Owed > 0) _pay(decoded._poolKey.token0, decoded.payer, pool, amount0Owed); if (amount1Owed > 0) _pay(decoded._poolKey.token1, decoded.payer, pool, amount1Owed); } /// @inheritdoc IUniV3PairManager function burn( uint128 liquidity, uint256 amount0Min, uint256 amount1Min, address to ) external override returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = IUniswapV3Pool(pool).burn(_TICK_LOWER, _TICK_UPPER, liquidity); if (amount0 < amount0Min || amount1 < amount1Min) revert ExcessiveSlippage(); IUniswapV3Pool(pool).collect(to, _TICK_LOWER, _TICK_UPPER, uint128(amount0), uint128(amount1)); _burn(msg.sender, liquidity); } /// @inheritdoc IUniV3PairManager function collect() external override onlyGovernance returns (uint256 amount0, uint256 amount1) { (, , , uint128 tokensOwed0, uint128 tokensOwed1) = IUniswapV3Pool(pool).positions( keccak256(abi.encodePacked(address(this), _TICK_LOWER, _TICK_UPPER)) ); (amount0, amount1) = IUniswapV3Pool(pool).collect(governance, _TICK_LOWER, _TICK_UPPER, tokensOwed0, tokensOwed1); } /// @inheritdoc IUniV3PairManager function position() external view override returns ( uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ) { (liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128, tokensOwed0, tokensOwed1) = IUniswapV3Pool(pool).positions( keccak256(abi.encodePacked(address(this), _TICK_LOWER, _TICK_UPPER)) ); } /// @inheritdoc IERC20 function approve(address spender, uint256 amount) external override returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /// @inheritdoc IERC20 function transfer(address to, uint256 amount) external override returns (bool) { _transferTokens(msg.sender, to, amount); return true; } /// @inheritdoc IERC20 function transferFrom( address from, address to, uint256 amount ) external override returns (bool) { address spender = msg.sender; uint256 spenderAllowance = allowance[from][spender]; if (spender != from && spenderAllowance != type(uint256).max) { uint256 newAllowance = spenderAllowance - amount; allowance[from][spender] = newAllowance; emit Approval(from, spender, newAllowance); } _transferTokens(from, to, amount); return true; } /// @notice Adds liquidity to an initialized pool /// @dev Reverts if the returned amount0 is less than amount0Min or if amount1 is less than amount1Min /// @dev This function calls the mint function of the corresponding Uniswap pool, which in turn calls UniswapV3Callback /// @param amount0Desired The amount of token0 we would like to provide /// @param amount1Desired The amount of token1 we would like to provide /// @param amount0Min The minimum amount of token0 we want to provide /// @param amount1Min The minimum amount of token1 we want to provide /// @return liquidity The calculated liquidity we get for the token amounts we provided /// @return amount0 The amount of token0 we ended up providing /// @return amount1 The amount of token1 we ended up providing function _addLiquidity( uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min ) internal returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ) { (uint160 sqrtPriceX96, , , , , , ) = IUniswapV3Pool(pool).slot0(); liquidity = LiquidityAmounts.getLiquidityForAmounts(sqrtPriceX96, sqrtRatioAX96, sqrtRatioBX96, amount0Desired, amount1Desired); (amount0, amount1) = IUniswapV3Pool(pool).mint( address(this), _TICK_LOWER, _TICK_UPPER, liquidity, abi.encode(MintCallbackData({_poolKey: _poolKey, payer: msg.sender})) ); if (amount0 < amount0Min || amount1 < amount1Min) revert ExcessiveSlippage(); } /// @notice Transfers the passed-in token from the payer to the recipient for the corresponding value /// @param token The token to be transferred to the recipient /// @param from The address of the payer /// @param to The address of the passed-in tokens recipient /// @param value How much of that token to be transferred from payer to the recipient function _pay( address token, address from, address to, uint256 value ) internal { _safeTransferFrom(token, from, to, value); } /// @notice Mints Keep3r credits to the passed-in address of recipient and increases total supply of Keep3r credits by the corresponding amount /// @param to The recipient of the Keep3r credits /// @param amount The amount Keep3r credits to be minted to the recipient function _mint(address to, uint256 amount) internal { totalSupply += amount; balanceOf[to] += amount; emit Transfer(address(0), to, amount); } /// @notice Burns Keep3r credits to the passed-in address of recipient and reduces total supply of Keep3r credits by the corresponding amount /// @param to The address that will get its Keep3r credits burned /// @param amount The amount Keep3r credits to be burned from the recipient/recipient function _burn(address to, uint256 amount) internal { totalSupply -= amount; balanceOf[to] -= amount; emit Transfer(to, address(0), amount); } /// @notice Transfers amount of Keep3r credits between two addresses /// @param from The user that transfers the Keep3r credits /// @param to The user that receives the Keep3r credits /// @param amount The amount of Keep3r credits to be transferred function _transferTokens( address from, address to, uint256 amount ) internal { balanceOf[from] -= amount; balanceOf[to] += amount; emit Transfer(from, to, amount); } /// @notice Transfers the passed-in token from the specified "from" to the specified "to" for the corresponding value /// @dev Reverts with IUniV3PairManager#UnsuccessfulTransfer if the transfer was not successful, /// or if the passed data length is different than 0 and the decoded data is not a boolean /// @param token The token to be transferred to the specified "to" /// @param from The address which is going to transfer the tokens /// @param value How much of that token to be transferred from "from" to "to" function _safeTransferFrom( address token, address from, address to, uint256 value ) internal { // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) revert UnsuccessfulTransfer(); } }
_pay
function _pay( address token, address from, address to, uint256 value ) internal { _safeTransferFrom(token, from, to, value); }
/// @notice Transfers the passed-in token from the payer to the recipient for the corresponding value /// @param token The token to be transferred to the recipient /// @param from The address of the payer /// @param to The address of the passed-in tokens recipient /// @param value How much of that token to be transferred from payer to the recipient
NatSpecSingleLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 7309, 7462 ] }
7,612
UniV3PairManagerFactory
solidity/contracts/UniV3PairManager.sol
0x005634cfef45e5a19c84aede6f0af17833471852
Solidity
UniV3PairManager
contract UniV3PairManager is IUniV3PairManager, Governable { /// @inheritdoc IERC20Metadata string public override name; /// @inheritdoc IERC20Metadata string public override symbol; /// @inheritdoc IERC20 uint256 public override totalSupply = 0; /// @inheritdoc IPairManager address public immutable override token0; /// @inheritdoc IPairManager address public immutable override token1; /// @inheritdoc IPairManager address public immutable override pool; /// @inheritdoc IUniV3PairManager uint24 public immutable override fee; /// @inheritdoc IUniV3PairManager uint160 public immutable override sqrtRatioAX96; /// @inheritdoc IUniV3PairManager uint160 public immutable override sqrtRatioBX96; /// @notice Lowest possible tick in the Uniswap's curve int24 private constant _TICK_LOWER = -887200; /// @notice Highest possible tick in the Uniswap's curve int24 private constant _TICK_UPPER = 887200; /// @inheritdoc IERC20Metadata //solhint-disable-next-line const-name-snakecase uint8 public constant override decimals = 18; /// @inheritdoc IERC20 mapping(address => mapping(address => uint256)) public override allowance; /// @inheritdoc IERC20 mapping(address => uint256) public override balanceOf; /// @notice Struct that contains token0, token1, and fee of the Uniswap pool PoolAddress.PoolKey private _poolKey; constructor(address _pool, address _governance) Governable(_governance) { pool = _pool; uint24 _fee = IUniswapV3Pool(_pool).fee(); fee = _fee; address _token0 = IUniswapV3Pool(_pool).token0(); address _token1 = IUniswapV3Pool(_pool).token1(); token0 = _token0; token1 = _token1; name = string(abi.encodePacked('Keep3rLP - ', ERC20(_token0).symbol(), '/', ERC20(_token1).symbol())); symbol = string(abi.encodePacked('kLP-', ERC20(_token0).symbol(), '/', ERC20(_token1).symbol())); sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(_TICK_LOWER); sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(_TICK_UPPER); _poolKey = PoolAddress.PoolKey({token0: _token0, token1: _token1, fee: _fee}); } // This low-level function should be called from a contract which performs important safety checks /// @inheritdoc IUniV3PairManager function mint( uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min, address to ) external override returns (uint128 liquidity) { (liquidity, , ) = _addLiquidity(amount0Desired, amount1Desired, amount0Min, amount1Min); _mint(to, liquidity); } /// @inheritdoc IUniV3PairManager function uniswapV3MintCallback( uint256 amount0Owed, uint256 amount1Owed, bytes calldata data ) external override { MintCallbackData memory decoded = abi.decode(data, (MintCallbackData)); if (msg.sender != pool) revert OnlyPool(); if (amount0Owed > 0) _pay(decoded._poolKey.token0, decoded.payer, pool, amount0Owed); if (amount1Owed > 0) _pay(decoded._poolKey.token1, decoded.payer, pool, amount1Owed); } /// @inheritdoc IUniV3PairManager function burn( uint128 liquidity, uint256 amount0Min, uint256 amount1Min, address to ) external override returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = IUniswapV3Pool(pool).burn(_TICK_LOWER, _TICK_UPPER, liquidity); if (amount0 < amount0Min || amount1 < amount1Min) revert ExcessiveSlippage(); IUniswapV3Pool(pool).collect(to, _TICK_LOWER, _TICK_UPPER, uint128(amount0), uint128(amount1)); _burn(msg.sender, liquidity); } /// @inheritdoc IUniV3PairManager function collect() external override onlyGovernance returns (uint256 amount0, uint256 amount1) { (, , , uint128 tokensOwed0, uint128 tokensOwed1) = IUniswapV3Pool(pool).positions( keccak256(abi.encodePacked(address(this), _TICK_LOWER, _TICK_UPPER)) ); (amount0, amount1) = IUniswapV3Pool(pool).collect(governance, _TICK_LOWER, _TICK_UPPER, tokensOwed0, tokensOwed1); } /// @inheritdoc IUniV3PairManager function position() external view override returns ( uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ) { (liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128, tokensOwed0, tokensOwed1) = IUniswapV3Pool(pool).positions( keccak256(abi.encodePacked(address(this), _TICK_LOWER, _TICK_UPPER)) ); } /// @inheritdoc IERC20 function approve(address spender, uint256 amount) external override returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /// @inheritdoc IERC20 function transfer(address to, uint256 amount) external override returns (bool) { _transferTokens(msg.sender, to, amount); return true; } /// @inheritdoc IERC20 function transferFrom( address from, address to, uint256 amount ) external override returns (bool) { address spender = msg.sender; uint256 spenderAllowance = allowance[from][spender]; if (spender != from && spenderAllowance != type(uint256).max) { uint256 newAllowance = spenderAllowance - amount; allowance[from][spender] = newAllowance; emit Approval(from, spender, newAllowance); } _transferTokens(from, to, amount); return true; } /// @notice Adds liquidity to an initialized pool /// @dev Reverts if the returned amount0 is less than amount0Min or if amount1 is less than amount1Min /// @dev This function calls the mint function of the corresponding Uniswap pool, which in turn calls UniswapV3Callback /// @param amount0Desired The amount of token0 we would like to provide /// @param amount1Desired The amount of token1 we would like to provide /// @param amount0Min The minimum amount of token0 we want to provide /// @param amount1Min The minimum amount of token1 we want to provide /// @return liquidity The calculated liquidity we get for the token amounts we provided /// @return amount0 The amount of token0 we ended up providing /// @return amount1 The amount of token1 we ended up providing function _addLiquidity( uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min ) internal returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ) { (uint160 sqrtPriceX96, , , , , , ) = IUniswapV3Pool(pool).slot0(); liquidity = LiquidityAmounts.getLiquidityForAmounts(sqrtPriceX96, sqrtRatioAX96, sqrtRatioBX96, amount0Desired, amount1Desired); (amount0, amount1) = IUniswapV3Pool(pool).mint( address(this), _TICK_LOWER, _TICK_UPPER, liquidity, abi.encode(MintCallbackData({_poolKey: _poolKey, payer: msg.sender})) ); if (amount0 < amount0Min || amount1 < amount1Min) revert ExcessiveSlippage(); } /// @notice Transfers the passed-in token from the payer to the recipient for the corresponding value /// @param token The token to be transferred to the recipient /// @param from The address of the payer /// @param to The address of the passed-in tokens recipient /// @param value How much of that token to be transferred from payer to the recipient function _pay( address token, address from, address to, uint256 value ) internal { _safeTransferFrom(token, from, to, value); } /// @notice Mints Keep3r credits to the passed-in address of recipient and increases total supply of Keep3r credits by the corresponding amount /// @param to The recipient of the Keep3r credits /// @param amount The amount Keep3r credits to be minted to the recipient function _mint(address to, uint256 amount) internal { totalSupply += amount; balanceOf[to] += amount; emit Transfer(address(0), to, amount); } /// @notice Burns Keep3r credits to the passed-in address of recipient and reduces total supply of Keep3r credits by the corresponding amount /// @param to The address that will get its Keep3r credits burned /// @param amount The amount Keep3r credits to be burned from the recipient/recipient function _burn(address to, uint256 amount) internal { totalSupply -= amount; balanceOf[to] -= amount; emit Transfer(to, address(0), amount); } /// @notice Transfers amount of Keep3r credits between two addresses /// @param from The user that transfers the Keep3r credits /// @param to The user that receives the Keep3r credits /// @param amount The amount of Keep3r credits to be transferred function _transferTokens( address from, address to, uint256 amount ) internal { balanceOf[from] -= amount; balanceOf[to] += amount; emit Transfer(from, to, amount); } /// @notice Transfers the passed-in token from the specified "from" to the specified "to" for the corresponding value /// @dev Reverts with IUniV3PairManager#UnsuccessfulTransfer if the transfer was not successful, /// or if the passed data length is different than 0 and the decoded data is not a boolean /// @param token The token to be transferred to the specified "to" /// @param from The address which is going to transfer the tokens /// @param value How much of that token to be transferred from "from" to "to" function _safeTransferFrom( address token, address from, address to, uint256 value ) internal { // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) revert UnsuccessfulTransfer(); } }
_mint
function _mint(address to, uint256 amount) internal { totalSupply += amount; balanceOf[to] += amount; emit Transfer(address(0), to, amount); }
/// @notice Mints Keep3r credits to the passed-in address of recipient and increases total supply of Keep3r credits by the corresponding amount /// @param to The recipient of the Keep3r credits /// @param amount The amount Keep3r credits to be minted to the recipient
NatSpecSingleLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 7738, 7896 ] }
7,613
UniV3PairManagerFactory
solidity/contracts/UniV3PairManager.sol
0x005634cfef45e5a19c84aede6f0af17833471852
Solidity
UniV3PairManager
contract UniV3PairManager is IUniV3PairManager, Governable { /// @inheritdoc IERC20Metadata string public override name; /// @inheritdoc IERC20Metadata string public override symbol; /// @inheritdoc IERC20 uint256 public override totalSupply = 0; /// @inheritdoc IPairManager address public immutable override token0; /// @inheritdoc IPairManager address public immutable override token1; /// @inheritdoc IPairManager address public immutable override pool; /// @inheritdoc IUniV3PairManager uint24 public immutable override fee; /// @inheritdoc IUniV3PairManager uint160 public immutable override sqrtRatioAX96; /// @inheritdoc IUniV3PairManager uint160 public immutable override sqrtRatioBX96; /// @notice Lowest possible tick in the Uniswap's curve int24 private constant _TICK_LOWER = -887200; /// @notice Highest possible tick in the Uniswap's curve int24 private constant _TICK_UPPER = 887200; /// @inheritdoc IERC20Metadata //solhint-disable-next-line const-name-snakecase uint8 public constant override decimals = 18; /// @inheritdoc IERC20 mapping(address => mapping(address => uint256)) public override allowance; /// @inheritdoc IERC20 mapping(address => uint256) public override balanceOf; /// @notice Struct that contains token0, token1, and fee of the Uniswap pool PoolAddress.PoolKey private _poolKey; constructor(address _pool, address _governance) Governable(_governance) { pool = _pool; uint24 _fee = IUniswapV3Pool(_pool).fee(); fee = _fee; address _token0 = IUniswapV3Pool(_pool).token0(); address _token1 = IUniswapV3Pool(_pool).token1(); token0 = _token0; token1 = _token1; name = string(abi.encodePacked('Keep3rLP - ', ERC20(_token0).symbol(), '/', ERC20(_token1).symbol())); symbol = string(abi.encodePacked('kLP-', ERC20(_token0).symbol(), '/', ERC20(_token1).symbol())); sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(_TICK_LOWER); sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(_TICK_UPPER); _poolKey = PoolAddress.PoolKey({token0: _token0, token1: _token1, fee: _fee}); } // This low-level function should be called from a contract which performs important safety checks /// @inheritdoc IUniV3PairManager function mint( uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min, address to ) external override returns (uint128 liquidity) { (liquidity, , ) = _addLiquidity(amount0Desired, amount1Desired, amount0Min, amount1Min); _mint(to, liquidity); } /// @inheritdoc IUniV3PairManager function uniswapV3MintCallback( uint256 amount0Owed, uint256 amount1Owed, bytes calldata data ) external override { MintCallbackData memory decoded = abi.decode(data, (MintCallbackData)); if (msg.sender != pool) revert OnlyPool(); if (amount0Owed > 0) _pay(decoded._poolKey.token0, decoded.payer, pool, amount0Owed); if (amount1Owed > 0) _pay(decoded._poolKey.token1, decoded.payer, pool, amount1Owed); } /// @inheritdoc IUniV3PairManager function burn( uint128 liquidity, uint256 amount0Min, uint256 amount1Min, address to ) external override returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = IUniswapV3Pool(pool).burn(_TICK_LOWER, _TICK_UPPER, liquidity); if (amount0 < amount0Min || amount1 < amount1Min) revert ExcessiveSlippage(); IUniswapV3Pool(pool).collect(to, _TICK_LOWER, _TICK_UPPER, uint128(amount0), uint128(amount1)); _burn(msg.sender, liquidity); } /// @inheritdoc IUniV3PairManager function collect() external override onlyGovernance returns (uint256 amount0, uint256 amount1) { (, , , uint128 tokensOwed0, uint128 tokensOwed1) = IUniswapV3Pool(pool).positions( keccak256(abi.encodePacked(address(this), _TICK_LOWER, _TICK_UPPER)) ); (amount0, amount1) = IUniswapV3Pool(pool).collect(governance, _TICK_LOWER, _TICK_UPPER, tokensOwed0, tokensOwed1); } /// @inheritdoc IUniV3PairManager function position() external view override returns ( uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ) { (liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128, tokensOwed0, tokensOwed1) = IUniswapV3Pool(pool).positions( keccak256(abi.encodePacked(address(this), _TICK_LOWER, _TICK_UPPER)) ); } /// @inheritdoc IERC20 function approve(address spender, uint256 amount) external override returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /// @inheritdoc IERC20 function transfer(address to, uint256 amount) external override returns (bool) { _transferTokens(msg.sender, to, amount); return true; } /// @inheritdoc IERC20 function transferFrom( address from, address to, uint256 amount ) external override returns (bool) { address spender = msg.sender; uint256 spenderAllowance = allowance[from][spender]; if (spender != from && spenderAllowance != type(uint256).max) { uint256 newAllowance = spenderAllowance - amount; allowance[from][spender] = newAllowance; emit Approval(from, spender, newAllowance); } _transferTokens(from, to, amount); return true; } /// @notice Adds liquidity to an initialized pool /// @dev Reverts if the returned amount0 is less than amount0Min or if amount1 is less than amount1Min /// @dev This function calls the mint function of the corresponding Uniswap pool, which in turn calls UniswapV3Callback /// @param amount0Desired The amount of token0 we would like to provide /// @param amount1Desired The amount of token1 we would like to provide /// @param amount0Min The minimum amount of token0 we want to provide /// @param amount1Min The minimum amount of token1 we want to provide /// @return liquidity The calculated liquidity we get for the token amounts we provided /// @return amount0 The amount of token0 we ended up providing /// @return amount1 The amount of token1 we ended up providing function _addLiquidity( uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min ) internal returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ) { (uint160 sqrtPriceX96, , , , , , ) = IUniswapV3Pool(pool).slot0(); liquidity = LiquidityAmounts.getLiquidityForAmounts(sqrtPriceX96, sqrtRatioAX96, sqrtRatioBX96, amount0Desired, amount1Desired); (amount0, amount1) = IUniswapV3Pool(pool).mint( address(this), _TICK_LOWER, _TICK_UPPER, liquidity, abi.encode(MintCallbackData({_poolKey: _poolKey, payer: msg.sender})) ); if (amount0 < amount0Min || amount1 < amount1Min) revert ExcessiveSlippage(); } /// @notice Transfers the passed-in token from the payer to the recipient for the corresponding value /// @param token The token to be transferred to the recipient /// @param from The address of the payer /// @param to The address of the passed-in tokens recipient /// @param value How much of that token to be transferred from payer to the recipient function _pay( address token, address from, address to, uint256 value ) internal { _safeTransferFrom(token, from, to, value); } /// @notice Mints Keep3r credits to the passed-in address of recipient and increases total supply of Keep3r credits by the corresponding amount /// @param to The recipient of the Keep3r credits /// @param amount The amount Keep3r credits to be minted to the recipient function _mint(address to, uint256 amount) internal { totalSupply += amount; balanceOf[to] += amount; emit Transfer(address(0), to, amount); } /// @notice Burns Keep3r credits to the passed-in address of recipient and reduces total supply of Keep3r credits by the corresponding amount /// @param to The address that will get its Keep3r credits burned /// @param amount The amount Keep3r credits to be burned from the recipient/recipient function _burn(address to, uint256 amount) internal { totalSupply -= amount; balanceOf[to] -= amount; emit Transfer(to, address(0), amount); } /// @notice Transfers amount of Keep3r credits between two addresses /// @param from The user that transfers the Keep3r credits /// @param to The user that receives the Keep3r credits /// @param amount The amount of Keep3r credits to be transferred function _transferTokens( address from, address to, uint256 amount ) internal { balanceOf[from] -= amount; balanceOf[to] += amount; emit Transfer(from, to, amount); } /// @notice Transfers the passed-in token from the specified "from" to the specified "to" for the corresponding value /// @dev Reverts with IUniV3PairManager#UnsuccessfulTransfer if the transfer was not successful, /// or if the passed data length is different than 0 and the decoded data is not a boolean /// @param token The token to be transferred to the specified "to" /// @param from The address which is going to transfer the tokens /// @param value How much of that token to be transferred from "from" to "to" function _safeTransferFrom( address token, address from, address to, uint256 value ) internal { // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) revert UnsuccessfulTransfer(); } }
_burn
function _burn(address to, uint256 amount) internal { totalSupply -= amount; balanceOf[to] -= amount; emit Transfer(to, address(0), amount); }
/// @notice Burns Keep3r credits to the passed-in address of recipient and reduces total supply of Keep3r credits by the corresponding amount /// @param to The address that will get its Keep3r credits burned /// @param amount The amount Keep3r credits to be burned from the recipient/recipient
NatSpecSingleLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 8198, 8356 ] }
7,614
UniV3PairManagerFactory
solidity/contracts/UniV3PairManager.sol
0x005634cfef45e5a19c84aede6f0af17833471852
Solidity
UniV3PairManager
contract UniV3PairManager is IUniV3PairManager, Governable { /// @inheritdoc IERC20Metadata string public override name; /// @inheritdoc IERC20Metadata string public override symbol; /// @inheritdoc IERC20 uint256 public override totalSupply = 0; /// @inheritdoc IPairManager address public immutable override token0; /// @inheritdoc IPairManager address public immutable override token1; /// @inheritdoc IPairManager address public immutable override pool; /// @inheritdoc IUniV3PairManager uint24 public immutable override fee; /// @inheritdoc IUniV3PairManager uint160 public immutable override sqrtRatioAX96; /// @inheritdoc IUniV3PairManager uint160 public immutable override sqrtRatioBX96; /// @notice Lowest possible tick in the Uniswap's curve int24 private constant _TICK_LOWER = -887200; /// @notice Highest possible tick in the Uniswap's curve int24 private constant _TICK_UPPER = 887200; /// @inheritdoc IERC20Metadata //solhint-disable-next-line const-name-snakecase uint8 public constant override decimals = 18; /// @inheritdoc IERC20 mapping(address => mapping(address => uint256)) public override allowance; /// @inheritdoc IERC20 mapping(address => uint256) public override balanceOf; /// @notice Struct that contains token0, token1, and fee of the Uniswap pool PoolAddress.PoolKey private _poolKey; constructor(address _pool, address _governance) Governable(_governance) { pool = _pool; uint24 _fee = IUniswapV3Pool(_pool).fee(); fee = _fee; address _token0 = IUniswapV3Pool(_pool).token0(); address _token1 = IUniswapV3Pool(_pool).token1(); token0 = _token0; token1 = _token1; name = string(abi.encodePacked('Keep3rLP - ', ERC20(_token0).symbol(), '/', ERC20(_token1).symbol())); symbol = string(abi.encodePacked('kLP-', ERC20(_token0).symbol(), '/', ERC20(_token1).symbol())); sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(_TICK_LOWER); sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(_TICK_UPPER); _poolKey = PoolAddress.PoolKey({token0: _token0, token1: _token1, fee: _fee}); } // This low-level function should be called from a contract which performs important safety checks /// @inheritdoc IUniV3PairManager function mint( uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min, address to ) external override returns (uint128 liquidity) { (liquidity, , ) = _addLiquidity(amount0Desired, amount1Desired, amount0Min, amount1Min); _mint(to, liquidity); } /// @inheritdoc IUniV3PairManager function uniswapV3MintCallback( uint256 amount0Owed, uint256 amount1Owed, bytes calldata data ) external override { MintCallbackData memory decoded = abi.decode(data, (MintCallbackData)); if (msg.sender != pool) revert OnlyPool(); if (amount0Owed > 0) _pay(decoded._poolKey.token0, decoded.payer, pool, amount0Owed); if (amount1Owed > 0) _pay(decoded._poolKey.token1, decoded.payer, pool, amount1Owed); } /// @inheritdoc IUniV3PairManager function burn( uint128 liquidity, uint256 amount0Min, uint256 amount1Min, address to ) external override returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = IUniswapV3Pool(pool).burn(_TICK_LOWER, _TICK_UPPER, liquidity); if (amount0 < amount0Min || amount1 < amount1Min) revert ExcessiveSlippage(); IUniswapV3Pool(pool).collect(to, _TICK_LOWER, _TICK_UPPER, uint128(amount0), uint128(amount1)); _burn(msg.sender, liquidity); } /// @inheritdoc IUniV3PairManager function collect() external override onlyGovernance returns (uint256 amount0, uint256 amount1) { (, , , uint128 tokensOwed0, uint128 tokensOwed1) = IUniswapV3Pool(pool).positions( keccak256(abi.encodePacked(address(this), _TICK_LOWER, _TICK_UPPER)) ); (amount0, amount1) = IUniswapV3Pool(pool).collect(governance, _TICK_LOWER, _TICK_UPPER, tokensOwed0, tokensOwed1); } /// @inheritdoc IUniV3PairManager function position() external view override returns ( uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ) { (liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128, tokensOwed0, tokensOwed1) = IUniswapV3Pool(pool).positions( keccak256(abi.encodePacked(address(this), _TICK_LOWER, _TICK_UPPER)) ); } /// @inheritdoc IERC20 function approve(address spender, uint256 amount) external override returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /// @inheritdoc IERC20 function transfer(address to, uint256 amount) external override returns (bool) { _transferTokens(msg.sender, to, amount); return true; } /// @inheritdoc IERC20 function transferFrom( address from, address to, uint256 amount ) external override returns (bool) { address spender = msg.sender; uint256 spenderAllowance = allowance[from][spender]; if (spender != from && spenderAllowance != type(uint256).max) { uint256 newAllowance = spenderAllowance - amount; allowance[from][spender] = newAllowance; emit Approval(from, spender, newAllowance); } _transferTokens(from, to, amount); return true; } /// @notice Adds liquidity to an initialized pool /// @dev Reverts if the returned amount0 is less than amount0Min or if amount1 is less than amount1Min /// @dev This function calls the mint function of the corresponding Uniswap pool, which in turn calls UniswapV3Callback /// @param amount0Desired The amount of token0 we would like to provide /// @param amount1Desired The amount of token1 we would like to provide /// @param amount0Min The minimum amount of token0 we want to provide /// @param amount1Min The minimum amount of token1 we want to provide /// @return liquidity The calculated liquidity we get for the token amounts we provided /// @return amount0 The amount of token0 we ended up providing /// @return amount1 The amount of token1 we ended up providing function _addLiquidity( uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min ) internal returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ) { (uint160 sqrtPriceX96, , , , , , ) = IUniswapV3Pool(pool).slot0(); liquidity = LiquidityAmounts.getLiquidityForAmounts(sqrtPriceX96, sqrtRatioAX96, sqrtRatioBX96, amount0Desired, amount1Desired); (amount0, amount1) = IUniswapV3Pool(pool).mint( address(this), _TICK_LOWER, _TICK_UPPER, liquidity, abi.encode(MintCallbackData({_poolKey: _poolKey, payer: msg.sender})) ); if (amount0 < amount0Min || amount1 < amount1Min) revert ExcessiveSlippage(); } /// @notice Transfers the passed-in token from the payer to the recipient for the corresponding value /// @param token The token to be transferred to the recipient /// @param from The address of the payer /// @param to The address of the passed-in tokens recipient /// @param value How much of that token to be transferred from payer to the recipient function _pay( address token, address from, address to, uint256 value ) internal { _safeTransferFrom(token, from, to, value); } /// @notice Mints Keep3r credits to the passed-in address of recipient and increases total supply of Keep3r credits by the corresponding amount /// @param to The recipient of the Keep3r credits /// @param amount The amount Keep3r credits to be minted to the recipient function _mint(address to, uint256 amount) internal { totalSupply += amount; balanceOf[to] += amount; emit Transfer(address(0), to, amount); } /// @notice Burns Keep3r credits to the passed-in address of recipient and reduces total supply of Keep3r credits by the corresponding amount /// @param to The address that will get its Keep3r credits burned /// @param amount The amount Keep3r credits to be burned from the recipient/recipient function _burn(address to, uint256 amount) internal { totalSupply -= amount; balanceOf[to] -= amount; emit Transfer(to, address(0), amount); } /// @notice Transfers amount of Keep3r credits between two addresses /// @param from The user that transfers the Keep3r credits /// @param to The user that receives the Keep3r credits /// @param amount The amount of Keep3r credits to be transferred function _transferTokens( address from, address to, uint256 amount ) internal { balanceOf[from] -= amount; balanceOf[to] += amount; emit Transfer(from, to, amount); } /// @notice Transfers the passed-in token from the specified "from" to the specified "to" for the corresponding value /// @dev Reverts with IUniV3PairManager#UnsuccessfulTransfer if the transfer was not successful, /// or if the passed data length is different than 0 and the decoded data is not a boolean /// @param token The token to be transferred to the specified "to" /// @param from The address which is going to transfer the tokens /// @param value How much of that token to be transferred from "from" to "to" function _safeTransferFrom( address token, address from, address to, uint256 value ) internal { // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) revert UnsuccessfulTransfer(); } }
_transferTokens
function _transferTokens( address from, address to, uint256 amount ) internal { balanceOf[from] -= amount; balanceOf[to] += amount; emit Transfer(from, to, amount); }
/// @notice Transfers amount of Keep3r credits between two addresses /// @param from The user that transfers the Keep3r credits /// @param to The user that receives the Keep3r credits /// @param amount The amount of Keep3r credits to be transferred
NatSpecSingleLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 8615, 8812 ] }
7,615
UniV3PairManagerFactory
solidity/contracts/UniV3PairManager.sol
0x005634cfef45e5a19c84aede6f0af17833471852
Solidity
UniV3PairManager
contract UniV3PairManager is IUniV3PairManager, Governable { /// @inheritdoc IERC20Metadata string public override name; /// @inheritdoc IERC20Metadata string public override symbol; /// @inheritdoc IERC20 uint256 public override totalSupply = 0; /// @inheritdoc IPairManager address public immutable override token0; /// @inheritdoc IPairManager address public immutable override token1; /// @inheritdoc IPairManager address public immutable override pool; /// @inheritdoc IUniV3PairManager uint24 public immutable override fee; /// @inheritdoc IUniV3PairManager uint160 public immutable override sqrtRatioAX96; /// @inheritdoc IUniV3PairManager uint160 public immutable override sqrtRatioBX96; /// @notice Lowest possible tick in the Uniswap's curve int24 private constant _TICK_LOWER = -887200; /// @notice Highest possible tick in the Uniswap's curve int24 private constant _TICK_UPPER = 887200; /// @inheritdoc IERC20Metadata //solhint-disable-next-line const-name-snakecase uint8 public constant override decimals = 18; /// @inheritdoc IERC20 mapping(address => mapping(address => uint256)) public override allowance; /// @inheritdoc IERC20 mapping(address => uint256) public override balanceOf; /// @notice Struct that contains token0, token1, and fee of the Uniswap pool PoolAddress.PoolKey private _poolKey; constructor(address _pool, address _governance) Governable(_governance) { pool = _pool; uint24 _fee = IUniswapV3Pool(_pool).fee(); fee = _fee; address _token0 = IUniswapV3Pool(_pool).token0(); address _token1 = IUniswapV3Pool(_pool).token1(); token0 = _token0; token1 = _token1; name = string(abi.encodePacked('Keep3rLP - ', ERC20(_token0).symbol(), '/', ERC20(_token1).symbol())); symbol = string(abi.encodePacked('kLP-', ERC20(_token0).symbol(), '/', ERC20(_token1).symbol())); sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(_TICK_LOWER); sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(_TICK_UPPER); _poolKey = PoolAddress.PoolKey({token0: _token0, token1: _token1, fee: _fee}); } // This low-level function should be called from a contract which performs important safety checks /// @inheritdoc IUniV3PairManager function mint( uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min, address to ) external override returns (uint128 liquidity) { (liquidity, , ) = _addLiquidity(amount0Desired, amount1Desired, amount0Min, amount1Min); _mint(to, liquidity); } /// @inheritdoc IUniV3PairManager function uniswapV3MintCallback( uint256 amount0Owed, uint256 amount1Owed, bytes calldata data ) external override { MintCallbackData memory decoded = abi.decode(data, (MintCallbackData)); if (msg.sender != pool) revert OnlyPool(); if (amount0Owed > 0) _pay(decoded._poolKey.token0, decoded.payer, pool, amount0Owed); if (amount1Owed > 0) _pay(decoded._poolKey.token1, decoded.payer, pool, amount1Owed); } /// @inheritdoc IUniV3PairManager function burn( uint128 liquidity, uint256 amount0Min, uint256 amount1Min, address to ) external override returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = IUniswapV3Pool(pool).burn(_TICK_LOWER, _TICK_UPPER, liquidity); if (amount0 < amount0Min || amount1 < amount1Min) revert ExcessiveSlippage(); IUniswapV3Pool(pool).collect(to, _TICK_LOWER, _TICK_UPPER, uint128(amount0), uint128(amount1)); _burn(msg.sender, liquidity); } /// @inheritdoc IUniV3PairManager function collect() external override onlyGovernance returns (uint256 amount0, uint256 amount1) { (, , , uint128 tokensOwed0, uint128 tokensOwed1) = IUniswapV3Pool(pool).positions( keccak256(abi.encodePacked(address(this), _TICK_LOWER, _TICK_UPPER)) ); (amount0, amount1) = IUniswapV3Pool(pool).collect(governance, _TICK_LOWER, _TICK_UPPER, tokensOwed0, tokensOwed1); } /// @inheritdoc IUniV3PairManager function position() external view override returns ( uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ) { (liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128, tokensOwed0, tokensOwed1) = IUniswapV3Pool(pool).positions( keccak256(abi.encodePacked(address(this), _TICK_LOWER, _TICK_UPPER)) ); } /// @inheritdoc IERC20 function approve(address spender, uint256 amount) external override returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /// @inheritdoc IERC20 function transfer(address to, uint256 amount) external override returns (bool) { _transferTokens(msg.sender, to, amount); return true; } /// @inheritdoc IERC20 function transferFrom( address from, address to, uint256 amount ) external override returns (bool) { address spender = msg.sender; uint256 spenderAllowance = allowance[from][spender]; if (spender != from && spenderAllowance != type(uint256).max) { uint256 newAllowance = spenderAllowance - amount; allowance[from][spender] = newAllowance; emit Approval(from, spender, newAllowance); } _transferTokens(from, to, amount); return true; } /// @notice Adds liquidity to an initialized pool /// @dev Reverts if the returned amount0 is less than amount0Min or if amount1 is less than amount1Min /// @dev This function calls the mint function of the corresponding Uniswap pool, which in turn calls UniswapV3Callback /// @param amount0Desired The amount of token0 we would like to provide /// @param amount1Desired The amount of token1 we would like to provide /// @param amount0Min The minimum amount of token0 we want to provide /// @param amount1Min The minimum amount of token1 we want to provide /// @return liquidity The calculated liquidity we get for the token amounts we provided /// @return amount0 The amount of token0 we ended up providing /// @return amount1 The amount of token1 we ended up providing function _addLiquidity( uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min ) internal returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ) { (uint160 sqrtPriceX96, , , , , , ) = IUniswapV3Pool(pool).slot0(); liquidity = LiquidityAmounts.getLiquidityForAmounts(sqrtPriceX96, sqrtRatioAX96, sqrtRatioBX96, amount0Desired, amount1Desired); (amount0, amount1) = IUniswapV3Pool(pool).mint( address(this), _TICK_LOWER, _TICK_UPPER, liquidity, abi.encode(MintCallbackData({_poolKey: _poolKey, payer: msg.sender})) ); if (amount0 < amount0Min || amount1 < amount1Min) revert ExcessiveSlippage(); } /// @notice Transfers the passed-in token from the payer to the recipient for the corresponding value /// @param token The token to be transferred to the recipient /// @param from The address of the payer /// @param to The address of the passed-in tokens recipient /// @param value How much of that token to be transferred from payer to the recipient function _pay( address token, address from, address to, uint256 value ) internal { _safeTransferFrom(token, from, to, value); } /// @notice Mints Keep3r credits to the passed-in address of recipient and increases total supply of Keep3r credits by the corresponding amount /// @param to The recipient of the Keep3r credits /// @param amount The amount Keep3r credits to be minted to the recipient function _mint(address to, uint256 amount) internal { totalSupply += amount; balanceOf[to] += amount; emit Transfer(address(0), to, amount); } /// @notice Burns Keep3r credits to the passed-in address of recipient and reduces total supply of Keep3r credits by the corresponding amount /// @param to The address that will get its Keep3r credits burned /// @param amount The amount Keep3r credits to be burned from the recipient/recipient function _burn(address to, uint256 amount) internal { totalSupply -= amount; balanceOf[to] -= amount; emit Transfer(to, address(0), amount); } /// @notice Transfers amount of Keep3r credits between two addresses /// @param from The user that transfers the Keep3r credits /// @param to The user that receives the Keep3r credits /// @param amount The amount of Keep3r credits to be transferred function _transferTokens( address from, address to, uint256 amount ) internal { balanceOf[from] -= amount; balanceOf[to] += amount; emit Transfer(from, to, amount); } /// @notice Transfers the passed-in token from the specified "from" to the specified "to" for the corresponding value /// @dev Reverts with IUniV3PairManager#UnsuccessfulTransfer if the transfer was not successful, /// or if the passed data length is different than 0 and the decoded data is not a boolean /// @param token The token to be transferred to the specified "to" /// @param from The address which is going to transfer the tokens /// @param value How much of that token to be transferred from "from" to "to" function _safeTransferFrom( address token, address from, address to, uint256 value ) internal { // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) revert UnsuccessfulTransfer(); } }
_safeTransferFrom
function _safeTransferFrom( address token, address from, address to, uint256 value ) internal { // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) revert UnsuccessfulTransfer(); }
/// @notice Transfers the passed-in token from the specified "from" to the specified "to" for the corresponding value /// @dev Reverts with IUniV3PairManager#UnsuccessfulTransfer if the transfer was not successful, /// or if the passed data length is different than 0 and the decoded data is not a boolean /// @param token The token to be transferred to the specified "to" /// @param from The address which is going to transfer the tokens /// @param value How much of that token to be transferred from "from" to "to"
NatSpecSingleLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 9349, 9746 ] }
7,616
NaturalFlavors
NaturalFlavors.sol
0xbd1ca111380b436350034c7040e7c44949605702
Solidity
NaturalFlavors
contract NaturalFlavors is ERC721, ERC721Burnable, Ownable { using Strings for uint256; bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; uint private _tokenIdCounter; string public baseDefaultUrl; string public baseDefaultUrlExtension; string public license; address public mintingAddress; address public royaltyBenificiary; uint public royaltyBasisPoints; mapping(uint256 => string) public tokenIdToMetadata; event ProjectEvent(address indexed poster, string indexed eventType, string content); event TokenEvent(address indexed poster, uint256 indexed tokenId, string indexed eventType, string content); constructor( string memory _baseDefaultUrl ) ERC721('NaturalFlavors', 'FLAV') { baseDefaultUrl = _baseDefaultUrl; baseDefaultUrlExtension = '.json'; license = 'CC BY-NC 4.0'; royaltyBasisPoints = 750; _tokenIdCounter = 0; mintingAddress = msg.sender; royaltyBenificiary = msg.sender; } function totalSupply() public view virtual returns (uint256) { return _tokenIdCounter - 1; } function mint(address to) public { require(mintingAddress == _msgSender(), 'Caller is not the minting address'); _mint(to, _tokenIdCounter); _tokenIdCounter++; } function batchMint(address[] memory addresses) public { require(mintingAddress == _msgSender(), 'Caller is not the minting address'); for (uint i = 0; i < addresses.length; i++) { _mint(addresses[i], _tokenIdCounter); _tokenIdCounter++; } } function setMintingAddress(address minter) public onlyOwner { mintingAddress = minter; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), 'ERC721Metadata: URI query for nonexistent token'); bytes memory stringBytes = bytes(tokenIdToMetadata[tokenId]); if (stringBytes.length == 0) { string memory tokenString = tokenId.toString(); return string(abi.encodePacked(baseDefaultUrl, tokenString, baseDefaultUrlExtension)); } string memory json = Base64.encode(stringBytes); return string(abi.encodePacked('data:application/json;base64,', json)); } function updateBaseUrl(string memory _baseDefaultUrl, string memory _baseUrlExtension) public onlyOwner { baseDefaultUrl = _baseDefaultUrl; baseDefaultUrlExtension = _baseUrlExtension; } function updateTokenMetadata( uint256 tokenId, string memory tokenMetadata ) public onlyOwner { tokenIdToMetadata[tokenId] = tokenMetadata; } function updateLicense( string memory _license ) public onlyOwner { license = _license; } function emitProjectEvent(string memory _eventType, string memory _content) public onlyOwner { emit ProjectEvent(_msgSender(), _eventType, _content); } function emitTokenEvent(uint256 tokenId, string memory _eventType, string memory _content) public { require( owner() == _msgSender() || ERC721.ownerOf(tokenId) == _msgSender(), 'Only project or token owner can emit token event' ); emit TokenEvent(_msgSender(), tokenId, _eventType, _content); } function updatRoyaltyInfo( address _royaltyBenificiary, uint256 _royaltyBasisPoints ) public onlyOwner { royaltyBenificiary = _royaltyBenificiary; royaltyBasisPoints = _royaltyBasisPoints; } function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address, uint256) { return (royaltyBenificiary, _salePrice * royaltyBasisPoints / 10000); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721) returns (bool) { return interfaceId == _INTERFACE_ID_ERC2981 || super.supportsInterface(interfaceId); } }
supportsInterface
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721) returns (bool) { return interfaceId == _INTERFACE_ID_ERC2981 || super.supportsInterface(interfaceId); }
/** * @dev See {IERC165-supportsInterface}. */
NatSpecMultiLine
v0.8.2+commit.661d1103
MIT
ipfs://91dd467f20c43cd652e343d83c94f42d1022239141651747c0e9ff30e838d007
{ "func_code_index": [ 3592, 3787 ] }
7,617
BasicStakingContract
BasicStakingContract.sol
0x583d4d39b740e2582febab65a9437e46692f932a
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } }
mul
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; }
/** * @dev Multiplies two numbers, throws on overflow. */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
None
bzzr://4b303eb18851047dc1d29ae82f12547c01d9658bb358f1143c0be5c6bdd9f246
{ "func_code_index": [ 89, 476 ] }
7,618
BasicStakingContract
BasicStakingContract.sol
0x583d4d39b740e2582febab65a9437e46692f932a
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } }
div
function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; }
/** * @dev Integer division of two numbers, truncating the quotient. */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
None
bzzr://4b303eb18851047dc1d29ae82f12547c01d9658bb358f1143c0be5c6bdd9f246
{ "func_code_index": [ 560, 840 ] }
7,619
BasicStakingContract
BasicStakingContract.sol
0x583d4d39b740e2582febab65a9437e46692f932a
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } }
sub
function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; }
/** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
None
bzzr://4b303eb18851047dc1d29ae82f12547c01d9658bb358f1143c0be5c6bdd9f246
{ "func_code_index": [ 954, 1070 ] }
7,620
BasicStakingContract
BasicStakingContract.sol
0x583d4d39b740e2582febab65a9437e46692f932a
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } }
add
function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; }
/** * @dev Adds two numbers, throws on overflow. */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
None
bzzr://4b303eb18851047dc1d29ae82f12547c01d9658bb358f1143c0be5c6bdd9f246
{ "func_code_index": [ 1134, 1264 ] }
7,621
BasicStakingContract
BasicStakingContract.sol
0x583d4d39b740e2582febab65a9437e46692f932a
Solidity
ERC900BasicStakeContract
contract ERC900BasicStakeContract is ERC900 { // @TODO: deploy this separately so we don't have to deploy it multiple times for each contract using SafeMath for uint256; // Token used for staking ERC20 stakingToken; // The default duration of stake lock-in (in seconds) uint256 public defaultLockInDuration; // To save on gas, rather than create a separate mapping for totalStakedFor & personalStakes, // both data structures are stored in a single mapping for a given addresses. // // It's possible to have a non-existing personalStakes, but have tokens in totalStakedFor // if other users are staking on behalf of a given address. mapping (address => StakeContract) public stakeHolders; // Struct for personal stakes (i.e., stakes made by this address) // unlockedTimestamp - when the stake unlocks (in seconds since Unix epoch) // actualAmount - the amount of tokens in the stake // stakedFor - the address the stake was staked for struct Stake { uint256 unlockedTimestamp; uint256 actualAmount; address stakedFor; } // Struct for all stake metadata at a particular address // totalStakedFor - the number of tokens staked for this address // personalStakeIndex - the index in the personalStakes array. // personalStakes - append only array of stakes made by this address // exists - whether or not there are stakes that involve this address struct StakeContract { uint256 totalStakedFor; uint256 personalStakeIndex; Stake[] personalStakes; bool exists; } /** * @dev Modifier that checks that this contract can transfer tokens from the * balance in the stakingToken contract for the given address. * @dev This modifier also transfers the tokens. * @param _address address to transfer tokens from * @param _amount uint256 the number of tokens */ modifier canStake(address _address, uint256 _amount) { require( stakingToken.transferFrom(_address, this, _amount), "Stake required"); _; } /** * @dev Constructor function * @param _stakingToken ERC20 The address of the token contract used for staking */ constructor(ERC20 _stakingToken) public { stakingToken = _stakingToken; } /** * @dev Returns the timestamps for when active personal stakes for an address will unlock * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return uint256[] array of timestamps */ function getPersonalStakeUnlockedTimestamps(address _address) external view returns (uint256[]) { uint256[] memory timestamps; (timestamps,,) = getPersonalStakes(_address); return timestamps; } /** * @dev Returns the stake actualAmount for active personal stakes for an address * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return uint256[] array of actualAmounts */ function getPersonalStakeActualAmounts(address _address) external view returns (uint256[]) { uint256[] memory actualAmounts; (,actualAmounts,) = getPersonalStakes(_address); return actualAmounts; } /** * @dev Returns the addresses that each personal stake was created for by an address * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return address[] array of amounts */ function getPersonalStakeForAddresses(address _address) external view returns (address[]) { address[] memory stakedFor; (,,stakedFor) = getPersonalStakes(_address); return stakedFor; } /** * @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the user * @notice MUST trigger Staked event * @param _amount uint256 the amount of tokens to stake * @param _data bytes optional data to include in the Stake event */ function stake(uint256 _amount, bytes _data) public { createStake( msg.sender, _amount, defaultLockInDuration, _data); } /** * @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the caller * @notice MUST trigger Staked event * @param _user address the address the tokens are staked for * @param _amount uint256 the amount of tokens to stake * @param _data bytes optional data to include in the Stake event */ function stakeFor(address _user, uint256 _amount, bytes _data) public { createStake( _user, _amount, defaultLockInDuration, _data); } /** * @notice Unstakes a certain amount of tokens, this SHOULD return the given amount of tokens to the user, if unstaking is currently not possible the function MUST revert * @notice MUST trigger Unstaked event * @dev Unstaking tokens is an atomic operation—either all of the tokens in a stake, or none of the tokens. * @dev Users can only unstake a single stake at a time, it is must be their oldest active stake. Upon releasing that stake, the tokens will be * transferred back to their account, and their personalStakeIndex will increment to the next active stake. * @param _amount uint256 the amount of tokens to unstake * @param _data bytes optional data to include in the Unstake event */ function unstake(uint256 _amount, bytes _data) public { withdrawStake( _amount, _data); } /** * @notice Returns the current total of tokens staked for an address * @param _address address The address to query * @return uint256 The number of tokens staked for the given address */ function totalStakedFor(address _address) public view returns (uint256) { return stakeHolders[_address].totalStakedFor; } /** * @notice Returns the current total of tokens staked * @return uint256 The number of tokens staked in the contract */ function totalStaked() public view returns (uint256) { return stakingToken.balanceOf(this); } /** * @notice Address of the token being used by the staking interface * @return address The address of the ERC20 token used for staking */ function token() public view returns (address) { return stakingToken; } /** * @notice MUST return true if the optional history functions are implemented, otherwise false * @dev Since we don't implement the optional interface, this always returns false * @return bool Whether or not the optional history functions are implemented */ function supportsHistory() public pure returns (bool) { return false; } /** * @dev Helper function to get specific properties of all of the personal stakes created by an address * @param _address address The address to query * @return (uint256[], uint256[], address[]) * timestamps array, actualAmounts array, stakedFor array */ function getPersonalStakes( address _address ) public view returns(uint256[], uint256[], address[]) { StakeContract storage stakeContract = stakeHolders[_address]; uint256 arraySize = stakeContract.personalStakes.length - stakeContract.personalStakeIndex; uint256[] memory unlockedTimestamps = new uint256[](arraySize); uint256[] memory actualAmounts = new uint256[](arraySize); address[] memory stakedFor = new address[](arraySize); for (uint256 i = stakeContract.personalStakeIndex; i < stakeContract.personalStakes.length; i++) { uint256 index = i - stakeContract.personalStakeIndex; unlockedTimestamps[index] = stakeContract.personalStakes[i].unlockedTimestamp; actualAmounts[index] = stakeContract.personalStakes[i].actualAmount; stakedFor[index] = stakeContract.personalStakes[i].stakedFor; } return ( unlockedTimestamps, actualAmounts, stakedFor ); } /** * @dev Helper function to create stakes for a given address * @param _address address The address the stake is being created for * @param _amount uint256 The number of tokens being staked * @param _lockInDuration uint256 The duration to lock the tokens for * @param _data bytes optional data to include in the Stake event */ function createStake( address _address, uint256 _amount, uint256 _lockInDuration, bytes _data ) internal canStake(msg.sender, _amount) { require( _amount > 0, "Stake amount has to be greater than 0!"); if (!stakeHolders[msg.sender].exists) { stakeHolders[msg.sender].exists = true; } stakeHolders[_address].totalStakedFor = stakeHolders[_address].totalStakedFor.add(_amount); stakeHolders[msg.sender].personalStakes.push( Stake( block.timestamp.add(_lockInDuration), _amount, _address) ); emit Staked( _address, _amount, totalStakedFor(_address), _data); } /** * @dev Helper function to withdraw stakes for the msg.sender * @param _amount uint256 The amount to withdraw. MUST match the stake amount for the * stake at personalStakeIndex. * @param _data bytes optional data to include in the Unstake event */ function withdrawStake( uint256 _amount, bytes _data ) internal { Stake storage personalStake = stakeHolders[msg.sender].personalStakes[stakeHolders[msg.sender].personalStakeIndex]; // Check that the current stake has unlocked & matches the unstake amount require( personalStake.unlockedTimestamp <= block.timestamp, "The current stake hasn't unlocked yet"); require( personalStake.actualAmount == _amount, "The unstake amount does not match the current stake"); // Transfer the staked tokens from this contract back to the sender // Notice that we are using transfer instead of transferFrom here, so // no approval is needed beforehand. require( stakingToken.transfer(msg.sender, _amount), "Unable to withdraw stake"); stakeHolders[personalStake.stakedFor].totalStakedFor = stakeHolders[personalStake.stakedFor] .totalStakedFor.sub(personalStake.actualAmount); personalStake.actualAmount = 0; stakeHolders[msg.sender].personalStakeIndex++; emit Unstaked( personalStake.stakedFor, _amount, totalStakedFor(personalStake.stakedFor), _data); } }
getPersonalStakeUnlockedTimestamps
function getPersonalStakeUnlockedTimestamps(address _address) external view returns (uint256[]) { uint256[] memory timestamps; (timestamps,,) = getPersonalStakes(_address); return timestamps; }
/** * @dev Returns the timestamps for when active personal stakes for an address will unlock * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return uint256[] array of timestamps */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
None
bzzr://4b303eb18851047dc1d29ae82f12547c01d9658bb358f1143c0be5c6bdd9f246
{ "func_code_index": [ 2614, 2830 ] }
7,622
BasicStakingContract
BasicStakingContract.sol
0x583d4d39b740e2582febab65a9437e46692f932a
Solidity
ERC900BasicStakeContract
contract ERC900BasicStakeContract is ERC900 { // @TODO: deploy this separately so we don't have to deploy it multiple times for each contract using SafeMath for uint256; // Token used for staking ERC20 stakingToken; // The default duration of stake lock-in (in seconds) uint256 public defaultLockInDuration; // To save on gas, rather than create a separate mapping for totalStakedFor & personalStakes, // both data structures are stored in a single mapping for a given addresses. // // It's possible to have a non-existing personalStakes, but have tokens in totalStakedFor // if other users are staking on behalf of a given address. mapping (address => StakeContract) public stakeHolders; // Struct for personal stakes (i.e., stakes made by this address) // unlockedTimestamp - when the stake unlocks (in seconds since Unix epoch) // actualAmount - the amount of tokens in the stake // stakedFor - the address the stake was staked for struct Stake { uint256 unlockedTimestamp; uint256 actualAmount; address stakedFor; } // Struct for all stake metadata at a particular address // totalStakedFor - the number of tokens staked for this address // personalStakeIndex - the index in the personalStakes array. // personalStakes - append only array of stakes made by this address // exists - whether or not there are stakes that involve this address struct StakeContract { uint256 totalStakedFor; uint256 personalStakeIndex; Stake[] personalStakes; bool exists; } /** * @dev Modifier that checks that this contract can transfer tokens from the * balance in the stakingToken contract for the given address. * @dev This modifier also transfers the tokens. * @param _address address to transfer tokens from * @param _amount uint256 the number of tokens */ modifier canStake(address _address, uint256 _amount) { require( stakingToken.transferFrom(_address, this, _amount), "Stake required"); _; } /** * @dev Constructor function * @param _stakingToken ERC20 The address of the token contract used for staking */ constructor(ERC20 _stakingToken) public { stakingToken = _stakingToken; } /** * @dev Returns the timestamps for when active personal stakes for an address will unlock * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return uint256[] array of timestamps */ function getPersonalStakeUnlockedTimestamps(address _address) external view returns (uint256[]) { uint256[] memory timestamps; (timestamps,,) = getPersonalStakes(_address); return timestamps; } /** * @dev Returns the stake actualAmount for active personal stakes for an address * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return uint256[] array of actualAmounts */ function getPersonalStakeActualAmounts(address _address) external view returns (uint256[]) { uint256[] memory actualAmounts; (,actualAmounts,) = getPersonalStakes(_address); return actualAmounts; } /** * @dev Returns the addresses that each personal stake was created for by an address * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return address[] array of amounts */ function getPersonalStakeForAddresses(address _address) external view returns (address[]) { address[] memory stakedFor; (,,stakedFor) = getPersonalStakes(_address); return stakedFor; } /** * @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the user * @notice MUST trigger Staked event * @param _amount uint256 the amount of tokens to stake * @param _data bytes optional data to include in the Stake event */ function stake(uint256 _amount, bytes _data) public { createStake( msg.sender, _amount, defaultLockInDuration, _data); } /** * @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the caller * @notice MUST trigger Staked event * @param _user address the address the tokens are staked for * @param _amount uint256 the amount of tokens to stake * @param _data bytes optional data to include in the Stake event */ function stakeFor(address _user, uint256 _amount, bytes _data) public { createStake( _user, _amount, defaultLockInDuration, _data); } /** * @notice Unstakes a certain amount of tokens, this SHOULD return the given amount of tokens to the user, if unstaking is currently not possible the function MUST revert * @notice MUST trigger Unstaked event * @dev Unstaking tokens is an atomic operation—either all of the tokens in a stake, or none of the tokens. * @dev Users can only unstake a single stake at a time, it is must be their oldest active stake. Upon releasing that stake, the tokens will be * transferred back to their account, and their personalStakeIndex will increment to the next active stake. * @param _amount uint256 the amount of tokens to unstake * @param _data bytes optional data to include in the Unstake event */ function unstake(uint256 _amount, bytes _data) public { withdrawStake( _amount, _data); } /** * @notice Returns the current total of tokens staked for an address * @param _address address The address to query * @return uint256 The number of tokens staked for the given address */ function totalStakedFor(address _address) public view returns (uint256) { return stakeHolders[_address].totalStakedFor; } /** * @notice Returns the current total of tokens staked * @return uint256 The number of tokens staked in the contract */ function totalStaked() public view returns (uint256) { return stakingToken.balanceOf(this); } /** * @notice Address of the token being used by the staking interface * @return address The address of the ERC20 token used for staking */ function token() public view returns (address) { return stakingToken; } /** * @notice MUST return true if the optional history functions are implemented, otherwise false * @dev Since we don't implement the optional interface, this always returns false * @return bool Whether or not the optional history functions are implemented */ function supportsHistory() public pure returns (bool) { return false; } /** * @dev Helper function to get specific properties of all of the personal stakes created by an address * @param _address address The address to query * @return (uint256[], uint256[], address[]) * timestamps array, actualAmounts array, stakedFor array */ function getPersonalStakes( address _address ) public view returns(uint256[], uint256[], address[]) { StakeContract storage stakeContract = stakeHolders[_address]; uint256 arraySize = stakeContract.personalStakes.length - stakeContract.personalStakeIndex; uint256[] memory unlockedTimestamps = new uint256[](arraySize); uint256[] memory actualAmounts = new uint256[](arraySize); address[] memory stakedFor = new address[](arraySize); for (uint256 i = stakeContract.personalStakeIndex; i < stakeContract.personalStakes.length; i++) { uint256 index = i - stakeContract.personalStakeIndex; unlockedTimestamps[index] = stakeContract.personalStakes[i].unlockedTimestamp; actualAmounts[index] = stakeContract.personalStakes[i].actualAmount; stakedFor[index] = stakeContract.personalStakes[i].stakedFor; } return ( unlockedTimestamps, actualAmounts, stakedFor ); } /** * @dev Helper function to create stakes for a given address * @param _address address The address the stake is being created for * @param _amount uint256 The number of tokens being staked * @param _lockInDuration uint256 The duration to lock the tokens for * @param _data bytes optional data to include in the Stake event */ function createStake( address _address, uint256 _amount, uint256 _lockInDuration, bytes _data ) internal canStake(msg.sender, _amount) { require( _amount > 0, "Stake amount has to be greater than 0!"); if (!stakeHolders[msg.sender].exists) { stakeHolders[msg.sender].exists = true; } stakeHolders[_address].totalStakedFor = stakeHolders[_address].totalStakedFor.add(_amount); stakeHolders[msg.sender].personalStakes.push( Stake( block.timestamp.add(_lockInDuration), _amount, _address) ); emit Staked( _address, _amount, totalStakedFor(_address), _data); } /** * @dev Helper function to withdraw stakes for the msg.sender * @param _amount uint256 The amount to withdraw. MUST match the stake amount for the * stake at personalStakeIndex. * @param _data bytes optional data to include in the Unstake event */ function withdrawStake( uint256 _amount, bytes _data ) internal { Stake storage personalStake = stakeHolders[msg.sender].personalStakes[stakeHolders[msg.sender].personalStakeIndex]; // Check that the current stake has unlocked & matches the unstake amount require( personalStake.unlockedTimestamp <= block.timestamp, "The current stake hasn't unlocked yet"); require( personalStake.actualAmount == _amount, "The unstake amount does not match the current stake"); // Transfer the staked tokens from this contract back to the sender // Notice that we are using transfer instead of transferFrom here, so // no approval is needed beforehand. require( stakingToken.transfer(msg.sender, _amount), "Unable to withdraw stake"); stakeHolders[personalStake.stakedFor].totalStakedFor = stakeHolders[personalStake.stakedFor] .totalStakedFor.sub(personalStake.actualAmount); personalStake.actualAmount = 0; stakeHolders[msg.sender].personalStakeIndex++; emit Unstaked( personalStake.stakedFor, _amount, totalStakedFor(personalStake.stakedFor), _data); } }
getPersonalStakeActualAmounts
function getPersonalStakeActualAmounts(address _address) external view returns (uint256[]) { uint256[] memory actualAmounts; (,actualAmounts,) = getPersonalStakes(_address); return actualAmounts; }
/** * @dev Returns the stake actualAmount for active personal stakes for an address * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return uint256[] array of actualAmounts */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
None
bzzr://4b303eb18851047dc1d29ae82f12547c01d9658bb358f1143c0be5c6bdd9f246
{ "func_code_index": [ 3144, 3364 ] }
7,623
BasicStakingContract
BasicStakingContract.sol
0x583d4d39b740e2582febab65a9437e46692f932a
Solidity
ERC900BasicStakeContract
contract ERC900BasicStakeContract is ERC900 { // @TODO: deploy this separately so we don't have to deploy it multiple times for each contract using SafeMath for uint256; // Token used for staking ERC20 stakingToken; // The default duration of stake lock-in (in seconds) uint256 public defaultLockInDuration; // To save on gas, rather than create a separate mapping for totalStakedFor & personalStakes, // both data structures are stored in a single mapping for a given addresses. // // It's possible to have a non-existing personalStakes, but have tokens in totalStakedFor // if other users are staking on behalf of a given address. mapping (address => StakeContract) public stakeHolders; // Struct for personal stakes (i.e., stakes made by this address) // unlockedTimestamp - when the stake unlocks (in seconds since Unix epoch) // actualAmount - the amount of tokens in the stake // stakedFor - the address the stake was staked for struct Stake { uint256 unlockedTimestamp; uint256 actualAmount; address stakedFor; } // Struct for all stake metadata at a particular address // totalStakedFor - the number of tokens staked for this address // personalStakeIndex - the index in the personalStakes array. // personalStakes - append only array of stakes made by this address // exists - whether or not there are stakes that involve this address struct StakeContract { uint256 totalStakedFor; uint256 personalStakeIndex; Stake[] personalStakes; bool exists; } /** * @dev Modifier that checks that this contract can transfer tokens from the * balance in the stakingToken contract for the given address. * @dev This modifier also transfers the tokens. * @param _address address to transfer tokens from * @param _amount uint256 the number of tokens */ modifier canStake(address _address, uint256 _amount) { require( stakingToken.transferFrom(_address, this, _amount), "Stake required"); _; } /** * @dev Constructor function * @param _stakingToken ERC20 The address of the token contract used for staking */ constructor(ERC20 _stakingToken) public { stakingToken = _stakingToken; } /** * @dev Returns the timestamps for when active personal stakes for an address will unlock * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return uint256[] array of timestamps */ function getPersonalStakeUnlockedTimestamps(address _address) external view returns (uint256[]) { uint256[] memory timestamps; (timestamps,,) = getPersonalStakes(_address); return timestamps; } /** * @dev Returns the stake actualAmount for active personal stakes for an address * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return uint256[] array of actualAmounts */ function getPersonalStakeActualAmounts(address _address) external view returns (uint256[]) { uint256[] memory actualAmounts; (,actualAmounts,) = getPersonalStakes(_address); return actualAmounts; } /** * @dev Returns the addresses that each personal stake was created for by an address * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return address[] array of amounts */ function getPersonalStakeForAddresses(address _address) external view returns (address[]) { address[] memory stakedFor; (,,stakedFor) = getPersonalStakes(_address); return stakedFor; } /** * @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the user * @notice MUST trigger Staked event * @param _amount uint256 the amount of tokens to stake * @param _data bytes optional data to include in the Stake event */ function stake(uint256 _amount, bytes _data) public { createStake( msg.sender, _amount, defaultLockInDuration, _data); } /** * @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the caller * @notice MUST trigger Staked event * @param _user address the address the tokens are staked for * @param _amount uint256 the amount of tokens to stake * @param _data bytes optional data to include in the Stake event */ function stakeFor(address _user, uint256 _amount, bytes _data) public { createStake( _user, _amount, defaultLockInDuration, _data); } /** * @notice Unstakes a certain amount of tokens, this SHOULD return the given amount of tokens to the user, if unstaking is currently not possible the function MUST revert * @notice MUST trigger Unstaked event * @dev Unstaking tokens is an atomic operation—either all of the tokens in a stake, or none of the tokens. * @dev Users can only unstake a single stake at a time, it is must be their oldest active stake. Upon releasing that stake, the tokens will be * transferred back to their account, and their personalStakeIndex will increment to the next active stake. * @param _amount uint256 the amount of tokens to unstake * @param _data bytes optional data to include in the Unstake event */ function unstake(uint256 _amount, bytes _data) public { withdrawStake( _amount, _data); } /** * @notice Returns the current total of tokens staked for an address * @param _address address The address to query * @return uint256 The number of tokens staked for the given address */ function totalStakedFor(address _address) public view returns (uint256) { return stakeHolders[_address].totalStakedFor; } /** * @notice Returns the current total of tokens staked * @return uint256 The number of tokens staked in the contract */ function totalStaked() public view returns (uint256) { return stakingToken.balanceOf(this); } /** * @notice Address of the token being used by the staking interface * @return address The address of the ERC20 token used for staking */ function token() public view returns (address) { return stakingToken; } /** * @notice MUST return true if the optional history functions are implemented, otherwise false * @dev Since we don't implement the optional interface, this always returns false * @return bool Whether or not the optional history functions are implemented */ function supportsHistory() public pure returns (bool) { return false; } /** * @dev Helper function to get specific properties of all of the personal stakes created by an address * @param _address address The address to query * @return (uint256[], uint256[], address[]) * timestamps array, actualAmounts array, stakedFor array */ function getPersonalStakes( address _address ) public view returns(uint256[], uint256[], address[]) { StakeContract storage stakeContract = stakeHolders[_address]; uint256 arraySize = stakeContract.personalStakes.length - stakeContract.personalStakeIndex; uint256[] memory unlockedTimestamps = new uint256[](arraySize); uint256[] memory actualAmounts = new uint256[](arraySize); address[] memory stakedFor = new address[](arraySize); for (uint256 i = stakeContract.personalStakeIndex; i < stakeContract.personalStakes.length; i++) { uint256 index = i - stakeContract.personalStakeIndex; unlockedTimestamps[index] = stakeContract.personalStakes[i].unlockedTimestamp; actualAmounts[index] = stakeContract.personalStakes[i].actualAmount; stakedFor[index] = stakeContract.personalStakes[i].stakedFor; } return ( unlockedTimestamps, actualAmounts, stakedFor ); } /** * @dev Helper function to create stakes for a given address * @param _address address The address the stake is being created for * @param _amount uint256 The number of tokens being staked * @param _lockInDuration uint256 The duration to lock the tokens for * @param _data bytes optional data to include in the Stake event */ function createStake( address _address, uint256 _amount, uint256 _lockInDuration, bytes _data ) internal canStake(msg.sender, _amount) { require( _amount > 0, "Stake amount has to be greater than 0!"); if (!stakeHolders[msg.sender].exists) { stakeHolders[msg.sender].exists = true; } stakeHolders[_address].totalStakedFor = stakeHolders[_address].totalStakedFor.add(_amount); stakeHolders[msg.sender].personalStakes.push( Stake( block.timestamp.add(_lockInDuration), _amount, _address) ); emit Staked( _address, _amount, totalStakedFor(_address), _data); } /** * @dev Helper function to withdraw stakes for the msg.sender * @param _amount uint256 The amount to withdraw. MUST match the stake amount for the * stake at personalStakeIndex. * @param _data bytes optional data to include in the Unstake event */ function withdrawStake( uint256 _amount, bytes _data ) internal { Stake storage personalStake = stakeHolders[msg.sender].personalStakes[stakeHolders[msg.sender].personalStakeIndex]; // Check that the current stake has unlocked & matches the unstake amount require( personalStake.unlockedTimestamp <= block.timestamp, "The current stake hasn't unlocked yet"); require( personalStake.actualAmount == _amount, "The unstake amount does not match the current stake"); // Transfer the staked tokens from this contract back to the sender // Notice that we are using transfer instead of transferFrom here, so // no approval is needed beforehand. require( stakingToken.transfer(msg.sender, _amount), "Unable to withdraw stake"); stakeHolders[personalStake.stakedFor].totalStakedFor = stakeHolders[personalStake.stakedFor] .totalStakedFor.sub(personalStake.actualAmount); personalStake.actualAmount = 0; stakeHolders[msg.sender].personalStakeIndex++; emit Unstaked( personalStake.stakedFor, _amount, totalStakedFor(personalStake.stakedFor), _data); } }
getPersonalStakeForAddresses
function getPersonalStakeForAddresses(address _address) external view returns (address[]) { address[] memory stakedFor; (,,stakedFor) = getPersonalStakes(_address); return stakedFor; }
/** * @dev Returns the addresses that each personal stake was created for by an address * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return address[] array of amounts */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
None
bzzr://4b303eb18851047dc1d29ae82f12547c01d9658bb358f1143c0be5c6bdd9f246
{ "func_code_index": [ 3676, 3883 ] }
7,624
BasicStakingContract
BasicStakingContract.sol
0x583d4d39b740e2582febab65a9437e46692f932a
Solidity
ERC900BasicStakeContract
contract ERC900BasicStakeContract is ERC900 { // @TODO: deploy this separately so we don't have to deploy it multiple times for each contract using SafeMath for uint256; // Token used for staking ERC20 stakingToken; // The default duration of stake lock-in (in seconds) uint256 public defaultLockInDuration; // To save on gas, rather than create a separate mapping for totalStakedFor & personalStakes, // both data structures are stored in a single mapping for a given addresses. // // It's possible to have a non-existing personalStakes, but have tokens in totalStakedFor // if other users are staking on behalf of a given address. mapping (address => StakeContract) public stakeHolders; // Struct for personal stakes (i.e., stakes made by this address) // unlockedTimestamp - when the stake unlocks (in seconds since Unix epoch) // actualAmount - the amount of tokens in the stake // stakedFor - the address the stake was staked for struct Stake { uint256 unlockedTimestamp; uint256 actualAmount; address stakedFor; } // Struct for all stake metadata at a particular address // totalStakedFor - the number of tokens staked for this address // personalStakeIndex - the index in the personalStakes array. // personalStakes - append only array of stakes made by this address // exists - whether or not there are stakes that involve this address struct StakeContract { uint256 totalStakedFor; uint256 personalStakeIndex; Stake[] personalStakes; bool exists; } /** * @dev Modifier that checks that this contract can transfer tokens from the * balance in the stakingToken contract for the given address. * @dev This modifier also transfers the tokens. * @param _address address to transfer tokens from * @param _amount uint256 the number of tokens */ modifier canStake(address _address, uint256 _amount) { require( stakingToken.transferFrom(_address, this, _amount), "Stake required"); _; } /** * @dev Constructor function * @param _stakingToken ERC20 The address of the token contract used for staking */ constructor(ERC20 _stakingToken) public { stakingToken = _stakingToken; } /** * @dev Returns the timestamps for when active personal stakes for an address will unlock * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return uint256[] array of timestamps */ function getPersonalStakeUnlockedTimestamps(address _address) external view returns (uint256[]) { uint256[] memory timestamps; (timestamps,,) = getPersonalStakes(_address); return timestamps; } /** * @dev Returns the stake actualAmount for active personal stakes for an address * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return uint256[] array of actualAmounts */ function getPersonalStakeActualAmounts(address _address) external view returns (uint256[]) { uint256[] memory actualAmounts; (,actualAmounts,) = getPersonalStakes(_address); return actualAmounts; } /** * @dev Returns the addresses that each personal stake was created for by an address * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return address[] array of amounts */ function getPersonalStakeForAddresses(address _address) external view returns (address[]) { address[] memory stakedFor; (,,stakedFor) = getPersonalStakes(_address); return stakedFor; } /** * @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the user * @notice MUST trigger Staked event * @param _amount uint256 the amount of tokens to stake * @param _data bytes optional data to include in the Stake event */ function stake(uint256 _amount, bytes _data) public { createStake( msg.sender, _amount, defaultLockInDuration, _data); } /** * @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the caller * @notice MUST trigger Staked event * @param _user address the address the tokens are staked for * @param _amount uint256 the amount of tokens to stake * @param _data bytes optional data to include in the Stake event */ function stakeFor(address _user, uint256 _amount, bytes _data) public { createStake( _user, _amount, defaultLockInDuration, _data); } /** * @notice Unstakes a certain amount of tokens, this SHOULD return the given amount of tokens to the user, if unstaking is currently not possible the function MUST revert * @notice MUST trigger Unstaked event * @dev Unstaking tokens is an atomic operation—either all of the tokens in a stake, or none of the tokens. * @dev Users can only unstake a single stake at a time, it is must be their oldest active stake. Upon releasing that stake, the tokens will be * transferred back to their account, and their personalStakeIndex will increment to the next active stake. * @param _amount uint256 the amount of tokens to unstake * @param _data bytes optional data to include in the Unstake event */ function unstake(uint256 _amount, bytes _data) public { withdrawStake( _amount, _data); } /** * @notice Returns the current total of tokens staked for an address * @param _address address The address to query * @return uint256 The number of tokens staked for the given address */ function totalStakedFor(address _address) public view returns (uint256) { return stakeHolders[_address].totalStakedFor; } /** * @notice Returns the current total of tokens staked * @return uint256 The number of tokens staked in the contract */ function totalStaked() public view returns (uint256) { return stakingToken.balanceOf(this); } /** * @notice Address of the token being used by the staking interface * @return address The address of the ERC20 token used for staking */ function token() public view returns (address) { return stakingToken; } /** * @notice MUST return true if the optional history functions are implemented, otherwise false * @dev Since we don't implement the optional interface, this always returns false * @return bool Whether or not the optional history functions are implemented */ function supportsHistory() public pure returns (bool) { return false; } /** * @dev Helper function to get specific properties of all of the personal stakes created by an address * @param _address address The address to query * @return (uint256[], uint256[], address[]) * timestamps array, actualAmounts array, stakedFor array */ function getPersonalStakes( address _address ) public view returns(uint256[], uint256[], address[]) { StakeContract storage stakeContract = stakeHolders[_address]; uint256 arraySize = stakeContract.personalStakes.length - stakeContract.personalStakeIndex; uint256[] memory unlockedTimestamps = new uint256[](arraySize); uint256[] memory actualAmounts = new uint256[](arraySize); address[] memory stakedFor = new address[](arraySize); for (uint256 i = stakeContract.personalStakeIndex; i < stakeContract.personalStakes.length; i++) { uint256 index = i - stakeContract.personalStakeIndex; unlockedTimestamps[index] = stakeContract.personalStakes[i].unlockedTimestamp; actualAmounts[index] = stakeContract.personalStakes[i].actualAmount; stakedFor[index] = stakeContract.personalStakes[i].stakedFor; } return ( unlockedTimestamps, actualAmounts, stakedFor ); } /** * @dev Helper function to create stakes for a given address * @param _address address The address the stake is being created for * @param _amount uint256 The number of tokens being staked * @param _lockInDuration uint256 The duration to lock the tokens for * @param _data bytes optional data to include in the Stake event */ function createStake( address _address, uint256 _amount, uint256 _lockInDuration, bytes _data ) internal canStake(msg.sender, _amount) { require( _amount > 0, "Stake amount has to be greater than 0!"); if (!stakeHolders[msg.sender].exists) { stakeHolders[msg.sender].exists = true; } stakeHolders[_address].totalStakedFor = stakeHolders[_address].totalStakedFor.add(_amount); stakeHolders[msg.sender].personalStakes.push( Stake( block.timestamp.add(_lockInDuration), _amount, _address) ); emit Staked( _address, _amount, totalStakedFor(_address), _data); } /** * @dev Helper function to withdraw stakes for the msg.sender * @param _amount uint256 The amount to withdraw. MUST match the stake amount for the * stake at personalStakeIndex. * @param _data bytes optional data to include in the Unstake event */ function withdrawStake( uint256 _amount, bytes _data ) internal { Stake storage personalStake = stakeHolders[msg.sender].personalStakes[stakeHolders[msg.sender].personalStakeIndex]; // Check that the current stake has unlocked & matches the unstake amount require( personalStake.unlockedTimestamp <= block.timestamp, "The current stake hasn't unlocked yet"); require( personalStake.actualAmount == _amount, "The unstake amount does not match the current stake"); // Transfer the staked tokens from this contract back to the sender // Notice that we are using transfer instead of transferFrom here, so // no approval is needed beforehand. require( stakingToken.transfer(msg.sender, _amount), "Unable to withdraw stake"); stakeHolders[personalStake.stakedFor].totalStakedFor = stakeHolders[personalStake.stakedFor] .totalStakedFor.sub(personalStake.actualAmount); personalStake.actualAmount = 0; stakeHolders[msg.sender].personalStakeIndex++; emit Unstaked( personalStake.stakedFor, _amount, totalStakedFor(personalStake.stakedFor), _data); } }
stake
function stake(uint256 _amount, bytes _data) public { createStake( msg.sender, _amount, defaultLockInDuration, _data); }
/** * @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the user * @notice MUST trigger Staked event * @param _amount uint256 the amount of tokens to stake * @param _data bytes optional data to include in the Stake event */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
None
bzzr://4b303eb18851047dc1d29ae82f12547c01d9658bb358f1143c0be5c6bdd9f246
{ "func_code_index": [ 4167, 4326 ] }
7,625
BasicStakingContract
BasicStakingContract.sol
0x583d4d39b740e2582febab65a9437e46692f932a
Solidity
ERC900BasicStakeContract
contract ERC900BasicStakeContract is ERC900 { // @TODO: deploy this separately so we don't have to deploy it multiple times for each contract using SafeMath for uint256; // Token used for staking ERC20 stakingToken; // The default duration of stake lock-in (in seconds) uint256 public defaultLockInDuration; // To save on gas, rather than create a separate mapping for totalStakedFor & personalStakes, // both data structures are stored in a single mapping for a given addresses. // // It's possible to have a non-existing personalStakes, but have tokens in totalStakedFor // if other users are staking on behalf of a given address. mapping (address => StakeContract) public stakeHolders; // Struct for personal stakes (i.e., stakes made by this address) // unlockedTimestamp - when the stake unlocks (in seconds since Unix epoch) // actualAmount - the amount of tokens in the stake // stakedFor - the address the stake was staked for struct Stake { uint256 unlockedTimestamp; uint256 actualAmount; address stakedFor; } // Struct for all stake metadata at a particular address // totalStakedFor - the number of tokens staked for this address // personalStakeIndex - the index in the personalStakes array. // personalStakes - append only array of stakes made by this address // exists - whether or not there are stakes that involve this address struct StakeContract { uint256 totalStakedFor; uint256 personalStakeIndex; Stake[] personalStakes; bool exists; } /** * @dev Modifier that checks that this contract can transfer tokens from the * balance in the stakingToken contract for the given address. * @dev This modifier also transfers the tokens. * @param _address address to transfer tokens from * @param _amount uint256 the number of tokens */ modifier canStake(address _address, uint256 _amount) { require( stakingToken.transferFrom(_address, this, _amount), "Stake required"); _; } /** * @dev Constructor function * @param _stakingToken ERC20 The address of the token contract used for staking */ constructor(ERC20 _stakingToken) public { stakingToken = _stakingToken; } /** * @dev Returns the timestamps for when active personal stakes for an address will unlock * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return uint256[] array of timestamps */ function getPersonalStakeUnlockedTimestamps(address _address) external view returns (uint256[]) { uint256[] memory timestamps; (timestamps,,) = getPersonalStakes(_address); return timestamps; } /** * @dev Returns the stake actualAmount for active personal stakes for an address * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return uint256[] array of actualAmounts */ function getPersonalStakeActualAmounts(address _address) external view returns (uint256[]) { uint256[] memory actualAmounts; (,actualAmounts,) = getPersonalStakes(_address); return actualAmounts; } /** * @dev Returns the addresses that each personal stake was created for by an address * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return address[] array of amounts */ function getPersonalStakeForAddresses(address _address) external view returns (address[]) { address[] memory stakedFor; (,,stakedFor) = getPersonalStakes(_address); return stakedFor; } /** * @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the user * @notice MUST trigger Staked event * @param _amount uint256 the amount of tokens to stake * @param _data bytes optional data to include in the Stake event */ function stake(uint256 _amount, bytes _data) public { createStake( msg.sender, _amount, defaultLockInDuration, _data); } /** * @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the caller * @notice MUST trigger Staked event * @param _user address the address the tokens are staked for * @param _amount uint256 the amount of tokens to stake * @param _data bytes optional data to include in the Stake event */ function stakeFor(address _user, uint256 _amount, bytes _data) public { createStake( _user, _amount, defaultLockInDuration, _data); } /** * @notice Unstakes a certain amount of tokens, this SHOULD return the given amount of tokens to the user, if unstaking is currently not possible the function MUST revert * @notice MUST trigger Unstaked event * @dev Unstaking tokens is an atomic operation—either all of the tokens in a stake, or none of the tokens. * @dev Users can only unstake a single stake at a time, it is must be their oldest active stake. Upon releasing that stake, the tokens will be * transferred back to their account, and their personalStakeIndex will increment to the next active stake. * @param _amount uint256 the amount of tokens to unstake * @param _data bytes optional data to include in the Unstake event */ function unstake(uint256 _amount, bytes _data) public { withdrawStake( _amount, _data); } /** * @notice Returns the current total of tokens staked for an address * @param _address address The address to query * @return uint256 The number of tokens staked for the given address */ function totalStakedFor(address _address) public view returns (uint256) { return stakeHolders[_address].totalStakedFor; } /** * @notice Returns the current total of tokens staked * @return uint256 The number of tokens staked in the contract */ function totalStaked() public view returns (uint256) { return stakingToken.balanceOf(this); } /** * @notice Address of the token being used by the staking interface * @return address The address of the ERC20 token used for staking */ function token() public view returns (address) { return stakingToken; } /** * @notice MUST return true if the optional history functions are implemented, otherwise false * @dev Since we don't implement the optional interface, this always returns false * @return bool Whether or not the optional history functions are implemented */ function supportsHistory() public pure returns (bool) { return false; } /** * @dev Helper function to get specific properties of all of the personal stakes created by an address * @param _address address The address to query * @return (uint256[], uint256[], address[]) * timestamps array, actualAmounts array, stakedFor array */ function getPersonalStakes( address _address ) public view returns(uint256[], uint256[], address[]) { StakeContract storage stakeContract = stakeHolders[_address]; uint256 arraySize = stakeContract.personalStakes.length - stakeContract.personalStakeIndex; uint256[] memory unlockedTimestamps = new uint256[](arraySize); uint256[] memory actualAmounts = new uint256[](arraySize); address[] memory stakedFor = new address[](arraySize); for (uint256 i = stakeContract.personalStakeIndex; i < stakeContract.personalStakes.length; i++) { uint256 index = i - stakeContract.personalStakeIndex; unlockedTimestamps[index] = stakeContract.personalStakes[i].unlockedTimestamp; actualAmounts[index] = stakeContract.personalStakes[i].actualAmount; stakedFor[index] = stakeContract.personalStakes[i].stakedFor; } return ( unlockedTimestamps, actualAmounts, stakedFor ); } /** * @dev Helper function to create stakes for a given address * @param _address address The address the stake is being created for * @param _amount uint256 The number of tokens being staked * @param _lockInDuration uint256 The duration to lock the tokens for * @param _data bytes optional data to include in the Stake event */ function createStake( address _address, uint256 _amount, uint256 _lockInDuration, bytes _data ) internal canStake(msg.sender, _amount) { require( _amount > 0, "Stake amount has to be greater than 0!"); if (!stakeHolders[msg.sender].exists) { stakeHolders[msg.sender].exists = true; } stakeHolders[_address].totalStakedFor = stakeHolders[_address].totalStakedFor.add(_amount); stakeHolders[msg.sender].personalStakes.push( Stake( block.timestamp.add(_lockInDuration), _amount, _address) ); emit Staked( _address, _amount, totalStakedFor(_address), _data); } /** * @dev Helper function to withdraw stakes for the msg.sender * @param _amount uint256 The amount to withdraw. MUST match the stake amount for the * stake at personalStakeIndex. * @param _data bytes optional data to include in the Unstake event */ function withdrawStake( uint256 _amount, bytes _data ) internal { Stake storage personalStake = stakeHolders[msg.sender].personalStakes[stakeHolders[msg.sender].personalStakeIndex]; // Check that the current stake has unlocked & matches the unstake amount require( personalStake.unlockedTimestamp <= block.timestamp, "The current stake hasn't unlocked yet"); require( personalStake.actualAmount == _amount, "The unstake amount does not match the current stake"); // Transfer the staked tokens from this contract back to the sender // Notice that we are using transfer instead of transferFrom here, so // no approval is needed beforehand. require( stakingToken.transfer(msg.sender, _amount), "Unable to withdraw stake"); stakeHolders[personalStake.stakedFor].totalStakedFor = stakeHolders[personalStake.stakedFor] .totalStakedFor.sub(personalStake.actualAmount); personalStake.actualAmount = 0; stakeHolders[msg.sender].personalStakeIndex++; emit Unstaked( personalStake.stakedFor, _amount, totalStakedFor(personalStake.stakedFor), _data); } }
stakeFor
function stakeFor(address _user, uint256 _amount, bytes _data) public { createStake( _user, _amount, defaultLockInDuration, _data); }
/** * @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the caller * @notice MUST trigger Staked event * @param _user address the address the tokens are staked for * @param _amount uint256 the amount of tokens to stake * @param _data bytes optional data to include in the Stake event */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
None
bzzr://4b303eb18851047dc1d29ae82f12547c01d9658bb358f1143c0be5c6bdd9f246
{ "func_code_index": [ 4677, 4849 ] }
7,626
BasicStakingContract
BasicStakingContract.sol
0x583d4d39b740e2582febab65a9437e46692f932a
Solidity
ERC900BasicStakeContract
contract ERC900BasicStakeContract is ERC900 { // @TODO: deploy this separately so we don't have to deploy it multiple times for each contract using SafeMath for uint256; // Token used for staking ERC20 stakingToken; // The default duration of stake lock-in (in seconds) uint256 public defaultLockInDuration; // To save on gas, rather than create a separate mapping for totalStakedFor & personalStakes, // both data structures are stored in a single mapping for a given addresses. // // It's possible to have a non-existing personalStakes, but have tokens in totalStakedFor // if other users are staking on behalf of a given address. mapping (address => StakeContract) public stakeHolders; // Struct for personal stakes (i.e., stakes made by this address) // unlockedTimestamp - when the stake unlocks (in seconds since Unix epoch) // actualAmount - the amount of tokens in the stake // stakedFor - the address the stake was staked for struct Stake { uint256 unlockedTimestamp; uint256 actualAmount; address stakedFor; } // Struct for all stake metadata at a particular address // totalStakedFor - the number of tokens staked for this address // personalStakeIndex - the index in the personalStakes array. // personalStakes - append only array of stakes made by this address // exists - whether or not there are stakes that involve this address struct StakeContract { uint256 totalStakedFor; uint256 personalStakeIndex; Stake[] personalStakes; bool exists; } /** * @dev Modifier that checks that this contract can transfer tokens from the * balance in the stakingToken contract for the given address. * @dev This modifier also transfers the tokens. * @param _address address to transfer tokens from * @param _amount uint256 the number of tokens */ modifier canStake(address _address, uint256 _amount) { require( stakingToken.transferFrom(_address, this, _amount), "Stake required"); _; } /** * @dev Constructor function * @param _stakingToken ERC20 The address of the token contract used for staking */ constructor(ERC20 _stakingToken) public { stakingToken = _stakingToken; } /** * @dev Returns the timestamps for when active personal stakes for an address will unlock * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return uint256[] array of timestamps */ function getPersonalStakeUnlockedTimestamps(address _address) external view returns (uint256[]) { uint256[] memory timestamps; (timestamps,,) = getPersonalStakes(_address); return timestamps; } /** * @dev Returns the stake actualAmount for active personal stakes for an address * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return uint256[] array of actualAmounts */ function getPersonalStakeActualAmounts(address _address) external view returns (uint256[]) { uint256[] memory actualAmounts; (,actualAmounts,) = getPersonalStakes(_address); return actualAmounts; } /** * @dev Returns the addresses that each personal stake was created for by an address * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return address[] array of amounts */ function getPersonalStakeForAddresses(address _address) external view returns (address[]) { address[] memory stakedFor; (,,stakedFor) = getPersonalStakes(_address); return stakedFor; } /** * @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the user * @notice MUST trigger Staked event * @param _amount uint256 the amount of tokens to stake * @param _data bytes optional data to include in the Stake event */ function stake(uint256 _amount, bytes _data) public { createStake( msg.sender, _amount, defaultLockInDuration, _data); } /** * @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the caller * @notice MUST trigger Staked event * @param _user address the address the tokens are staked for * @param _amount uint256 the amount of tokens to stake * @param _data bytes optional data to include in the Stake event */ function stakeFor(address _user, uint256 _amount, bytes _data) public { createStake( _user, _amount, defaultLockInDuration, _data); } /** * @notice Unstakes a certain amount of tokens, this SHOULD return the given amount of tokens to the user, if unstaking is currently not possible the function MUST revert * @notice MUST trigger Unstaked event * @dev Unstaking tokens is an atomic operation—either all of the tokens in a stake, or none of the tokens. * @dev Users can only unstake a single stake at a time, it is must be their oldest active stake. Upon releasing that stake, the tokens will be * transferred back to their account, and their personalStakeIndex will increment to the next active stake. * @param _amount uint256 the amount of tokens to unstake * @param _data bytes optional data to include in the Unstake event */ function unstake(uint256 _amount, bytes _data) public { withdrawStake( _amount, _data); } /** * @notice Returns the current total of tokens staked for an address * @param _address address The address to query * @return uint256 The number of tokens staked for the given address */ function totalStakedFor(address _address) public view returns (uint256) { return stakeHolders[_address].totalStakedFor; } /** * @notice Returns the current total of tokens staked * @return uint256 The number of tokens staked in the contract */ function totalStaked() public view returns (uint256) { return stakingToken.balanceOf(this); } /** * @notice Address of the token being used by the staking interface * @return address The address of the ERC20 token used for staking */ function token() public view returns (address) { return stakingToken; } /** * @notice MUST return true if the optional history functions are implemented, otherwise false * @dev Since we don't implement the optional interface, this always returns false * @return bool Whether or not the optional history functions are implemented */ function supportsHistory() public pure returns (bool) { return false; } /** * @dev Helper function to get specific properties of all of the personal stakes created by an address * @param _address address The address to query * @return (uint256[], uint256[], address[]) * timestamps array, actualAmounts array, stakedFor array */ function getPersonalStakes( address _address ) public view returns(uint256[], uint256[], address[]) { StakeContract storage stakeContract = stakeHolders[_address]; uint256 arraySize = stakeContract.personalStakes.length - stakeContract.personalStakeIndex; uint256[] memory unlockedTimestamps = new uint256[](arraySize); uint256[] memory actualAmounts = new uint256[](arraySize); address[] memory stakedFor = new address[](arraySize); for (uint256 i = stakeContract.personalStakeIndex; i < stakeContract.personalStakes.length; i++) { uint256 index = i - stakeContract.personalStakeIndex; unlockedTimestamps[index] = stakeContract.personalStakes[i].unlockedTimestamp; actualAmounts[index] = stakeContract.personalStakes[i].actualAmount; stakedFor[index] = stakeContract.personalStakes[i].stakedFor; } return ( unlockedTimestamps, actualAmounts, stakedFor ); } /** * @dev Helper function to create stakes for a given address * @param _address address The address the stake is being created for * @param _amount uint256 The number of tokens being staked * @param _lockInDuration uint256 The duration to lock the tokens for * @param _data bytes optional data to include in the Stake event */ function createStake( address _address, uint256 _amount, uint256 _lockInDuration, bytes _data ) internal canStake(msg.sender, _amount) { require( _amount > 0, "Stake amount has to be greater than 0!"); if (!stakeHolders[msg.sender].exists) { stakeHolders[msg.sender].exists = true; } stakeHolders[_address].totalStakedFor = stakeHolders[_address].totalStakedFor.add(_amount); stakeHolders[msg.sender].personalStakes.push( Stake( block.timestamp.add(_lockInDuration), _amount, _address) ); emit Staked( _address, _amount, totalStakedFor(_address), _data); } /** * @dev Helper function to withdraw stakes for the msg.sender * @param _amount uint256 The amount to withdraw. MUST match the stake amount for the * stake at personalStakeIndex. * @param _data bytes optional data to include in the Unstake event */ function withdrawStake( uint256 _amount, bytes _data ) internal { Stake storage personalStake = stakeHolders[msg.sender].personalStakes[stakeHolders[msg.sender].personalStakeIndex]; // Check that the current stake has unlocked & matches the unstake amount require( personalStake.unlockedTimestamp <= block.timestamp, "The current stake hasn't unlocked yet"); require( personalStake.actualAmount == _amount, "The unstake amount does not match the current stake"); // Transfer the staked tokens from this contract back to the sender // Notice that we are using transfer instead of transferFrom here, so // no approval is needed beforehand. require( stakingToken.transfer(msg.sender, _amount), "Unable to withdraw stake"); stakeHolders[personalStake.stakedFor].totalStakedFor = stakeHolders[personalStake.stakedFor] .totalStakedFor.sub(personalStake.actualAmount); personalStake.actualAmount = 0; stakeHolders[msg.sender].personalStakeIndex++; emit Unstaked( personalStake.stakedFor, _amount, totalStakedFor(personalStake.stakedFor), _data); } }
unstake
function unstake(uint256 _amount, bytes _data) public { withdrawStake( _amount, _data); }
/** * @notice Unstakes a certain amount of tokens, this SHOULD return the given amount of tokens to the user, if unstaking is currently not possible the function MUST revert * @notice MUST trigger Unstaked event * @dev Unstaking tokens is an atomic operation—either all of the tokens in a stake, or none of the tokens. * @dev Users can only unstake a single stake at a time, it is must be their oldest active stake. Upon releasing that stake, the tokens will be * transferred back to their account, and their personalStakeIndex will increment to the next active stake. * @param _amount uint256 the amount of tokens to unstake * @param _data bytes optional data to include in the Unstake event */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
None
bzzr://4b303eb18851047dc1d29ae82f12547c01d9658bb358f1143c0be5c6bdd9f246
{ "func_code_index": [ 5584, 5698 ] }
7,627
BasicStakingContract
BasicStakingContract.sol
0x583d4d39b740e2582febab65a9437e46692f932a
Solidity
ERC900BasicStakeContract
contract ERC900BasicStakeContract is ERC900 { // @TODO: deploy this separately so we don't have to deploy it multiple times for each contract using SafeMath for uint256; // Token used for staking ERC20 stakingToken; // The default duration of stake lock-in (in seconds) uint256 public defaultLockInDuration; // To save on gas, rather than create a separate mapping for totalStakedFor & personalStakes, // both data structures are stored in a single mapping for a given addresses. // // It's possible to have a non-existing personalStakes, but have tokens in totalStakedFor // if other users are staking on behalf of a given address. mapping (address => StakeContract) public stakeHolders; // Struct for personal stakes (i.e., stakes made by this address) // unlockedTimestamp - when the stake unlocks (in seconds since Unix epoch) // actualAmount - the amount of tokens in the stake // stakedFor - the address the stake was staked for struct Stake { uint256 unlockedTimestamp; uint256 actualAmount; address stakedFor; } // Struct for all stake metadata at a particular address // totalStakedFor - the number of tokens staked for this address // personalStakeIndex - the index in the personalStakes array. // personalStakes - append only array of stakes made by this address // exists - whether or not there are stakes that involve this address struct StakeContract { uint256 totalStakedFor; uint256 personalStakeIndex; Stake[] personalStakes; bool exists; } /** * @dev Modifier that checks that this contract can transfer tokens from the * balance in the stakingToken contract for the given address. * @dev This modifier also transfers the tokens. * @param _address address to transfer tokens from * @param _amount uint256 the number of tokens */ modifier canStake(address _address, uint256 _amount) { require( stakingToken.transferFrom(_address, this, _amount), "Stake required"); _; } /** * @dev Constructor function * @param _stakingToken ERC20 The address of the token contract used for staking */ constructor(ERC20 _stakingToken) public { stakingToken = _stakingToken; } /** * @dev Returns the timestamps for when active personal stakes for an address will unlock * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return uint256[] array of timestamps */ function getPersonalStakeUnlockedTimestamps(address _address) external view returns (uint256[]) { uint256[] memory timestamps; (timestamps,,) = getPersonalStakes(_address); return timestamps; } /** * @dev Returns the stake actualAmount for active personal stakes for an address * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return uint256[] array of actualAmounts */ function getPersonalStakeActualAmounts(address _address) external view returns (uint256[]) { uint256[] memory actualAmounts; (,actualAmounts,) = getPersonalStakes(_address); return actualAmounts; } /** * @dev Returns the addresses that each personal stake was created for by an address * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return address[] array of amounts */ function getPersonalStakeForAddresses(address _address) external view returns (address[]) { address[] memory stakedFor; (,,stakedFor) = getPersonalStakes(_address); return stakedFor; } /** * @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the user * @notice MUST trigger Staked event * @param _amount uint256 the amount of tokens to stake * @param _data bytes optional data to include in the Stake event */ function stake(uint256 _amount, bytes _data) public { createStake( msg.sender, _amount, defaultLockInDuration, _data); } /** * @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the caller * @notice MUST trigger Staked event * @param _user address the address the tokens are staked for * @param _amount uint256 the amount of tokens to stake * @param _data bytes optional data to include in the Stake event */ function stakeFor(address _user, uint256 _amount, bytes _data) public { createStake( _user, _amount, defaultLockInDuration, _data); } /** * @notice Unstakes a certain amount of tokens, this SHOULD return the given amount of tokens to the user, if unstaking is currently not possible the function MUST revert * @notice MUST trigger Unstaked event * @dev Unstaking tokens is an atomic operation—either all of the tokens in a stake, or none of the tokens. * @dev Users can only unstake a single stake at a time, it is must be their oldest active stake. Upon releasing that stake, the tokens will be * transferred back to their account, and their personalStakeIndex will increment to the next active stake. * @param _amount uint256 the amount of tokens to unstake * @param _data bytes optional data to include in the Unstake event */ function unstake(uint256 _amount, bytes _data) public { withdrawStake( _amount, _data); } /** * @notice Returns the current total of tokens staked for an address * @param _address address The address to query * @return uint256 The number of tokens staked for the given address */ function totalStakedFor(address _address) public view returns (uint256) { return stakeHolders[_address].totalStakedFor; } /** * @notice Returns the current total of tokens staked * @return uint256 The number of tokens staked in the contract */ function totalStaked() public view returns (uint256) { return stakingToken.balanceOf(this); } /** * @notice Address of the token being used by the staking interface * @return address The address of the ERC20 token used for staking */ function token() public view returns (address) { return stakingToken; } /** * @notice MUST return true if the optional history functions are implemented, otherwise false * @dev Since we don't implement the optional interface, this always returns false * @return bool Whether or not the optional history functions are implemented */ function supportsHistory() public pure returns (bool) { return false; } /** * @dev Helper function to get specific properties of all of the personal stakes created by an address * @param _address address The address to query * @return (uint256[], uint256[], address[]) * timestamps array, actualAmounts array, stakedFor array */ function getPersonalStakes( address _address ) public view returns(uint256[], uint256[], address[]) { StakeContract storage stakeContract = stakeHolders[_address]; uint256 arraySize = stakeContract.personalStakes.length - stakeContract.personalStakeIndex; uint256[] memory unlockedTimestamps = new uint256[](arraySize); uint256[] memory actualAmounts = new uint256[](arraySize); address[] memory stakedFor = new address[](arraySize); for (uint256 i = stakeContract.personalStakeIndex; i < stakeContract.personalStakes.length; i++) { uint256 index = i - stakeContract.personalStakeIndex; unlockedTimestamps[index] = stakeContract.personalStakes[i].unlockedTimestamp; actualAmounts[index] = stakeContract.personalStakes[i].actualAmount; stakedFor[index] = stakeContract.personalStakes[i].stakedFor; } return ( unlockedTimestamps, actualAmounts, stakedFor ); } /** * @dev Helper function to create stakes for a given address * @param _address address The address the stake is being created for * @param _amount uint256 The number of tokens being staked * @param _lockInDuration uint256 The duration to lock the tokens for * @param _data bytes optional data to include in the Stake event */ function createStake( address _address, uint256 _amount, uint256 _lockInDuration, bytes _data ) internal canStake(msg.sender, _amount) { require( _amount > 0, "Stake amount has to be greater than 0!"); if (!stakeHolders[msg.sender].exists) { stakeHolders[msg.sender].exists = true; } stakeHolders[_address].totalStakedFor = stakeHolders[_address].totalStakedFor.add(_amount); stakeHolders[msg.sender].personalStakes.push( Stake( block.timestamp.add(_lockInDuration), _amount, _address) ); emit Staked( _address, _amount, totalStakedFor(_address), _data); } /** * @dev Helper function to withdraw stakes for the msg.sender * @param _amount uint256 The amount to withdraw. MUST match the stake amount for the * stake at personalStakeIndex. * @param _data bytes optional data to include in the Unstake event */ function withdrawStake( uint256 _amount, bytes _data ) internal { Stake storage personalStake = stakeHolders[msg.sender].personalStakes[stakeHolders[msg.sender].personalStakeIndex]; // Check that the current stake has unlocked & matches the unstake amount require( personalStake.unlockedTimestamp <= block.timestamp, "The current stake hasn't unlocked yet"); require( personalStake.actualAmount == _amount, "The unstake amount does not match the current stake"); // Transfer the staked tokens from this contract back to the sender // Notice that we are using transfer instead of transferFrom here, so // no approval is needed beforehand. require( stakingToken.transfer(msg.sender, _amount), "Unable to withdraw stake"); stakeHolders[personalStake.stakedFor].totalStakedFor = stakeHolders[personalStake.stakedFor] .totalStakedFor.sub(personalStake.actualAmount); personalStake.actualAmount = 0; stakeHolders[msg.sender].personalStakeIndex++; emit Unstaked( personalStake.stakedFor, _amount, totalStakedFor(personalStake.stakedFor), _data); } }
totalStakedFor
function totalStakedFor(address _address) public view returns (uint256) { return stakeHolders[_address].totalStakedFor; }
/** * @notice Returns the current total of tokens staked for an address * @param _address address The address to query * @return uint256 The number of tokens staked for the given address */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
None
bzzr://4b303eb18851047dc1d29ae82f12547c01d9658bb358f1143c0be5c6bdd9f246
{ "func_code_index": [ 5910, 6042 ] }
7,628
BasicStakingContract
BasicStakingContract.sol
0x583d4d39b740e2582febab65a9437e46692f932a
Solidity
ERC900BasicStakeContract
contract ERC900BasicStakeContract is ERC900 { // @TODO: deploy this separately so we don't have to deploy it multiple times for each contract using SafeMath for uint256; // Token used for staking ERC20 stakingToken; // The default duration of stake lock-in (in seconds) uint256 public defaultLockInDuration; // To save on gas, rather than create a separate mapping for totalStakedFor & personalStakes, // both data structures are stored in a single mapping for a given addresses. // // It's possible to have a non-existing personalStakes, but have tokens in totalStakedFor // if other users are staking on behalf of a given address. mapping (address => StakeContract) public stakeHolders; // Struct for personal stakes (i.e., stakes made by this address) // unlockedTimestamp - when the stake unlocks (in seconds since Unix epoch) // actualAmount - the amount of tokens in the stake // stakedFor - the address the stake was staked for struct Stake { uint256 unlockedTimestamp; uint256 actualAmount; address stakedFor; } // Struct for all stake metadata at a particular address // totalStakedFor - the number of tokens staked for this address // personalStakeIndex - the index in the personalStakes array. // personalStakes - append only array of stakes made by this address // exists - whether or not there are stakes that involve this address struct StakeContract { uint256 totalStakedFor; uint256 personalStakeIndex; Stake[] personalStakes; bool exists; } /** * @dev Modifier that checks that this contract can transfer tokens from the * balance in the stakingToken contract for the given address. * @dev This modifier also transfers the tokens. * @param _address address to transfer tokens from * @param _amount uint256 the number of tokens */ modifier canStake(address _address, uint256 _amount) { require( stakingToken.transferFrom(_address, this, _amount), "Stake required"); _; } /** * @dev Constructor function * @param _stakingToken ERC20 The address of the token contract used for staking */ constructor(ERC20 _stakingToken) public { stakingToken = _stakingToken; } /** * @dev Returns the timestamps for when active personal stakes for an address will unlock * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return uint256[] array of timestamps */ function getPersonalStakeUnlockedTimestamps(address _address) external view returns (uint256[]) { uint256[] memory timestamps; (timestamps,,) = getPersonalStakes(_address); return timestamps; } /** * @dev Returns the stake actualAmount for active personal stakes for an address * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return uint256[] array of actualAmounts */ function getPersonalStakeActualAmounts(address _address) external view returns (uint256[]) { uint256[] memory actualAmounts; (,actualAmounts,) = getPersonalStakes(_address); return actualAmounts; } /** * @dev Returns the addresses that each personal stake was created for by an address * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return address[] array of amounts */ function getPersonalStakeForAddresses(address _address) external view returns (address[]) { address[] memory stakedFor; (,,stakedFor) = getPersonalStakes(_address); return stakedFor; } /** * @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the user * @notice MUST trigger Staked event * @param _amount uint256 the amount of tokens to stake * @param _data bytes optional data to include in the Stake event */ function stake(uint256 _amount, bytes _data) public { createStake( msg.sender, _amount, defaultLockInDuration, _data); } /** * @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the caller * @notice MUST trigger Staked event * @param _user address the address the tokens are staked for * @param _amount uint256 the amount of tokens to stake * @param _data bytes optional data to include in the Stake event */ function stakeFor(address _user, uint256 _amount, bytes _data) public { createStake( _user, _amount, defaultLockInDuration, _data); } /** * @notice Unstakes a certain amount of tokens, this SHOULD return the given amount of tokens to the user, if unstaking is currently not possible the function MUST revert * @notice MUST trigger Unstaked event * @dev Unstaking tokens is an atomic operation—either all of the tokens in a stake, or none of the tokens. * @dev Users can only unstake a single stake at a time, it is must be their oldest active stake. Upon releasing that stake, the tokens will be * transferred back to their account, and their personalStakeIndex will increment to the next active stake. * @param _amount uint256 the amount of tokens to unstake * @param _data bytes optional data to include in the Unstake event */ function unstake(uint256 _amount, bytes _data) public { withdrawStake( _amount, _data); } /** * @notice Returns the current total of tokens staked for an address * @param _address address The address to query * @return uint256 The number of tokens staked for the given address */ function totalStakedFor(address _address) public view returns (uint256) { return stakeHolders[_address].totalStakedFor; } /** * @notice Returns the current total of tokens staked * @return uint256 The number of tokens staked in the contract */ function totalStaked() public view returns (uint256) { return stakingToken.balanceOf(this); } /** * @notice Address of the token being used by the staking interface * @return address The address of the ERC20 token used for staking */ function token() public view returns (address) { return stakingToken; } /** * @notice MUST return true if the optional history functions are implemented, otherwise false * @dev Since we don't implement the optional interface, this always returns false * @return bool Whether or not the optional history functions are implemented */ function supportsHistory() public pure returns (bool) { return false; } /** * @dev Helper function to get specific properties of all of the personal stakes created by an address * @param _address address The address to query * @return (uint256[], uint256[], address[]) * timestamps array, actualAmounts array, stakedFor array */ function getPersonalStakes( address _address ) public view returns(uint256[], uint256[], address[]) { StakeContract storage stakeContract = stakeHolders[_address]; uint256 arraySize = stakeContract.personalStakes.length - stakeContract.personalStakeIndex; uint256[] memory unlockedTimestamps = new uint256[](arraySize); uint256[] memory actualAmounts = new uint256[](arraySize); address[] memory stakedFor = new address[](arraySize); for (uint256 i = stakeContract.personalStakeIndex; i < stakeContract.personalStakes.length; i++) { uint256 index = i - stakeContract.personalStakeIndex; unlockedTimestamps[index] = stakeContract.personalStakes[i].unlockedTimestamp; actualAmounts[index] = stakeContract.personalStakes[i].actualAmount; stakedFor[index] = stakeContract.personalStakes[i].stakedFor; } return ( unlockedTimestamps, actualAmounts, stakedFor ); } /** * @dev Helper function to create stakes for a given address * @param _address address The address the stake is being created for * @param _amount uint256 The number of tokens being staked * @param _lockInDuration uint256 The duration to lock the tokens for * @param _data bytes optional data to include in the Stake event */ function createStake( address _address, uint256 _amount, uint256 _lockInDuration, bytes _data ) internal canStake(msg.sender, _amount) { require( _amount > 0, "Stake amount has to be greater than 0!"); if (!stakeHolders[msg.sender].exists) { stakeHolders[msg.sender].exists = true; } stakeHolders[_address].totalStakedFor = stakeHolders[_address].totalStakedFor.add(_amount); stakeHolders[msg.sender].personalStakes.push( Stake( block.timestamp.add(_lockInDuration), _amount, _address) ); emit Staked( _address, _amount, totalStakedFor(_address), _data); } /** * @dev Helper function to withdraw stakes for the msg.sender * @param _amount uint256 The amount to withdraw. MUST match the stake amount for the * stake at personalStakeIndex. * @param _data bytes optional data to include in the Unstake event */ function withdrawStake( uint256 _amount, bytes _data ) internal { Stake storage personalStake = stakeHolders[msg.sender].personalStakes[stakeHolders[msg.sender].personalStakeIndex]; // Check that the current stake has unlocked & matches the unstake amount require( personalStake.unlockedTimestamp <= block.timestamp, "The current stake hasn't unlocked yet"); require( personalStake.actualAmount == _amount, "The unstake amount does not match the current stake"); // Transfer the staked tokens from this contract back to the sender // Notice that we are using transfer instead of transferFrom here, so // no approval is needed beforehand. require( stakingToken.transfer(msg.sender, _amount), "Unable to withdraw stake"); stakeHolders[personalStake.stakedFor].totalStakedFor = stakeHolders[personalStake.stakedFor] .totalStakedFor.sub(personalStake.actualAmount); personalStake.actualAmount = 0; stakeHolders[msg.sender].personalStakeIndex++; emit Unstaked( personalStake.stakedFor, _amount, totalStakedFor(personalStake.stakedFor), _data); } }
totalStaked
function totalStaked() public view returns (uint256) { return stakingToken.balanceOf(this); }
/** * @notice Returns the current total of tokens staked * @return uint256 The number of tokens staked in the contract */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
None
bzzr://4b303eb18851047dc1d29ae82f12547c01d9658bb358f1143c0be5c6bdd9f246
{ "func_code_index": [ 6182, 6286 ] }
7,629
BasicStakingContract
BasicStakingContract.sol
0x583d4d39b740e2582febab65a9437e46692f932a
Solidity
ERC900BasicStakeContract
contract ERC900BasicStakeContract is ERC900 { // @TODO: deploy this separately so we don't have to deploy it multiple times for each contract using SafeMath for uint256; // Token used for staking ERC20 stakingToken; // The default duration of stake lock-in (in seconds) uint256 public defaultLockInDuration; // To save on gas, rather than create a separate mapping for totalStakedFor & personalStakes, // both data structures are stored in a single mapping for a given addresses. // // It's possible to have a non-existing personalStakes, but have tokens in totalStakedFor // if other users are staking on behalf of a given address. mapping (address => StakeContract) public stakeHolders; // Struct for personal stakes (i.e., stakes made by this address) // unlockedTimestamp - when the stake unlocks (in seconds since Unix epoch) // actualAmount - the amount of tokens in the stake // stakedFor - the address the stake was staked for struct Stake { uint256 unlockedTimestamp; uint256 actualAmount; address stakedFor; } // Struct for all stake metadata at a particular address // totalStakedFor - the number of tokens staked for this address // personalStakeIndex - the index in the personalStakes array. // personalStakes - append only array of stakes made by this address // exists - whether or not there are stakes that involve this address struct StakeContract { uint256 totalStakedFor; uint256 personalStakeIndex; Stake[] personalStakes; bool exists; } /** * @dev Modifier that checks that this contract can transfer tokens from the * balance in the stakingToken contract for the given address. * @dev This modifier also transfers the tokens. * @param _address address to transfer tokens from * @param _amount uint256 the number of tokens */ modifier canStake(address _address, uint256 _amount) { require( stakingToken.transferFrom(_address, this, _amount), "Stake required"); _; } /** * @dev Constructor function * @param _stakingToken ERC20 The address of the token contract used for staking */ constructor(ERC20 _stakingToken) public { stakingToken = _stakingToken; } /** * @dev Returns the timestamps for when active personal stakes for an address will unlock * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return uint256[] array of timestamps */ function getPersonalStakeUnlockedTimestamps(address _address) external view returns (uint256[]) { uint256[] memory timestamps; (timestamps,,) = getPersonalStakes(_address); return timestamps; } /** * @dev Returns the stake actualAmount for active personal stakes for an address * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return uint256[] array of actualAmounts */ function getPersonalStakeActualAmounts(address _address) external view returns (uint256[]) { uint256[] memory actualAmounts; (,actualAmounts,) = getPersonalStakes(_address); return actualAmounts; } /** * @dev Returns the addresses that each personal stake was created for by an address * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return address[] array of amounts */ function getPersonalStakeForAddresses(address _address) external view returns (address[]) { address[] memory stakedFor; (,,stakedFor) = getPersonalStakes(_address); return stakedFor; } /** * @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the user * @notice MUST trigger Staked event * @param _amount uint256 the amount of tokens to stake * @param _data bytes optional data to include in the Stake event */ function stake(uint256 _amount, bytes _data) public { createStake( msg.sender, _amount, defaultLockInDuration, _data); } /** * @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the caller * @notice MUST trigger Staked event * @param _user address the address the tokens are staked for * @param _amount uint256 the amount of tokens to stake * @param _data bytes optional data to include in the Stake event */ function stakeFor(address _user, uint256 _amount, bytes _data) public { createStake( _user, _amount, defaultLockInDuration, _data); } /** * @notice Unstakes a certain amount of tokens, this SHOULD return the given amount of tokens to the user, if unstaking is currently not possible the function MUST revert * @notice MUST trigger Unstaked event * @dev Unstaking tokens is an atomic operation—either all of the tokens in a stake, or none of the tokens. * @dev Users can only unstake a single stake at a time, it is must be their oldest active stake. Upon releasing that stake, the tokens will be * transferred back to their account, and their personalStakeIndex will increment to the next active stake. * @param _amount uint256 the amount of tokens to unstake * @param _data bytes optional data to include in the Unstake event */ function unstake(uint256 _amount, bytes _data) public { withdrawStake( _amount, _data); } /** * @notice Returns the current total of tokens staked for an address * @param _address address The address to query * @return uint256 The number of tokens staked for the given address */ function totalStakedFor(address _address) public view returns (uint256) { return stakeHolders[_address].totalStakedFor; } /** * @notice Returns the current total of tokens staked * @return uint256 The number of tokens staked in the contract */ function totalStaked() public view returns (uint256) { return stakingToken.balanceOf(this); } /** * @notice Address of the token being used by the staking interface * @return address The address of the ERC20 token used for staking */ function token() public view returns (address) { return stakingToken; } /** * @notice MUST return true if the optional history functions are implemented, otherwise false * @dev Since we don't implement the optional interface, this always returns false * @return bool Whether or not the optional history functions are implemented */ function supportsHistory() public pure returns (bool) { return false; } /** * @dev Helper function to get specific properties of all of the personal stakes created by an address * @param _address address The address to query * @return (uint256[], uint256[], address[]) * timestamps array, actualAmounts array, stakedFor array */ function getPersonalStakes( address _address ) public view returns(uint256[], uint256[], address[]) { StakeContract storage stakeContract = stakeHolders[_address]; uint256 arraySize = stakeContract.personalStakes.length - stakeContract.personalStakeIndex; uint256[] memory unlockedTimestamps = new uint256[](arraySize); uint256[] memory actualAmounts = new uint256[](arraySize); address[] memory stakedFor = new address[](arraySize); for (uint256 i = stakeContract.personalStakeIndex; i < stakeContract.personalStakes.length; i++) { uint256 index = i - stakeContract.personalStakeIndex; unlockedTimestamps[index] = stakeContract.personalStakes[i].unlockedTimestamp; actualAmounts[index] = stakeContract.personalStakes[i].actualAmount; stakedFor[index] = stakeContract.personalStakes[i].stakedFor; } return ( unlockedTimestamps, actualAmounts, stakedFor ); } /** * @dev Helper function to create stakes for a given address * @param _address address The address the stake is being created for * @param _amount uint256 The number of tokens being staked * @param _lockInDuration uint256 The duration to lock the tokens for * @param _data bytes optional data to include in the Stake event */ function createStake( address _address, uint256 _amount, uint256 _lockInDuration, bytes _data ) internal canStake(msg.sender, _amount) { require( _amount > 0, "Stake amount has to be greater than 0!"); if (!stakeHolders[msg.sender].exists) { stakeHolders[msg.sender].exists = true; } stakeHolders[_address].totalStakedFor = stakeHolders[_address].totalStakedFor.add(_amount); stakeHolders[msg.sender].personalStakes.push( Stake( block.timestamp.add(_lockInDuration), _amount, _address) ); emit Staked( _address, _amount, totalStakedFor(_address), _data); } /** * @dev Helper function to withdraw stakes for the msg.sender * @param _amount uint256 The amount to withdraw. MUST match the stake amount for the * stake at personalStakeIndex. * @param _data bytes optional data to include in the Unstake event */ function withdrawStake( uint256 _amount, bytes _data ) internal { Stake storage personalStake = stakeHolders[msg.sender].personalStakes[stakeHolders[msg.sender].personalStakeIndex]; // Check that the current stake has unlocked & matches the unstake amount require( personalStake.unlockedTimestamp <= block.timestamp, "The current stake hasn't unlocked yet"); require( personalStake.actualAmount == _amount, "The unstake amount does not match the current stake"); // Transfer the staked tokens from this contract back to the sender // Notice that we are using transfer instead of transferFrom here, so // no approval is needed beforehand. require( stakingToken.transfer(msg.sender, _amount), "Unable to withdraw stake"); stakeHolders[personalStake.stakedFor].totalStakedFor = stakeHolders[personalStake.stakedFor] .totalStakedFor.sub(personalStake.actualAmount); personalStake.actualAmount = 0; stakeHolders[msg.sender].personalStakeIndex++; emit Unstaked( personalStake.stakedFor, _amount, totalStakedFor(personalStake.stakedFor), _data); } }
token
function token() public view returns (address) { return stakingToken; }
/** * @notice Address of the token being used by the staking interface * @return address The address of the ERC20 token used for staking */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
None
bzzr://4b303eb18851047dc1d29ae82f12547c01d9658bb358f1143c0be5c6bdd9f246
{ "func_code_index": [ 6444, 6526 ] }
7,630
BasicStakingContract
BasicStakingContract.sol
0x583d4d39b740e2582febab65a9437e46692f932a
Solidity
ERC900BasicStakeContract
contract ERC900BasicStakeContract is ERC900 { // @TODO: deploy this separately so we don't have to deploy it multiple times for each contract using SafeMath for uint256; // Token used for staking ERC20 stakingToken; // The default duration of stake lock-in (in seconds) uint256 public defaultLockInDuration; // To save on gas, rather than create a separate mapping for totalStakedFor & personalStakes, // both data structures are stored in a single mapping for a given addresses. // // It's possible to have a non-existing personalStakes, but have tokens in totalStakedFor // if other users are staking on behalf of a given address. mapping (address => StakeContract) public stakeHolders; // Struct for personal stakes (i.e., stakes made by this address) // unlockedTimestamp - when the stake unlocks (in seconds since Unix epoch) // actualAmount - the amount of tokens in the stake // stakedFor - the address the stake was staked for struct Stake { uint256 unlockedTimestamp; uint256 actualAmount; address stakedFor; } // Struct for all stake metadata at a particular address // totalStakedFor - the number of tokens staked for this address // personalStakeIndex - the index in the personalStakes array. // personalStakes - append only array of stakes made by this address // exists - whether or not there are stakes that involve this address struct StakeContract { uint256 totalStakedFor; uint256 personalStakeIndex; Stake[] personalStakes; bool exists; } /** * @dev Modifier that checks that this contract can transfer tokens from the * balance in the stakingToken contract for the given address. * @dev This modifier also transfers the tokens. * @param _address address to transfer tokens from * @param _amount uint256 the number of tokens */ modifier canStake(address _address, uint256 _amount) { require( stakingToken.transferFrom(_address, this, _amount), "Stake required"); _; } /** * @dev Constructor function * @param _stakingToken ERC20 The address of the token contract used for staking */ constructor(ERC20 _stakingToken) public { stakingToken = _stakingToken; } /** * @dev Returns the timestamps for when active personal stakes for an address will unlock * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return uint256[] array of timestamps */ function getPersonalStakeUnlockedTimestamps(address _address) external view returns (uint256[]) { uint256[] memory timestamps; (timestamps,,) = getPersonalStakes(_address); return timestamps; } /** * @dev Returns the stake actualAmount for active personal stakes for an address * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return uint256[] array of actualAmounts */ function getPersonalStakeActualAmounts(address _address) external view returns (uint256[]) { uint256[] memory actualAmounts; (,actualAmounts,) = getPersonalStakes(_address); return actualAmounts; } /** * @dev Returns the addresses that each personal stake was created for by an address * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return address[] array of amounts */ function getPersonalStakeForAddresses(address _address) external view returns (address[]) { address[] memory stakedFor; (,,stakedFor) = getPersonalStakes(_address); return stakedFor; } /** * @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the user * @notice MUST trigger Staked event * @param _amount uint256 the amount of tokens to stake * @param _data bytes optional data to include in the Stake event */ function stake(uint256 _amount, bytes _data) public { createStake( msg.sender, _amount, defaultLockInDuration, _data); } /** * @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the caller * @notice MUST trigger Staked event * @param _user address the address the tokens are staked for * @param _amount uint256 the amount of tokens to stake * @param _data bytes optional data to include in the Stake event */ function stakeFor(address _user, uint256 _amount, bytes _data) public { createStake( _user, _amount, defaultLockInDuration, _data); } /** * @notice Unstakes a certain amount of tokens, this SHOULD return the given amount of tokens to the user, if unstaking is currently not possible the function MUST revert * @notice MUST trigger Unstaked event * @dev Unstaking tokens is an atomic operation—either all of the tokens in a stake, or none of the tokens. * @dev Users can only unstake a single stake at a time, it is must be their oldest active stake. Upon releasing that stake, the tokens will be * transferred back to their account, and their personalStakeIndex will increment to the next active stake. * @param _amount uint256 the amount of tokens to unstake * @param _data bytes optional data to include in the Unstake event */ function unstake(uint256 _amount, bytes _data) public { withdrawStake( _amount, _data); } /** * @notice Returns the current total of tokens staked for an address * @param _address address The address to query * @return uint256 The number of tokens staked for the given address */ function totalStakedFor(address _address) public view returns (uint256) { return stakeHolders[_address].totalStakedFor; } /** * @notice Returns the current total of tokens staked * @return uint256 The number of tokens staked in the contract */ function totalStaked() public view returns (uint256) { return stakingToken.balanceOf(this); } /** * @notice Address of the token being used by the staking interface * @return address The address of the ERC20 token used for staking */ function token() public view returns (address) { return stakingToken; } /** * @notice MUST return true if the optional history functions are implemented, otherwise false * @dev Since we don't implement the optional interface, this always returns false * @return bool Whether or not the optional history functions are implemented */ function supportsHistory() public pure returns (bool) { return false; } /** * @dev Helper function to get specific properties of all of the personal stakes created by an address * @param _address address The address to query * @return (uint256[], uint256[], address[]) * timestamps array, actualAmounts array, stakedFor array */ function getPersonalStakes( address _address ) public view returns(uint256[], uint256[], address[]) { StakeContract storage stakeContract = stakeHolders[_address]; uint256 arraySize = stakeContract.personalStakes.length - stakeContract.personalStakeIndex; uint256[] memory unlockedTimestamps = new uint256[](arraySize); uint256[] memory actualAmounts = new uint256[](arraySize); address[] memory stakedFor = new address[](arraySize); for (uint256 i = stakeContract.personalStakeIndex; i < stakeContract.personalStakes.length; i++) { uint256 index = i - stakeContract.personalStakeIndex; unlockedTimestamps[index] = stakeContract.personalStakes[i].unlockedTimestamp; actualAmounts[index] = stakeContract.personalStakes[i].actualAmount; stakedFor[index] = stakeContract.personalStakes[i].stakedFor; } return ( unlockedTimestamps, actualAmounts, stakedFor ); } /** * @dev Helper function to create stakes for a given address * @param _address address The address the stake is being created for * @param _amount uint256 The number of tokens being staked * @param _lockInDuration uint256 The duration to lock the tokens for * @param _data bytes optional data to include in the Stake event */ function createStake( address _address, uint256 _amount, uint256 _lockInDuration, bytes _data ) internal canStake(msg.sender, _amount) { require( _amount > 0, "Stake amount has to be greater than 0!"); if (!stakeHolders[msg.sender].exists) { stakeHolders[msg.sender].exists = true; } stakeHolders[_address].totalStakedFor = stakeHolders[_address].totalStakedFor.add(_amount); stakeHolders[msg.sender].personalStakes.push( Stake( block.timestamp.add(_lockInDuration), _amount, _address) ); emit Staked( _address, _amount, totalStakedFor(_address), _data); } /** * @dev Helper function to withdraw stakes for the msg.sender * @param _amount uint256 The amount to withdraw. MUST match the stake amount for the * stake at personalStakeIndex. * @param _data bytes optional data to include in the Unstake event */ function withdrawStake( uint256 _amount, bytes _data ) internal { Stake storage personalStake = stakeHolders[msg.sender].personalStakes[stakeHolders[msg.sender].personalStakeIndex]; // Check that the current stake has unlocked & matches the unstake amount require( personalStake.unlockedTimestamp <= block.timestamp, "The current stake hasn't unlocked yet"); require( personalStake.actualAmount == _amount, "The unstake amount does not match the current stake"); // Transfer the staked tokens from this contract back to the sender // Notice that we are using transfer instead of transferFrom here, so // no approval is needed beforehand. require( stakingToken.transfer(msg.sender, _amount), "Unable to withdraw stake"); stakeHolders[personalStake.stakedFor].totalStakedFor = stakeHolders[personalStake.stakedFor] .totalStakedFor.sub(personalStake.actualAmount); personalStake.actualAmount = 0; stakeHolders[msg.sender].personalStakeIndex++; emit Unstaked( personalStake.stakedFor, _amount, totalStakedFor(personalStake.stakedFor), _data); } }
supportsHistory
function supportsHistory() public pure returns (bool) { return false; }
/** * @notice MUST return true if the optional history functions are implemented, otherwise false * @dev Since we don't implement the optional interface, this always returns false * @return bool Whether or not the optional history functions are implemented */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
None
bzzr://4b303eb18851047dc1d29ae82f12547c01d9658bb358f1143c0be5c6bdd9f246
{ "func_code_index": [ 6808, 6890 ] }
7,631
BasicStakingContract
BasicStakingContract.sol
0x583d4d39b740e2582febab65a9437e46692f932a
Solidity
ERC900BasicStakeContract
contract ERC900BasicStakeContract is ERC900 { // @TODO: deploy this separately so we don't have to deploy it multiple times for each contract using SafeMath for uint256; // Token used for staking ERC20 stakingToken; // The default duration of stake lock-in (in seconds) uint256 public defaultLockInDuration; // To save on gas, rather than create a separate mapping for totalStakedFor & personalStakes, // both data structures are stored in a single mapping for a given addresses. // // It's possible to have a non-existing personalStakes, but have tokens in totalStakedFor // if other users are staking on behalf of a given address. mapping (address => StakeContract) public stakeHolders; // Struct for personal stakes (i.e., stakes made by this address) // unlockedTimestamp - when the stake unlocks (in seconds since Unix epoch) // actualAmount - the amount of tokens in the stake // stakedFor - the address the stake was staked for struct Stake { uint256 unlockedTimestamp; uint256 actualAmount; address stakedFor; } // Struct for all stake metadata at a particular address // totalStakedFor - the number of tokens staked for this address // personalStakeIndex - the index in the personalStakes array. // personalStakes - append only array of stakes made by this address // exists - whether or not there are stakes that involve this address struct StakeContract { uint256 totalStakedFor; uint256 personalStakeIndex; Stake[] personalStakes; bool exists; } /** * @dev Modifier that checks that this contract can transfer tokens from the * balance in the stakingToken contract for the given address. * @dev This modifier also transfers the tokens. * @param _address address to transfer tokens from * @param _amount uint256 the number of tokens */ modifier canStake(address _address, uint256 _amount) { require( stakingToken.transferFrom(_address, this, _amount), "Stake required"); _; } /** * @dev Constructor function * @param _stakingToken ERC20 The address of the token contract used for staking */ constructor(ERC20 _stakingToken) public { stakingToken = _stakingToken; } /** * @dev Returns the timestamps for when active personal stakes for an address will unlock * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return uint256[] array of timestamps */ function getPersonalStakeUnlockedTimestamps(address _address) external view returns (uint256[]) { uint256[] memory timestamps; (timestamps,,) = getPersonalStakes(_address); return timestamps; } /** * @dev Returns the stake actualAmount for active personal stakes for an address * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return uint256[] array of actualAmounts */ function getPersonalStakeActualAmounts(address _address) external view returns (uint256[]) { uint256[] memory actualAmounts; (,actualAmounts,) = getPersonalStakes(_address); return actualAmounts; } /** * @dev Returns the addresses that each personal stake was created for by an address * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return address[] array of amounts */ function getPersonalStakeForAddresses(address _address) external view returns (address[]) { address[] memory stakedFor; (,,stakedFor) = getPersonalStakes(_address); return stakedFor; } /** * @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the user * @notice MUST trigger Staked event * @param _amount uint256 the amount of tokens to stake * @param _data bytes optional data to include in the Stake event */ function stake(uint256 _amount, bytes _data) public { createStake( msg.sender, _amount, defaultLockInDuration, _data); } /** * @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the caller * @notice MUST trigger Staked event * @param _user address the address the tokens are staked for * @param _amount uint256 the amount of tokens to stake * @param _data bytes optional data to include in the Stake event */ function stakeFor(address _user, uint256 _amount, bytes _data) public { createStake( _user, _amount, defaultLockInDuration, _data); } /** * @notice Unstakes a certain amount of tokens, this SHOULD return the given amount of tokens to the user, if unstaking is currently not possible the function MUST revert * @notice MUST trigger Unstaked event * @dev Unstaking tokens is an atomic operation—either all of the tokens in a stake, or none of the tokens. * @dev Users can only unstake a single stake at a time, it is must be their oldest active stake. Upon releasing that stake, the tokens will be * transferred back to their account, and their personalStakeIndex will increment to the next active stake. * @param _amount uint256 the amount of tokens to unstake * @param _data bytes optional data to include in the Unstake event */ function unstake(uint256 _amount, bytes _data) public { withdrawStake( _amount, _data); } /** * @notice Returns the current total of tokens staked for an address * @param _address address The address to query * @return uint256 The number of tokens staked for the given address */ function totalStakedFor(address _address) public view returns (uint256) { return stakeHolders[_address].totalStakedFor; } /** * @notice Returns the current total of tokens staked * @return uint256 The number of tokens staked in the contract */ function totalStaked() public view returns (uint256) { return stakingToken.balanceOf(this); } /** * @notice Address of the token being used by the staking interface * @return address The address of the ERC20 token used for staking */ function token() public view returns (address) { return stakingToken; } /** * @notice MUST return true if the optional history functions are implemented, otherwise false * @dev Since we don't implement the optional interface, this always returns false * @return bool Whether or not the optional history functions are implemented */ function supportsHistory() public pure returns (bool) { return false; } /** * @dev Helper function to get specific properties of all of the personal stakes created by an address * @param _address address The address to query * @return (uint256[], uint256[], address[]) * timestamps array, actualAmounts array, stakedFor array */ function getPersonalStakes( address _address ) public view returns(uint256[], uint256[], address[]) { StakeContract storage stakeContract = stakeHolders[_address]; uint256 arraySize = stakeContract.personalStakes.length - stakeContract.personalStakeIndex; uint256[] memory unlockedTimestamps = new uint256[](arraySize); uint256[] memory actualAmounts = new uint256[](arraySize); address[] memory stakedFor = new address[](arraySize); for (uint256 i = stakeContract.personalStakeIndex; i < stakeContract.personalStakes.length; i++) { uint256 index = i - stakeContract.personalStakeIndex; unlockedTimestamps[index] = stakeContract.personalStakes[i].unlockedTimestamp; actualAmounts[index] = stakeContract.personalStakes[i].actualAmount; stakedFor[index] = stakeContract.personalStakes[i].stakedFor; } return ( unlockedTimestamps, actualAmounts, stakedFor ); } /** * @dev Helper function to create stakes for a given address * @param _address address The address the stake is being created for * @param _amount uint256 The number of tokens being staked * @param _lockInDuration uint256 The duration to lock the tokens for * @param _data bytes optional data to include in the Stake event */ function createStake( address _address, uint256 _amount, uint256 _lockInDuration, bytes _data ) internal canStake(msg.sender, _amount) { require( _amount > 0, "Stake amount has to be greater than 0!"); if (!stakeHolders[msg.sender].exists) { stakeHolders[msg.sender].exists = true; } stakeHolders[_address].totalStakedFor = stakeHolders[_address].totalStakedFor.add(_amount); stakeHolders[msg.sender].personalStakes.push( Stake( block.timestamp.add(_lockInDuration), _amount, _address) ); emit Staked( _address, _amount, totalStakedFor(_address), _data); } /** * @dev Helper function to withdraw stakes for the msg.sender * @param _amount uint256 The amount to withdraw. MUST match the stake amount for the * stake at personalStakeIndex. * @param _data bytes optional data to include in the Unstake event */ function withdrawStake( uint256 _amount, bytes _data ) internal { Stake storage personalStake = stakeHolders[msg.sender].personalStakes[stakeHolders[msg.sender].personalStakeIndex]; // Check that the current stake has unlocked & matches the unstake amount require( personalStake.unlockedTimestamp <= block.timestamp, "The current stake hasn't unlocked yet"); require( personalStake.actualAmount == _amount, "The unstake amount does not match the current stake"); // Transfer the staked tokens from this contract back to the sender // Notice that we are using transfer instead of transferFrom here, so // no approval is needed beforehand. require( stakingToken.transfer(msg.sender, _amount), "Unable to withdraw stake"); stakeHolders[personalStake.stakedFor].totalStakedFor = stakeHolders[personalStake.stakedFor] .totalStakedFor.sub(personalStake.actualAmount); personalStake.actualAmount = 0; stakeHolders[msg.sender].personalStakeIndex++; emit Unstaked( personalStake.stakedFor, _amount, totalStakedFor(personalStake.stakedFor), _data); } }
getPersonalStakes
function getPersonalStakes( address _address ) public view returns(uint256[], uint256[], address[]) { StakeContract storage stakeContract = stakeHolders[_address]; uint256 arraySize = stakeContract.personalStakes.length - stakeContract.personalStakeIndex; uint256[] memory unlockedTimestamps = new uint256[](arraySize); uint256[] memory actualAmounts = new uint256[](arraySize); address[] memory stakedFor = new address[](arraySize); for (uint256 i = stakeContract.personalStakeIndex; i < stakeContract.personalStakes.length; i++) { uint256 index = i - stakeContract.personalStakeIndex; unlockedTimestamps[index] = stakeContract.personalStakes[i].unlockedTimestamp; actualAmounts[index] = stakeContract.personalStakes[i].actualAmount; stakedFor[index] = stakeContract.personalStakes[i].stakedFor; } return ( unlockedTimestamps, actualAmounts, stakedFor ); }
/** * @dev Helper function to get specific properties of all of the personal stakes created by an address * @param _address address The address to query * @return (uint256[], uint256[], address[]) * timestamps array, actualAmounts array, stakedFor array */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
None
bzzr://4b303eb18851047dc1d29ae82f12547c01d9658bb358f1143c0be5c6bdd9f246
{ "func_code_index": [ 7174, 8163 ] }
7,632
BasicStakingContract
BasicStakingContract.sol
0x583d4d39b740e2582febab65a9437e46692f932a
Solidity
ERC900BasicStakeContract
contract ERC900BasicStakeContract is ERC900 { // @TODO: deploy this separately so we don't have to deploy it multiple times for each contract using SafeMath for uint256; // Token used for staking ERC20 stakingToken; // The default duration of stake lock-in (in seconds) uint256 public defaultLockInDuration; // To save on gas, rather than create a separate mapping for totalStakedFor & personalStakes, // both data structures are stored in a single mapping for a given addresses. // // It's possible to have a non-existing personalStakes, but have tokens in totalStakedFor // if other users are staking on behalf of a given address. mapping (address => StakeContract) public stakeHolders; // Struct for personal stakes (i.e., stakes made by this address) // unlockedTimestamp - when the stake unlocks (in seconds since Unix epoch) // actualAmount - the amount of tokens in the stake // stakedFor - the address the stake was staked for struct Stake { uint256 unlockedTimestamp; uint256 actualAmount; address stakedFor; } // Struct for all stake metadata at a particular address // totalStakedFor - the number of tokens staked for this address // personalStakeIndex - the index in the personalStakes array. // personalStakes - append only array of stakes made by this address // exists - whether or not there are stakes that involve this address struct StakeContract { uint256 totalStakedFor; uint256 personalStakeIndex; Stake[] personalStakes; bool exists; } /** * @dev Modifier that checks that this contract can transfer tokens from the * balance in the stakingToken contract for the given address. * @dev This modifier also transfers the tokens. * @param _address address to transfer tokens from * @param _amount uint256 the number of tokens */ modifier canStake(address _address, uint256 _amount) { require( stakingToken.transferFrom(_address, this, _amount), "Stake required"); _; } /** * @dev Constructor function * @param _stakingToken ERC20 The address of the token contract used for staking */ constructor(ERC20 _stakingToken) public { stakingToken = _stakingToken; } /** * @dev Returns the timestamps for when active personal stakes for an address will unlock * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return uint256[] array of timestamps */ function getPersonalStakeUnlockedTimestamps(address _address) external view returns (uint256[]) { uint256[] memory timestamps; (timestamps,,) = getPersonalStakes(_address); return timestamps; } /** * @dev Returns the stake actualAmount for active personal stakes for an address * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return uint256[] array of actualAmounts */ function getPersonalStakeActualAmounts(address _address) external view returns (uint256[]) { uint256[] memory actualAmounts; (,actualAmounts,) = getPersonalStakes(_address); return actualAmounts; } /** * @dev Returns the addresses that each personal stake was created for by an address * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return address[] array of amounts */ function getPersonalStakeForAddresses(address _address) external view returns (address[]) { address[] memory stakedFor; (,,stakedFor) = getPersonalStakes(_address); return stakedFor; } /** * @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the user * @notice MUST trigger Staked event * @param _amount uint256 the amount of tokens to stake * @param _data bytes optional data to include in the Stake event */ function stake(uint256 _amount, bytes _data) public { createStake( msg.sender, _amount, defaultLockInDuration, _data); } /** * @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the caller * @notice MUST trigger Staked event * @param _user address the address the tokens are staked for * @param _amount uint256 the amount of tokens to stake * @param _data bytes optional data to include in the Stake event */ function stakeFor(address _user, uint256 _amount, bytes _data) public { createStake( _user, _amount, defaultLockInDuration, _data); } /** * @notice Unstakes a certain amount of tokens, this SHOULD return the given amount of tokens to the user, if unstaking is currently not possible the function MUST revert * @notice MUST trigger Unstaked event * @dev Unstaking tokens is an atomic operation—either all of the tokens in a stake, or none of the tokens. * @dev Users can only unstake a single stake at a time, it is must be their oldest active stake. Upon releasing that stake, the tokens will be * transferred back to their account, and their personalStakeIndex will increment to the next active stake. * @param _amount uint256 the amount of tokens to unstake * @param _data bytes optional data to include in the Unstake event */ function unstake(uint256 _amount, bytes _data) public { withdrawStake( _amount, _data); } /** * @notice Returns the current total of tokens staked for an address * @param _address address The address to query * @return uint256 The number of tokens staked for the given address */ function totalStakedFor(address _address) public view returns (uint256) { return stakeHolders[_address].totalStakedFor; } /** * @notice Returns the current total of tokens staked * @return uint256 The number of tokens staked in the contract */ function totalStaked() public view returns (uint256) { return stakingToken.balanceOf(this); } /** * @notice Address of the token being used by the staking interface * @return address The address of the ERC20 token used for staking */ function token() public view returns (address) { return stakingToken; } /** * @notice MUST return true if the optional history functions are implemented, otherwise false * @dev Since we don't implement the optional interface, this always returns false * @return bool Whether or not the optional history functions are implemented */ function supportsHistory() public pure returns (bool) { return false; } /** * @dev Helper function to get specific properties of all of the personal stakes created by an address * @param _address address The address to query * @return (uint256[], uint256[], address[]) * timestamps array, actualAmounts array, stakedFor array */ function getPersonalStakes( address _address ) public view returns(uint256[], uint256[], address[]) { StakeContract storage stakeContract = stakeHolders[_address]; uint256 arraySize = stakeContract.personalStakes.length - stakeContract.personalStakeIndex; uint256[] memory unlockedTimestamps = new uint256[](arraySize); uint256[] memory actualAmounts = new uint256[](arraySize); address[] memory stakedFor = new address[](arraySize); for (uint256 i = stakeContract.personalStakeIndex; i < stakeContract.personalStakes.length; i++) { uint256 index = i - stakeContract.personalStakeIndex; unlockedTimestamps[index] = stakeContract.personalStakes[i].unlockedTimestamp; actualAmounts[index] = stakeContract.personalStakes[i].actualAmount; stakedFor[index] = stakeContract.personalStakes[i].stakedFor; } return ( unlockedTimestamps, actualAmounts, stakedFor ); } /** * @dev Helper function to create stakes for a given address * @param _address address The address the stake is being created for * @param _amount uint256 The number of tokens being staked * @param _lockInDuration uint256 The duration to lock the tokens for * @param _data bytes optional data to include in the Stake event */ function createStake( address _address, uint256 _amount, uint256 _lockInDuration, bytes _data ) internal canStake(msg.sender, _amount) { require( _amount > 0, "Stake amount has to be greater than 0!"); if (!stakeHolders[msg.sender].exists) { stakeHolders[msg.sender].exists = true; } stakeHolders[_address].totalStakedFor = stakeHolders[_address].totalStakedFor.add(_amount); stakeHolders[msg.sender].personalStakes.push( Stake( block.timestamp.add(_lockInDuration), _amount, _address) ); emit Staked( _address, _amount, totalStakedFor(_address), _data); } /** * @dev Helper function to withdraw stakes for the msg.sender * @param _amount uint256 The amount to withdraw. MUST match the stake amount for the * stake at personalStakeIndex. * @param _data bytes optional data to include in the Unstake event */ function withdrawStake( uint256 _amount, bytes _data ) internal { Stake storage personalStake = stakeHolders[msg.sender].personalStakes[stakeHolders[msg.sender].personalStakeIndex]; // Check that the current stake has unlocked & matches the unstake amount require( personalStake.unlockedTimestamp <= block.timestamp, "The current stake hasn't unlocked yet"); require( personalStake.actualAmount == _amount, "The unstake amount does not match the current stake"); // Transfer the staked tokens from this contract back to the sender // Notice that we are using transfer instead of transferFrom here, so // no approval is needed beforehand. require( stakingToken.transfer(msg.sender, _amount), "Unable to withdraw stake"); stakeHolders[personalStake.stakedFor].totalStakedFor = stakeHolders[personalStake.stakedFor] .totalStakedFor.sub(personalStake.actualAmount); personalStake.actualAmount = 0; stakeHolders[msg.sender].personalStakeIndex++; emit Unstaked( personalStake.stakedFor, _amount, totalStakedFor(personalStake.stakedFor), _data); } }
createStake
function createStake( address _address, uint256 _amount, uint256 _lockInDuration, bytes _data ) internal canStake(msg.sender, _amount) { require( _amount > 0, "Stake amount has to be greater than 0!"); if (!stakeHolders[msg.sender].exists) { stakeHolders[msg.sender].exists = true; } stakeHolders[_address].totalStakedFor = stakeHolders[_address].totalStakedFor.add(_amount); stakeHolders[msg.sender].personalStakes.push( Stake( block.timestamp.add(_lockInDuration), _amount, _address) ); emit Staked( _address, _amount, totalStakedFor(_address), _data); }
/** * @dev Helper function to create stakes for a given address * @param _address address The address the stake is being created for * @param _amount uint256 The number of tokens being staked * @param _lockInDuration uint256 The duration to lock the tokens for * @param _data bytes optional data to include in the Stake event */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
None
bzzr://4b303eb18851047dc1d29ae82f12547c01d9658bb358f1143c0be5c6bdd9f246
{ "func_code_index": [ 8522, 9244 ] }
7,633
BasicStakingContract
BasicStakingContract.sol
0x583d4d39b740e2582febab65a9437e46692f932a
Solidity
ERC900BasicStakeContract
contract ERC900BasicStakeContract is ERC900 { // @TODO: deploy this separately so we don't have to deploy it multiple times for each contract using SafeMath for uint256; // Token used for staking ERC20 stakingToken; // The default duration of stake lock-in (in seconds) uint256 public defaultLockInDuration; // To save on gas, rather than create a separate mapping for totalStakedFor & personalStakes, // both data structures are stored in a single mapping for a given addresses. // // It's possible to have a non-existing personalStakes, but have tokens in totalStakedFor // if other users are staking on behalf of a given address. mapping (address => StakeContract) public stakeHolders; // Struct for personal stakes (i.e., stakes made by this address) // unlockedTimestamp - when the stake unlocks (in seconds since Unix epoch) // actualAmount - the amount of tokens in the stake // stakedFor - the address the stake was staked for struct Stake { uint256 unlockedTimestamp; uint256 actualAmount; address stakedFor; } // Struct for all stake metadata at a particular address // totalStakedFor - the number of tokens staked for this address // personalStakeIndex - the index in the personalStakes array. // personalStakes - append only array of stakes made by this address // exists - whether or not there are stakes that involve this address struct StakeContract { uint256 totalStakedFor; uint256 personalStakeIndex; Stake[] personalStakes; bool exists; } /** * @dev Modifier that checks that this contract can transfer tokens from the * balance in the stakingToken contract for the given address. * @dev This modifier also transfers the tokens. * @param _address address to transfer tokens from * @param _amount uint256 the number of tokens */ modifier canStake(address _address, uint256 _amount) { require( stakingToken.transferFrom(_address, this, _amount), "Stake required"); _; } /** * @dev Constructor function * @param _stakingToken ERC20 The address of the token contract used for staking */ constructor(ERC20 _stakingToken) public { stakingToken = _stakingToken; } /** * @dev Returns the timestamps for when active personal stakes for an address will unlock * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return uint256[] array of timestamps */ function getPersonalStakeUnlockedTimestamps(address _address) external view returns (uint256[]) { uint256[] memory timestamps; (timestamps,,) = getPersonalStakes(_address); return timestamps; } /** * @dev Returns the stake actualAmount for active personal stakes for an address * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return uint256[] array of actualAmounts */ function getPersonalStakeActualAmounts(address _address) external view returns (uint256[]) { uint256[] memory actualAmounts; (,actualAmounts,) = getPersonalStakes(_address); return actualAmounts; } /** * @dev Returns the addresses that each personal stake was created for by an address * @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved * @param _address address that created the stakes * @return address[] array of amounts */ function getPersonalStakeForAddresses(address _address) external view returns (address[]) { address[] memory stakedFor; (,,stakedFor) = getPersonalStakes(_address); return stakedFor; } /** * @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the user * @notice MUST trigger Staked event * @param _amount uint256 the amount of tokens to stake * @param _data bytes optional data to include in the Stake event */ function stake(uint256 _amount, bytes _data) public { createStake( msg.sender, _amount, defaultLockInDuration, _data); } /** * @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the caller * @notice MUST trigger Staked event * @param _user address the address the tokens are staked for * @param _amount uint256 the amount of tokens to stake * @param _data bytes optional data to include in the Stake event */ function stakeFor(address _user, uint256 _amount, bytes _data) public { createStake( _user, _amount, defaultLockInDuration, _data); } /** * @notice Unstakes a certain amount of tokens, this SHOULD return the given amount of tokens to the user, if unstaking is currently not possible the function MUST revert * @notice MUST trigger Unstaked event * @dev Unstaking tokens is an atomic operation—either all of the tokens in a stake, or none of the tokens. * @dev Users can only unstake a single stake at a time, it is must be their oldest active stake. Upon releasing that stake, the tokens will be * transferred back to their account, and their personalStakeIndex will increment to the next active stake. * @param _amount uint256 the amount of tokens to unstake * @param _data bytes optional data to include in the Unstake event */ function unstake(uint256 _amount, bytes _data) public { withdrawStake( _amount, _data); } /** * @notice Returns the current total of tokens staked for an address * @param _address address The address to query * @return uint256 The number of tokens staked for the given address */ function totalStakedFor(address _address) public view returns (uint256) { return stakeHolders[_address].totalStakedFor; } /** * @notice Returns the current total of tokens staked * @return uint256 The number of tokens staked in the contract */ function totalStaked() public view returns (uint256) { return stakingToken.balanceOf(this); } /** * @notice Address of the token being used by the staking interface * @return address The address of the ERC20 token used for staking */ function token() public view returns (address) { return stakingToken; } /** * @notice MUST return true if the optional history functions are implemented, otherwise false * @dev Since we don't implement the optional interface, this always returns false * @return bool Whether or not the optional history functions are implemented */ function supportsHistory() public pure returns (bool) { return false; } /** * @dev Helper function to get specific properties of all of the personal stakes created by an address * @param _address address The address to query * @return (uint256[], uint256[], address[]) * timestamps array, actualAmounts array, stakedFor array */ function getPersonalStakes( address _address ) public view returns(uint256[], uint256[], address[]) { StakeContract storage stakeContract = stakeHolders[_address]; uint256 arraySize = stakeContract.personalStakes.length - stakeContract.personalStakeIndex; uint256[] memory unlockedTimestamps = new uint256[](arraySize); uint256[] memory actualAmounts = new uint256[](arraySize); address[] memory stakedFor = new address[](arraySize); for (uint256 i = stakeContract.personalStakeIndex; i < stakeContract.personalStakes.length; i++) { uint256 index = i - stakeContract.personalStakeIndex; unlockedTimestamps[index] = stakeContract.personalStakes[i].unlockedTimestamp; actualAmounts[index] = stakeContract.personalStakes[i].actualAmount; stakedFor[index] = stakeContract.personalStakes[i].stakedFor; } return ( unlockedTimestamps, actualAmounts, stakedFor ); } /** * @dev Helper function to create stakes for a given address * @param _address address The address the stake is being created for * @param _amount uint256 The number of tokens being staked * @param _lockInDuration uint256 The duration to lock the tokens for * @param _data bytes optional data to include in the Stake event */ function createStake( address _address, uint256 _amount, uint256 _lockInDuration, bytes _data ) internal canStake(msg.sender, _amount) { require( _amount > 0, "Stake amount has to be greater than 0!"); if (!stakeHolders[msg.sender].exists) { stakeHolders[msg.sender].exists = true; } stakeHolders[_address].totalStakedFor = stakeHolders[_address].totalStakedFor.add(_amount); stakeHolders[msg.sender].personalStakes.push( Stake( block.timestamp.add(_lockInDuration), _amount, _address) ); emit Staked( _address, _amount, totalStakedFor(_address), _data); } /** * @dev Helper function to withdraw stakes for the msg.sender * @param _amount uint256 The amount to withdraw. MUST match the stake amount for the * stake at personalStakeIndex. * @param _data bytes optional data to include in the Unstake event */ function withdrawStake( uint256 _amount, bytes _data ) internal { Stake storage personalStake = stakeHolders[msg.sender].personalStakes[stakeHolders[msg.sender].personalStakeIndex]; // Check that the current stake has unlocked & matches the unstake amount require( personalStake.unlockedTimestamp <= block.timestamp, "The current stake hasn't unlocked yet"); require( personalStake.actualAmount == _amount, "The unstake amount does not match the current stake"); // Transfer the staked tokens from this contract back to the sender // Notice that we are using transfer instead of transferFrom here, so // no approval is needed beforehand. require( stakingToken.transfer(msg.sender, _amount), "Unable to withdraw stake"); stakeHolders[personalStake.stakedFor].totalStakedFor = stakeHolders[personalStake.stakedFor] .totalStakedFor.sub(personalStake.actualAmount); personalStake.actualAmount = 0; stakeHolders[msg.sender].personalStakeIndex++; emit Unstaked( personalStake.stakedFor, _amount, totalStakedFor(personalStake.stakedFor), _data); } }
withdrawStake
function withdrawStake( uint256 _amount, bytes _data ) internal { Stake storage personalStake = stakeHolders[msg.sender].personalStakes[stakeHolders[msg.sender].personalStakeIndex]; // Check that the current stake has unlocked & matches the unstake amount require( personalStake.unlockedTimestamp <= block.timestamp, "The current stake hasn't unlocked yet"); require( personalStake.actualAmount == _amount, "The unstake amount does not match the current stake"); // Transfer the staked tokens from this contract back to the sender // Notice that we are using transfer instead of transferFrom here, so // no approval is needed beforehand. require( stakingToken.transfer(msg.sender, _amount), "Unable to withdraw stake"); stakeHolders[personalStake.stakedFor].totalStakedFor = stakeHolders[personalStake.stakedFor] .totalStakedFor.sub(personalStake.actualAmount); personalStake.actualAmount = 0; stakeHolders[msg.sender].personalStakeIndex++; emit Unstaked( personalStake.stakedFor, _amount, totalStakedFor(personalStake.stakedFor), _data); }
/** * @dev Helper function to withdraw stakes for the msg.sender * @param _amount uint256 The amount to withdraw. MUST match the stake amount for the * stake at personalStakeIndex. * @param _data bytes optional data to include in the Unstake event */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
None
bzzr://4b303eb18851047dc1d29ae82f12547c01d9658bb358f1143c0be5c6bdd9f246
{ "func_code_index": [ 9522, 10739 ] }
7,634
MewtwoRise
MewtwoRise.sol
0xabf941ee6094703d2394916f28a09f3674baa0fc
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.s * * 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); }
totalSupply
function totalSupply() external view returns (uint256);
/** * @dev Returns the amount of tokens in existence. */
NatSpecMultiLine
v0.6.12+commit.27d51765
None
ipfs://873e3ad67ca064d8b52085709d9e5c4566d457ed26abe8238f784aa353a21b68
{ "func_code_index": [ 94, 154 ] }
7,635
MewtwoRise
MewtwoRise.sol
0xabf941ee6094703d2394916f28a09f3674baa0fc
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.s * * 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); }
balanceOf
function balanceOf(address account) external view returns (uint256);
/** * @dev Returns the amount of tokens owned by `account`. */
NatSpecMultiLine
v0.6.12+commit.27d51765
None
ipfs://873e3ad67ca064d8b52085709d9e5c4566d457ed26abe8238f784aa353a21b68
{ "func_code_index": [ 237, 310 ] }
7,636
MewtwoRise
MewtwoRise.sol
0xabf941ee6094703d2394916f28a09f3674baa0fc
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.s * * 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); }
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.s * * Emits a {Transfer} event. */
NatSpecMultiLine
v0.6.12+commit.27d51765
None
ipfs://873e3ad67ca064d8b52085709d9e5c4566d457ed26abe8238f784aa353a21b68
{ "func_code_index": [ 535, 617 ] }
7,637
MewtwoRise
MewtwoRise.sol
0xabf941ee6094703d2394916f28a09f3674baa0fc
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.s * * 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); }
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.12+commit.27d51765
None
ipfs://873e3ad67ca064d8b52085709d9e5c4566d457ed26abe8238f784aa353a21b68
{ "func_code_index": [ 896, 984 ] }
7,638
MewtwoRise
MewtwoRise.sol
0xabf941ee6094703d2394916f28a09f3674baa0fc
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.s * * 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); }
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.12+commit.27d51765
None
ipfs://873e3ad67ca064d8b52085709d9e5c4566d457ed26abe8238f784aa353a21b68
{ "func_code_index": [ 1648, 1727 ] }
7,639
MewtwoRise
MewtwoRise.sol
0xabf941ee6094703d2394916f28a09f3674baa0fc
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.s * * 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); }
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.12+commit.27d51765
None
ipfs://873e3ad67ca064d8b52085709d9e5c4566d457ed26abe8238f784aa353a21b68
{ "func_code_index": [ 2040, 2142 ] }
7,640
MewtwoRise
MewtwoRise.sol
0xabf941ee6094703d2394916f28a09f3674baa0fc
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
isContract
function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); }
/** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */
NatSpecMultiLine
v0.6.12+commit.27d51765
None
ipfs://873e3ad67ca064d8b52085709d9e5c4566d457ed26abe8238f784aa353a21b68
{ "func_code_index": [ 606, 1230 ] }
7,641
MewtwoRise
MewtwoRise.sol
0xabf941ee6094703d2394916f28a09f3674baa0fc
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
sendValue
function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); }
/** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */
NatSpecMultiLine
v0.6.12+commit.27d51765
None
ipfs://873e3ad67ca064d8b52085709d9e5c4566d457ed26abe8238f784aa353a21b68
{ "func_code_index": [ 2160, 2562 ] }
7,642
MewtwoRise
MewtwoRise.sol
0xabf941ee6094703d2394916f28a09f3674baa0fc
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
functionCall
function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); }
/** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */
NatSpecMultiLine
v0.6.12+commit.27d51765
None
ipfs://873e3ad67ca064d8b52085709d9e5c4566d457ed26abe8238f784aa353a21b68
{ "func_code_index": [ 3318, 3496 ] }
7,643
MewtwoRise
MewtwoRise.sol
0xabf941ee6094703d2394916f28a09f3674baa0fc
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
functionCall
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); }
/** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */
NatSpecMultiLine
v0.6.12+commit.27d51765
None
ipfs://873e3ad67ca064d8b52085709d9e5c4566d457ed26abe8238f784aa353a21b68
{ "func_code_index": [ 3721, 3922 ] }
7,644
MewtwoRise
MewtwoRise.sol
0xabf941ee6094703d2394916f28a09f3674baa0fc
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
functionCallWithValue
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); }
/** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */
NatSpecMultiLine
v0.6.12+commit.27d51765
None
ipfs://873e3ad67ca064d8b52085709d9e5c4566d457ed26abe8238f784aa353a21b68
{ "func_code_index": [ 4292, 4523 ] }
7,645
MewtwoRise
MewtwoRise.sol
0xabf941ee6094703d2394916f28a09f3674baa0fc
Solidity
Address
library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
functionCallWithValue
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); }
/** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */
NatSpecMultiLine
v0.6.12+commit.27d51765
None
ipfs://873e3ad67ca064d8b52085709d9e5c4566d457ed26abe8238f784aa353a21b68
{ "func_code_index": [ 4774, 5095 ] }
7,646
MewtwoRise
MewtwoRise.sol
0xabf941ee6094703d2394916f28a09f3674baa0fc
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; } }
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.12+commit.27d51765
None
ipfs://873e3ad67ca064d8b52085709d9e5c4566d457ed26abe8238f784aa353a21b68
{ "func_code_index": [ 259, 445 ] }
7,647
MewtwoRise
MewtwoRise.sol
0xabf941ee6094703d2394916f28a09f3674baa0fc
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; } }
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.12+commit.27d51765
None
ipfs://873e3ad67ca064d8b52085709d9e5c4566d457ed26abe8238f784aa353a21b68
{ "func_code_index": [ 723, 864 ] }
7,648
MewtwoRise
MewtwoRise.sol
0xabf941ee6094703d2394916f28a09f3674baa0fc
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; } }
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.12+commit.27d51765
None
ipfs://873e3ad67ca064d8b52085709d9e5c4566d457ed26abe8238f784aa353a21b68
{ "func_code_index": [ 1162, 1359 ] }
7,649
MewtwoRise
MewtwoRise.sol
0xabf941ee6094703d2394916f28a09f3674baa0fc
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; } }
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.12+commit.27d51765
None
ipfs://873e3ad67ca064d8b52085709d9e5c4566d457ed26abe8238f784aa353a21b68
{ "func_code_index": [ 1613, 2089 ] }
7,650
MewtwoRise
MewtwoRise.sol
0xabf941ee6094703d2394916f28a09f3674baa0fc
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; } }
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.12+commit.27d51765
None
ipfs://873e3ad67ca064d8b52085709d9e5c4566d457ed26abe8238f784aa353a21b68
{ "func_code_index": [ 2560, 2697 ] }
7,651
MewtwoRise
MewtwoRise.sol
0xabf941ee6094703d2394916f28a09f3674baa0fc
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; } }
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.12+commit.27d51765
None
ipfs://873e3ad67ca064d8b52085709d9e5c4566d457ed26abe8238f784aa353a21b68
{ "func_code_index": [ 3188, 3471 ] }
7,652
MewtwoRise
MewtwoRise.sol
0xabf941ee6094703d2394916f28a09f3674baa0fc
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; } }
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.12+commit.27d51765
None
ipfs://873e3ad67ca064d8b52085709d9e5c4566d457ed26abe8238f784aa353a21b68
{ "func_code_index": [ 3931, 4066 ] }
7,653
MewtwoRise
MewtwoRise.sol
0xabf941ee6094703d2394916f28a09f3674baa0fc
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; } }
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.12+commit.27d51765
None
ipfs://873e3ad67ca064d8b52085709d9e5c4566d457ed26abe8238f784aa353a21b68
{ "func_code_index": [ 4546, 4717 ] }
7,654
MewtwoRise
MewtwoRise.sol
0xabf941ee6094703d2394916f28a09f3674baa0fc
Solidity
Ownable
contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return address(0); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
owner
function owner() public view returns (address) { return address(0); }
/** * @dev Returns the address of the current owner. */
NatSpecMultiLine
v0.6.12+commit.27d51765
None
ipfs://873e3ad67ca064d8b52085709d9e5c4566d457ed26abe8238f784aa353a21b68
{ "func_code_index": [ 497, 585 ] }
7,655
MewtwoRise
MewtwoRise.sol
0xabf941ee6094703d2394916f28a09f3674baa0fc
Solidity
Ownable
contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return address(0); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
renounceOwnership
function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); }
/** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */
NatSpecMultiLine
v0.6.12+commit.27d51765
None
ipfs://873e3ad67ca064d8b52085709d9e5c4566d457ed26abe8238f784aa353a21b68
{ "func_code_index": [ 1143, 1266 ] }
7,656
MewtwoRise
MewtwoRise.sol
0xabf941ee6094703d2394916f28a09f3674baa0fc
Solidity
Ownable
contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return address(0); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
transferOwnership
function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; }
/** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */
NatSpecMultiLine
v0.6.12+commit.27d51765
None
ipfs://873e3ad67ca064d8b52085709d9e5c4566d457ed26abe8238f784aa353a21b68
{ "func_code_index": [ 1416, 1665 ] }
7,657
JointProvider
JointProvider.sol
0x580ae3aed3e8e8d83c970fa6d2766c0fb8af759f
Solidity
JointProvider
contract JointProvider is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint; IRebalancer public rebalancer; IPriceFeed public oracle; uint constant public max = type(uint).max; bool internal isOriginal = true; constructor(address _vault, address _oracle) public BaseStrategy(_vault) { _initializeStrat(_oracle); } function initialize( address _vault, address _strategist, address _rewards, address _keeper, address _oracle ) external { _initialize(_vault, _strategist, _rewards, _keeper); _initializeStrat(_oracle); } function _initializeStrat(address _oracle) internal { oracle = IPriceFeed(_oracle); healthCheck = address(0xDDCea799fF1699e98EDF118e0629A974Df7DF012); } function setRebalancer(address payable _rebalancer) external onlyVaultManagers { want.approve(_rebalancer, max); rebalancer = IRebalancer(_rebalancer); require(rebalancer.tokenA() == want || rebalancer.tokenB() == want); } event Cloned(address indexed clone); function cloneProvider( address _vault, address _strategist, address _rewards, address _keeper, address _oracle ) external returns (address newStrategy) { require(isOriginal); bytes20 addressBytes = bytes20(address(this)); assembly { // EIP-1167 bytecode let clone_code := mload(0x40) mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone_code, 0x14), addressBytes) mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) newStrategy := create(0, clone_code, 0x37) } JointProvider(newStrategy).initialize( _vault, _strategist, _rewards, _keeper, _oracle ); emit Cloned(newStrategy); } // ******** OVERRIDE THESE METHODS FROM BASE CONTRACT ************ function name() external view override returns (string memory) { if (address(rebalancer) == address(0x0)) { return string(abi.encodePacked(ISymbol(address(want)).symbol(), " JointProvider ")); } else { return string( abi.encodePacked(rebalancer.name()[0], ISymbol(address(want)).symbol(), " JointProvider ", rebalancer.name()[1]) ); } } function estimatedTotalAssets() public view override returns (uint) { return want.balanceOf(address(this)).add(rebalancer.totalBalanceOf(want)); } function harvestTrigger(uint callCostInWei) public view override returns (bool){ return super.harvestTrigger(callCostInWei) && rebalancer.shouldHarvest(); } function tendTrigger(uint callCostInWei) public view override returns (bool){ return rebalancer.shouldTend(); } function prepareReturn(uint _debtOutstanding) internal override returns (uint _profit, uint _loss, uint _debtPayment) { uint beforeWant = balanceOfWant(); rebalancer.collectTradingFees(); _profit += balanceOfWant().sub(beforeWant); if (_debtOutstanding > 0) { if (vault.strategies(address(this)).debtRatio == 0) { _debtPayment = _liquidateAllPositions(); _loss = _debtOutstanding > _debtPayment ? _debtOutstanding.sub(_debtPayment) : 0; } else { (_debtPayment, _loss) = _liquidatePosition(_debtOutstanding); } } // Interestingly, if you overpay on debt payment, the overpaid amount just sits in the strat. // Report overpayment as profit if (_debtPayment > _debtOutstanding) { _profit += _debtPayment.sub(_debtOutstanding); _debtPayment = _debtOutstanding; } beforeWant = balanceOfWant(); rebalancer.sellRewards(); _profit += balanceOfWant().sub(beforeWant); if (_profit > _loss) { _profit = _profit.sub(_loss); _loss = 0; } else { _loss = _loss.sub(_profit); _profit = 0; } } // called by tend. 0 bc there's no change in debt function adjustPosition(uint _debtOutstanding) internal override { _adjustPosition(0); } // Called during withdraw in order to rebalance to the new debt. // This is necessary so that withdraws will rebalance immediately (instead of waiting for keeper) function _adjustPosition(uint _amountWithdrawn) internal { rebalancer.adjustPosition(_amountWithdrawn, want); } // without adjustPosition. Called internally by prepareReturn. Harvests will call adjustPosition after. function _liquidatePosition(uint _amountNeeded) internal returns (uint _liquidatedAmount, uint _loss) { uint loose = balanceOfWant(); uint pooled = rebalancer.pooledBalance(rebalancer.tokenIndex(want)); if (_amountNeeded > loose) { uint _amountNeededMore = _amountNeeded.sub(loose); if (_amountNeededMore >= pooled) { rebalancer.liquidateAllPositions(want, address(this)); } else { rebalancer.liquidatePosition(_amountNeededMore, want, address(this)); } _liquidatedAmount = balanceOfWant(); _loss = _amountNeeded.sub(_liquidatedAmount); } else { _liquidatedAmount = _amountNeeded; _loss = 0; } } // called when user withdraws from vault. Rebalance after function liquidatePosition(uint _amountNeeded) internal override returns (uint _liquidatedAmount, uint _loss) { (_liquidatedAmount, _loss) = _liquidatePosition(_amountNeeded); _adjustPosition(_amountNeeded); } // without adjustPosition. Called internally by prepareReturn. Harvests will call adjustPosition after. function _liquidateAllPositions() internal returns (uint _amountFreed) { rebalancer.liquidateAllPositions(want, address(this)); return want.balanceOf(address(this)); } // called during emergency exit. Rebalance after to halt pool function liquidateAllPositions() internal override returns (uint _amountFreed) { _amountFreed = _liquidateAllPositions(); _adjustPosition(type(uint).max); } // NOTE: Can override `tendTrigger` and `harvestTrigger` if necessary function prepareMigration(address _newStrategy) internal override { // NOTE: `migrate` will automatically forward all `want` in this strategy to the new one rebalancer.migrateProvider(_newStrategy); } // only called by rebalancer function migrateRebalancer(address payable _newRebalancer) external { require(msg.sender == address(rebalancer), "Not rebalancer!"); rebalancer = IRebalancer(_newRebalancer); want.approve(_newRebalancer, max); } function protectedTokens() internal view override returns (address[] memory) {} function ethToWant(uint _amtInWei) public view virtual override returns (uint) { return rebalancer.ethToWant(address(want), _amtInWei); } // Helpers // function balanceOfWant() public view returns (uint _balance){ return want.balanceOf(address(this)); } function totalDebt() public view returns (uint _debt){ return vault.strategies(address(this)).totalDebt; } function getPriceFeed() public view returns (uint _lastestAnswer){ return oracle.latestAnswer(); } function getPriceFeedDecimals() public view returns (uint _dec){ return oracle.decimals(); } function isVaultManagers(address _address) public view returns (bool){ return _address == vault.governance() || _address == vault.management(); } }
/** * Adapts Vault hooks to Balancer Contract and JointAdapter pair */
NatSpecMultiLine
name
function name() external view override returns (string memory) { if (address(rebalancer) == address(0x0)) { return string(abi.encodePacked(ISymbol(address(want)).symbol(), " JointProvider ")); } else { return string( abi.encodePacked(rebalancer.name()[0], ISymbol(address(want)).symbol(), " JointProvider ", rebalancer.name()[1]) ); } }
// ******** OVERRIDE THESE METHODS FROM BASE CONTRACT ************
LineComment
v0.6.12+commit.27d51765
Unknown
ipfs://0e6c2d2fdb84fd980f0785284dfb7ccbeda15e40002a582c536ba262eed1a3e8
{ "func_code_index": [ 2215, 2644 ] }
7,658
JointProvider
JointProvider.sol
0x580ae3aed3e8e8d83c970fa6d2766c0fb8af759f
Solidity
JointProvider
contract JointProvider is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint; IRebalancer public rebalancer; IPriceFeed public oracle; uint constant public max = type(uint).max; bool internal isOriginal = true; constructor(address _vault, address _oracle) public BaseStrategy(_vault) { _initializeStrat(_oracle); } function initialize( address _vault, address _strategist, address _rewards, address _keeper, address _oracle ) external { _initialize(_vault, _strategist, _rewards, _keeper); _initializeStrat(_oracle); } function _initializeStrat(address _oracle) internal { oracle = IPriceFeed(_oracle); healthCheck = address(0xDDCea799fF1699e98EDF118e0629A974Df7DF012); } function setRebalancer(address payable _rebalancer) external onlyVaultManagers { want.approve(_rebalancer, max); rebalancer = IRebalancer(_rebalancer); require(rebalancer.tokenA() == want || rebalancer.tokenB() == want); } event Cloned(address indexed clone); function cloneProvider( address _vault, address _strategist, address _rewards, address _keeper, address _oracle ) external returns (address newStrategy) { require(isOriginal); bytes20 addressBytes = bytes20(address(this)); assembly { // EIP-1167 bytecode let clone_code := mload(0x40) mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone_code, 0x14), addressBytes) mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) newStrategy := create(0, clone_code, 0x37) } JointProvider(newStrategy).initialize( _vault, _strategist, _rewards, _keeper, _oracle ); emit Cloned(newStrategy); } // ******** OVERRIDE THESE METHODS FROM BASE CONTRACT ************ function name() external view override returns (string memory) { if (address(rebalancer) == address(0x0)) { return string(abi.encodePacked(ISymbol(address(want)).symbol(), " JointProvider ")); } else { return string( abi.encodePacked(rebalancer.name()[0], ISymbol(address(want)).symbol(), " JointProvider ", rebalancer.name()[1]) ); } } function estimatedTotalAssets() public view override returns (uint) { return want.balanceOf(address(this)).add(rebalancer.totalBalanceOf(want)); } function harvestTrigger(uint callCostInWei) public view override returns (bool){ return super.harvestTrigger(callCostInWei) && rebalancer.shouldHarvest(); } function tendTrigger(uint callCostInWei) public view override returns (bool){ return rebalancer.shouldTend(); } function prepareReturn(uint _debtOutstanding) internal override returns (uint _profit, uint _loss, uint _debtPayment) { uint beforeWant = balanceOfWant(); rebalancer.collectTradingFees(); _profit += balanceOfWant().sub(beforeWant); if (_debtOutstanding > 0) { if (vault.strategies(address(this)).debtRatio == 0) { _debtPayment = _liquidateAllPositions(); _loss = _debtOutstanding > _debtPayment ? _debtOutstanding.sub(_debtPayment) : 0; } else { (_debtPayment, _loss) = _liquidatePosition(_debtOutstanding); } } // Interestingly, if you overpay on debt payment, the overpaid amount just sits in the strat. // Report overpayment as profit if (_debtPayment > _debtOutstanding) { _profit += _debtPayment.sub(_debtOutstanding); _debtPayment = _debtOutstanding; } beforeWant = balanceOfWant(); rebalancer.sellRewards(); _profit += balanceOfWant().sub(beforeWant); if (_profit > _loss) { _profit = _profit.sub(_loss); _loss = 0; } else { _loss = _loss.sub(_profit); _profit = 0; } } // called by tend. 0 bc there's no change in debt function adjustPosition(uint _debtOutstanding) internal override { _adjustPosition(0); } // Called during withdraw in order to rebalance to the new debt. // This is necessary so that withdraws will rebalance immediately (instead of waiting for keeper) function _adjustPosition(uint _amountWithdrawn) internal { rebalancer.adjustPosition(_amountWithdrawn, want); } // without adjustPosition. Called internally by prepareReturn. Harvests will call adjustPosition after. function _liquidatePosition(uint _amountNeeded) internal returns (uint _liquidatedAmount, uint _loss) { uint loose = balanceOfWant(); uint pooled = rebalancer.pooledBalance(rebalancer.tokenIndex(want)); if (_amountNeeded > loose) { uint _amountNeededMore = _amountNeeded.sub(loose); if (_amountNeededMore >= pooled) { rebalancer.liquidateAllPositions(want, address(this)); } else { rebalancer.liquidatePosition(_amountNeededMore, want, address(this)); } _liquidatedAmount = balanceOfWant(); _loss = _amountNeeded.sub(_liquidatedAmount); } else { _liquidatedAmount = _amountNeeded; _loss = 0; } } // called when user withdraws from vault. Rebalance after function liquidatePosition(uint _amountNeeded) internal override returns (uint _liquidatedAmount, uint _loss) { (_liquidatedAmount, _loss) = _liquidatePosition(_amountNeeded); _adjustPosition(_amountNeeded); } // without adjustPosition. Called internally by prepareReturn. Harvests will call adjustPosition after. function _liquidateAllPositions() internal returns (uint _amountFreed) { rebalancer.liquidateAllPositions(want, address(this)); return want.balanceOf(address(this)); } // called during emergency exit. Rebalance after to halt pool function liquidateAllPositions() internal override returns (uint _amountFreed) { _amountFreed = _liquidateAllPositions(); _adjustPosition(type(uint).max); } // NOTE: Can override `tendTrigger` and `harvestTrigger` if necessary function prepareMigration(address _newStrategy) internal override { // NOTE: `migrate` will automatically forward all `want` in this strategy to the new one rebalancer.migrateProvider(_newStrategy); } // only called by rebalancer function migrateRebalancer(address payable _newRebalancer) external { require(msg.sender == address(rebalancer), "Not rebalancer!"); rebalancer = IRebalancer(_newRebalancer); want.approve(_newRebalancer, max); } function protectedTokens() internal view override returns (address[] memory) {} function ethToWant(uint _amtInWei) public view virtual override returns (uint) { return rebalancer.ethToWant(address(want), _amtInWei); } // Helpers // function balanceOfWant() public view returns (uint _balance){ return want.balanceOf(address(this)); } function totalDebt() public view returns (uint _debt){ return vault.strategies(address(this)).totalDebt; } function getPriceFeed() public view returns (uint _lastestAnswer){ return oracle.latestAnswer(); } function getPriceFeedDecimals() public view returns (uint _dec){ return oracle.decimals(); } function isVaultManagers(address _address) public view returns (bool){ return _address == vault.governance() || _address == vault.management(); } }
/** * Adapts Vault hooks to Balancer Contract and JointAdapter pair */
NatSpecMultiLine
adjustPosition
function adjustPosition(uint _debtOutstanding) internal override { _adjustPosition(0); }
// called by tend. 0 bc there's no change in debt
LineComment
v0.6.12+commit.27d51765
Unknown
ipfs://0e6c2d2fdb84fd980f0785284dfb7ccbeda15e40002a582c536ba262eed1a3e8
{ "func_code_index": [ 4481, 4588 ] }
7,659
JointProvider
JointProvider.sol
0x580ae3aed3e8e8d83c970fa6d2766c0fb8af759f
Solidity
JointProvider
contract JointProvider is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint; IRebalancer public rebalancer; IPriceFeed public oracle; uint constant public max = type(uint).max; bool internal isOriginal = true; constructor(address _vault, address _oracle) public BaseStrategy(_vault) { _initializeStrat(_oracle); } function initialize( address _vault, address _strategist, address _rewards, address _keeper, address _oracle ) external { _initialize(_vault, _strategist, _rewards, _keeper); _initializeStrat(_oracle); } function _initializeStrat(address _oracle) internal { oracle = IPriceFeed(_oracle); healthCheck = address(0xDDCea799fF1699e98EDF118e0629A974Df7DF012); } function setRebalancer(address payable _rebalancer) external onlyVaultManagers { want.approve(_rebalancer, max); rebalancer = IRebalancer(_rebalancer); require(rebalancer.tokenA() == want || rebalancer.tokenB() == want); } event Cloned(address indexed clone); function cloneProvider( address _vault, address _strategist, address _rewards, address _keeper, address _oracle ) external returns (address newStrategy) { require(isOriginal); bytes20 addressBytes = bytes20(address(this)); assembly { // EIP-1167 bytecode let clone_code := mload(0x40) mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone_code, 0x14), addressBytes) mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) newStrategy := create(0, clone_code, 0x37) } JointProvider(newStrategy).initialize( _vault, _strategist, _rewards, _keeper, _oracle ); emit Cloned(newStrategy); } // ******** OVERRIDE THESE METHODS FROM BASE CONTRACT ************ function name() external view override returns (string memory) { if (address(rebalancer) == address(0x0)) { return string(abi.encodePacked(ISymbol(address(want)).symbol(), " JointProvider ")); } else { return string( abi.encodePacked(rebalancer.name()[0], ISymbol(address(want)).symbol(), " JointProvider ", rebalancer.name()[1]) ); } } function estimatedTotalAssets() public view override returns (uint) { return want.balanceOf(address(this)).add(rebalancer.totalBalanceOf(want)); } function harvestTrigger(uint callCostInWei) public view override returns (bool){ return super.harvestTrigger(callCostInWei) && rebalancer.shouldHarvest(); } function tendTrigger(uint callCostInWei) public view override returns (bool){ return rebalancer.shouldTend(); } function prepareReturn(uint _debtOutstanding) internal override returns (uint _profit, uint _loss, uint _debtPayment) { uint beforeWant = balanceOfWant(); rebalancer.collectTradingFees(); _profit += balanceOfWant().sub(beforeWant); if (_debtOutstanding > 0) { if (vault.strategies(address(this)).debtRatio == 0) { _debtPayment = _liquidateAllPositions(); _loss = _debtOutstanding > _debtPayment ? _debtOutstanding.sub(_debtPayment) : 0; } else { (_debtPayment, _loss) = _liquidatePosition(_debtOutstanding); } } // Interestingly, if you overpay on debt payment, the overpaid amount just sits in the strat. // Report overpayment as profit if (_debtPayment > _debtOutstanding) { _profit += _debtPayment.sub(_debtOutstanding); _debtPayment = _debtOutstanding; } beforeWant = balanceOfWant(); rebalancer.sellRewards(); _profit += balanceOfWant().sub(beforeWant); if (_profit > _loss) { _profit = _profit.sub(_loss); _loss = 0; } else { _loss = _loss.sub(_profit); _profit = 0; } } // called by tend. 0 bc there's no change in debt function adjustPosition(uint _debtOutstanding) internal override { _adjustPosition(0); } // Called during withdraw in order to rebalance to the new debt. // This is necessary so that withdraws will rebalance immediately (instead of waiting for keeper) function _adjustPosition(uint _amountWithdrawn) internal { rebalancer.adjustPosition(_amountWithdrawn, want); } // without adjustPosition. Called internally by prepareReturn. Harvests will call adjustPosition after. function _liquidatePosition(uint _amountNeeded) internal returns (uint _liquidatedAmount, uint _loss) { uint loose = balanceOfWant(); uint pooled = rebalancer.pooledBalance(rebalancer.tokenIndex(want)); if (_amountNeeded > loose) { uint _amountNeededMore = _amountNeeded.sub(loose); if (_amountNeededMore >= pooled) { rebalancer.liquidateAllPositions(want, address(this)); } else { rebalancer.liquidatePosition(_amountNeededMore, want, address(this)); } _liquidatedAmount = balanceOfWant(); _loss = _amountNeeded.sub(_liquidatedAmount); } else { _liquidatedAmount = _amountNeeded; _loss = 0; } } // called when user withdraws from vault. Rebalance after function liquidatePosition(uint _amountNeeded) internal override returns (uint _liquidatedAmount, uint _loss) { (_liquidatedAmount, _loss) = _liquidatePosition(_amountNeeded); _adjustPosition(_amountNeeded); } // without adjustPosition. Called internally by prepareReturn. Harvests will call adjustPosition after. function _liquidateAllPositions() internal returns (uint _amountFreed) { rebalancer.liquidateAllPositions(want, address(this)); return want.balanceOf(address(this)); } // called during emergency exit. Rebalance after to halt pool function liquidateAllPositions() internal override returns (uint _amountFreed) { _amountFreed = _liquidateAllPositions(); _adjustPosition(type(uint).max); } // NOTE: Can override `tendTrigger` and `harvestTrigger` if necessary function prepareMigration(address _newStrategy) internal override { // NOTE: `migrate` will automatically forward all `want` in this strategy to the new one rebalancer.migrateProvider(_newStrategy); } // only called by rebalancer function migrateRebalancer(address payable _newRebalancer) external { require(msg.sender == address(rebalancer), "Not rebalancer!"); rebalancer = IRebalancer(_newRebalancer); want.approve(_newRebalancer, max); } function protectedTokens() internal view override returns (address[] memory) {} function ethToWant(uint _amtInWei) public view virtual override returns (uint) { return rebalancer.ethToWant(address(want), _amtInWei); } // Helpers // function balanceOfWant() public view returns (uint _balance){ return want.balanceOf(address(this)); } function totalDebt() public view returns (uint _debt){ return vault.strategies(address(this)).totalDebt; } function getPriceFeed() public view returns (uint _lastestAnswer){ return oracle.latestAnswer(); } function getPriceFeedDecimals() public view returns (uint _dec){ return oracle.decimals(); } function isVaultManagers(address _address) public view returns (bool){ return _address == vault.governance() || _address == vault.management(); } }
/** * Adapts Vault hooks to Balancer Contract and JointAdapter pair */
NatSpecMultiLine
_adjustPosition
function _adjustPosition(uint _amountWithdrawn) internal { rebalancer.adjustPosition(_amountWithdrawn, want); }
// Called during withdraw in order to rebalance to the new debt. // This is necessary so that withdraws will rebalance immediately (instead of waiting for keeper)
LineComment
v0.6.12+commit.27d51765
Unknown
ipfs://0e6c2d2fdb84fd980f0785284dfb7ccbeda15e40002a582c536ba262eed1a3e8
{ "func_code_index": [ 4764, 4894 ] }
7,660
JointProvider
JointProvider.sol
0x580ae3aed3e8e8d83c970fa6d2766c0fb8af759f
Solidity
JointProvider
contract JointProvider is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint; IRebalancer public rebalancer; IPriceFeed public oracle; uint constant public max = type(uint).max; bool internal isOriginal = true; constructor(address _vault, address _oracle) public BaseStrategy(_vault) { _initializeStrat(_oracle); } function initialize( address _vault, address _strategist, address _rewards, address _keeper, address _oracle ) external { _initialize(_vault, _strategist, _rewards, _keeper); _initializeStrat(_oracle); } function _initializeStrat(address _oracle) internal { oracle = IPriceFeed(_oracle); healthCheck = address(0xDDCea799fF1699e98EDF118e0629A974Df7DF012); } function setRebalancer(address payable _rebalancer) external onlyVaultManagers { want.approve(_rebalancer, max); rebalancer = IRebalancer(_rebalancer); require(rebalancer.tokenA() == want || rebalancer.tokenB() == want); } event Cloned(address indexed clone); function cloneProvider( address _vault, address _strategist, address _rewards, address _keeper, address _oracle ) external returns (address newStrategy) { require(isOriginal); bytes20 addressBytes = bytes20(address(this)); assembly { // EIP-1167 bytecode let clone_code := mload(0x40) mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone_code, 0x14), addressBytes) mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) newStrategy := create(0, clone_code, 0x37) } JointProvider(newStrategy).initialize( _vault, _strategist, _rewards, _keeper, _oracle ); emit Cloned(newStrategy); } // ******** OVERRIDE THESE METHODS FROM BASE CONTRACT ************ function name() external view override returns (string memory) { if (address(rebalancer) == address(0x0)) { return string(abi.encodePacked(ISymbol(address(want)).symbol(), " JointProvider ")); } else { return string( abi.encodePacked(rebalancer.name()[0], ISymbol(address(want)).symbol(), " JointProvider ", rebalancer.name()[1]) ); } } function estimatedTotalAssets() public view override returns (uint) { return want.balanceOf(address(this)).add(rebalancer.totalBalanceOf(want)); } function harvestTrigger(uint callCostInWei) public view override returns (bool){ return super.harvestTrigger(callCostInWei) && rebalancer.shouldHarvest(); } function tendTrigger(uint callCostInWei) public view override returns (bool){ return rebalancer.shouldTend(); } function prepareReturn(uint _debtOutstanding) internal override returns (uint _profit, uint _loss, uint _debtPayment) { uint beforeWant = balanceOfWant(); rebalancer.collectTradingFees(); _profit += balanceOfWant().sub(beforeWant); if (_debtOutstanding > 0) { if (vault.strategies(address(this)).debtRatio == 0) { _debtPayment = _liquidateAllPositions(); _loss = _debtOutstanding > _debtPayment ? _debtOutstanding.sub(_debtPayment) : 0; } else { (_debtPayment, _loss) = _liquidatePosition(_debtOutstanding); } } // Interestingly, if you overpay on debt payment, the overpaid amount just sits in the strat. // Report overpayment as profit if (_debtPayment > _debtOutstanding) { _profit += _debtPayment.sub(_debtOutstanding); _debtPayment = _debtOutstanding; } beforeWant = balanceOfWant(); rebalancer.sellRewards(); _profit += balanceOfWant().sub(beforeWant); if (_profit > _loss) { _profit = _profit.sub(_loss); _loss = 0; } else { _loss = _loss.sub(_profit); _profit = 0; } } // called by tend. 0 bc there's no change in debt function adjustPosition(uint _debtOutstanding) internal override { _adjustPosition(0); } // Called during withdraw in order to rebalance to the new debt. // This is necessary so that withdraws will rebalance immediately (instead of waiting for keeper) function _adjustPosition(uint _amountWithdrawn) internal { rebalancer.adjustPosition(_amountWithdrawn, want); } // without adjustPosition. Called internally by prepareReturn. Harvests will call adjustPosition after. function _liquidatePosition(uint _amountNeeded) internal returns (uint _liquidatedAmount, uint _loss) { uint loose = balanceOfWant(); uint pooled = rebalancer.pooledBalance(rebalancer.tokenIndex(want)); if (_amountNeeded > loose) { uint _amountNeededMore = _amountNeeded.sub(loose); if (_amountNeededMore >= pooled) { rebalancer.liquidateAllPositions(want, address(this)); } else { rebalancer.liquidatePosition(_amountNeededMore, want, address(this)); } _liquidatedAmount = balanceOfWant(); _loss = _amountNeeded.sub(_liquidatedAmount); } else { _liquidatedAmount = _amountNeeded; _loss = 0; } } // called when user withdraws from vault. Rebalance after function liquidatePosition(uint _amountNeeded) internal override returns (uint _liquidatedAmount, uint _loss) { (_liquidatedAmount, _loss) = _liquidatePosition(_amountNeeded); _adjustPosition(_amountNeeded); } // without adjustPosition. Called internally by prepareReturn. Harvests will call adjustPosition after. function _liquidateAllPositions() internal returns (uint _amountFreed) { rebalancer.liquidateAllPositions(want, address(this)); return want.balanceOf(address(this)); } // called during emergency exit. Rebalance after to halt pool function liquidateAllPositions() internal override returns (uint _amountFreed) { _amountFreed = _liquidateAllPositions(); _adjustPosition(type(uint).max); } // NOTE: Can override `tendTrigger` and `harvestTrigger` if necessary function prepareMigration(address _newStrategy) internal override { // NOTE: `migrate` will automatically forward all `want` in this strategy to the new one rebalancer.migrateProvider(_newStrategy); } // only called by rebalancer function migrateRebalancer(address payable _newRebalancer) external { require(msg.sender == address(rebalancer), "Not rebalancer!"); rebalancer = IRebalancer(_newRebalancer); want.approve(_newRebalancer, max); } function protectedTokens() internal view override returns (address[] memory) {} function ethToWant(uint _amtInWei) public view virtual override returns (uint) { return rebalancer.ethToWant(address(want), _amtInWei); } // Helpers // function balanceOfWant() public view returns (uint _balance){ return want.balanceOf(address(this)); } function totalDebt() public view returns (uint _debt){ return vault.strategies(address(this)).totalDebt; } function getPriceFeed() public view returns (uint _lastestAnswer){ return oracle.latestAnswer(); } function getPriceFeedDecimals() public view returns (uint _dec){ return oracle.decimals(); } function isVaultManagers(address _address) public view returns (bool){ return _address == vault.governance() || _address == vault.management(); } }
/** * Adapts Vault hooks to Balancer Contract and JointAdapter pair */
NatSpecMultiLine
_liquidatePosition
function _liquidatePosition(uint _amountNeeded) internal returns (uint _liquidatedAmount, uint _loss) { uint loose = balanceOfWant(); uint pooled = rebalancer.pooledBalance(rebalancer.tokenIndex(want)); if (_amountNeeded > loose) { uint _amountNeededMore = _amountNeeded.sub(loose); if (_amountNeededMore >= pooled) { rebalancer.liquidateAllPositions(want, address(this)); } else { rebalancer.liquidatePosition(_amountNeededMore, want, address(this)); } _liquidatedAmount = balanceOfWant(); _loss = _amountNeeded.sub(_liquidatedAmount); } else { _liquidatedAmount = _amountNeeded; _loss = 0; } }
// without adjustPosition. Called internally by prepareReturn. Harvests will call adjustPosition after.
LineComment
v0.6.12+commit.27d51765
Unknown
ipfs://0e6c2d2fdb84fd980f0785284dfb7ccbeda15e40002a582c536ba262eed1a3e8
{ "func_code_index": [ 5006, 5796 ] }
7,661
JointProvider
JointProvider.sol
0x580ae3aed3e8e8d83c970fa6d2766c0fb8af759f
Solidity
JointProvider
contract JointProvider is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint; IRebalancer public rebalancer; IPriceFeed public oracle; uint constant public max = type(uint).max; bool internal isOriginal = true; constructor(address _vault, address _oracle) public BaseStrategy(_vault) { _initializeStrat(_oracle); } function initialize( address _vault, address _strategist, address _rewards, address _keeper, address _oracle ) external { _initialize(_vault, _strategist, _rewards, _keeper); _initializeStrat(_oracle); } function _initializeStrat(address _oracle) internal { oracle = IPriceFeed(_oracle); healthCheck = address(0xDDCea799fF1699e98EDF118e0629A974Df7DF012); } function setRebalancer(address payable _rebalancer) external onlyVaultManagers { want.approve(_rebalancer, max); rebalancer = IRebalancer(_rebalancer); require(rebalancer.tokenA() == want || rebalancer.tokenB() == want); } event Cloned(address indexed clone); function cloneProvider( address _vault, address _strategist, address _rewards, address _keeper, address _oracle ) external returns (address newStrategy) { require(isOriginal); bytes20 addressBytes = bytes20(address(this)); assembly { // EIP-1167 bytecode let clone_code := mload(0x40) mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone_code, 0x14), addressBytes) mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) newStrategy := create(0, clone_code, 0x37) } JointProvider(newStrategy).initialize( _vault, _strategist, _rewards, _keeper, _oracle ); emit Cloned(newStrategy); } // ******** OVERRIDE THESE METHODS FROM BASE CONTRACT ************ function name() external view override returns (string memory) { if (address(rebalancer) == address(0x0)) { return string(abi.encodePacked(ISymbol(address(want)).symbol(), " JointProvider ")); } else { return string( abi.encodePacked(rebalancer.name()[0], ISymbol(address(want)).symbol(), " JointProvider ", rebalancer.name()[1]) ); } } function estimatedTotalAssets() public view override returns (uint) { return want.balanceOf(address(this)).add(rebalancer.totalBalanceOf(want)); } function harvestTrigger(uint callCostInWei) public view override returns (bool){ return super.harvestTrigger(callCostInWei) && rebalancer.shouldHarvest(); } function tendTrigger(uint callCostInWei) public view override returns (bool){ return rebalancer.shouldTend(); } function prepareReturn(uint _debtOutstanding) internal override returns (uint _profit, uint _loss, uint _debtPayment) { uint beforeWant = balanceOfWant(); rebalancer.collectTradingFees(); _profit += balanceOfWant().sub(beforeWant); if (_debtOutstanding > 0) { if (vault.strategies(address(this)).debtRatio == 0) { _debtPayment = _liquidateAllPositions(); _loss = _debtOutstanding > _debtPayment ? _debtOutstanding.sub(_debtPayment) : 0; } else { (_debtPayment, _loss) = _liquidatePosition(_debtOutstanding); } } // Interestingly, if you overpay on debt payment, the overpaid amount just sits in the strat. // Report overpayment as profit if (_debtPayment > _debtOutstanding) { _profit += _debtPayment.sub(_debtOutstanding); _debtPayment = _debtOutstanding; } beforeWant = balanceOfWant(); rebalancer.sellRewards(); _profit += balanceOfWant().sub(beforeWant); if (_profit > _loss) { _profit = _profit.sub(_loss); _loss = 0; } else { _loss = _loss.sub(_profit); _profit = 0; } } // called by tend. 0 bc there's no change in debt function adjustPosition(uint _debtOutstanding) internal override { _adjustPosition(0); } // Called during withdraw in order to rebalance to the new debt. // This is necessary so that withdraws will rebalance immediately (instead of waiting for keeper) function _adjustPosition(uint _amountWithdrawn) internal { rebalancer.adjustPosition(_amountWithdrawn, want); } // without adjustPosition. Called internally by prepareReturn. Harvests will call adjustPosition after. function _liquidatePosition(uint _amountNeeded) internal returns (uint _liquidatedAmount, uint _loss) { uint loose = balanceOfWant(); uint pooled = rebalancer.pooledBalance(rebalancer.tokenIndex(want)); if (_amountNeeded > loose) { uint _amountNeededMore = _amountNeeded.sub(loose); if (_amountNeededMore >= pooled) { rebalancer.liquidateAllPositions(want, address(this)); } else { rebalancer.liquidatePosition(_amountNeededMore, want, address(this)); } _liquidatedAmount = balanceOfWant(); _loss = _amountNeeded.sub(_liquidatedAmount); } else { _liquidatedAmount = _amountNeeded; _loss = 0; } } // called when user withdraws from vault. Rebalance after function liquidatePosition(uint _amountNeeded) internal override returns (uint _liquidatedAmount, uint _loss) { (_liquidatedAmount, _loss) = _liquidatePosition(_amountNeeded); _adjustPosition(_amountNeeded); } // without adjustPosition. Called internally by prepareReturn. Harvests will call adjustPosition after. function _liquidateAllPositions() internal returns (uint _amountFreed) { rebalancer.liquidateAllPositions(want, address(this)); return want.balanceOf(address(this)); } // called during emergency exit. Rebalance after to halt pool function liquidateAllPositions() internal override returns (uint _amountFreed) { _amountFreed = _liquidateAllPositions(); _adjustPosition(type(uint).max); } // NOTE: Can override `tendTrigger` and `harvestTrigger` if necessary function prepareMigration(address _newStrategy) internal override { // NOTE: `migrate` will automatically forward all `want` in this strategy to the new one rebalancer.migrateProvider(_newStrategy); } // only called by rebalancer function migrateRebalancer(address payable _newRebalancer) external { require(msg.sender == address(rebalancer), "Not rebalancer!"); rebalancer = IRebalancer(_newRebalancer); want.approve(_newRebalancer, max); } function protectedTokens() internal view override returns (address[] memory) {} function ethToWant(uint _amtInWei) public view virtual override returns (uint) { return rebalancer.ethToWant(address(want), _amtInWei); } // Helpers // function balanceOfWant() public view returns (uint _balance){ return want.balanceOf(address(this)); } function totalDebt() public view returns (uint _debt){ return vault.strategies(address(this)).totalDebt; } function getPriceFeed() public view returns (uint _lastestAnswer){ return oracle.latestAnswer(); } function getPriceFeedDecimals() public view returns (uint _dec){ return oracle.decimals(); } function isVaultManagers(address _address) public view returns (bool){ return _address == vault.governance() || _address == vault.management(); } }
/** * Adapts Vault hooks to Balancer Contract and JointAdapter pair */
NatSpecMultiLine
liquidatePosition
function liquidatePosition(uint _amountNeeded) internal override returns (uint _liquidatedAmount, uint _loss) { (_liquidatedAmount, _loss) = _liquidatePosition(_amountNeeded); _adjustPosition(_amountNeeded); }
// called when user withdraws from vault. Rebalance after
LineComment
v0.6.12+commit.27d51765
Unknown
ipfs://0e6c2d2fdb84fd980f0785284dfb7ccbeda15e40002a582c536ba262eed1a3e8
{ "func_code_index": [ 5862, 6099 ] }
7,662
JointProvider
JointProvider.sol
0x580ae3aed3e8e8d83c970fa6d2766c0fb8af759f
Solidity
JointProvider
contract JointProvider is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint; IRebalancer public rebalancer; IPriceFeed public oracle; uint constant public max = type(uint).max; bool internal isOriginal = true; constructor(address _vault, address _oracle) public BaseStrategy(_vault) { _initializeStrat(_oracle); } function initialize( address _vault, address _strategist, address _rewards, address _keeper, address _oracle ) external { _initialize(_vault, _strategist, _rewards, _keeper); _initializeStrat(_oracle); } function _initializeStrat(address _oracle) internal { oracle = IPriceFeed(_oracle); healthCheck = address(0xDDCea799fF1699e98EDF118e0629A974Df7DF012); } function setRebalancer(address payable _rebalancer) external onlyVaultManagers { want.approve(_rebalancer, max); rebalancer = IRebalancer(_rebalancer); require(rebalancer.tokenA() == want || rebalancer.tokenB() == want); } event Cloned(address indexed clone); function cloneProvider( address _vault, address _strategist, address _rewards, address _keeper, address _oracle ) external returns (address newStrategy) { require(isOriginal); bytes20 addressBytes = bytes20(address(this)); assembly { // EIP-1167 bytecode let clone_code := mload(0x40) mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone_code, 0x14), addressBytes) mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) newStrategy := create(0, clone_code, 0x37) } JointProvider(newStrategy).initialize( _vault, _strategist, _rewards, _keeper, _oracle ); emit Cloned(newStrategy); } // ******** OVERRIDE THESE METHODS FROM BASE CONTRACT ************ function name() external view override returns (string memory) { if (address(rebalancer) == address(0x0)) { return string(abi.encodePacked(ISymbol(address(want)).symbol(), " JointProvider ")); } else { return string( abi.encodePacked(rebalancer.name()[0], ISymbol(address(want)).symbol(), " JointProvider ", rebalancer.name()[1]) ); } } function estimatedTotalAssets() public view override returns (uint) { return want.balanceOf(address(this)).add(rebalancer.totalBalanceOf(want)); } function harvestTrigger(uint callCostInWei) public view override returns (bool){ return super.harvestTrigger(callCostInWei) && rebalancer.shouldHarvest(); } function tendTrigger(uint callCostInWei) public view override returns (bool){ return rebalancer.shouldTend(); } function prepareReturn(uint _debtOutstanding) internal override returns (uint _profit, uint _loss, uint _debtPayment) { uint beforeWant = balanceOfWant(); rebalancer.collectTradingFees(); _profit += balanceOfWant().sub(beforeWant); if (_debtOutstanding > 0) { if (vault.strategies(address(this)).debtRatio == 0) { _debtPayment = _liquidateAllPositions(); _loss = _debtOutstanding > _debtPayment ? _debtOutstanding.sub(_debtPayment) : 0; } else { (_debtPayment, _loss) = _liquidatePosition(_debtOutstanding); } } // Interestingly, if you overpay on debt payment, the overpaid amount just sits in the strat. // Report overpayment as profit if (_debtPayment > _debtOutstanding) { _profit += _debtPayment.sub(_debtOutstanding); _debtPayment = _debtOutstanding; } beforeWant = balanceOfWant(); rebalancer.sellRewards(); _profit += balanceOfWant().sub(beforeWant); if (_profit > _loss) { _profit = _profit.sub(_loss); _loss = 0; } else { _loss = _loss.sub(_profit); _profit = 0; } } // called by tend. 0 bc there's no change in debt function adjustPosition(uint _debtOutstanding) internal override { _adjustPosition(0); } // Called during withdraw in order to rebalance to the new debt. // This is necessary so that withdraws will rebalance immediately (instead of waiting for keeper) function _adjustPosition(uint _amountWithdrawn) internal { rebalancer.adjustPosition(_amountWithdrawn, want); } // without adjustPosition. Called internally by prepareReturn. Harvests will call adjustPosition after. function _liquidatePosition(uint _amountNeeded) internal returns (uint _liquidatedAmount, uint _loss) { uint loose = balanceOfWant(); uint pooled = rebalancer.pooledBalance(rebalancer.tokenIndex(want)); if (_amountNeeded > loose) { uint _amountNeededMore = _amountNeeded.sub(loose); if (_amountNeededMore >= pooled) { rebalancer.liquidateAllPositions(want, address(this)); } else { rebalancer.liquidatePosition(_amountNeededMore, want, address(this)); } _liquidatedAmount = balanceOfWant(); _loss = _amountNeeded.sub(_liquidatedAmount); } else { _liquidatedAmount = _amountNeeded; _loss = 0; } } // called when user withdraws from vault. Rebalance after function liquidatePosition(uint _amountNeeded) internal override returns (uint _liquidatedAmount, uint _loss) { (_liquidatedAmount, _loss) = _liquidatePosition(_amountNeeded); _adjustPosition(_amountNeeded); } // without adjustPosition. Called internally by prepareReturn. Harvests will call adjustPosition after. function _liquidateAllPositions() internal returns (uint _amountFreed) { rebalancer.liquidateAllPositions(want, address(this)); return want.balanceOf(address(this)); } // called during emergency exit. Rebalance after to halt pool function liquidateAllPositions() internal override returns (uint _amountFreed) { _amountFreed = _liquidateAllPositions(); _adjustPosition(type(uint).max); } // NOTE: Can override `tendTrigger` and `harvestTrigger` if necessary function prepareMigration(address _newStrategy) internal override { // NOTE: `migrate` will automatically forward all `want` in this strategy to the new one rebalancer.migrateProvider(_newStrategy); } // only called by rebalancer function migrateRebalancer(address payable _newRebalancer) external { require(msg.sender == address(rebalancer), "Not rebalancer!"); rebalancer = IRebalancer(_newRebalancer); want.approve(_newRebalancer, max); } function protectedTokens() internal view override returns (address[] memory) {} function ethToWant(uint _amtInWei) public view virtual override returns (uint) { return rebalancer.ethToWant(address(want), _amtInWei); } // Helpers // function balanceOfWant() public view returns (uint _balance){ return want.balanceOf(address(this)); } function totalDebt() public view returns (uint _debt){ return vault.strategies(address(this)).totalDebt; } function getPriceFeed() public view returns (uint _lastestAnswer){ return oracle.latestAnswer(); } function getPriceFeedDecimals() public view returns (uint _dec){ return oracle.decimals(); } function isVaultManagers(address _address) public view returns (bool){ return _address == vault.governance() || _address == vault.management(); } }
/** * Adapts Vault hooks to Balancer Contract and JointAdapter pair */
NatSpecMultiLine
_liquidateAllPositions
function _liquidateAllPositions() internal returns (uint _amountFreed) { rebalancer.liquidateAllPositions(want, address(this)); return want.balanceOf(address(this)); }
// without adjustPosition. Called internally by prepareReturn. Harvests will call adjustPosition after.
LineComment
v0.6.12+commit.27d51765
Unknown
ipfs://0e6c2d2fdb84fd980f0785284dfb7ccbeda15e40002a582c536ba262eed1a3e8
{ "func_code_index": [ 6211, 6406 ] }
7,663
JointProvider
JointProvider.sol
0x580ae3aed3e8e8d83c970fa6d2766c0fb8af759f
Solidity
JointProvider
contract JointProvider is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint; IRebalancer public rebalancer; IPriceFeed public oracle; uint constant public max = type(uint).max; bool internal isOriginal = true; constructor(address _vault, address _oracle) public BaseStrategy(_vault) { _initializeStrat(_oracle); } function initialize( address _vault, address _strategist, address _rewards, address _keeper, address _oracle ) external { _initialize(_vault, _strategist, _rewards, _keeper); _initializeStrat(_oracle); } function _initializeStrat(address _oracle) internal { oracle = IPriceFeed(_oracle); healthCheck = address(0xDDCea799fF1699e98EDF118e0629A974Df7DF012); } function setRebalancer(address payable _rebalancer) external onlyVaultManagers { want.approve(_rebalancer, max); rebalancer = IRebalancer(_rebalancer); require(rebalancer.tokenA() == want || rebalancer.tokenB() == want); } event Cloned(address indexed clone); function cloneProvider( address _vault, address _strategist, address _rewards, address _keeper, address _oracle ) external returns (address newStrategy) { require(isOriginal); bytes20 addressBytes = bytes20(address(this)); assembly { // EIP-1167 bytecode let clone_code := mload(0x40) mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone_code, 0x14), addressBytes) mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) newStrategy := create(0, clone_code, 0x37) } JointProvider(newStrategy).initialize( _vault, _strategist, _rewards, _keeper, _oracle ); emit Cloned(newStrategy); } // ******** OVERRIDE THESE METHODS FROM BASE CONTRACT ************ function name() external view override returns (string memory) { if (address(rebalancer) == address(0x0)) { return string(abi.encodePacked(ISymbol(address(want)).symbol(), " JointProvider ")); } else { return string( abi.encodePacked(rebalancer.name()[0], ISymbol(address(want)).symbol(), " JointProvider ", rebalancer.name()[1]) ); } } function estimatedTotalAssets() public view override returns (uint) { return want.balanceOf(address(this)).add(rebalancer.totalBalanceOf(want)); } function harvestTrigger(uint callCostInWei) public view override returns (bool){ return super.harvestTrigger(callCostInWei) && rebalancer.shouldHarvest(); } function tendTrigger(uint callCostInWei) public view override returns (bool){ return rebalancer.shouldTend(); } function prepareReturn(uint _debtOutstanding) internal override returns (uint _profit, uint _loss, uint _debtPayment) { uint beforeWant = balanceOfWant(); rebalancer.collectTradingFees(); _profit += balanceOfWant().sub(beforeWant); if (_debtOutstanding > 0) { if (vault.strategies(address(this)).debtRatio == 0) { _debtPayment = _liquidateAllPositions(); _loss = _debtOutstanding > _debtPayment ? _debtOutstanding.sub(_debtPayment) : 0; } else { (_debtPayment, _loss) = _liquidatePosition(_debtOutstanding); } } // Interestingly, if you overpay on debt payment, the overpaid amount just sits in the strat. // Report overpayment as profit if (_debtPayment > _debtOutstanding) { _profit += _debtPayment.sub(_debtOutstanding); _debtPayment = _debtOutstanding; } beforeWant = balanceOfWant(); rebalancer.sellRewards(); _profit += balanceOfWant().sub(beforeWant); if (_profit > _loss) { _profit = _profit.sub(_loss); _loss = 0; } else { _loss = _loss.sub(_profit); _profit = 0; } } // called by tend. 0 bc there's no change in debt function adjustPosition(uint _debtOutstanding) internal override { _adjustPosition(0); } // Called during withdraw in order to rebalance to the new debt. // This is necessary so that withdraws will rebalance immediately (instead of waiting for keeper) function _adjustPosition(uint _amountWithdrawn) internal { rebalancer.adjustPosition(_amountWithdrawn, want); } // without adjustPosition. Called internally by prepareReturn. Harvests will call adjustPosition after. function _liquidatePosition(uint _amountNeeded) internal returns (uint _liquidatedAmount, uint _loss) { uint loose = balanceOfWant(); uint pooled = rebalancer.pooledBalance(rebalancer.tokenIndex(want)); if (_amountNeeded > loose) { uint _amountNeededMore = _amountNeeded.sub(loose); if (_amountNeededMore >= pooled) { rebalancer.liquidateAllPositions(want, address(this)); } else { rebalancer.liquidatePosition(_amountNeededMore, want, address(this)); } _liquidatedAmount = balanceOfWant(); _loss = _amountNeeded.sub(_liquidatedAmount); } else { _liquidatedAmount = _amountNeeded; _loss = 0; } } // called when user withdraws from vault. Rebalance after function liquidatePosition(uint _amountNeeded) internal override returns (uint _liquidatedAmount, uint _loss) { (_liquidatedAmount, _loss) = _liquidatePosition(_amountNeeded); _adjustPosition(_amountNeeded); } // without adjustPosition. Called internally by prepareReturn. Harvests will call adjustPosition after. function _liquidateAllPositions() internal returns (uint _amountFreed) { rebalancer.liquidateAllPositions(want, address(this)); return want.balanceOf(address(this)); } // called during emergency exit. Rebalance after to halt pool function liquidateAllPositions() internal override returns (uint _amountFreed) { _amountFreed = _liquidateAllPositions(); _adjustPosition(type(uint).max); } // NOTE: Can override `tendTrigger` and `harvestTrigger` if necessary function prepareMigration(address _newStrategy) internal override { // NOTE: `migrate` will automatically forward all `want` in this strategy to the new one rebalancer.migrateProvider(_newStrategy); } // only called by rebalancer function migrateRebalancer(address payable _newRebalancer) external { require(msg.sender == address(rebalancer), "Not rebalancer!"); rebalancer = IRebalancer(_newRebalancer); want.approve(_newRebalancer, max); } function protectedTokens() internal view override returns (address[] memory) {} function ethToWant(uint _amtInWei) public view virtual override returns (uint) { return rebalancer.ethToWant(address(want), _amtInWei); } // Helpers // function balanceOfWant() public view returns (uint _balance){ return want.balanceOf(address(this)); } function totalDebt() public view returns (uint _debt){ return vault.strategies(address(this)).totalDebt; } function getPriceFeed() public view returns (uint _lastestAnswer){ return oracle.latestAnswer(); } function getPriceFeedDecimals() public view returns (uint _dec){ return oracle.decimals(); } function isVaultManagers(address _address) public view returns (bool){ return _address == vault.governance() || _address == vault.management(); } }
/** * Adapts Vault hooks to Balancer Contract and JointAdapter pair */
NatSpecMultiLine
liquidateAllPositions
function liquidateAllPositions() internal override returns (uint _amountFreed) { _amountFreed = _liquidateAllPositions(); _adjustPosition(type(uint).max); }
// called during emergency exit. Rebalance after to halt pool
LineComment
v0.6.12+commit.27d51765
Unknown
ipfs://0e6c2d2fdb84fd980f0785284dfb7ccbeda15e40002a582c536ba262eed1a3e8
{ "func_code_index": [ 6476, 6660 ] }
7,664
JointProvider
JointProvider.sol
0x580ae3aed3e8e8d83c970fa6d2766c0fb8af759f
Solidity
JointProvider
contract JointProvider is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint; IRebalancer public rebalancer; IPriceFeed public oracle; uint constant public max = type(uint).max; bool internal isOriginal = true; constructor(address _vault, address _oracle) public BaseStrategy(_vault) { _initializeStrat(_oracle); } function initialize( address _vault, address _strategist, address _rewards, address _keeper, address _oracle ) external { _initialize(_vault, _strategist, _rewards, _keeper); _initializeStrat(_oracle); } function _initializeStrat(address _oracle) internal { oracle = IPriceFeed(_oracle); healthCheck = address(0xDDCea799fF1699e98EDF118e0629A974Df7DF012); } function setRebalancer(address payable _rebalancer) external onlyVaultManagers { want.approve(_rebalancer, max); rebalancer = IRebalancer(_rebalancer); require(rebalancer.tokenA() == want || rebalancer.tokenB() == want); } event Cloned(address indexed clone); function cloneProvider( address _vault, address _strategist, address _rewards, address _keeper, address _oracle ) external returns (address newStrategy) { require(isOriginal); bytes20 addressBytes = bytes20(address(this)); assembly { // EIP-1167 bytecode let clone_code := mload(0x40) mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone_code, 0x14), addressBytes) mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) newStrategy := create(0, clone_code, 0x37) } JointProvider(newStrategy).initialize( _vault, _strategist, _rewards, _keeper, _oracle ); emit Cloned(newStrategy); } // ******** OVERRIDE THESE METHODS FROM BASE CONTRACT ************ function name() external view override returns (string memory) { if (address(rebalancer) == address(0x0)) { return string(abi.encodePacked(ISymbol(address(want)).symbol(), " JointProvider ")); } else { return string( abi.encodePacked(rebalancer.name()[0], ISymbol(address(want)).symbol(), " JointProvider ", rebalancer.name()[1]) ); } } function estimatedTotalAssets() public view override returns (uint) { return want.balanceOf(address(this)).add(rebalancer.totalBalanceOf(want)); } function harvestTrigger(uint callCostInWei) public view override returns (bool){ return super.harvestTrigger(callCostInWei) && rebalancer.shouldHarvest(); } function tendTrigger(uint callCostInWei) public view override returns (bool){ return rebalancer.shouldTend(); } function prepareReturn(uint _debtOutstanding) internal override returns (uint _profit, uint _loss, uint _debtPayment) { uint beforeWant = balanceOfWant(); rebalancer.collectTradingFees(); _profit += balanceOfWant().sub(beforeWant); if (_debtOutstanding > 0) { if (vault.strategies(address(this)).debtRatio == 0) { _debtPayment = _liquidateAllPositions(); _loss = _debtOutstanding > _debtPayment ? _debtOutstanding.sub(_debtPayment) : 0; } else { (_debtPayment, _loss) = _liquidatePosition(_debtOutstanding); } } // Interestingly, if you overpay on debt payment, the overpaid amount just sits in the strat. // Report overpayment as profit if (_debtPayment > _debtOutstanding) { _profit += _debtPayment.sub(_debtOutstanding); _debtPayment = _debtOutstanding; } beforeWant = balanceOfWant(); rebalancer.sellRewards(); _profit += balanceOfWant().sub(beforeWant); if (_profit > _loss) { _profit = _profit.sub(_loss); _loss = 0; } else { _loss = _loss.sub(_profit); _profit = 0; } } // called by tend. 0 bc there's no change in debt function adjustPosition(uint _debtOutstanding) internal override { _adjustPosition(0); } // Called during withdraw in order to rebalance to the new debt. // This is necessary so that withdraws will rebalance immediately (instead of waiting for keeper) function _adjustPosition(uint _amountWithdrawn) internal { rebalancer.adjustPosition(_amountWithdrawn, want); } // without adjustPosition. Called internally by prepareReturn. Harvests will call adjustPosition after. function _liquidatePosition(uint _amountNeeded) internal returns (uint _liquidatedAmount, uint _loss) { uint loose = balanceOfWant(); uint pooled = rebalancer.pooledBalance(rebalancer.tokenIndex(want)); if (_amountNeeded > loose) { uint _amountNeededMore = _amountNeeded.sub(loose); if (_amountNeededMore >= pooled) { rebalancer.liquidateAllPositions(want, address(this)); } else { rebalancer.liquidatePosition(_amountNeededMore, want, address(this)); } _liquidatedAmount = balanceOfWant(); _loss = _amountNeeded.sub(_liquidatedAmount); } else { _liquidatedAmount = _amountNeeded; _loss = 0; } } // called when user withdraws from vault. Rebalance after function liquidatePosition(uint _amountNeeded) internal override returns (uint _liquidatedAmount, uint _loss) { (_liquidatedAmount, _loss) = _liquidatePosition(_amountNeeded); _adjustPosition(_amountNeeded); } // without adjustPosition. Called internally by prepareReturn. Harvests will call adjustPosition after. function _liquidateAllPositions() internal returns (uint _amountFreed) { rebalancer.liquidateAllPositions(want, address(this)); return want.balanceOf(address(this)); } // called during emergency exit. Rebalance after to halt pool function liquidateAllPositions() internal override returns (uint _amountFreed) { _amountFreed = _liquidateAllPositions(); _adjustPosition(type(uint).max); } // NOTE: Can override `tendTrigger` and `harvestTrigger` if necessary function prepareMigration(address _newStrategy) internal override { // NOTE: `migrate` will automatically forward all `want` in this strategy to the new one rebalancer.migrateProvider(_newStrategy); } // only called by rebalancer function migrateRebalancer(address payable _newRebalancer) external { require(msg.sender == address(rebalancer), "Not rebalancer!"); rebalancer = IRebalancer(_newRebalancer); want.approve(_newRebalancer, max); } function protectedTokens() internal view override returns (address[] memory) {} function ethToWant(uint _amtInWei) public view virtual override returns (uint) { return rebalancer.ethToWant(address(want), _amtInWei); } // Helpers // function balanceOfWant() public view returns (uint _balance){ return want.balanceOf(address(this)); } function totalDebt() public view returns (uint _debt){ return vault.strategies(address(this)).totalDebt; } function getPriceFeed() public view returns (uint _lastestAnswer){ return oracle.latestAnswer(); } function getPriceFeedDecimals() public view returns (uint _dec){ return oracle.decimals(); } function isVaultManagers(address _address) public view returns (bool){ return _address == vault.governance() || _address == vault.management(); } }
/** * Adapts Vault hooks to Balancer Contract and JointAdapter pair */
NatSpecMultiLine
prepareMigration
function prepareMigration(address _newStrategy) internal override { // NOTE: `migrate` will automatically forward all `want` in this strategy to the new one rebalancer.migrateProvider(_newStrategy); }
// NOTE: Can override `tendTrigger` and `harvestTrigger` if necessary
LineComment
v0.6.12+commit.27d51765
Unknown
ipfs://0e6c2d2fdb84fd980f0785284dfb7ccbeda15e40002a582c536ba262eed1a3e8
{ "func_code_index": [ 6738, 6966 ] }
7,665
JointProvider
JointProvider.sol
0x580ae3aed3e8e8d83c970fa6d2766c0fb8af759f
Solidity
JointProvider
contract JointProvider is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint; IRebalancer public rebalancer; IPriceFeed public oracle; uint constant public max = type(uint).max; bool internal isOriginal = true; constructor(address _vault, address _oracle) public BaseStrategy(_vault) { _initializeStrat(_oracle); } function initialize( address _vault, address _strategist, address _rewards, address _keeper, address _oracle ) external { _initialize(_vault, _strategist, _rewards, _keeper); _initializeStrat(_oracle); } function _initializeStrat(address _oracle) internal { oracle = IPriceFeed(_oracle); healthCheck = address(0xDDCea799fF1699e98EDF118e0629A974Df7DF012); } function setRebalancer(address payable _rebalancer) external onlyVaultManagers { want.approve(_rebalancer, max); rebalancer = IRebalancer(_rebalancer); require(rebalancer.tokenA() == want || rebalancer.tokenB() == want); } event Cloned(address indexed clone); function cloneProvider( address _vault, address _strategist, address _rewards, address _keeper, address _oracle ) external returns (address newStrategy) { require(isOriginal); bytes20 addressBytes = bytes20(address(this)); assembly { // EIP-1167 bytecode let clone_code := mload(0x40) mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone_code, 0x14), addressBytes) mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) newStrategy := create(0, clone_code, 0x37) } JointProvider(newStrategy).initialize( _vault, _strategist, _rewards, _keeper, _oracle ); emit Cloned(newStrategy); } // ******** OVERRIDE THESE METHODS FROM BASE CONTRACT ************ function name() external view override returns (string memory) { if (address(rebalancer) == address(0x0)) { return string(abi.encodePacked(ISymbol(address(want)).symbol(), " JointProvider ")); } else { return string( abi.encodePacked(rebalancer.name()[0], ISymbol(address(want)).symbol(), " JointProvider ", rebalancer.name()[1]) ); } } function estimatedTotalAssets() public view override returns (uint) { return want.balanceOf(address(this)).add(rebalancer.totalBalanceOf(want)); } function harvestTrigger(uint callCostInWei) public view override returns (bool){ return super.harvestTrigger(callCostInWei) && rebalancer.shouldHarvest(); } function tendTrigger(uint callCostInWei) public view override returns (bool){ return rebalancer.shouldTend(); } function prepareReturn(uint _debtOutstanding) internal override returns (uint _profit, uint _loss, uint _debtPayment) { uint beforeWant = balanceOfWant(); rebalancer.collectTradingFees(); _profit += balanceOfWant().sub(beforeWant); if (_debtOutstanding > 0) { if (vault.strategies(address(this)).debtRatio == 0) { _debtPayment = _liquidateAllPositions(); _loss = _debtOutstanding > _debtPayment ? _debtOutstanding.sub(_debtPayment) : 0; } else { (_debtPayment, _loss) = _liquidatePosition(_debtOutstanding); } } // Interestingly, if you overpay on debt payment, the overpaid amount just sits in the strat. // Report overpayment as profit if (_debtPayment > _debtOutstanding) { _profit += _debtPayment.sub(_debtOutstanding); _debtPayment = _debtOutstanding; } beforeWant = balanceOfWant(); rebalancer.sellRewards(); _profit += balanceOfWant().sub(beforeWant); if (_profit > _loss) { _profit = _profit.sub(_loss); _loss = 0; } else { _loss = _loss.sub(_profit); _profit = 0; } } // called by tend. 0 bc there's no change in debt function adjustPosition(uint _debtOutstanding) internal override { _adjustPosition(0); } // Called during withdraw in order to rebalance to the new debt. // This is necessary so that withdraws will rebalance immediately (instead of waiting for keeper) function _adjustPosition(uint _amountWithdrawn) internal { rebalancer.adjustPosition(_amountWithdrawn, want); } // without adjustPosition. Called internally by prepareReturn. Harvests will call adjustPosition after. function _liquidatePosition(uint _amountNeeded) internal returns (uint _liquidatedAmount, uint _loss) { uint loose = balanceOfWant(); uint pooled = rebalancer.pooledBalance(rebalancer.tokenIndex(want)); if (_amountNeeded > loose) { uint _amountNeededMore = _amountNeeded.sub(loose); if (_amountNeededMore >= pooled) { rebalancer.liquidateAllPositions(want, address(this)); } else { rebalancer.liquidatePosition(_amountNeededMore, want, address(this)); } _liquidatedAmount = balanceOfWant(); _loss = _amountNeeded.sub(_liquidatedAmount); } else { _liquidatedAmount = _amountNeeded; _loss = 0; } } // called when user withdraws from vault. Rebalance after function liquidatePosition(uint _amountNeeded) internal override returns (uint _liquidatedAmount, uint _loss) { (_liquidatedAmount, _loss) = _liquidatePosition(_amountNeeded); _adjustPosition(_amountNeeded); } // without adjustPosition. Called internally by prepareReturn. Harvests will call adjustPosition after. function _liquidateAllPositions() internal returns (uint _amountFreed) { rebalancer.liquidateAllPositions(want, address(this)); return want.balanceOf(address(this)); } // called during emergency exit. Rebalance after to halt pool function liquidateAllPositions() internal override returns (uint _amountFreed) { _amountFreed = _liquidateAllPositions(); _adjustPosition(type(uint).max); } // NOTE: Can override `tendTrigger` and `harvestTrigger` if necessary function prepareMigration(address _newStrategy) internal override { // NOTE: `migrate` will automatically forward all `want` in this strategy to the new one rebalancer.migrateProvider(_newStrategy); } // only called by rebalancer function migrateRebalancer(address payable _newRebalancer) external { require(msg.sender == address(rebalancer), "Not rebalancer!"); rebalancer = IRebalancer(_newRebalancer); want.approve(_newRebalancer, max); } function protectedTokens() internal view override returns (address[] memory) {} function ethToWant(uint _amtInWei) public view virtual override returns (uint) { return rebalancer.ethToWant(address(want), _amtInWei); } // Helpers // function balanceOfWant() public view returns (uint _balance){ return want.balanceOf(address(this)); } function totalDebt() public view returns (uint _debt){ return vault.strategies(address(this)).totalDebt; } function getPriceFeed() public view returns (uint _lastestAnswer){ return oracle.latestAnswer(); } function getPriceFeedDecimals() public view returns (uint _dec){ return oracle.decimals(); } function isVaultManagers(address _address) public view returns (bool){ return _address == vault.governance() || _address == vault.management(); } }
/** * Adapts Vault hooks to Balancer Contract and JointAdapter pair */
NatSpecMultiLine
migrateRebalancer
function migrateRebalancer(address payable _newRebalancer) external { require(msg.sender == address(rebalancer), "Not rebalancer!"); rebalancer = IRebalancer(_newRebalancer); want.approve(_newRebalancer, max); }
// only called by rebalancer
LineComment
v0.6.12+commit.27d51765
Unknown
ipfs://0e6c2d2fdb84fd980f0785284dfb7ccbeda15e40002a582c536ba262eed1a3e8
{ "func_code_index": [ 7003, 7251 ] }
7,666
JointProvider
JointProvider.sol
0x580ae3aed3e8e8d83c970fa6d2766c0fb8af759f
Solidity
JointProvider
contract JointProvider is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint; IRebalancer public rebalancer; IPriceFeed public oracle; uint constant public max = type(uint).max; bool internal isOriginal = true; constructor(address _vault, address _oracle) public BaseStrategy(_vault) { _initializeStrat(_oracle); } function initialize( address _vault, address _strategist, address _rewards, address _keeper, address _oracle ) external { _initialize(_vault, _strategist, _rewards, _keeper); _initializeStrat(_oracle); } function _initializeStrat(address _oracle) internal { oracle = IPriceFeed(_oracle); healthCheck = address(0xDDCea799fF1699e98EDF118e0629A974Df7DF012); } function setRebalancer(address payable _rebalancer) external onlyVaultManagers { want.approve(_rebalancer, max); rebalancer = IRebalancer(_rebalancer); require(rebalancer.tokenA() == want || rebalancer.tokenB() == want); } event Cloned(address indexed clone); function cloneProvider( address _vault, address _strategist, address _rewards, address _keeper, address _oracle ) external returns (address newStrategy) { require(isOriginal); bytes20 addressBytes = bytes20(address(this)); assembly { // EIP-1167 bytecode let clone_code := mload(0x40) mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone_code, 0x14), addressBytes) mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) newStrategy := create(0, clone_code, 0x37) } JointProvider(newStrategy).initialize( _vault, _strategist, _rewards, _keeper, _oracle ); emit Cloned(newStrategy); } // ******** OVERRIDE THESE METHODS FROM BASE CONTRACT ************ function name() external view override returns (string memory) { if (address(rebalancer) == address(0x0)) { return string(abi.encodePacked(ISymbol(address(want)).symbol(), " JointProvider ")); } else { return string( abi.encodePacked(rebalancer.name()[0], ISymbol(address(want)).symbol(), " JointProvider ", rebalancer.name()[1]) ); } } function estimatedTotalAssets() public view override returns (uint) { return want.balanceOf(address(this)).add(rebalancer.totalBalanceOf(want)); } function harvestTrigger(uint callCostInWei) public view override returns (bool){ return super.harvestTrigger(callCostInWei) && rebalancer.shouldHarvest(); } function tendTrigger(uint callCostInWei) public view override returns (bool){ return rebalancer.shouldTend(); } function prepareReturn(uint _debtOutstanding) internal override returns (uint _profit, uint _loss, uint _debtPayment) { uint beforeWant = balanceOfWant(); rebalancer.collectTradingFees(); _profit += balanceOfWant().sub(beforeWant); if (_debtOutstanding > 0) { if (vault.strategies(address(this)).debtRatio == 0) { _debtPayment = _liquidateAllPositions(); _loss = _debtOutstanding > _debtPayment ? _debtOutstanding.sub(_debtPayment) : 0; } else { (_debtPayment, _loss) = _liquidatePosition(_debtOutstanding); } } // Interestingly, if you overpay on debt payment, the overpaid amount just sits in the strat. // Report overpayment as profit if (_debtPayment > _debtOutstanding) { _profit += _debtPayment.sub(_debtOutstanding); _debtPayment = _debtOutstanding; } beforeWant = balanceOfWant(); rebalancer.sellRewards(); _profit += balanceOfWant().sub(beforeWant); if (_profit > _loss) { _profit = _profit.sub(_loss); _loss = 0; } else { _loss = _loss.sub(_profit); _profit = 0; } } // called by tend. 0 bc there's no change in debt function adjustPosition(uint _debtOutstanding) internal override { _adjustPosition(0); } // Called during withdraw in order to rebalance to the new debt. // This is necessary so that withdraws will rebalance immediately (instead of waiting for keeper) function _adjustPosition(uint _amountWithdrawn) internal { rebalancer.adjustPosition(_amountWithdrawn, want); } // without adjustPosition. Called internally by prepareReturn. Harvests will call adjustPosition after. function _liquidatePosition(uint _amountNeeded) internal returns (uint _liquidatedAmount, uint _loss) { uint loose = balanceOfWant(); uint pooled = rebalancer.pooledBalance(rebalancer.tokenIndex(want)); if (_amountNeeded > loose) { uint _amountNeededMore = _amountNeeded.sub(loose); if (_amountNeededMore >= pooled) { rebalancer.liquidateAllPositions(want, address(this)); } else { rebalancer.liquidatePosition(_amountNeededMore, want, address(this)); } _liquidatedAmount = balanceOfWant(); _loss = _amountNeeded.sub(_liquidatedAmount); } else { _liquidatedAmount = _amountNeeded; _loss = 0; } } // called when user withdraws from vault. Rebalance after function liquidatePosition(uint _amountNeeded) internal override returns (uint _liquidatedAmount, uint _loss) { (_liquidatedAmount, _loss) = _liquidatePosition(_amountNeeded); _adjustPosition(_amountNeeded); } // without adjustPosition. Called internally by prepareReturn. Harvests will call adjustPosition after. function _liquidateAllPositions() internal returns (uint _amountFreed) { rebalancer.liquidateAllPositions(want, address(this)); return want.balanceOf(address(this)); } // called during emergency exit. Rebalance after to halt pool function liquidateAllPositions() internal override returns (uint _amountFreed) { _amountFreed = _liquidateAllPositions(); _adjustPosition(type(uint).max); } // NOTE: Can override `tendTrigger` and `harvestTrigger` if necessary function prepareMigration(address _newStrategy) internal override { // NOTE: `migrate` will automatically forward all `want` in this strategy to the new one rebalancer.migrateProvider(_newStrategy); } // only called by rebalancer function migrateRebalancer(address payable _newRebalancer) external { require(msg.sender == address(rebalancer), "Not rebalancer!"); rebalancer = IRebalancer(_newRebalancer); want.approve(_newRebalancer, max); } function protectedTokens() internal view override returns (address[] memory) {} function ethToWant(uint _amtInWei) public view virtual override returns (uint) { return rebalancer.ethToWant(address(want), _amtInWei); } // Helpers // function balanceOfWant() public view returns (uint _balance){ return want.balanceOf(address(this)); } function totalDebt() public view returns (uint _debt){ return vault.strategies(address(this)).totalDebt; } function getPriceFeed() public view returns (uint _lastestAnswer){ return oracle.latestAnswer(); } function getPriceFeedDecimals() public view returns (uint _dec){ return oracle.decimals(); } function isVaultManagers(address _address) public view returns (bool){ return _address == vault.governance() || _address == vault.management(); } }
/** * Adapts Vault hooks to Balancer Contract and JointAdapter pair */
NatSpecMultiLine
balanceOfWant
function balanceOfWant() public view returns (uint _balance){ return want.balanceOf(address(this)); }
// Helpers //
LineComment
v0.6.12+commit.27d51765
Unknown
ipfs://0e6c2d2fdb84fd980f0785284dfb7ccbeda15e40002a582c536ba262eed1a3e8
{ "func_code_index": [ 7519, 7639 ] }
7,667
XPNSignal
contracts/XPNSimpleSignal.sol
0xa7a564621ce88665bb7ca37b72af14da11fb1db1
Solidity
XPNSignal
contract XPNSignal is ISignal, Ownable { struct signalMetaData { string signalType; bool signalExist; bool signalActive; } mapping(address => mapping(string => bool)) ownSignals; mapping(string => int256[]) signalsWeight; mapping(string => string[]) signalsSymbol; mapping(string => signalMetaData) signalsMetaData; mapping(address => bool) signalProviderWhitelist; address[] assetAddress; event SignalProviderWhitelisted(address wallet); event SignalProviderDeWhitelisted(address wallet); constructor() { whitelistsignalProvider(msg.sender); } // @notice register a new signal. caller will own the signal // @param signalName unique identifier of the signal. // @param signalType general info about the signal. // @param symbols list of symbol that this signal will address. order sensitive. immutable function registerSignal( string memory signalName, string memory signalType, string[] memory symbols ) external override returns (string memory) { require( _signalProviderIsWhitelisted(msg.sender), "Wallet is not whitelisted" ); if (signalsMetaData[signalName].signalExist) { revert("signal already exist"); } ownSignals[msg.sender][signalName] = true; signalsMetaData[signalName] = signalMetaData({ signalType: signalType, signalExist: true, signalActive: false }); signalsSymbol[signalName] = symbols; } // @notice whitelist wallet by address // @param address of the wallet to whitelist // @dev only callable by owner function whitelistsignalProvider(address wallet) public onlyOwner { signalProviderWhitelist[wallet] = true; emit SignalProviderWhitelisted(wallet); } // @notice un-whitelist wallet by address // @param address of the wallet to un-whitelist // @dev only callable by owner function deWhitelistsignalProvider(address wallet) public onlyOwner { signalProviderWhitelist[wallet] = false; emit SignalProviderDeWhitelisted(wallet); } function _signalProviderIsWhitelisted(address wallet) private view returns (bool) { return signalProviderWhitelist[wallet]; } // @notice make a signal inactive // @dev caller must be signal owner function withdrawSignal(string memory signalName) external override { require(ownSignals[msg.sender][signalName], "not your signal"); signalsMetaData[signalName].signalActive = false; } // @notice signal weight setter. just store signal weight as signal. // @dev some of the param are just from ISignal, not really in use. // @param signalName unique identifier of signal // @param ref not in use. // @param weights of each asset. // @param data not in use. function submitSignal( string memory signalName, string[] memory ref, int256[] memory weights, bytes calldata data ) external override { require(ownSignals[msg.sender][signalName], "not your signal"); require( weights.length == signalsSymbol[signalName].length, "signal length mismatch" ); signalsWeight[signalName] = weights; signalsMetaData[signalName].signalActive = true; } // @notice do nothing. this function is from ISignal. function updateSignal(string memory signalName) external override { revert("this signal do not require any update"); } // @notice get symbol list of the signal // @param signalName unique identifier of signal // @return string[] list of symbol function getSignalSymbols(string memory signalName) external view override returns (string[] memory) { require( signalsMetaData[signalName].signalActive, "signal not available" ); return signalsSymbol[signalName]; } // @notice get symbol list of the signal // @param signalName unique identifier of signal // @return int256[] signal, % target allocation between each symbols. function getSignal(string memory signalName) external view override returns (int256[] memory) { require( signalsMetaData[signalName].signalActive, "signal not available" ); return signalsWeight[signalName]; } }
registerSignal
function registerSignal( string memory signalName, string memory signalType, string[] memory symbols ) external override returns (string memory) { require( _signalProviderIsWhitelisted(msg.sender), "Wallet is not whitelisted" ); if (signalsMetaData[signalName].signalExist) { revert("signal already exist"); } ownSignals[msg.sender][signalName] = true; signalsMetaData[signalName] = signalMetaData({ signalType: signalType, signalExist: true, signalActive: false }); signalsSymbol[signalName] = symbols; }
// @notice register a new signal. caller will own the signal // @param signalName unique identifier of the signal. // @param signalType general info about the signal. // @param symbols list of symbol that this signal will address. order sensitive. immutable
LineComment
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 902, 1581 ] }
7,668
XPNSignal
contracts/XPNSimpleSignal.sol
0xa7a564621ce88665bb7ca37b72af14da11fb1db1
Solidity
XPNSignal
contract XPNSignal is ISignal, Ownable { struct signalMetaData { string signalType; bool signalExist; bool signalActive; } mapping(address => mapping(string => bool)) ownSignals; mapping(string => int256[]) signalsWeight; mapping(string => string[]) signalsSymbol; mapping(string => signalMetaData) signalsMetaData; mapping(address => bool) signalProviderWhitelist; address[] assetAddress; event SignalProviderWhitelisted(address wallet); event SignalProviderDeWhitelisted(address wallet); constructor() { whitelistsignalProvider(msg.sender); } // @notice register a new signal. caller will own the signal // @param signalName unique identifier of the signal. // @param signalType general info about the signal. // @param symbols list of symbol that this signal will address. order sensitive. immutable function registerSignal( string memory signalName, string memory signalType, string[] memory symbols ) external override returns (string memory) { require( _signalProviderIsWhitelisted(msg.sender), "Wallet is not whitelisted" ); if (signalsMetaData[signalName].signalExist) { revert("signal already exist"); } ownSignals[msg.sender][signalName] = true; signalsMetaData[signalName] = signalMetaData({ signalType: signalType, signalExist: true, signalActive: false }); signalsSymbol[signalName] = symbols; } // @notice whitelist wallet by address // @param address of the wallet to whitelist // @dev only callable by owner function whitelistsignalProvider(address wallet) public onlyOwner { signalProviderWhitelist[wallet] = true; emit SignalProviderWhitelisted(wallet); } // @notice un-whitelist wallet by address // @param address of the wallet to un-whitelist // @dev only callable by owner function deWhitelistsignalProvider(address wallet) public onlyOwner { signalProviderWhitelist[wallet] = false; emit SignalProviderDeWhitelisted(wallet); } function _signalProviderIsWhitelisted(address wallet) private view returns (bool) { return signalProviderWhitelist[wallet]; } // @notice make a signal inactive // @dev caller must be signal owner function withdrawSignal(string memory signalName) external override { require(ownSignals[msg.sender][signalName], "not your signal"); signalsMetaData[signalName].signalActive = false; } // @notice signal weight setter. just store signal weight as signal. // @dev some of the param are just from ISignal, not really in use. // @param signalName unique identifier of signal // @param ref not in use. // @param weights of each asset. // @param data not in use. function submitSignal( string memory signalName, string[] memory ref, int256[] memory weights, bytes calldata data ) external override { require(ownSignals[msg.sender][signalName], "not your signal"); require( weights.length == signalsSymbol[signalName].length, "signal length mismatch" ); signalsWeight[signalName] = weights; signalsMetaData[signalName].signalActive = true; } // @notice do nothing. this function is from ISignal. function updateSignal(string memory signalName) external override { revert("this signal do not require any update"); } // @notice get symbol list of the signal // @param signalName unique identifier of signal // @return string[] list of symbol function getSignalSymbols(string memory signalName) external view override returns (string[] memory) { require( signalsMetaData[signalName].signalActive, "signal not available" ); return signalsSymbol[signalName]; } // @notice get symbol list of the signal // @param signalName unique identifier of signal // @return int256[] signal, % target allocation between each symbols. function getSignal(string memory signalName) external view override returns (int256[] memory) { require( signalsMetaData[signalName].signalActive, "signal not available" ); return signalsWeight[signalName]; } }
whitelistsignalProvider
function whitelistsignalProvider(address wallet) public onlyOwner { signalProviderWhitelist[wallet] = true; emit SignalProviderWhitelisted(wallet); }
// @notice whitelist wallet by address // @param address of the wallet to whitelist // @dev only callable by owner
LineComment
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 1710, 1883 ] }
7,669
XPNSignal
contracts/XPNSimpleSignal.sol
0xa7a564621ce88665bb7ca37b72af14da11fb1db1
Solidity
XPNSignal
contract XPNSignal is ISignal, Ownable { struct signalMetaData { string signalType; bool signalExist; bool signalActive; } mapping(address => mapping(string => bool)) ownSignals; mapping(string => int256[]) signalsWeight; mapping(string => string[]) signalsSymbol; mapping(string => signalMetaData) signalsMetaData; mapping(address => bool) signalProviderWhitelist; address[] assetAddress; event SignalProviderWhitelisted(address wallet); event SignalProviderDeWhitelisted(address wallet); constructor() { whitelistsignalProvider(msg.sender); } // @notice register a new signal. caller will own the signal // @param signalName unique identifier of the signal. // @param signalType general info about the signal. // @param symbols list of symbol that this signal will address. order sensitive. immutable function registerSignal( string memory signalName, string memory signalType, string[] memory symbols ) external override returns (string memory) { require( _signalProviderIsWhitelisted(msg.sender), "Wallet is not whitelisted" ); if (signalsMetaData[signalName].signalExist) { revert("signal already exist"); } ownSignals[msg.sender][signalName] = true; signalsMetaData[signalName] = signalMetaData({ signalType: signalType, signalExist: true, signalActive: false }); signalsSymbol[signalName] = symbols; } // @notice whitelist wallet by address // @param address of the wallet to whitelist // @dev only callable by owner function whitelistsignalProvider(address wallet) public onlyOwner { signalProviderWhitelist[wallet] = true; emit SignalProviderWhitelisted(wallet); } // @notice un-whitelist wallet by address // @param address of the wallet to un-whitelist // @dev only callable by owner function deWhitelistsignalProvider(address wallet) public onlyOwner { signalProviderWhitelist[wallet] = false; emit SignalProviderDeWhitelisted(wallet); } function _signalProviderIsWhitelisted(address wallet) private view returns (bool) { return signalProviderWhitelist[wallet]; } // @notice make a signal inactive // @dev caller must be signal owner function withdrawSignal(string memory signalName) external override { require(ownSignals[msg.sender][signalName], "not your signal"); signalsMetaData[signalName].signalActive = false; } // @notice signal weight setter. just store signal weight as signal. // @dev some of the param are just from ISignal, not really in use. // @param signalName unique identifier of signal // @param ref not in use. // @param weights of each asset. // @param data not in use. function submitSignal( string memory signalName, string[] memory ref, int256[] memory weights, bytes calldata data ) external override { require(ownSignals[msg.sender][signalName], "not your signal"); require( weights.length == signalsSymbol[signalName].length, "signal length mismatch" ); signalsWeight[signalName] = weights; signalsMetaData[signalName].signalActive = true; } // @notice do nothing. this function is from ISignal. function updateSignal(string memory signalName) external override { revert("this signal do not require any update"); } // @notice get symbol list of the signal // @param signalName unique identifier of signal // @return string[] list of symbol function getSignalSymbols(string memory signalName) external view override returns (string[] memory) { require( signalsMetaData[signalName].signalActive, "signal not available" ); return signalsSymbol[signalName]; } // @notice get symbol list of the signal // @param signalName unique identifier of signal // @return int256[] signal, % target allocation between each symbols. function getSignal(string memory signalName) external view override returns (int256[] memory) { require( signalsMetaData[signalName].signalActive, "signal not available" ); return signalsWeight[signalName]; } }
deWhitelistsignalProvider
function deWhitelistsignalProvider(address wallet) public onlyOwner { signalProviderWhitelist[wallet] = false; emit SignalProviderDeWhitelisted(wallet); }
// @notice un-whitelist wallet by address // @param address of the wallet to un-whitelist // @dev only callable by owner
LineComment
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 2018, 2196 ] }
7,670
XPNSignal
contracts/XPNSimpleSignal.sol
0xa7a564621ce88665bb7ca37b72af14da11fb1db1
Solidity
XPNSignal
contract XPNSignal is ISignal, Ownable { struct signalMetaData { string signalType; bool signalExist; bool signalActive; } mapping(address => mapping(string => bool)) ownSignals; mapping(string => int256[]) signalsWeight; mapping(string => string[]) signalsSymbol; mapping(string => signalMetaData) signalsMetaData; mapping(address => bool) signalProviderWhitelist; address[] assetAddress; event SignalProviderWhitelisted(address wallet); event SignalProviderDeWhitelisted(address wallet); constructor() { whitelistsignalProvider(msg.sender); } // @notice register a new signal. caller will own the signal // @param signalName unique identifier of the signal. // @param signalType general info about the signal. // @param symbols list of symbol that this signal will address. order sensitive. immutable function registerSignal( string memory signalName, string memory signalType, string[] memory symbols ) external override returns (string memory) { require( _signalProviderIsWhitelisted(msg.sender), "Wallet is not whitelisted" ); if (signalsMetaData[signalName].signalExist) { revert("signal already exist"); } ownSignals[msg.sender][signalName] = true; signalsMetaData[signalName] = signalMetaData({ signalType: signalType, signalExist: true, signalActive: false }); signalsSymbol[signalName] = symbols; } // @notice whitelist wallet by address // @param address of the wallet to whitelist // @dev only callable by owner function whitelistsignalProvider(address wallet) public onlyOwner { signalProviderWhitelist[wallet] = true; emit SignalProviderWhitelisted(wallet); } // @notice un-whitelist wallet by address // @param address of the wallet to un-whitelist // @dev only callable by owner function deWhitelistsignalProvider(address wallet) public onlyOwner { signalProviderWhitelist[wallet] = false; emit SignalProviderDeWhitelisted(wallet); } function _signalProviderIsWhitelisted(address wallet) private view returns (bool) { return signalProviderWhitelist[wallet]; } // @notice make a signal inactive // @dev caller must be signal owner function withdrawSignal(string memory signalName) external override { require(ownSignals[msg.sender][signalName], "not your signal"); signalsMetaData[signalName].signalActive = false; } // @notice signal weight setter. just store signal weight as signal. // @dev some of the param are just from ISignal, not really in use. // @param signalName unique identifier of signal // @param ref not in use. // @param weights of each asset. // @param data not in use. function submitSignal( string memory signalName, string[] memory ref, int256[] memory weights, bytes calldata data ) external override { require(ownSignals[msg.sender][signalName], "not your signal"); require( weights.length == signalsSymbol[signalName].length, "signal length mismatch" ); signalsWeight[signalName] = weights; signalsMetaData[signalName].signalActive = true; } // @notice do nothing. this function is from ISignal. function updateSignal(string memory signalName) external override { revert("this signal do not require any update"); } // @notice get symbol list of the signal // @param signalName unique identifier of signal // @return string[] list of symbol function getSignalSymbols(string memory signalName) external view override returns (string[] memory) { require( signalsMetaData[signalName].signalActive, "signal not available" ); return signalsSymbol[signalName]; } // @notice get symbol list of the signal // @param signalName unique identifier of signal // @return int256[] signal, % target allocation between each symbols. function getSignal(string memory signalName) external view override returns (int256[] memory) { require( signalsMetaData[signalName].signalActive, "signal not available" ); return signalsWeight[signalName]; } }
withdrawSignal
function withdrawSignal(string memory signalName) external override { require(ownSignals[msg.sender][signalName], "not your signal"); signalsMetaData[signalName].signalActive = false; }
// @notice make a signal inactive // @dev caller must be signal owner
LineComment
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 2447, 2656 ] }
7,671
XPNSignal
contracts/XPNSimpleSignal.sol
0xa7a564621ce88665bb7ca37b72af14da11fb1db1
Solidity
XPNSignal
contract XPNSignal is ISignal, Ownable { struct signalMetaData { string signalType; bool signalExist; bool signalActive; } mapping(address => mapping(string => bool)) ownSignals; mapping(string => int256[]) signalsWeight; mapping(string => string[]) signalsSymbol; mapping(string => signalMetaData) signalsMetaData; mapping(address => bool) signalProviderWhitelist; address[] assetAddress; event SignalProviderWhitelisted(address wallet); event SignalProviderDeWhitelisted(address wallet); constructor() { whitelistsignalProvider(msg.sender); } // @notice register a new signal. caller will own the signal // @param signalName unique identifier of the signal. // @param signalType general info about the signal. // @param symbols list of symbol that this signal will address. order sensitive. immutable function registerSignal( string memory signalName, string memory signalType, string[] memory symbols ) external override returns (string memory) { require( _signalProviderIsWhitelisted(msg.sender), "Wallet is not whitelisted" ); if (signalsMetaData[signalName].signalExist) { revert("signal already exist"); } ownSignals[msg.sender][signalName] = true; signalsMetaData[signalName] = signalMetaData({ signalType: signalType, signalExist: true, signalActive: false }); signalsSymbol[signalName] = symbols; } // @notice whitelist wallet by address // @param address of the wallet to whitelist // @dev only callable by owner function whitelistsignalProvider(address wallet) public onlyOwner { signalProviderWhitelist[wallet] = true; emit SignalProviderWhitelisted(wallet); } // @notice un-whitelist wallet by address // @param address of the wallet to un-whitelist // @dev only callable by owner function deWhitelistsignalProvider(address wallet) public onlyOwner { signalProviderWhitelist[wallet] = false; emit SignalProviderDeWhitelisted(wallet); } function _signalProviderIsWhitelisted(address wallet) private view returns (bool) { return signalProviderWhitelist[wallet]; } // @notice make a signal inactive // @dev caller must be signal owner function withdrawSignal(string memory signalName) external override { require(ownSignals[msg.sender][signalName], "not your signal"); signalsMetaData[signalName].signalActive = false; } // @notice signal weight setter. just store signal weight as signal. // @dev some of the param are just from ISignal, not really in use. // @param signalName unique identifier of signal // @param ref not in use. // @param weights of each asset. // @param data not in use. function submitSignal( string memory signalName, string[] memory ref, int256[] memory weights, bytes calldata data ) external override { require(ownSignals[msg.sender][signalName], "not your signal"); require( weights.length == signalsSymbol[signalName].length, "signal length mismatch" ); signalsWeight[signalName] = weights; signalsMetaData[signalName].signalActive = true; } // @notice do nothing. this function is from ISignal. function updateSignal(string memory signalName) external override { revert("this signal do not require any update"); } // @notice get symbol list of the signal // @param signalName unique identifier of signal // @return string[] list of symbol function getSignalSymbols(string memory signalName) external view override returns (string[] memory) { require( signalsMetaData[signalName].signalActive, "signal not available" ); return signalsSymbol[signalName]; } // @notice get symbol list of the signal // @param signalName unique identifier of signal // @return int256[] signal, % target allocation between each symbols. function getSignal(string memory signalName) external view override returns (int256[] memory) { require( signalsMetaData[signalName].signalActive, "signal not available" ); return signalsWeight[signalName]; } }
submitSignal
function submitSignal( string memory signalName, string[] memory ref, int256[] memory weights, bytes calldata data ) external override { require(ownSignals[msg.sender][signalName], "not your signal"); require( weights.length == signalsSymbol[signalName].length, "signal length mismatch" ); signalsWeight[signalName] = weights; signalsMetaData[signalName].signalActive = true; }
// @notice signal weight setter. just store signal weight as signal. // @dev some of the param are just from ISignal, not really in use. // @param signalName unique identifier of signal // @param ref not in use. // @param weights of each asset. // @param data not in use.
LineComment
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 2954, 3439 ] }
7,672
XPNSignal
contracts/XPNSimpleSignal.sol
0xa7a564621ce88665bb7ca37b72af14da11fb1db1
Solidity
XPNSignal
contract XPNSignal is ISignal, Ownable { struct signalMetaData { string signalType; bool signalExist; bool signalActive; } mapping(address => mapping(string => bool)) ownSignals; mapping(string => int256[]) signalsWeight; mapping(string => string[]) signalsSymbol; mapping(string => signalMetaData) signalsMetaData; mapping(address => bool) signalProviderWhitelist; address[] assetAddress; event SignalProviderWhitelisted(address wallet); event SignalProviderDeWhitelisted(address wallet); constructor() { whitelistsignalProvider(msg.sender); } // @notice register a new signal. caller will own the signal // @param signalName unique identifier of the signal. // @param signalType general info about the signal. // @param symbols list of symbol that this signal will address. order sensitive. immutable function registerSignal( string memory signalName, string memory signalType, string[] memory symbols ) external override returns (string memory) { require( _signalProviderIsWhitelisted(msg.sender), "Wallet is not whitelisted" ); if (signalsMetaData[signalName].signalExist) { revert("signal already exist"); } ownSignals[msg.sender][signalName] = true; signalsMetaData[signalName] = signalMetaData({ signalType: signalType, signalExist: true, signalActive: false }); signalsSymbol[signalName] = symbols; } // @notice whitelist wallet by address // @param address of the wallet to whitelist // @dev only callable by owner function whitelistsignalProvider(address wallet) public onlyOwner { signalProviderWhitelist[wallet] = true; emit SignalProviderWhitelisted(wallet); } // @notice un-whitelist wallet by address // @param address of the wallet to un-whitelist // @dev only callable by owner function deWhitelistsignalProvider(address wallet) public onlyOwner { signalProviderWhitelist[wallet] = false; emit SignalProviderDeWhitelisted(wallet); } function _signalProviderIsWhitelisted(address wallet) private view returns (bool) { return signalProviderWhitelist[wallet]; } // @notice make a signal inactive // @dev caller must be signal owner function withdrawSignal(string memory signalName) external override { require(ownSignals[msg.sender][signalName], "not your signal"); signalsMetaData[signalName].signalActive = false; } // @notice signal weight setter. just store signal weight as signal. // @dev some of the param are just from ISignal, not really in use. // @param signalName unique identifier of signal // @param ref not in use. // @param weights of each asset. // @param data not in use. function submitSignal( string memory signalName, string[] memory ref, int256[] memory weights, bytes calldata data ) external override { require(ownSignals[msg.sender][signalName], "not your signal"); require( weights.length == signalsSymbol[signalName].length, "signal length mismatch" ); signalsWeight[signalName] = weights; signalsMetaData[signalName].signalActive = true; } // @notice do nothing. this function is from ISignal. function updateSignal(string memory signalName) external override { revert("this signal do not require any update"); } // @notice get symbol list of the signal // @param signalName unique identifier of signal // @return string[] list of symbol function getSignalSymbols(string memory signalName) external view override returns (string[] memory) { require( signalsMetaData[signalName].signalActive, "signal not available" ); return signalsSymbol[signalName]; } // @notice get symbol list of the signal // @param signalName unique identifier of signal // @return int256[] signal, % target allocation between each symbols. function getSignal(string memory signalName) external view override returns (int256[] memory) { require( signalsMetaData[signalName].signalActive, "signal not available" ); return signalsWeight[signalName]; } }
updateSignal
function updateSignal(string memory signalName) external override { revert("this signal do not require any update"); }
// @notice do nothing. this function is from ISignal.
LineComment
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 3499, 3633 ] }
7,673
XPNSignal
contracts/XPNSimpleSignal.sol
0xa7a564621ce88665bb7ca37b72af14da11fb1db1
Solidity
XPNSignal
contract XPNSignal is ISignal, Ownable { struct signalMetaData { string signalType; bool signalExist; bool signalActive; } mapping(address => mapping(string => bool)) ownSignals; mapping(string => int256[]) signalsWeight; mapping(string => string[]) signalsSymbol; mapping(string => signalMetaData) signalsMetaData; mapping(address => bool) signalProviderWhitelist; address[] assetAddress; event SignalProviderWhitelisted(address wallet); event SignalProviderDeWhitelisted(address wallet); constructor() { whitelistsignalProvider(msg.sender); } // @notice register a new signal. caller will own the signal // @param signalName unique identifier of the signal. // @param signalType general info about the signal. // @param symbols list of symbol that this signal will address. order sensitive. immutable function registerSignal( string memory signalName, string memory signalType, string[] memory symbols ) external override returns (string memory) { require( _signalProviderIsWhitelisted(msg.sender), "Wallet is not whitelisted" ); if (signalsMetaData[signalName].signalExist) { revert("signal already exist"); } ownSignals[msg.sender][signalName] = true; signalsMetaData[signalName] = signalMetaData({ signalType: signalType, signalExist: true, signalActive: false }); signalsSymbol[signalName] = symbols; } // @notice whitelist wallet by address // @param address of the wallet to whitelist // @dev only callable by owner function whitelistsignalProvider(address wallet) public onlyOwner { signalProviderWhitelist[wallet] = true; emit SignalProviderWhitelisted(wallet); } // @notice un-whitelist wallet by address // @param address of the wallet to un-whitelist // @dev only callable by owner function deWhitelistsignalProvider(address wallet) public onlyOwner { signalProviderWhitelist[wallet] = false; emit SignalProviderDeWhitelisted(wallet); } function _signalProviderIsWhitelisted(address wallet) private view returns (bool) { return signalProviderWhitelist[wallet]; } // @notice make a signal inactive // @dev caller must be signal owner function withdrawSignal(string memory signalName) external override { require(ownSignals[msg.sender][signalName], "not your signal"); signalsMetaData[signalName].signalActive = false; } // @notice signal weight setter. just store signal weight as signal. // @dev some of the param are just from ISignal, not really in use. // @param signalName unique identifier of signal // @param ref not in use. // @param weights of each asset. // @param data not in use. function submitSignal( string memory signalName, string[] memory ref, int256[] memory weights, bytes calldata data ) external override { require(ownSignals[msg.sender][signalName], "not your signal"); require( weights.length == signalsSymbol[signalName].length, "signal length mismatch" ); signalsWeight[signalName] = weights; signalsMetaData[signalName].signalActive = true; } // @notice do nothing. this function is from ISignal. function updateSignal(string memory signalName) external override { revert("this signal do not require any update"); } // @notice get symbol list of the signal // @param signalName unique identifier of signal // @return string[] list of symbol function getSignalSymbols(string memory signalName) external view override returns (string[] memory) { require( signalsMetaData[signalName].signalActive, "signal not available" ); return signalsSymbol[signalName]; } // @notice get symbol list of the signal // @param signalName unique identifier of signal // @return int256[] signal, % target allocation between each symbols. function getSignal(string memory signalName) external view override returns (int256[] memory) { require( signalsMetaData[signalName].signalActive, "signal not available" ); return signalsWeight[signalName]; } }
getSignalSymbols
function getSignalSymbols(string memory signalName) external view override returns (string[] memory) { require( signalsMetaData[signalName].signalActive, "signal not available" ); return signalsSymbol[signalName]; }
// @notice get symbol list of the signal // @param signalName unique identifier of signal // @return string[] list of symbol
LineComment
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 3772, 4079 ] }
7,674
XPNSignal
contracts/XPNSimpleSignal.sol
0xa7a564621ce88665bb7ca37b72af14da11fb1db1
Solidity
XPNSignal
contract XPNSignal is ISignal, Ownable { struct signalMetaData { string signalType; bool signalExist; bool signalActive; } mapping(address => mapping(string => bool)) ownSignals; mapping(string => int256[]) signalsWeight; mapping(string => string[]) signalsSymbol; mapping(string => signalMetaData) signalsMetaData; mapping(address => bool) signalProviderWhitelist; address[] assetAddress; event SignalProviderWhitelisted(address wallet); event SignalProviderDeWhitelisted(address wallet); constructor() { whitelistsignalProvider(msg.sender); } // @notice register a new signal. caller will own the signal // @param signalName unique identifier of the signal. // @param signalType general info about the signal. // @param symbols list of symbol that this signal will address. order sensitive. immutable function registerSignal( string memory signalName, string memory signalType, string[] memory symbols ) external override returns (string memory) { require( _signalProviderIsWhitelisted(msg.sender), "Wallet is not whitelisted" ); if (signalsMetaData[signalName].signalExist) { revert("signal already exist"); } ownSignals[msg.sender][signalName] = true; signalsMetaData[signalName] = signalMetaData({ signalType: signalType, signalExist: true, signalActive: false }); signalsSymbol[signalName] = symbols; } // @notice whitelist wallet by address // @param address of the wallet to whitelist // @dev only callable by owner function whitelistsignalProvider(address wallet) public onlyOwner { signalProviderWhitelist[wallet] = true; emit SignalProviderWhitelisted(wallet); } // @notice un-whitelist wallet by address // @param address of the wallet to un-whitelist // @dev only callable by owner function deWhitelistsignalProvider(address wallet) public onlyOwner { signalProviderWhitelist[wallet] = false; emit SignalProviderDeWhitelisted(wallet); } function _signalProviderIsWhitelisted(address wallet) private view returns (bool) { return signalProviderWhitelist[wallet]; } // @notice make a signal inactive // @dev caller must be signal owner function withdrawSignal(string memory signalName) external override { require(ownSignals[msg.sender][signalName], "not your signal"); signalsMetaData[signalName].signalActive = false; } // @notice signal weight setter. just store signal weight as signal. // @dev some of the param are just from ISignal, not really in use. // @param signalName unique identifier of signal // @param ref not in use. // @param weights of each asset. // @param data not in use. function submitSignal( string memory signalName, string[] memory ref, int256[] memory weights, bytes calldata data ) external override { require(ownSignals[msg.sender][signalName], "not your signal"); require( weights.length == signalsSymbol[signalName].length, "signal length mismatch" ); signalsWeight[signalName] = weights; signalsMetaData[signalName].signalActive = true; } // @notice do nothing. this function is from ISignal. function updateSignal(string memory signalName) external override { revert("this signal do not require any update"); } // @notice get symbol list of the signal // @param signalName unique identifier of signal // @return string[] list of symbol function getSignalSymbols(string memory signalName) external view override returns (string[] memory) { require( signalsMetaData[signalName].signalActive, "signal not available" ); return signalsSymbol[signalName]; } // @notice get symbol list of the signal // @param signalName unique identifier of signal // @return int256[] signal, % target allocation between each symbols. function getSignal(string memory signalName) external view override returns (int256[] memory) { require( signalsMetaData[signalName].signalActive, "signal not available" ); return signalsWeight[signalName]; } }
getSignal
function getSignal(string memory signalName) external view override returns (int256[] memory) { require( signalsMetaData[signalName].signalActive, "signal not available" ); return signalsWeight[signalName]; }
// @notice get symbol list of the signal // @param signalName unique identifier of signal // @return int256[] signal, % target allocation between each symbols.
LineComment
v0.8.0+commit.c7dfd78e
{ "func_code_index": [ 4253, 4554 ] }
7,675
GardenContractV2
contracts/GardenContractV2.sol
0x1d6efde41748bc14ec13202f2fcf68a726a21c50
Solidity
GardenContractV2
contract GardenContractV2 is Ownable { using SafeMath for uint256; using SafeERC20 for TulipToken; using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ address internal _benefitiaryAddress = 0x68c1A22aD90f168aa19F800bFB115fB4D52F4AD9; //Founder Address uint256 internal _epochBlockStart = 1600610400; uint256 internal _timeScale = (1 days); //uint256 internal _timeScale = (1 seconds); //uint8 private _pinkTulipDivider = 100; uint256 private _decimalConverter = 10**9; //uint256[3] internal _totalGrowing; uint256[3] internal _totalGrown; /* REMEMBER THE DIFFERENCE */ uint256[3] internal _totalBurnt; uint256[2] internal _totalDecomposed; TulipToken[3] private _token; uint256[3] private _totalSupply; struct tulipToken{ mapping(address => bool) forSeeds; mapping(address => uint256) planted; mapping(address => uint256) periodFinish; //combine with decomposing mapping(address => bool) isDecomposing; } tulipToken[10][3] private _tulipToken; /* ========== CONSTRUCTOR ========== */ constructor(address _seedToken, address _basicTulipToken, address _advTulipToken) public Ownable() { _token[0] = TulipToken(_seedToken); _token[1] = TulipToken(_basicTulipToken); _token[2] = TulipToken(_advTulipToken); } /* ========== VIEWS ========== */ /* ========== internal ========== */ function totalGardenSupply(string calldata name) external view returns (uint256) { uint8 i = tulipType(name); return _totalSupply[i] ; } function totalBedSupply(string calldata name, uint8 garden) external view returns (uint256, bool, bool) { uint8 i = tulipType(name); return (_tulipToken[i][garden].planted[msg.sender], _tulipToken[i][garden].isDecomposing[msg.sender], _tulipToken[i][garden].forSeeds[msg.sender]); } /*function totalTLPGrowing(string calldata name) external view returns (uint256) { uint8 i = tulipType(name); return _totalGrowing[i]; }*/ function totalTLPDecomposed(string calldata name) external view returns (uint256) { uint8 i = tulipType(name) - 1; return _totalDecomposed[i]; } function totalTLPGrown(string calldata name) external view returns (uint256) { uint8 i = tulipType(name); return _totalGrown[i]; } function totalTLPBurnt(string calldata name) external view returns (uint256) { uint8 i = tulipType(name); return _totalBurnt[i]; } function growthRemaining(address account, string calldata name, uint8 garden) external view returns (uint256) { uint8 i = tulipType(name); //return _tulipToken[i][garden].periodFinish[account].sub(now); return _tulipToken[i][garden].periodFinish[account]; } function timeUntilNextTLP(string calldata name, uint8 garden) external view returns (uint256) { uint256 plantTimeSeconds = _tulipToken[tulipType(name)][garden].periodFinish[msg.sender].sub(7 * _timeScale); uint256 secondsDifference = now - plantTimeSeconds; uint256 weeksSincePlanting = (secondsDifference).div(60).div(60).div(24).div(7); //uint256 weeksSincePlanting = (secondsDifference).div(7); if((((secondsDifference).div(60).div(60).div(24)) % 7) > 0){ //if((((secondsDifference)) % 7) > 0){ weeksSincePlanting = weeksSincePlanting.add(1); return plantTimeSeconds.add(weeksSincePlanting.mul(7 * _timeScale)).sub(secondsDifference); } else{ return 0; } } function balanceOf(address account, string calldata name) external view returns (uint256) { uint8 i = tulipType(name); uint256 total; for(uint8 k; k < _tulipToken[0].length; k++){ total = total + _tulipToken[i][k].planted[account]; } return total; } function getTotalrTLPHarvest(uint8 garden) external view returns (uint256){ uint256 total; total = redTulipRewardAmount(garden); return total; } function getTotalpTLPHarvest(uint8 garden) external view returns (uint256[2] memory){ uint256[2] memory total; if(_tulipToken[1][garden].forSeeds[msg.sender]){ total[1] = pinkTulipRewardAmount(garden); } else{ total[0] = _tulipToken[1][garden].planted[msg.sender]; } return total; } /*function getTotalsTLPHarvest(uint8 garden) external view returns (uint256){ uint256 total; total = _tulipToken[0][garden].planted[msg.sender]; return total; } */ /* ========== MUTATIVE FUNCTIONS ========== */ /* ========== internal garden ========== */ function plant(uint256 amount, string calldata name, uint8 garden, bool forSeeds) external { uint8 i = tulipType(name); //require(amount >= 1, "199");//Cannot stake less than 1 require(_tulipToken[i][garden].planted[msg.sender] == 0 && now > _tulipToken[i][garden].periodFinish[msg.sender], "201");//You must withdraw or harvest the previous crop if(i == 1 && !forSeeds){ require((amount % 100) == 0, "203");//Has to be multiple of 100 } _token[i].safeTransferFrom(msg.sender, address(this), amount.mul(_decimalConverter)); _totalSupply[i] = _totalSupply[i].add(amount); _tulipToken[i][garden].planted[msg.sender] = _tulipToken[i][garden].planted[msg.sender].add(amount); //_totalGrowing[i] = _totalGrowing[i] + amount; if(forSeeds && i != 0){ _tulipToken[i][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); _tulipToken[i][garden].forSeeds[msg.sender] = true; } else{ setTimeStamp(i, garden); } emit Staked(msg.sender, amount); } function withdraw(string memory name, uint8 garden) public { uint8 i = tulipType(name); require(!_tulipToken[i][garden].isDecomposing[msg.sender], "226");//Cannot withdraw a decomposing bed if(now > _tulipToken[i][garden].periodFinish[msg.sender] && _tulipToken[i][garden].periodFinish[msg.sender] > 0 && _tulipToken[i][garden].forSeeds[msg.sender]){ harvestHelper(name, garden, true); } /*else{ _totalGrowing[i] = _totalGrowing[i].sub(_tulipToken[i][garden].planted[msg.sender]); }*/ _token[i].safeTransfer(msg.sender, _tulipToken[i][garden].planted[msg.sender].mul(_decimalConverter)); _tulipToken[i][garden].forSeeds[msg.sender] = false; emit Withdrawn(msg.sender, _tulipToken[i][garden].planted[msg.sender]); zeroHoldings(i, garden); } function harvest(string memory name, uint8 garden) public { require(!_tulipToken[tulipType(name)][garden].isDecomposing[msg.sender], "245");//Cannot withdraw a decomposing bed harvestHelper(name, garden, false); } function harvestAllBeds(string memory name) public { uint8 i; uint256[6] memory amount; i = tulipType(name); amount = utilityBedHarvest(i); for(i = 0; i < 3; i++){ if(amount[i] > 0){ _token[i].contractMint(msg.sender, amount[i]); _totalGrown[i] = _totalGrown[i].add(amount[i].div(_decimalConverter)); emit RewardPaid(msg.sender, amount[i].div(_decimalConverter)); } if(amount[i + 3] > 0){ _token[i].contractBurn(address(this), amount[i + 3]); //_totalGrowing[i] = _totalGrowing[i].sub(amount[i + 3].div(_decimalConverter)); _totalBurnt[i] = _totalBurnt[i].add(amount[i + 3].div(_decimalConverter)); } } } function decompose(string memory name, uint8 garden, uint256 amount) public { uint8 i = tulipType(name); //require(amount >= 1, "291");//Cannot stake less than 1 require(_tulipToken[i][garden].planted[msg.sender] == 0 && (_tulipToken[i][garden].periodFinish[msg.sender] == 0 || now > _tulipToken[i][garden].periodFinish[msg.sender]), "293");//Claim your last decomposing reward! require(i > 0, "310");//Cannot decompose a seed! _token[i].safeTransferFrom(msg.sender, address(this), amount.mul(_decimalConverter)); _totalSupply[i] = _totalSupply[i].add(amount); _tulipToken[i][garden].planted[msg.sender] = amount; _tulipToken[i][garden].periodFinish[msg.sender] = now.add(1 * _timeScale); _tulipToken[i][garden].isDecomposing[msg.sender] = true; emit Decomposing(msg.sender, amount); } // test morning function claimDecompose(string memory name, uint8 garden) public { uint8 i = tulipType(name); require(_tulipToken[i][garden].isDecomposing[msg.sender], "308");//This token is not decomposing require(i > 0, "310");//Cannot decompose a seed! //redundant //require(_tulipToken[i][garden].planted[msg.sender] > 0, "311");//Cannot decompose 0 require(now > _tulipToken[i][garden].periodFinish[msg.sender], "312");//Cannot claim decomposition! uint256 amount = _tulipToken[i][garden].planted[msg.sender].mul(_decimalConverter); uint256 subAmount; uint8 scalingCoef; // Checks if token is pink (i = 1) or reds if(i == 1){ subAmount = (amount * 4).div(5); scalingCoef = 1; } else{ subAmount = (amount * 9).div(10); scalingCoef = 100; } // Burns 80% or 90% + (50% * leftovers (this is gone forever from ecosystem)) _token[i].contractBurn(address(this), subAmount + (amount - subAmount).div(2)); _totalDecomposed[i - 1] = _totalDecomposed[i - 1].add(amount.div(_decimalConverter)); // Mints the new amount of seeds to owners account _token[0].contractMint(msg.sender, subAmount.mul(scalingCoef)); _totalGrown[0] = _totalGrown[0].add(amount.div(_decimalConverter).mul(scalingCoef)); _token[i].safeTransfer(_benefitiaryAddress, (amount - subAmount).div(2)); _tulipToken[i][garden].planted[msg.sender] = 0; _totalSupply[i] = _totalSupply[i].sub(amount.div(_decimalConverter)); _tulipToken[i][garden].isDecomposing[msg.sender] = false; emit ClaimedDecomposing(msg.sender, subAmount); } /* ========== RESTRICTED FUNCTIONS ========== */ /* ========== internal functions ========== */ function addTokenOwner(address _tokenAddress, address _newOwner) external onlyOwner { TulipToken tempToken = TulipToken(_tokenAddress); tempToken.addOwner(_newOwner); } function renounceTokenOwner(address _tokenAddress) external onlyOwner { TulipToken tempToken = TulipToken(_tokenAddress); tempToken.renounceOwner(); } function changeOwner(address _newOwner) external onlyOwner { transferOwnership(_newOwner); } function changeBenefitiary(address _newOwner) external onlyOwner { _benefitiaryAddress = _newOwner; } /* ========== HELPER FUNCTIONS ========== */ function tulipType(string memory name) internal pure returns (uint8) { if (keccak256(abi.encodePacked(name)) == keccak256(abi.encodePacked("sTLP"))) { return 0; } if (keccak256(abi.encodePacked(name)) == keccak256(abi.encodePacked("pTLP"))) { return 1; } if (keccak256(abi.encodePacked(name)) == keccak256(abi.encodePacked("rTLP"))) { return 2; } else { return 99; } } function setTimeStamp(uint8 i, uint8 garden) internal{ if (i == 0) { setRewardDurationSeeds(garden); } if (i == 1) { _tulipToken[1][garden].periodFinish[msg.sender] = now.add(30 * _timeScale); } if (i == 2) { _tulipToken[2][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); } } function zeroHoldings(uint8 i, uint8 garden) internal{ _totalSupply[i] = _totalSupply[i] - _tulipToken[i][garden].planted[msg.sender]; _tulipToken[i][garden].planted[msg.sender] = 0; _tulipToken[i][garden].periodFinish[msg.sender] = 0; } function operationBurnMint(uint8 token, uint8 garden, uint256 amount) internal{ _token[token].contractBurn(address(this), _tulipToken[token][garden].planted[msg.sender].mul(_decimalConverter)); _totalBurnt[token] = _totalBurnt[token].add(_tulipToken[token][garden].planted[msg.sender]); //_totalGrowing[token] = _totalGrowing[token].sub(_tulipToken[token][garden].planted[msg.sender]); _token[token + 1].contractMint(msg.sender, amount.mul(_decimalConverter)); _totalGrown[token + 1] = _totalGrown[token + 1].add(amount); } function utilityBedHarvest(uint8 token) internal returns(uint256[6] memory){ uint256[6] memory amount; for(uint8 k; k < _tulipToken[0].length; k++){ if(!_tulipToken[token][k].isDecomposing[msg.sender]) { if (_tulipToken[token][k].planted[msg.sender] > 0 && now > _tulipToken[token][k].periodFinish[msg.sender]){ /* rTLP harvest condition */ if (token == 2) { amount[0] = amount[0] + redTulipRewardAmount(k); _tulipToken[token][k].periodFinish[msg.sender] = now.add(7 * _timeScale); } else { /* pTLP harvest condition */ if(token == 1){ if(_tulipToken[token][k].forSeeds[msg.sender]){ amount[0] = amount[0] + pinkTulipRewardAmount(k); _tulipToken[token][k].periodFinish[msg.sender] = now.add(7 * _timeScale); } else{ amount[token + 1] = amount[token + 1] + _tulipToken[token][k].planted[msg.sender].mul(_decimalConverter).div(100); amount[token + 3] = amount[token + 3] + _tulipToken[token][k].planted[msg.sender].mul(_decimalConverter); zeroHoldings(token, k); } } /* sTLP harvest condition */ else{ amount[token + 1] = amount[token + 1] + _tulipToken[token][k].planted[msg.sender].mul(_decimalConverter); amount[token + 3] = amount[token + 3] + _tulipToken[token][k].planted[msg.sender].mul(_decimalConverter); zeroHoldings(token, k); } } } } } return(amount); } function harvestHelper(string memory name, uint8 garden, bool withdrawing) internal { uint8 i = tulipType(name); if(!withdrawing){ require(_tulipToken[i][garden].planted[msg.sender] > 0, "464"); //Cannot harvest 0 require(now > _tulipToken[i][garden].periodFinish[msg.sender], "465");//Cannot harvest until bloomed! } uint256 tempAmount; /* rTLP harvest condition */ if (i == 2) { tempAmount = redTulipRewardAmount(garden); _token[0].contractMint(msg.sender, tempAmount); _tulipToken[i][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); _totalGrown[0] = _totalGrown[0].add(tempAmount.div(_decimalConverter)); } else { /* pTLP harvest condition */ if(i == 1){ if(_tulipToken[i][garden].forSeeds[msg.sender]){ tempAmount = pinkTulipRewardAmount(garden); _token[0].contractMint(msg.sender, tempAmount); _tulipToken[i][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); _totalGrown[0] = _totalGrown[0].add(tempAmount.div(_decimalConverter)); } else{ tempAmount = _tulipToken[i][garden].planted[msg.sender].div(100); operationBurnMint(i, garden, tempAmount); zeroHoldings(i, garden); } } /* sTLP harvest condition */ else{ tempAmount = _tulipToken[i][garden].planted[msg.sender]; operationBurnMint(i, garden, tempAmount); zeroHoldings(i, garden); } } //_totalGrowing[i] = _totalGrowing[i].sub(_tulipToken[i][garden].planted[msg.sender]); emit RewardPaid(msg.sender, tempAmount); } /* ========== REAL FUNCTIONS ========== */ function setRewardDurationSeeds(uint8 garden) internal returns (bool) { uint256 timeSinceEpoch = ((now - _epochBlockStart) / 60 / 60 / 24 / 30) + 1; if (timeSinceEpoch >= 7) { _tulipToken[0][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); return true; } else { _tulipToken[0][garden].periodFinish[msg.sender] = now.add( timeSinceEpoch.mul(1 * _timeScale) ); return true; } } function redTulipRewardAmount(uint8 garden) internal view returns (uint256) { uint256 timeSinceEpoch = (now - _tulipToken[2][garden].periodFinish[msg.sender].sub(7 * _timeScale)).div(60).div(60).div(24); //uint256 timeSinceEpoch = (now - _tulipToken[2][garden].periodFinish[msg.sender].sub(7 * _timeScale)); uint256 amountWeeks = timeSinceEpoch.div(7); uint256 value; for (uint256 i = amountWeeks; i != 0; i--) { uint256 tokens = 10; value = value.add(tokens.mul(_decimalConverter)); } return value * _tulipToken[2][garden].planted[msg.sender]; } /***************************ONLY WHEN forSeeds is TRUE*****************************8*/ function pinkTulipRewardAmount(uint8 garden) internal view returns (uint256) { uint256 timeSinceEpoch = (now - _tulipToken[1][garden].periodFinish[msg.sender].sub(7 * _timeScale)).div(60).div(60).div(24); //uint256 timeSinceEpoch = (now - _tulipToken[1][garden].periodFinish[msg.sender].sub(7 * _timeScale)); uint256 amountWeeks = timeSinceEpoch.div(7); uint256 value; for (uint256 i = amountWeeks; i != 0; i--) { uint256 tokens = 10; value = value.add(tokens.mul(_decimalConverter).div(500)); } return value * _tulipToken[1][garden].planted[msg.sender]; } /* ========== EVENTS ========== */ event Staked(address indexed user, uint256 amount); //add timestamps event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event Decomposing(address indexed user, uint256 amount); event ClaimedDecomposing(address indexed user, uint256 reward); }
totalGardenSupply
function totalGardenSupply(string calldata name) external view returns (uint256) { uint8 i = tulipType(name); return _totalSupply[i] ; }
/* ========== internal ========== */
Comment
v0.5.16+commit.9c3226ce
MIT
bzzr://3d4f4967b66dbf4f029b44a5b8fd6f0310cc8965cc7b2664cde35fa8aa468deb
{ "func_code_index": [ 1465, 1619 ] }
7,676
GardenContractV2
contracts/GardenContractV2.sol
0x1d6efde41748bc14ec13202f2fcf68a726a21c50
Solidity
GardenContractV2
contract GardenContractV2 is Ownable { using SafeMath for uint256; using SafeERC20 for TulipToken; using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ address internal _benefitiaryAddress = 0x68c1A22aD90f168aa19F800bFB115fB4D52F4AD9; //Founder Address uint256 internal _epochBlockStart = 1600610400; uint256 internal _timeScale = (1 days); //uint256 internal _timeScale = (1 seconds); //uint8 private _pinkTulipDivider = 100; uint256 private _decimalConverter = 10**9; //uint256[3] internal _totalGrowing; uint256[3] internal _totalGrown; /* REMEMBER THE DIFFERENCE */ uint256[3] internal _totalBurnt; uint256[2] internal _totalDecomposed; TulipToken[3] private _token; uint256[3] private _totalSupply; struct tulipToken{ mapping(address => bool) forSeeds; mapping(address => uint256) planted; mapping(address => uint256) periodFinish; //combine with decomposing mapping(address => bool) isDecomposing; } tulipToken[10][3] private _tulipToken; /* ========== CONSTRUCTOR ========== */ constructor(address _seedToken, address _basicTulipToken, address _advTulipToken) public Ownable() { _token[0] = TulipToken(_seedToken); _token[1] = TulipToken(_basicTulipToken); _token[2] = TulipToken(_advTulipToken); } /* ========== VIEWS ========== */ /* ========== internal ========== */ function totalGardenSupply(string calldata name) external view returns (uint256) { uint8 i = tulipType(name); return _totalSupply[i] ; } function totalBedSupply(string calldata name, uint8 garden) external view returns (uint256, bool, bool) { uint8 i = tulipType(name); return (_tulipToken[i][garden].planted[msg.sender], _tulipToken[i][garden].isDecomposing[msg.sender], _tulipToken[i][garden].forSeeds[msg.sender]); } /*function totalTLPGrowing(string calldata name) external view returns (uint256) { uint8 i = tulipType(name); return _totalGrowing[i]; }*/ function totalTLPDecomposed(string calldata name) external view returns (uint256) { uint8 i = tulipType(name) - 1; return _totalDecomposed[i]; } function totalTLPGrown(string calldata name) external view returns (uint256) { uint8 i = tulipType(name); return _totalGrown[i]; } function totalTLPBurnt(string calldata name) external view returns (uint256) { uint8 i = tulipType(name); return _totalBurnt[i]; } function growthRemaining(address account, string calldata name, uint8 garden) external view returns (uint256) { uint8 i = tulipType(name); //return _tulipToken[i][garden].periodFinish[account].sub(now); return _tulipToken[i][garden].periodFinish[account]; } function timeUntilNextTLP(string calldata name, uint8 garden) external view returns (uint256) { uint256 plantTimeSeconds = _tulipToken[tulipType(name)][garden].periodFinish[msg.sender].sub(7 * _timeScale); uint256 secondsDifference = now - plantTimeSeconds; uint256 weeksSincePlanting = (secondsDifference).div(60).div(60).div(24).div(7); //uint256 weeksSincePlanting = (secondsDifference).div(7); if((((secondsDifference).div(60).div(60).div(24)) % 7) > 0){ //if((((secondsDifference)) % 7) > 0){ weeksSincePlanting = weeksSincePlanting.add(1); return plantTimeSeconds.add(weeksSincePlanting.mul(7 * _timeScale)).sub(secondsDifference); } else{ return 0; } } function balanceOf(address account, string calldata name) external view returns (uint256) { uint8 i = tulipType(name); uint256 total; for(uint8 k; k < _tulipToken[0].length; k++){ total = total + _tulipToken[i][k].planted[account]; } return total; } function getTotalrTLPHarvest(uint8 garden) external view returns (uint256){ uint256 total; total = redTulipRewardAmount(garden); return total; } function getTotalpTLPHarvest(uint8 garden) external view returns (uint256[2] memory){ uint256[2] memory total; if(_tulipToken[1][garden].forSeeds[msg.sender]){ total[1] = pinkTulipRewardAmount(garden); } else{ total[0] = _tulipToken[1][garden].planted[msg.sender]; } return total; } /*function getTotalsTLPHarvest(uint8 garden) external view returns (uint256){ uint256 total; total = _tulipToken[0][garden].planted[msg.sender]; return total; } */ /* ========== MUTATIVE FUNCTIONS ========== */ /* ========== internal garden ========== */ function plant(uint256 amount, string calldata name, uint8 garden, bool forSeeds) external { uint8 i = tulipType(name); //require(amount >= 1, "199");//Cannot stake less than 1 require(_tulipToken[i][garden].planted[msg.sender] == 0 && now > _tulipToken[i][garden].periodFinish[msg.sender], "201");//You must withdraw or harvest the previous crop if(i == 1 && !forSeeds){ require((amount % 100) == 0, "203");//Has to be multiple of 100 } _token[i].safeTransferFrom(msg.sender, address(this), amount.mul(_decimalConverter)); _totalSupply[i] = _totalSupply[i].add(amount); _tulipToken[i][garden].planted[msg.sender] = _tulipToken[i][garden].planted[msg.sender].add(amount); //_totalGrowing[i] = _totalGrowing[i] + amount; if(forSeeds && i != 0){ _tulipToken[i][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); _tulipToken[i][garden].forSeeds[msg.sender] = true; } else{ setTimeStamp(i, garden); } emit Staked(msg.sender, amount); } function withdraw(string memory name, uint8 garden) public { uint8 i = tulipType(name); require(!_tulipToken[i][garden].isDecomposing[msg.sender], "226");//Cannot withdraw a decomposing bed if(now > _tulipToken[i][garden].periodFinish[msg.sender] && _tulipToken[i][garden].periodFinish[msg.sender] > 0 && _tulipToken[i][garden].forSeeds[msg.sender]){ harvestHelper(name, garden, true); } /*else{ _totalGrowing[i] = _totalGrowing[i].sub(_tulipToken[i][garden].planted[msg.sender]); }*/ _token[i].safeTransfer(msg.sender, _tulipToken[i][garden].planted[msg.sender].mul(_decimalConverter)); _tulipToken[i][garden].forSeeds[msg.sender] = false; emit Withdrawn(msg.sender, _tulipToken[i][garden].planted[msg.sender]); zeroHoldings(i, garden); } function harvest(string memory name, uint8 garden) public { require(!_tulipToken[tulipType(name)][garden].isDecomposing[msg.sender], "245");//Cannot withdraw a decomposing bed harvestHelper(name, garden, false); } function harvestAllBeds(string memory name) public { uint8 i; uint256[6] memory amount; i = tulipType(name); amount = utilityBedHarvest(i); for(i = 0; i < 3; i++){ if(amount[i] > 0){ _token[i].contractMint(msg.sender, amount[i]); _totalGrown[i] = _totalGrown[i].add(amount[i].div(_decimalConverter)); emit RewardPaid(msg.sender, amount[i].div(_decimalConverter)); } if(amount[i + 3] > 0){ _token[i].contractBurn(address(this), amount[i + 3]); //_totalGrowing[i] = _totalGrowing[i].sub(amount[i + 3].div(_decimalConverter)); _totalBurnt[i] = _totalBurnt[i].add(amount[i + 3].div(_decimalConverter)); } } } function decompose(string memory name, uint8 garden, uint256 amount) public { uint8 i = tulipType(name); //require(amount >= 1, "291");//Cannot stake less than 1 require(_tulipToken[i][garden].planted[msg.sender] == 0 && (_tulipToken[i][garden].periodFinish[msg.sender] == 0 || now > _tulipToken[i][garden].periodFinish[msg.sender]), "293");//Claim your last decomposing reward! require(i > 0, "310");//Cannot decompose a seed! _token[i].safeTransferFrom(msg.sender, address(this), amount.mul(_decimalConverter)); _totalSupply[i] = _totalSupply[i].add(amount); _tulipToken[i][garden].planted[msg.sender] = amount; _tulipToken[i][garden].periodFinish[msg.sender] = now.add(1 * _timeScale); _tulipToken[i][garden].isDecomposing[msg.sender] = true; emit Decomposing(msg.sender, amount); } // test morning function claimDecompose(string memory name, uint8 garden) public { uint8 i = tulipType(name); require(_tulipToken[i][garden].isDecomposing[msg.sender], "308");//This token is not decomposing require(i > 0, "310");//Cannot decompose a seed! //redundant //require(_tulipToken[i][garden].planted[msg.sender] > 0, "311");//Cannot decompose 0 require(now > _tulipToken[i][garden].periodFinish[msg.sender], "312");//Cannot claim decomposition! uint256 amount = _tulipToken[i][garden].planted[msg.sender].mul(_decimalConverter); uint256 subAmount; uint8 scalingCoef; // Checks if token is pink (i = 1) or reds if(i == 1){ subAmount = (amount * 4).div(5); scalingCoef = 1; } else{ subAmount = (amount * 9).div(10); scalingCoef = 100; } // Burns 80% or 90% + (50% * leftovers (this is gone forever from ecosystem)) _token[i].contractBurn(address(this), subAmount + (amount - subAmount).div(2)); _totalDecomposed[i - 1] = _totalDecomposed[i - 1].add(amount.div(_decimalConverter)); // Mints the new amount of seeds to owners account _token[0].contractMint(msg.sender, subAmount.mul(scalingCoef)); _totalGrown[0] = _totalGrown[0].add(amount.div(_decimalConverter).mul(scalingCoef)); _token[i].safeTransfer(_benefitiaryAddress, (amount - subAmount).div(2)); _tulipToken[i][garden].planted[msg.sender] = 0; _totalSupply[i] = _totalSupply[i].sub(amount.div(_decimalConverter)); _tulipToken[i][garden].isDecomposing[msg.sender] = false; emit ClaimedDecomposing(msg.sender, subAmount); } /* ========== RESTRICTED FUNCTIONS ========== */ /* ========== internal functions ========== */ function addTokenOwner(address _tokenAddress, address _newOwner) external onlyOwner { TulipToken tempToken = TulipToken(_tokenAddress); tempToken.addOwner(_newOwner); } function renounceTokenOwner(address _tokenAddress) external onlyOwner { TulipToken tempToken = TulipToken(_tokenAddress); tempToken.renounceOwner(); } function changeOwner(address _newOwner) external onlyOwner { transferOwnership(_newOwner); } function changeBenefitiary(address _newOwner) external onlyOwner { _benefitiaryAddress = _newOwner; } /* ========== HELPER FUNCTIONS ========== */ function tulipType(string memory name) internal pure returns (uint8) { if (keccak256(abi.encodePacked(name)) == keccak256(abi.encodePacked("sTLP"))) { return 0; } if (keccak256(abi.encodePacked(name)) == keccak256(abi.encodePacked("pTLP"))) { return 1; } if (keccak256(abi.encodePacked(name)) == keccak256(abi.encodePacked("rTLP"))) { return 2; } else { return 99; } } function setTimeStamp(uint8 i, uint8 garden) internal{ if (i == 0) { setRewardDurationSeeds(garden); } if (i == 1) { _tulipToken[1][garden].periodFinish[msg.sender] = now.add(30 * _timeScale); } if (i == 2) { _tulipToken[2][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); } } function zeroHoldings(uint8 i, uint8 garden) internal{ _totalSupply[i] = _totalSupply[i] - _tulipToken[i][garden].planted[msg.sender]; _tulipToken[i][garden].planted[msg.sender] = 0; _tulipToken[i][garden].periodFinish[msg.sender] = 0; } function operationBurnMint(uint8 token, uint8 garden, uint256 amount) internal{ _token[token].contractBurn(address(this), _tulipToken[token][garden].planted[msg.sender].mul(_decimalConverter)); _totalBurnt[token] = _totalBurnt[token].add(_tulipToken[token][garden].planted[msg.sender]); //_totalGrowing[token] = _totalGrowing[token].sub(_tulipToken[token][garden].planted[msg.sender]); _token[token + 1].contractMint(msg.sender, amount.mul(_decimalConverter)); _totalGrown[token + 1] = _totalGrown[token + 1].add(amount); } function utilityBedHarvest(uint8 token) internal returns(uint256[6] memory){ uint256[6] memory amount; for(uint8 k; k < _tulipToken[0].length; k++){ if(!_tulipToken[token][k].isDecomposing[msg.sender]) { if (_tulipToken[token][k].planted[msg.sender] > 0 && now > _tulipToken[token][k].periodFinish[msg.sender]){ /* rTLP harvest condition */ if (token == 2) { amount[0] = amount[0] + redTulipRewardAmount(k); _tulipToken[token][k].periodFinish[msg.sender] = now.add(7 * _timeScale); } else { /* pTLP harvest condition */ if(token == 1){ if(_tulipToken[token][k].forSeeds[msg.sender]){ amount[0] = amount[0] + pinkTulipRewardAmount(k); _tulipToken[token][k].periodFinish[msg.sender] = now.add(7 * _timeScale); } else{ amount[token + 1] = amount[token + 1] + _tulipToken[token][k].planted[msg.sender].mul(_decimalConverter).div(100); amount[token + 3] = amount[token + 3] + _tulipToken[token][k].planted[msg.sender].mul(_decimalConverter); zeroHoldings(token, k); } } /* sTLP harvest condition */ else{ amount[token + 1] = amount[token + 1] + _tulipToken[token][k].planted[msg.sender].mul(_decimalConverter); amount[token + 3] = amount[token + 3] + _tulipToken[token][k].planted[msg.sender].mul(_decimalConverter); zeroHoldings(token, k); } } } } } return(amount); } function harvestHelper(string memory name, uint8 garden, bool withdrawing) internal { uint8 i = tulipType(name); if(!withdrawing){ require(_tulipToken[i][garden].planted[msg.sender] > 0, "464"); //Cannot harvest 0 require(now > _tulipToken[i][garden].periodFinish[msg.sender], "465");//Cannot harvest until bloomed! } uint256 tempAmount; /* rTLP harvest condition */ if (i == 2) { tempAmount = redTulipRewardAmount(garden); _token[0].contractMint(msg.sender, tempAmount); _tulipToken[i][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); _totalGrown[0] = _totalGrown[0].add(tempAmount.div(_decimalConverter)); } else { /* pTLP harvest condition */ if(i == 1){ if(_tulipToken[i][garden].forSeeds[msg.sender]){ tempAmount = pinkTulipRewardAmount(garden); _token[0].contractMint(msg.sender, tempAmount); _tulipToken[i][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); _totalGrown[0] = _totalGrown[0].add(tempAmount.div(_decimalConverter)); } else{ tempAmount = _tulipToken[i][garden].planted[msg.sender].div(100); operationBurnMint(i, garden, tempAmount); zeroHoldings(i, garden); } } /* sTLP harvest condition */ else{ tempAmount = _tulipToken[i][garden].planted[msg.sender]; operationBurnMint(i, garden, tempAmount); zeroHoldings(i, garden); } } //_totalGrowing[i] = _totalGrowing[i].sub(_tulipToken[i][garden].planted[msg.sender]); emit RewardPaid(msg.sender, tempAmount); } /* ========== REAL FUNCTIONS ========== */ function setRewardDurationSeeds(uint8 garden) internal returns (bool) { uint256 timeSinceEpoch = ((now - _epochBlockStart) / 60 / 60 / 24 / 30) + 1; if (timeSinceEpoch >= 7) { _tulipToken[0][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); return true; } else { _tulipToken[0][garden].periodFinish[msg.sender] = now.add( timeSinceEpoch.mul(1 * _timeScale) ); return true; } } function redTulipRewardAmount(uint8 garden) internal view returns (uint256) { uint256 timeSinceEpoch = (now - _tulipToken[2][garden].periodFinish[msg.sender].sub(7 * _timeScale)).div(60).div(60).div(24); //uint256 timeSinceEpoch = (now - _tulipToken[2][garden].periodFinish[msg.sender].sub(7 * _timeScale)); uint256 amountWeeks = timeSinceEpoch.div(7); uint256 value; for (uint256 i = amountWeeks; i != 0; i--) { uint256 tokens = 10; value = value.add(tokens.mul(_decimalConverter)); } return value * _tulipToken[2][garden].planted[msg.sender]; } /***************************ONLY WHEN forSeeds is TRUE*****************************8*/ function pinkTulipRewardAmount(uint8 garden) internal view returns (uint256) { uint256 timeSinceEpoch = (now - _tulipToken[1][garden].periodFinish[msg.sender].sub(7 * _timeScale)).div(60).div(60).div(24); //uint256 timeSinceEpoch = (now - _tulipToken[1][garden].periodFinish[msg.sender].sub(7 * _timeScale)); uint256 amountWeeks = timeSinceEpoch.div(7); uint256 value; for (uint256 i = amountWeeks; i != 0; i--) { uint256 tokens = 10; value = value.add(tokens.mul(_decimalConverter).div(500)); } return value * _tulipToken[1][garden].planted[msg.sender]; } /* ========== EVENTS ========== */ event Staked(address indexed user, uint256 amount); //add timestamps event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event Decomposing(address indexed user, uint256 amount); event ClaimedDecomposing(address indexed user, uint256 reward); }
totalTLPDecomposed
function totalTLPDecomposed(string calldata name) external view returns (uint256) { uint8 i = tulipType(name) - 1; return _totalDecomposed[i]; }
/*function totalTLPGrowing(string calldata name) external view returns (uint256) { uint8 i = tulipType(name); return _totalGrowing[i]; }*/
Comment
v0.5.16+commit.9c3226ce
MIT
bzzr://3d4f4967b66dbf4f029b44a5b8fd6f0310cc8965cc7b2664cde35fa8aa468deb
{ "func_code_index": [ 2086, 2248 ] }
7,677
GardenContractV2
contracts/GardenContractV2.sol
0x1d6efde41748bc14ec13202f2fcf68a726a21c50
Solidity
GardenContractV2
contract GardenContractV2 is Ownable { using SafeMath for uint256; using SafeERC20 for TulipToken; using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ address internal _benefitiaryAddress = 0x68c1A22aD90f168aa19F800bFB115fB4D52F4AD9; //Founder Address uint256 internal _epochBlockStart = 1600610400; uint256 internal _timeScale = (1 days); //uint256 internal _timeScale = (1 seconds); //uint8 private _pinkTulipDivider = 100; uint256 private _decimalConverter = 10**9; //uint256[3] internal _totalGrowing; uint256[3] internal _totalGrown; /* REMEMBER THE DIFFERENCE */ uint256[3] internal _totalBurnt; uint256[2] internal _totalDecomposed; TulipToken[3] private _token; uint256[3] private _totalSupply; struct tulipToken{ mapping(address => bool) forSeeds; mapping(address => uint256) planted; mapping(address => uint256) periodFinish; //combine with decomposing mapping(address => bool) isDecomposing; } tulipToken[10][3] private _tulipToken; /* ========== CONSTRUCTOR ========== */ constructor(address _seedToken, address _basicTulipToken, address _advTulipToken) public Ownable() { _token[0] = TulipToken(_seedToken); _token[1] = TulipToken(_basicTulipToken); _token[2] = TulipToken(_advTulipToken); } /* ========== VIEWS ========== */ /* ========== internal ========== */ function totalGardenSupply(string calldata name) external view returns (uint256) { uint8 i = tulipType(name); return _totalSupply[i] ; } function totalBedSupply(string calldata name, uint8 garden) external view returns (uint256, bool, bool) { uint8 i = tulipType(name); return (_tulipToken[i][garden].planted[msg.sender], _tulipToken[i][garden].isDecomposing[msg.sender], _tulipToken[i][garden].forSeeds[msg.sender]); } /*function totalTLPGrowing(string calldata name) external view returns (uint256) { uint8 i = tulipType(name); return _totalGrowing[i]; }*/ function totalTLPDecomposed(string calldata name) external view returns (uint256) { uint8 i = tulipType(name) - 1; return _totalDecomposed[i]; } function totalTLPGrown(string calldata name) external view returns (uint256) { uint8 i = tulipType(name); return _totalGrown[i]; } function totalTLPBurnt(string calldata name) external view returns (uint256) { uint8 i = tulipType(name); return _totalBurnt[i]; } function growthRemaining(address account, string calldata name, uint8 garden) external view returns (uint256) { uint8 i = tulipType(name); //return _tulipToken[i][garden].periodFinish[account].sub(now); return _tulipToken[i][garden].periodFinish[account]; } function timeUntilNextTLP(string calldata name, uint8 garden) external view returns (uint256) { uint256 plantTimeSeconds = _tulipToken[tulipType(name)][garden].periodFinish[msg.sender].sub(7 * _timeScale); uint256 secondsDifference = now - plantTimeSeconds; uint256 weeksSincePlanting = (secondsDifference).div(60).div(60).div(24).div(7); //uint256 weeksSincePlanting = (secondsDifference).div(7); if((((secondsDifference).div(60).div(60).div(24)) % 7) > 0){ //if((((secondsDifference)) % 7) > 0){ weeksSincePlanting = weeksSincePlanting.add(1); return plantTimeSeconds.add(weeksSincePlanting.mul(7 * _timeScale)).sub(secondsDifference); } else{ return 0; } } function balanceOf(address account, string calldata name) external view returns (uint256) { uint8 i = tulipType(name); uint256 total; for(uint8 k; k < _tulipToken[0].length; k++){ total = total + _tulipToken[i][k].planted[account]; } return total; } function getTotalrTLPHarvest(uint8 garden) external view returns (uint256){ uint256 total; total = redTulipRewardAmount(garden); return total; } function getTotalpTLPHarvest(uint8 garden) external view returns (uint256[2] memory){ uint256[2] memory total; if(_tulipToken[1][garden].forSeeds[msg.sender]){ total[1] = pinkTulipRewardAmount(garden); } else{ total[0] = _tulipToken[1][garden].planted[msg.sender]; } return total; } /*function getTotalsTLPHarvest(uint8 garden) external view returns (uint256){ uint256 total; total = _tulipToken[0][garden].planted[msg.sender]; return total; } */ /* ========== MUTATIVE FUNCTIONS ========== */ /* ========== internal garden ========== */ function plant(uint256 amount, string calldata name, uint8 garden, bool forSeeds) external { uint8 i = tulipType(name); //require(amount >= 1, "199");//Cannot stake less than 1 require(_tulipToken[i][garden].planted[msg.sender] == 0 && now > _tulipToken[i][garden].periodFinish[msg.sender], "201");//You must withdraw or harvest the previous crop if(i == 1 && !forSeeds){ require((amount % 100) == 0, "203");//Has to be multiple of 100 } _token[i].safeTransferFrom(msg.sender, address(this), amount.mul(_decimalConverter)); _totalSupply[i] = _totalSupply[i].add(amount); _tulipToken[i][garden].planted[msg.sender] = _tulipToken[i][garden].planted[msg.sender].add(amount); //_totalGrowing[i] = _totalGrowing[i] + amount; if(forSeeds && i != 0){ _tulipToken[i][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); _tulipToken[i][garden].forSeeds[msg.sender] = true; } else{ setTimeStamp(i, garden); } emit Staked(msg.sender, amount); } function withdraw(string memory name, uint8 garden) public { uint8 i = tulipType(name); require(!_tulipToken[i][garden].isDecomposing[msg.sender], "226");//Cannot withdraw a decomposing bed if(now > _tulipToken[i][garden].periodFinish[msg.sender] && _tulipToken[i][garden].periodFinish[msg.sender] > 0 && _tulipToken[i][garden].forSeeds[msg.sender]){ harvestHelper(name, garden, true); } /*else{ _totalGrowing[i] = _totalGrowing[i].sub(_tulipToken[i][garden].planted[msg.sender]); }*/ _token[i].safeTransfer(msg.sender, _tulipToken[i][garden].planted[msg.sender].mul(_decimalConverter)); _tulipToken[i][garden].forSeeds[msg.sender] = false; emit Withdrawn(msg.sender, _tulipToken[i][garden].planted[msg.sender]); zeroHoldings(i, garden); } function harvest(string memory name, uint8 garden) public { require(!_tulipToken[tulipType(name)][garden].isDecomposing[msg.sender], "245");//Cannot withdraw a decomposing bed harvestHelper(name, garden, false); } function harvestAllBeds(string memory name) public { uint8 i; uint256[6] memory amount; i = tulipType(name); amount = utilityBedHarvest(i); for(i = 0; i < 3; i++){ if(amount[i] > 0){ _token[i].contractMint(msg.sender, amount[i]); _totalGrown[i] = _totalGrown[i].add(amount[i].div(_decimalConverter)); emit RewardPaid(msg.sender, amount[i].div(_decimalConverter)); } if(amount[i + 3] > 0){ _token[i].contractBurn(address(this), amount[i + 3]); //_totalGrowing[i] = _totalGrowing[i].sub(amount[i + 3].div(_decimalConverter)); _totalBurnt[i] = _totalBurnt[i].add(amount[i + 3].div(_decimalConverter)); } } } function decompose(string memory name, uint8 garden, uint256 amount) public { uint8 i = tulipType(name); //require(amount >= 1, "291");//Cannot stake less than 1 require(_tulipToken[i][garden].planted[msg.sender] == 0 && (_tulipToken[i][garden].periodFinish[msg.sender] == 0 || now > _tulipToken[i][garden].periodFinish[msg.sender]), "293");//Claim your last decomposing reward! require(i > 0, "310");//Cannot decompose a seed! _token[i].safeTransferFrom(msg.sender, address(this), amount.mul(_decimalConverter)); _totalSupply[i] = _totalSupply[i].add(amount); _tulipToken[i][garden].planted[msg.sender] = amount; _tulipToken[i][garden].periodFinish[msg.sender] = now.add(1 * _timeScale); _tulipToken[i][garden].isDecomposing[msg.sender] = true; emit Decomposing(msg.sender, amount); } // test morning function claimDecompose(string memory name, uint8 garden) public { uint8 i = tulipType(name); require(_tulipToken[i][garden].isDecomposing[msg.sender], "308");//This token is not decomposing require(i > 0, "310");//Cannot decompose a seed! //redundant //require(_tulipToken[i][garden].planted[msg.sender] > 0, "311");//Cannot decompose 0 require(now > _tulipToken[i][garden].periodFinish[msg.sender], "312");//Cannot claim decomposition! uint256 amount = _tulipToken[i][garden].planted[msg.sender].mul(_decimalConverter); uint256 subAmount; uint8 scalingCoef; // Checks if token is pink (i = 1) or reds if(i == 1){ subAmount = (amount * 4).div(5); scalingCoef = 1; } else{ subAmount = (amount * 9).div(10); scalingCoef = 100; } // Burns 80% or 90% + (50% * leftovers (this is gone forever from ecosystem)) _token[i].contractBurn(address(this), subAmount + (amount - subAmount).div(2)); _totalDecomposed[i - 1] = _totalDecomposed[i - 1].add(amount.div(_decimalConverter)); // Mints the new amount of seeds to owners account _token[0].contractMint(msg.sender, subAmount.mul(scalingCoef)); _totalGrown[0] = _totalGrown[0].add(amount.div(_decimalConverter).mul(scalingCoef)); _token[i].safeTransfer(_benefitiaryAddress, (amount - subAmount).div(2)); _tulipToken[i][garden].planted[msg.sender] = 0; _totalSupply[i] = _totalSupply[i].sub(amount.div(_decimalConverter)); _tulipToken[i][garden].isDecomposing[msg.sender] = false; emit ClaimedDecomposing(msg.sender, subAmount); } /* ========== RESTRICTED FUNCTIONS ========== */ /* ========== internal functions ========== */ function addTokenOwner(address _tokenAddress, address _newOwner) external onlyOwner { TulipToken tempToken = TulipToken(_tokenAddress); tempToken.addOwner(_newOwner); } function renounceTokenOwner(address _tokenAddress) external onlyOwner { TulipToken tempToken = TulipToken(_tokenAddress); tempToken.renounceOwner(); } function changeOwner(address _newOwner) external onlyOwner { transferOwnership(_newOwner); } function changeBenefitiary(address _newOwner) external onlyOwner { _benefitiaryAddress = _newOwner; } /* ========== HELPER FUNCTIONS ========== */ function tulipType(string memory name) internal pure returns (uint8) { if (keccak256(abi.encodePacked(name)) == keccak256(abi.encodePacked("sTLP"))) { return 0; } if (keccak256(abi.encodePacked(name)) == keccak256(abi.encodePacked("pTLP"))) { return 1; } if (keccak256(abi.encodePacked(name)) == keccak256(abi.encodePacked("rTLP"))) { return 2; } else { return 99; } } function setTimeStamp(uint8 i, uint8 garden) internal{ if (i == 0) { setRewardDurationSeeds(garden); } if (i == 1) { _tulipToken[1][garden].periodFinish[msg.sender] = now.add(30 * _timeScale); } if (i == 2) { _tulipToken[2][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); } } function zeroHoldings(uint8 i, uint8 garden) internal{ _totalSupply[i] = _totalSupply[i] - _tulipToken[i][garden].planted[msg.sender]; _tulipToken[i][garden].planted[msg.sender] = 0; _tulipToken[i][garden].periodFinish[msg.sender] = 0; } function operationBurnMint(uint8 token, uint8 garden, uint256 amount) internal{ _token[token].contractBurn(address(this), _tulipToken[token][garden].planted[msg.sender].mul(_decimalConverter)); _totalBurnt[token] = _totalBurnt[token].add(_tulipToken[token][garden].planted[msg.sender]); //_totalGrowing[token] = _totalGrowing[token].sub(_tulipToken[token][garden].planted[msg.sender]); _token[token + 1].contractMint(msg.sender, amount.mul(_decimalConverter)); _totalGrown[token + 1] = _totalGrown[token + 1].add(amount); } function utilityBedHarvest(uint8 token) internal returns(uint256[6] memory){ uint256[6] memory amount; for(uint8 k; k < _tulipToken[0].length; k++){ if(!_tulipToken[token][k].isDecomposing[msg.sender]) { if (_tulipToken[token][k].planted[msg.sender] > 0 && now > _tulipToken[token][k].periodFinish[msg.sender]){ /* rTLP harvest condition */ if (token == 2) { amount[0] = amount[0] + redTulipRewardAmount(k); _tulipToken[token][k].periodFinish[msg.sender] = now.add(7 * _timeScale); } else { /* pTLP harvest condition */ if(token == 1){ if(_tulipToken[token][k].forSeeds[msg.sender]){ amount[0] = amount[0] + pinkTulipRewardAmount(k); _tulipToken[token][k].periodFinish[msg.sender] = now.add(7 * _timeScale); } else{ amount[token + 1] = amount[token + 1] + _tulipToken[token][k].planted[msg.sender].mul(_decimalConverter).div(100); amount[token + 3] = amount[token + 3] + _tulipToken[token][k].planted[msg.sender].mul(_decimalConverter); zeroHoldings(token, k); } } /* sTLP harvest condition */ else{ amount[token + 1] = amount[token + 1] + _tulipToken[token][k].planted[msg.sender].mul(_decimalConverter); amount[token + 3] = amount[token + 3] + _tulipToken[token][k].planted[msg.sender].mul(_decimalConverter); zeroHoldings(token, k); } } } } } return(amount); } function harvestHelper(string memory name, uint8 garden, bool withdrawing) internal { uint8 i = tulipType(name); if(!withdrawing){ require(_tulipToken[i][garden].planted[msg.sender] > 0, "464"); //Cannot harvest 0 require(now > _tulipToken[i][garden].periodFinish[msg.sender], "465");//Cannot harvest until bloomed! } uint256 tempAmount; /* rTLP harvest condition */ if (i == 2) { tempAmount = redTulipRewardAmount(garden); _token[0].contractMint(msg.sender, tempAmount); _tulipToken[i][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); _totalGrown[0] = _totalGrown[0].add(tempAmount.div(_decimalConverter)); } else { /* pTLP harvest condition */ if(i == 1){ if(_tulipToken[i][garden].forSeeds[msg.sender]){ tempAmount = pinkTulipRewardAmount(garden); _token[0].contractMint(msg.sender, tempAmount); _tulipToken[i][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); _totalGrown[0] = _totalGrown[0].add(tempAmount.div(_decimalConverter)); } else{ tempAmount = _tulipToken[i][garden].planted[msg.sender].div(100); operationBurnMint(i, garden, tempAmount); zeroHoldings(i, garden); } } /* sTLP harvest condition */ else{ tempAmount = _tulipToken[i][garden].planted[msg.sender]; operationBurnMint(i, garden, tempAmount); zeroHoldings(i, garden); } } //_totalGrowing[i] = _totalGrowing[i].sub(_tulipToken[i][garden].planted[msg.sender]); emit RewardPaid(msg.sender, tempAmount); } /* ========== REAL FUNCTIONS ========== */ function setRewardDurationSeeds(uint8 garden) internal returns (bool) { uint256 timeSinceEpoch = ((now - _epochBlockStart) / 60 / 60 / 24 / 30) + 1; if (timeSinceEpoch >= 7) { _tulipToken[0][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); return true; } else { _tulipToken[0][garden].periodFinish[msg.sender] = now.add( timeSinceEpoch.mul(1 * _timeScale) ); return true; } } function redTulipRewardAmount(uint8 garden) internal view returns (uint256) { uint256 timeSinceEpoch = (now - _tulipToken[2][garden].periodFinish[msg.sender].sub(7 * _timeScale)).div(60).div(60).div(24); //uint256 timeSinceEpoch = (now - _tulipToken[2][garden].periodFinish[msg.sender].sub(7 * _timeScale)); uint256 amountWeeks = timeSinceEpoch.div(7); uint256 value; for (uint256 i = amountWeeks; i != 0; i--) { uint256 tokens = 10; value = value.add(tokens.mul(_decimalConverter)); } return value * _tulipToken[2][garden].planted[msg.sender]; } /***************************ONLY WHEN forSeeds is TRUE*****************************8*/ function pinkTulipRewardAmount(uint8 garden) internal view returns (uint256) { uint256 timeSinceEpoch = (now - _tulipToken[1][garden].periodFinish[msg.sender].sub(7 * _timeScale)).div(60).div(60).div(24); //uint256 timeSinceEpoch = (now - _tulipToken[1][garden].periodFinish[msg.sender].sub(7 * _timeScale)); uint256 amountWeeks = timeSinceEpoch.div(7); uint256 value; for (uint256 i = amountWeeks; i != 0; i--) { uint256 tokens = 10; value = value.add(tokens.mul(_decimalConverter).div(500)); } return value * _tulipToken[1][garden].planted[msg.sender]; } /* ========== EVENTS ========== */ event Staked(address indexed user, uint256 amount); //add timestamps event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event Decomposing(address indexed user, uint256 amount); event ClaimedDecomposing(address indexed user, uint256 reward); }
plant
function plant(uint256 amount, string calldata name, uint8 garden, bool forSeeds) external { uint8 i = tulipType(name); //require(amount >= 1, "199");//Cannot stake less than 1 require(_tulipToken[i][garden].planted[msg.sender] == 0 && now > _tulipToken[i][garden].periodFinish[msg.sender], "201");//You must withdraw or harvest the previous crop if(i == 1 && !forSeeds){ require((amount % 100) == 0, "203");//Has to be multiple of 100 } _token[i].safeTransferFrom(msg.sender, address(this), amount.mul(_decimalConverter)); _totalSupply[i] = _totalSupply[i].add(amount); _tulipToken[i][garden].planted[msg.sender] = _tulipToken[i][garden].planted[msg.sender].add(amount); //_totalGrowing[i] = _totalGrowing[i] + amount; if(forSeeds && i != 0){ _tulipToken[i][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); _tulipToken[i][garden].forSeeds[msg.sender] = true; } else{ setTimeStamp(i, garden); } emit Staked(msg.sender, amount); }
/* ========== internal garden ========== */
Comment
v0.5.16+commit.9c3226ce
MIT
bzzr://3d4f4967b66dbf4f029b44a5b8fd6f0310cc8965cc7b2664cde35fa8aa468deb
{ "func_code_index": [ 4705, 5768 ] }
7,678
GardenContractV2
contracts/GardenContractV2.sol
0x1d6efde41748bc14ec13202f2fcf68a726a21c50
Solidity
GardenContractV2
contract GardenContractV2 is Ownable { using SafeMath for uint256; using SafeERC20 for TulipToken; using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ address internal _benefitiaryAddress = 0x68c1A22aD90f168aa19F800bFB115fB4D52F4AD9; //Founder Address uint256 internal _epochBlockStart = 1600610400; uint256 internal _timeScale = (1 days); //uint256 internal _timeScale = (1 seconds); //uint8 private _pinkTulipDivider = 100; uint256 private _decimalConverter = 10**9; //uint256[3] internal _totalGrowing; uint256[3] internal _totalGrown; /* REMEMBER THE DIFFERENCE */ uint256[3] internal _totalBurnt; uint256[2] internal _totalDecomposed; TulipToken[3] private _token; uint256[3] private _totalSupply; struct tulipToken{ mapping(address => bool) forSeeds; mapping(address => uint256) planted; mapping(address => uint256) periodFinish; //combine with decomposing mapping(address => bool) isDecomposing; } tulipToken[10][3] private _tulipToken; /* ========== CONSTRUCTOR ========== */ constructor(address _seedToken, address _basicTulipToken, address _advTulipToken) public Ownable() { _token[0] = TulipToken(_seedToken); _token[1] = TulipToken(_basicTulipToken); _token[2] = TulipToken(_advTulipToken); } /* ========== VIEWS ========== */ /* ========== internal ========== */ function totalGardenSupply(string calldata name) external view returns (uint256) { uint8 i = tulipType(name); return _totalSupply[i] ; } function totalBedSupply(string calldata name, uint8 garden) external view returns (uint256, bool, bool) { uint8 i = tulipType(name); return (_tulipToken[i][garden].planted[msg.sender], _tulipToken[i][garden].isDecomposing[msg.sender], _tulipToken[i][garden].forSeeds[msg.sender]); } /*function totalTLPGrowing(string calldata name) external view returns (uint256) { uint8 i = tulipType(name); return _totalGrowing[i]; }*/ function totalTLPDecomposed(string calldata name) external view returns (uint256) { uint8 i = tulipType(name) - 1; return _totalDecomposed[i]; } function totalTLPGrown(string calldata name) external view returns (uint256) { uint8 i = tulipType(name); return _totalGrown[i]; } function totalTLPBurnt(string calldata name) external view returns (uint256) { uint8 i = tulipType(name); return _totalBurnt[i]; } function growthRemaining(address account, string calldata name, uint8 garden) external view returns (uint256) { uint8 i = tulipType(name); //return _tulipToken[i][garden].periodFinish[account].sub(now); return _tulipToken[i][garden].periodFinish[account]; } function timeUntilNextTLP(string calldata name, uint8 garden) external view returns (uint256) { uint256 plantTimeSeconds = _tulipToken[tulipType(name)][garden].periodFinish[msg.sender].sub(7 * _timeScale); uint256 secondsDifference = now - plantTimeSeconds; uint256 weeksSincePlanting = (secondsDifference).div(60).div(60).div(24).div(7); //uint256 weeksSincePlanting = (secondsDifference).div(7); if((((secondsDifference).div(60).div(60).div(24)) % 7) > 0){ //if((((secondsDifference)) % 7) > 0){ weeksSincePlanting = weeksSincePlanting.add(1); return plantTimeSeconds.add(weeksSincePlanting.mul(7 * _timeScale)).sub(secondsDifference); } else{ return 0; } } function balanceOf(address account, string calldata name) external view returns (uint256) { uint8 i = tulipType(name); uint256 total; for(uint8 k; k < _tulipToken[0].length; k++){ total = total + _tulipToken[i][k].planted[account]; } return total; } function getTotalrTLPHarvest(uint8 garden) external view returns (uint256){ uint256 total; total = redTulipRewardAmount(garden); return total; } function getTotalpTLPHarvest(uint8 garden) external view returns (uint256[2] memory){ uint256[2] memory total; if(_tulipToken[1][garden].forSeeds[msg.sender]){ total[1] = pinkTulipRewardAmount(garden); } else{ total[0] = _tulipToken[1][garden].planted[msg.sender]; } return total; } /*function getTotalsTLPHarvest(uint8 garden) external view returns (uint256){ uint256 total; total = _tulipToken[0][garden].planted[msg.sender]; return total; } */ /* ========== MUTATIVE FUNCTIONS ========== */ /* ========== internal garden ========== */ function plant(uint256 amount, string calldata name, uint8 garden, bool forSeeds) external { uint8 i = tulipType(name); //require(amount >= 1, "199");//Cannot stake less than 1 require(_tulipToken[i][garden].planted[msg.sender] == 0 && now > _tulipToken[i][garden].periodFinish[msg.sender], "201");//You must withdraw or harvest the previous crop if(i == 1 && !forSeeds){ require((amount % 100) == 0, "203");//Has to be multiple of 100 } _token[i].safeTransferFrom(msg.sender, address(this), amount.mul(_decimalConverter)); _totalSupply[i] = _totalSupply[i].add(amount); _tulipToken[i][garden].planted[msg.sender] = _tulipToken[i][garden].planted[msg.sender].add(amount); //_totalGrowing[i] = _totalGrowing[i] + amount; if(forSeeds && i != 0){ _tulipToken[i][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); _tulipToken[i][garden].forSeeds[msg.sender] = true; } else{ setTimeStamp(i, garden); } emit Staked(msg.sender, amount); } function withdraw(string memory name, uint8 garden) public { uint8 i = tulipType(name); require(!_tulipToken[i][garden].isDecomposing[msg.sender], "226");//Cannot withdraw a decomposing bed if(now > _tulipToken[i][garden].periodFinish[msg.sender] && _tulipToken[i][garden].periodFinish[msg.sender] > 0 && _tulipToken[i][garden].forSeeds[msg.sender]){ harvestHelper(name, garden, true); } /*else{ _totalGrowing[i] = _totalGrowing[i].sub(_tulipToken[i][garden].planted[msg.sender]); }*/ _token[i].safeTransfer(msg.sender, _tulipToken[i][garden].planted[msg.sender].mul(_decimalConverter)); _tulipToken[i][garden].forSeeds[msg.sender] = false; emit Withdrawn(msg.sender, _tulipToken[i][garden].planted[msg.sender]); zeroHoldings(i, garden); } function harvest(string memory name, uint8 garden) public { require(!_tulipToken[tulipType(name)][garden].isDecomposing[msg.sender], "245");//Cannot withdraw a decomposing bed harvestHelper(name, garden, false); } function harvestAllBeds(string memory name) public { uint8 i; uint256[6] memory amount; i = tulipType(name); amount = utilityBedHarvest(i); for(i = 0; i < 3; i++){ if(amount[i] > 0){ _token[i].contractMint(msg.sender, amount[i]); _totalGrown[i] = _totalGrown[i].add(amount[i].div(_decimalConverter)); emit RewardPaid(msg.sender, amount[i].div(_decimalConverter)); } if(amount[i + 3] > 0){ _token[i].contractBurn(address(this), amount[i + 3]); //_totalGrowing[i] = _totalGrowing[i].sub(amount[i + 3].div(_decimalConverter)); _totalBurnt[i] = _totalBurnt[i].add(amount[i + 3].div(_decimalConverter)); } } } function decompose(string memory name, uint8 garden, uint256 amount) public { uint8 i = tulipType(name); //require(amount >= 1, "291");//Cannot stake less than 1 require(_tulipToken[i][garden].planted[msg.sender] == 0 && (_tulipToken[i][garden].periodFinish[msg.sender] == 0 || now > _tulipToken[i][garden].periodFinish[msg.sender]), "293");//Claim your last decomposing reward! require(i > 0, "310");//Cannot decompose a seed! _token[i].safeTransferFrom(msg.sender, address(this), amount.mul(_decimalConverter)); _totalSupply[i] = _totalSupply[i].add(amount); _tulipToken[i][garden].planted[msg.sender] = amount; _tulipToken[i][garden].periodFinish[msg.sender] = now.add(1 * _timeScale); _tulipToken[i][garden].isDecomposing[msg.sender] = true; emit Decomposing(msg.sender, amount); } // test morning function claimDecompose(string memory name, uint8 garden) public { uint8 i = tulipType(name); require(_tulipToken[i][garden].isDecomposing[msg.sender], "308");//This token is not decomposing require(i > 0, "310");//Cannot decompose a seed! //redundant //require(_tulipToken[i][garden].planted[msg.sender] > 0, "311");//Cannot decompose 0 require(now > _tulipToken[i][garden].periodFinish[msg.sender], "312");//Cannot claim decomposition! uint256 amount = _tulipToken[i][garden].planted[msg.sender].mul(_decimalConverter); uint256 subAmount; uint8 scalingCoef; // Checks if token is pink (i = 1) or reds if(i == 1){ subAmount = (amount * 4).div(5); scalingCoef = 1; } else{ subAmount = (amount * 9).div(10); scalingCoef = 100; } // Burns 80% or 90% + (50% * leftovers (this is gone forever from ecosystem)) _token[i].contractBurn(address(this), subAmount + (amount - subAmount).div(2)); _totalDecomposed[i - 1] = _totalDecomposed[i - 1].add(amount.div(_decimalConverter)); // Mints the new amount of seeds to owners account _token[0].contractMint(msg.sender, subAmount.mul(scalingCoef)); _totalGrown[0] = _totalGrown[0].add(amount.div(_decimalConverter).mul(scalingCoef)); _token[i].safeTransfer(_benefitiaryAddress, (amount - subAmount).div(2)); _tulipToken[i][garden].planted[msg.sender] = 0; _totalSupply[i] = _totalSupply[i].sub(amount.div(_decimalConverter)); _tulipToken[i][garden].isDecomposing[msg.sender] = false; emit ClaimedDecomposing(msg.sender, subAmount); } /* ========== RESTRICTED FUNCTIONS ========== */ /* ========== internal functions ========== */ function addTokenOwner(address _tokenAddress, address _newOwner) external onlyOwner { TulipToken tempToken = TulipToken(_tokenAddress); tempToken.addOwner(_newOwner); } function renounceTokenOwner(address _tokenAddress) external onlyOwner { TulipToken tempToken = TulipToken(_tokenAddress); tempToken.renounceOwner(); } function changeOwner(address _newOwner) external onlyOwner { transferOwnership(_newOwner); } function changeBenefitiary(address _newOwner) external onlyOwner { _benefitiaryAddress = _newOwner; } /* ========== HELPER FUNCTIONS ========== */ function tulipType(string memory name) internal pure returns (uint8) { if (keccak256(abi.encodePacked(name)) == keccak256(abi.encodePacked("sTLP"))) { return 0; } if (keccak256(abi.encodePacked(name)) == keccak256(abi.encodePacked("pTLP"))) { return 1; } if (keccak256(abi.encodePacked(name)) == keccak256(abi.encodePacked("rTLP"))) { return 2; } else { return 99; } } function setTimeStamp(uint8 i, uint8 garden) internal{ if (i == 0) { setRewardDurationSeeds(garden); } if (i == 1) { _tulipToken[1][garden].periodFinish[msg.sender] = now.add(30 * _timeScale); } if (i == 2) { _tulipToken[2][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); } } function zeroHoldings(uint8 i, uint8 garden) internal{ _totalSupply[i] = _totalSupply[i] - _tulipToken[i][garden].planted[msg.sender]; _tulipToken[i][garden].planted[msg.sender] = 0; _tulipToken[i][garden].periodFinish[msg.sender] = 0; } function operationBurnMint(uint8 token, uint8 garden, uint256 amount) internal{ _token[token].contractBurn(address(this), _tulipToken[token][garden].planted[msg.sender].mul(_decimalConverter)); _totalBurnt[token] = _totalBurnt[token].add(_tulipToken[token][garden].planted[msg.sender]); //_totalGrowing[token] = _totalGrowing[token].sub(_tulipToken[token][garden].planted[msg.sender]); _token[token + 1].contractMint(msg.sender, amount.mul(_decimalConverter)); _totalGrown[token + 1] = _totalGrown[token + 1].add(amount); } function utilityBedHarvest(uint8 token) internal returns(uint256[6] memory){ uint256[6] memory amount; for(uint8 k; k < _tulipToken[0].length; k++){ if(!_tulipToken[token][k].isDecomposing[msg.sender]) { if (_tulipToken[token][k].planted[msg.sender] > 0 && now > _tulipToken[token][k].periodFinish[msg.sender]){ /* rTLP harvest condition */ if (token == 2) { amount[0] = amount[0] + redTulipRewardAmount(k); _tulipToken[token][k].periodFinish[msg.sender] = now.add(7 * _timeScale); } else { /* pTLP harvest condition */ if(token == 1){ if(_tulipToken[token][k].forSeeds[msg.sender]){ amount[0] = amount[0] + pinkTulipRewardAmount(k); _tulipToken[token][k].periodFinish[msg.sender] = now.add(7 * _timeScale); } else{ amount[token + 1] = amount[token + 1] + _tulipToken[token][k].planted[msg.sender].mul(_decimalConverter).div(100); amount[token + 3] = amount[token + 3] + _tulipToken[token][k].planted[msg.sender].mul(_decimalConverter); zeroHoldings(token, k); } } /* sTLP harvest condition */ else{ amount[token + 1] = amount[token + 1] + _tulipToken[token][k].planted[msg.sender].mul(_decimalConverter); amount[token + 3] = amount[token + 3] + _tulipToken[token][k].planted[msg.sender].mul(_decimalConverter); zeroHoldings(token, k); } } } } } return(amount); } function harvestHelper(string memory name, uint8 garden, bool withdrawing) internal { uint8 i = tulipType(name); if(!withdrawing){ require(_tulipToken[i][garden].planted[msg.sender] > 0, "464"); //Cannot harvest 0 require(now > _tulipToken[i][garden].periodFinish[msg.sender], "465");//Cannot harvest until bloomed! } uint256 tempAmount; /* rTLP harvest condition */ if (i == 2) { tempAmount = redTulipRewardAmount(garden); _token[0].contractMint(msg.sender, tempAmount); _tulipToken[i][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); _totalGrown[0] = _totalGrown[0].add(tempAmount.div(_decimalConverter)); } else { /* pTLP harvest condition */ if(i == 1){ if(_tulipToken[i][garden].forSeeds[msg.sender]){ tempAmount = pinkTulipRewardAmount(garden); _token[0].contractMint(msg.sender, tempAmount); _tulipToken[i][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); _totalGrown[0] = _totalGrown[0].add(tempAmount.div(_decimalConverter)); } else{ tempAmount = _tulipToken[i][garden].planted[msg.sender].div(100); operationBurnMint(i, garden, tempAmount); zeroHoldings(i, garden); } } /* sTLP harvest condition */ else{ tempAmount = _tulipToken[i][garden].planted[msg.sender]; operationBurnMint(i, garden, tempAmount); zeroHoldings(i, garden); } } //_totalGrowing[i] = _totalGrowing[i].sub(_tulipToken[i][garden].planted[msg.sender]); emit RewardPaid(msg.sender, tempAmount); } /* ========== REAL FUNCTIONS ========== */ function setRewardDurationSeeds(uint8 garden) internal returns (bool) { uint256 timeSinceEpoch = ((now - _epochBlockStart) / 60 / 60 / 24 / 30) + 1; if (timeSinceEpoch >= 7) { _tulipToken[0][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); return true; } else { _tulipToken[0][garden].periodFinish[msg.sender] = now.add( timeSinceEpoch.mul(1 * _timeScale) ); return true; } } function redTulipRewardAmount(uint8 garden) internal view returns (uint256) { uint256 timeSinceEpoch = (now - _tulipToken[2][garden].periodFinish[msg.sender].sub(7 * _timeScale)).div(60).div(60).div(24); //uint256 timeSinceEpoch = (now - _tulipToken[2][garden].periodFinish[msg.sender].sub(7 * _timeScale)); uint256 amountWeeks = timeSinceEpoch.div(7); uint256 value; for (uint256 i = amountWeeks; i != 0; i--) { uint256 tokens = 10; value = value.add(tokens.mul(_decimalConverter)); } return value * _tulipToken[2][garden].planted[msg.sender]; } /***************************ONLY WHEN forSeeds is TRUE*****************************8*/ function pinkTulipRewardAmount(uint8 garden) internal view returns (uint256) { uint256 timeSinceEpoch = (now - _tulipToken[1][garden].periodFinish[msg.sender].sub(7 * _timeScale)).div(60).div(60).div(24); //uint256 timeSinceEpoch = (now - _tulipToken[1][garden].periodFinish[msg.sender].sub(7 * _timeScale)); uint256 amountWeeks = timeSinceEpoch.div(7); uint256 value; for (uint256 i = amountWeeks; i != 0; i--) { uint256 tokens = 10; value = value.add(tokens.mul(_decimalConverter).div(500)); } return value * _tulipToken[1][garden].planted[msg.sender]; } /* ========== EVENTS ========== */ event Staked(address indexed user, uint256 amount); //add timestamps event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event Decomposing(address indexed user, uint256 amount); event ClaimedDecomposing(address indexed user, uint256 reward); }
claimDecompose
function claimDecompose(string memory name, uint8 garden) public { uint8 i = tulipType(name); require(_tulipToken[i][garden].isDecomposing[msg.sender], "308");//This token is not decomposing require(i > 0, "310");//Cannot decompose a seed! //redundant //require(_tulipToken[i][garden].planted[msg.sender] > 0, "311");//Cannot decompose 0 require(now > _tulipToken[i][garden].periodFinish[msg.sender], "312");//Cannot claim decomposition! uint256 amount = _tulipToken[i][garden].planted[msg.sender].mul(_decimalConverter); uint256 subAmount; uint8 scalingCoef; // Checks if token is pink (i = 1) or reds if(i == 1){ subAmount = (amount * 4).div(5); scalingCoef = 1; } else{ subAmount = (amount * 9).div(10); scalingCoef = 100; } // Burns 80% or 90% + (50% * leftovers (this is gone forever from ecosystem)) _token[i].contractBurn(address(this), subAmount + (amount - subAmount).div(2)); _totalDecomposed[i - 1] = _totalDecomposed[i - 1].add(amount.div(_decimalConverter)); // Mints the new amount of seeds to owners account _token[0].contractMint(msg.sender, subAmount.mul(scalingCoef)); _totalGrown[0] = _totalGrown[0].add(amount.div(_decimalConverter).mul(scalingCoef)); _token[i].safeTransfer(_benefitiaryAddress, (amount - subAmount).div(2)); _tulipToken[i][garden].planted[msg.sender] = 0; _totalSupply[i] = _totalSupply[i].sub(amount.div(_decimalConverter)); _tulipToken[i][garden].isDecomposing[msg.sender] = false; emit ClaimedDecomposing(msg.sender, subAmount); }
// test morning
LineComment
v0.5.16+commit.9c3226ce
MIT
bzzr://3d4f4967b66dbf4f029b44a5b8fd6f0310cc8965cc7b2664cde35fa8aa468deb
{ "func_code_index": [ 8474, 10114 ] }
7,679
GardenContractV2
contracts/GardenContractV2.sol
0x1d6efde41748bc14ec13202f2fcf68a726a21c50
Solidity
GardenContractV2
contract GardenContractV2 is Ownable { using SafeMath for uint256; using SafeERC20 for TulipToken; using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ address internal _benefitiaryAddress = 0x68c1A22aD90f168aa19F800bFB115fB4D52F4AD9; //Founder Address uint256 internal _epochBlockStart = 1600610400; uint256 internal _timeScale = (1 days); //uint256 internal _timeScale = (1 seconds); //uint8 private _pinkTulipDivider = 100; uint256 private _decimalConverter = 10**9; //uint256[3] internal _totalGrowing; uint256[3] internal _totalGrown; /* REMEMBER THE DIFFERENCE */ uint256[3] internal _totalBurnt; uint256[2] internal _totalDecomposed; TulipToken[3] private _token; uint256[3] private _totalSupply; struct tulipToken{ mapping(address => bool) forSeeds; mapping(address => uint256) planted; mapping(address => uint256) periodFinish; //combine with decomposing mapping(address => bool) isDecomposing; } tulipToken[10][3] private _tulipToken; /* ========== CONSTRUCTOR ========== */ constructor(address _seedToken, address _basicTulipToken, address _advTulipToken) public Ownable() { _token[0] = TulipToken(_seedToken); _token[1] = TulipToken(_basicTulipToken); _token[2] = TulipToken(_advTulipToken); } /* ========== VIEWS ========== */ /* ========== internal ========== */ function totalGardenSupply(string calldata name) external view returns (uint256) { uint8 i = tulipType(name); return _totalSupply[i] ; } function totalBedSupply(string calldata name, uint8 garden) external view returns (uint256, bool, bool) { uint8 i = tulipType(name); return (_tulipToken[i][garden].planted[msg.sender], _tulipToken[i][garden].isDecomposing[msg.sender], _tulipToken[i][garden].forSeeds[msg.sender]); } /*function totalTLPGrowing(string calldata name) external view returns (uint256) { uint8 i = tulipType(name); return _totalGrowing[i]; }*/ function totalTLPDecomposed(string calldata name) external view returns (uint256) { uint8 i = tulipType(name) - 1; return _totalDecomposed[i]; } function totalTLPGrown(string calldata name) external view returns (uint256) { uint8 i = tulipType(name); return _totalGrown[i]; } function totalTLPBurnt(string calldata name) external view returns (uint256) { uint8 i = tulipType(name); return _totalBurnt[i]; } function growthRemaining(address account, string calldata name, uint8 garden) external view returns (uint256) { uint8 i = tulipType(name); //return _tulipToken[i][garden].periodFinish[account].sub(now); return _tulipToken[i][garden].periodFinish[account]; } function timeUntilNextTLP(string calldata name, uint8 garden) external view returns (uint256) { uint256 plantTimeSeconds = _tulipToken[tulipType(name)][garden].periodFinish[msg.sender].sub(7 * _timeScale); uint256 secondsDifference = now - plantTimeSeconds; uint256 weeksSincePlanting = (secondsDifference).div(60).div(60).div(24).div(7); //uint256 weeksSincePlanting = (secondsDifference).div(7); if((((secondsDifference).div(60).div(60).div(24)) % 7) > 0){ //if((((secondsDifference)) % 7) > 0){ weeksSincePlanting = weeksSincePlanting.add(1); return plantTimeSeconds.add(weeksSincePlanting.mul(7 * _timeScale)).sub(secondsDifference); } else{ return 0; } } function balanceOf(address account, string calldata name) external view returns (uint256) { uint8 i = tulipType(name); uint256 total; for(uint8 k; k < _tulipToken[0].length; k++){ total = total + _tulipToken[i][k].planted[account]; } return total; } function getTotalrTLPHarvest(uint8 garden) external view returns (uint256){ uint256 total; total = redTulipRewardAmount(garden); return total; } function getTotalpTLPHarvest(uint8 garden) external view returns (uint256[2] memory){ uint256[2] memory total; if(_tulipToken[1][garden].forSeeds[msg.sender]){ total[1] = pinkTulipRewardAmount(garden); } else{ total[0] = _tulipToken[1][garden].planted[msg.sender]; } return total; } /*function getTotalsTLPHarvest(uint8 garden) external view returns (uint256){ uint256 total; total = _tulipToken[0][garden].planted[msg.sender]; return total; } */ /* ========== MUTATIVE FUNCTIONS ========== */ /* ========== internal garden ========== */ function plant(uint256 amount, string calldata name, uint8 garden, bool forSeeds) external { uint8 i = tulipType(name); //require(amount >= 1, "199");//Cannot stake less than 1 require(_tulipToken[i][garden].planted[msg.sender] == 0 && now > _tulipToken[i][garden].periodFinish[msg.sender], "201");//You must withdraw or harvest the previous crop if(i == 1 && !forSeeds){ require((amount % 100) == 0, "203");//Has to be multiple of 100 } _token[i].safeTransferFrom(msg.sender, address(this), amount.mul(_decimalConverter)); _totalSupply[i] = _totalSupply[i].add(amount); _tulipToken[i][garden].planted[msg.sender] = _tulipToken[i][garden].planted[msg.sender].add(amount); //_totalGrowing[i] = _totalGrowing[i] + amount; if(forSeeds && i != 0){ _tulipToken[i][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); _tulipToken[i][garden].forSeeds[msg.sender] = true; } else{ setTimeStamp(i, garden); } emit Staked(msg.sender, amount); } function withdraw(string memory name, uint8 garden) public { uint8 i = tulipType(name); require(!_tulipToken[i][garden].isDecomposing[msg.sender], "226");//Cannot withdraw a decomposing bed if(now > _tulipToken[i][garden].periodFinish[msg.sender] && _tulipToken[i][garden].periodFinish[msg.sender] > 0 && _tulipToken[i][garden].forSeeds[msg.sender]){ harvestHelper(name, garden, true); } /*else{ _totalGrowing[i] = _totalGrowing[i].sub(_tulipToken[i][garden].planted[msg.sender]); }*/ _token[i].safeTransfer(msg.sender, _tulipToken[i][garden].planted[msg.sender].mul(_decimalConverter)); _tulipToken[i][garden].forSeeds[msg.sender] = false; emit Withdrawn(msg.sender, _tulipToken[i][garden].planted[msg.sender]); zeroHoldings(i, garden); } function harvest(string memory name, uint8 garden) public { require(!_tulipToken[tulipType(name)][garden].isDecomposing[msg.sender], "245");//Cannot withdraw a decomposing bed harvestHelper(name, garden, false); } function harvestAllBeds(string memory name) public { uint8 i; uint256[6] memory amount; i = tulipType(name); amount = utilityBedHarvest(i); for(i = 0; i < 3; i++){ if(amount[i] > 0){ _token[i].contractMint(msg.sender, amount[i]); _totalGrown[i] = _totalGrown[i].add(amount[i].div(_decimalConverter)); emit RewardPaid(msg.sender, amount[i].div(_decimalConverter)); } if(amount[i + 3] > 0){ _token[i].contractBurn(address(this), amount[i + 3]); //_totalGrowing[i] = _totalGrowing[i].sub(amount[i + 3].div(_decimalConverter)); _totalBurnt[i] = _totalBurnt[i].add(amount[i + 3].div(_decimalConverter)); } } } function decompose(string memory name, uint8 garden, uint256 amount) public { uint8 i = tulipType(name); //require(amount >= 1, "291");//Cannot stake less than 1 require(_tulipToken[i][garden].planted[msg.sender] == 0 && (_tulipToken[i][garden].periodFinish[msg.sender] == 0 || now > _tulipToken[i][garden].periodFinish[msg.sender]), "293");//Claim your last decomposing reward! require(i > 0, "310");//Cannot decompose a seed! _token[i].safeTransferFrom(msg.sender, address(this), amount.mul(_decimalConverter)); _totalSupply[i] = _totalSupply[i].add(amount); _tulipToken[i][garden].planted[msg.sender] = amount; _tulipToken[i][garden].periodFinish[msg.sender] = now.add(1 * _timeScale); _tulipToken[i][garden].isDecomposing[msg.sender] = true; emit Decomposing(msg.sender, amount); } // test morning function claimDecompose(string memory name, uint8 garden) public { uint8 i = tulipType(name); require(_tulipToken[i][garden].isDecomposing[msg.sender], "308");//This token is not decomposing require(i > 0, "310");//Cannot decompose a seed! //redundant //require(_tulipToken[i][garden].planted[msg.sender] > 0, "311");//Cannot decompose 0 require(now > _tulipToken[i][garden].periodFinish[msg.sender], "312");//Cannot claim decomposition! uint256 amount = _tulipToken[i][garden].planted[msg.sender].mul(_decimalConverter); uint256 subAmount; uint8 scalingCoef; // Checks if token is pink (i = 1) or reds if(i == 1){ subAmount = (amount * 4).div(5); scalingCoef = 1; } else{ subAmount = (amount * 9).div(10); scalingCoef = 100; } // Burns 80% or 90% + (50% * leftovers (this is gone forever from ecosystem)) _token[i].contractBurn(address(this), subAmount + (amount - subAmount).div(2)); _totalDecomposed[i - 1] = _totalDecomposed[i - 1].add(amount.div(_decimalConverter)); // Mints the new amount of seeds to owners account _token[0].contractMint(msg.sender, subAmount.mul(scalingCoef)); _totalGrown[0] = _totalGrown[0].add(amount.div(_decimalConverter).mul(scalingCoef)); _token[i].safeTransfer(_benefitiaryAddress, (amount - subAmount).div(2)); _tulipToken[i][garden].planted[msg.sender] = 0; _totalSupply[i] = _totalSupply[i].sub(amount.div(_decimalConverter)); _tulipToken[i][garden].isDecomposing[msg.sender] = false; emit ClaimedDecomposing(msg.sender, subAmount); } /* ========== RESTRICTED FUNCTIONS ========== */ /* ========== internal functions ========== */ function addTokenOwner(address _tokenAddress, address _newOwner) external onlyOwner { TulipToken tempToken = TulipToken(_tokenAddress); tempToken.addOwner(_newOwner); } function renounceTokenOwner(address _tokenAddress) external onlyOwner { TulipToken tempToken = TulipToken(_tokenAddress); tempToken.renounceOwner(); } function changeOwner(address _newOwner) external onlyOwner { transferOwnership(_newOwner); } function changeBenefitiary(address _newOwner) external onlyOwner { _benefitiaryAddress = _newOwner; } /* ========== HELPER FUNCTIONS ========== */ function tulipType(string memory name) internal pure returns (uint8) { if (keccak256(abi.encodePacked(name)) == keccak256(abi.encodePacked("sTLP"))) { return 0; } if (keccak256(abi.encodePacked(name)) == keccak256(abi.encodePacked("pTLP"))) { return 1; } if (keccak256(abi.encodePacked(name)) == keccak256(abi.encodePacked("rTLP"))) { return 2; } else { return 99; } } function setTimeStamp(uint8 i, uint8 garden) internal{ if (i == 0) { setRewardDurationSeeds(garden); } if (i == 1) { _tulipToken[1][garden].periodFinish[msg.sender] = now.add(30 * _timeScale); } if (i == 2) { _tulipToken[2][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); } } function zeroHoldings(uint8 i, uint8 garden) internal{ _totalSupply[i] = _totalSupply[i] - _tulipToken[i][garden].planted[msg.sender]; _tulipToken[i][garden].planted[msg.sender] = 0; _tulipToken[i][garden].periodFinish[msg.sender] = 0; } function operationBurnMint(uint8 token, uint8 garden, uint256 amount) internal{ _token[token].contractBurn(address(this), _tulipToken[token][garden].planted[msg.sender].mul(_decimalConverter)); _totalBurnt[token] = _totalBurnt[token].add(_tulipToken[token][garden].planted[msg.sender]); //_totalGrowing[token] = _totalGrowing[token].sub(_tulipToken[token][garden].planted[msg.sender]); _token[token + 1].contractMint(msg.sender, amount.mul(_decimalConverter)); _totalGrown[token + 1] = _totalGrown[token + 1].add(amount); } function utilityBedHarvest(uint8 token) internal returns(uint256[6] memory){ uint256[6] memory amount; for(uint8 k; k < _tulipToken[0].length; k++){ if(!_tulipToken[token][k].isDecomposing[msg.sender]) { if (_tulipToken[token][k].planted[msg.sender] > 0 && now > _tulipToken[token][k].periodFinish[msg.sender]){ /* rTLP harvest condition */ if (token == 2) { amount[0] = amount[0] + redTulipRewardAmount(k); _tulipToken[token][k].periodFinish[msg.sender] = now.add(7 * _timeScale); } else { /* pTLP harvest condition */ if(token == 1){ if(_tulipToken[token][k].forSeeds[msg.sender]){ amount[0] = amount[0] + pinkTulipRewardAmount(k); _tulipToken[token][k].periodFinish[msg.sender] = now.add(7 * _timeScale); } else{ amount[token + 1] = amount[token + 1] + _tulipToken[token][k].planted[msg.sender].mul(_decimalConverter).div(100); amount[token + 3] = amount[token + 3] + _tulipToken[token][k].planted[msg.sender].mul(_decimalConverter); zeroHoldings(token, k); } } /* sTLP harvest condition */ else{ amount[token + 1] = amount[token + 1] + _tulipToken[token][k].planted[msg.sender].mul(_decimalConverter); amount[token + 3] = amount[token + 3] + _tulipToken[token][k].planted[msg.sender].mul(_decimalConverter); zeroHoldings(token, k); } } } } } return(amount); } function harvestHelper(string memory name, uint8 garden, bool withdrawing) internal { uint8 i = tulipType(name); if(!withdrawing){ require(_tulipToken[i][garden].planted[msg.sender] > 0, "464"); //Cannot harvest 0 require(now > _tulipToken[i][garden].periodFinish[msg.sender], "465");//Cannot harvest until bloomed! } uint256 tempAmount; /* rTLP harvest condition */ if (i == 2) { tempAmount = redTulipRewardAmount(garden); _token[0].contractMint(msg.sender, tempAmount); _tulipToken[i][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); _totalGrown[0] = _totalGrown[0].add(tempAmount.div(_decimalConverter)); } else { /* pTLP harvest condition */ if(i == 1){ if(_tulipToken[i][garden].forSeeds[msg.sender]){ tempAmount = pinkTulipRewardAmount(garden); _token[0].contractMint(msg.sender, tempAmount); _tulipToken[i][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); _totalGrown[0] = _totalGrown[0].add(tempAmount.div(_decimalConverter)); } else{ tempAmount = _tulipToken[i][garden].planted[msg.sender].div(100); operationBurnMint(i, garden, tempAmount); zeroHoldings(i, garden); } } /* sTLP harvest condition */ else{ tempAmount = _tulipToken[i][garden].planted[msg.sender]; operationBurnMint(i, garden, tempAmount); zeroHoldings(i, garden); } } //_totalGrowing[i] = _totalGrowing[i].sub(_tulipToken[i][garden].planted[msg.sender]); emit RewardPaid(msg.sender, tempAmount); } /* ========== REAL FUNCTIONS ========== */ function setRewardDurationSeeds(uint8 garden) internal returns (bool) { uint256 timeSinceEpoch = ((now - _epochBlockStart) / 60 / 60 / 24 / 30) + 1; if (timeSinceEpoch >= 7) { _tulipToken[0][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); return true; } else { _tulipToken[0][garden].periodFinish[msg.sender] = now.add( timeSinceEpoch.mul(1 * _timeScale) ); return true; } } function redTulipRewardAmount(uint8 garden) internal view returns (uint256) { uint256 timeSinceEpoch = (now - _tulipToken[2][garden].periodFinish[msg.sender].sub(7 * _timeScale)).div(60).div(60).div(24); //uint256 timeSinceEpoch = (now - _tulipToken[2][garden].periodFinish[msg.sender].sub(7 * _timeScale)); uint256 amountWeeks = timeSinceEpoch.div(7); uint256 value; for (uint256 i = amountWeeks; i != 0; i--) { uint256 tokens = 10; value = value.add(tokens.mul(_decimalConverter)); } return value * _tulipToken[2][garden].planted[msg.sender]; } /***************************ONLY WHEN forSeeds is TRUE*****************************8*/ function pinkTulipRewardAmount(uint8 garden) internal view returns (uint256) { uint256 timeSinceEpoch = (now - _tulipToken[1][garden].periodFinish[msg.sender].sub(7 * _timeScale)).div(60).div(60).div(24); //uint256 timeSinceEpoch = (now - _tulipToken[1][garden].periodFinish[msg.sender].sub(7 * _timeScale)); uint256 amountWeeks = timeSinceEpoch.div(7); uint256 value; for (uint256 i = amountWeeks; i != 0; i--) { uint256 tokens = 10; value = value.add(tokens.mul(_decimalConverter).div(500)); } return value * _tulipToken[1][garden].planted[msg.sender]; } /* ========== EVENTS ========== */ event Staked(address indexed user, uint256 amount); //add timestamps event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event Decomposing(address indexed user, uint256 amount); event ClaimedDecomposing(address indexed user, uint256 reward); }
addTokenOwner
function addTokenOwner(address _tokenAddress, address _newOwner) external onlyOwner { TulipToken tempToken = TulipToken(_tokenAddress); tempToken.addOwner(_newOwner); }
/* ========== internal functions ========== */
Comment
v0.5.16+commit.9c3226ce
MIT
bzzr://3d4f4967b66dbf4f029b44a5b8fd6f0310cc8965cc7b2664cde35fa8aa468deb
{ "func_code_index": [ 10227, 10414 ] }
7,680
GardenContractV2
contracts/GardenContractV2.sol
0x1d6efde41748bc14ec13202f2fcf68a726a21c50
Solidity
GardenContractV2
contract GardenContractV2 is Ownable { using SafeMath for uint256; using SafeERC20 for TulipToken; using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ address internal _benefitiaryAddress = 0x68c1A22aD90f168aa19F800bFB115fB4D52F4AD9; //Founder Address uint256 internal _epochBlockStart = 1600610400; uint256 internal _timeScale = (1 days); //uint256 internal _timeScale = (1 seconds); //uint8 private _pinkTulipDivider = 100; uint256 private _decimalConverter = 10**9; //uint256[3] internal _totalGrowing; uint256[3] internal _totalGrown; /* REMEMBER THE DIFFERENCE */ uint256[3] internal _totalBurnt; uint256[2] internal _totalDecomposed; TulipToken[3] private _token; uint256[3] private _totalSupply; struct tulipToken{ mapping(address => bool) forSeeds; mapping(address => uint256) planted; mapping(address => uint256) periodFinish; //combine with decomposing mapping(address => bool) isDecomposing; } tulipToken[10][3] private _tulipToken; /* ========== CONSTRUCTOR ========== */ constructor(address _seedToken, address _basicTulipToken, address _advTulipToken) public Ownable() { _token[0] = TulipToken(_seedToken); _token[1] = TulipToken(_basicTulipToken); _token[2] = TulipToken(_advTulipToken); } /* ========== VIEWS ========== */ /* ========== internal ========== */ function totalGardenSupply(string calldata name) external view returns (uint256) { uint8 i = tulipType(name); return _totalSupply[i] ; } function totalBedSupply(string calldata name, uint8 garden) external view returns (uint256, bool, bool) { uint8 i = tulipType(name); return (_tulipToken[i][garden].planted[msg.sender], _tulipToken[i][garden].isDecomposing[msg.sender], _tulipToken[i][garden].forSeeds[msg.sender]); } /*function totalTLPGrowing(string calldata name) external view returns (uint256) { uint8 i = tulipType(name); return _totalGrowing[i]; }*/ function totalTLPDecomposed(string calldata name) external view returns (uint256) { uint8 i = tulipType(name) - 1; return _totalDecomposed[i]; } function totalTLPGrown(string calldata name) external view returns (uint256) { uint8 i = tulipType(name); return _totalGrown[i]; } function totalTLPBurnt(string calldata name) external view returns (uint256) { uint8 i = tulipType(name); return _totalBurnt[i]; } function growthRemaining(address account, string calldata name, uint8 garden) external view returns (uint256) { uint8 i = tulipType(name); //return _tulipToken[i][garden].periodFinish[account].sub(now); return _tulipToken[i][garden].periodFinish[account]; } function timeUntilNextTLP(string calldata name, uint8 garden) external view returns (uint256) { uint256 plantTimeSeconds = _tulipToken[tulipType(name)][garden].periodFinish[msg.sender].sub(7 * _timeScale); uint256 secondsDifference = now - plantTimeSeconds; uint256 weeksSincePlanting = (secondsDifference).div(60).div(60).div(24).div(7); //uint256 weeksSincePlanting = (secondsDifference).div(7); if((((secondsDifference).div(60).div(60).div(24)) % 7) > 0){ //if((((secondsDifference)) % 7) > 0){ weeksSincePlanting = weeksSincePlanting.add(1); return plantTimeSeconds.add(weeksSincePlanting.mul(7 * _timeScale)).sub(secondsDifference); } else{ return 0; } } function balanceOf(address account, string calldata name) external view returns (uint256) { uint8 i = tulipType(name); uint256 total; for(uint8 k; k < _tulipToken[0].length; k++){ total = total + _tulipToken[i][k].planted[account]; } return total; } function getTotalrTLPHarvest(uint8 garden) external view returns (uint256){ uint256 total; total = redTulipRewardAmount(garden); return total; } function getTotalpTLPHarvest(uint8 garden) external view returns (uint256[2] memory){ uint256[2] memory total; if(_tulipToken[1][garden].forSeeds[msg.sender]){ total[1] = pinkTulipRewardAmount(garden); } else{ total[0] = _tulipToken[1][garden].planted[msg.sender]; } return total; } /*function getTotalsTLPHarvest(uint8 garden) external view returns (uint256){ uint256 total; total = _tulipToken[0][garden].planted[msg.sender]; return total; } */ /* ========== MUTATIVE FUNCTIONS ========== */ /* ========== internal garden ========== */ function plant(uint256 amount, string calldata name, uint8 garden, bool forSeeds) external { uint8 i = tulipType(name); //require(amount >= 1, "199");//Cannot stake less than 1 require(_tulipToken[i][garden].planted[msg.sender] == 0 && now > _tulipToken[i][garden].periodFinish[msg.sender], "201");//You must withdraw or harvest the previous crop if(i == 1 && !forSeeds){ require((amount % 100) == 0, "203");//Has to be multiple of 100 } _token[i].safeTransferFrom(msg.sender, address(this), amount.mul(_decimalConverter)); _totalSupply[i] = _totalSupply[i].add(amount); _tulipToken[i][garden].planted[msg.sender] = _tulipToken[i][garden].planted[msg.sender].add(amount); //_totalGrowing[i] = _totalGrowing[i] + amount; if(forSeeds && i != 0){ _tulipToken[i][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); _tulipToken[i][garden].forSeeds[msg.sender] = true; } else{ setTimeStamp(i, garden); } emit Staked(msg.sender, amount); } function withdraw(string memory name, uint8 garden) public { uint8 i = tulipType(name); require(!_tulipToken[i][garden].isDecomposing[msg.sender], "226");//Cannot withdraw a decomposing bed if(now > _tulipToken[i][garden].periodFinish[msg.sender] && _tulipToken[i][garden].periodFinish[msg.sender] > 0 && _tulipToken[i][garden].forSeeds[msg.sender]){ harvestHelper(name, garden, true); } /*else{ _totalGrowing[i] = _totalGrowing[i].sub(_tulipToken[i][garden].planted[msg.sender]); }*/ _token[i].safeTransfer(msg.sender, _tulipToken[i][garden].planted[msg.sender].mul(_decimalConverter)); _tulipToken[i][garden].forSeeds[msg.sender] = false; emit Withdrawn(msg.sender, _tulipToken[i][garden].planted[msg.sender]); zeroHoldings(i, garden); } function harvest(string memory name, uint8 garden) public { require(!_tulipToken[tulipType(name)][garden].isDecomposing[msg.sender], "245");//Cannot withdraw a decomposing bed harvestHelper(name, garden, false); } function harvestAllBeds(string memory name) public { uint8 i; uint256[6] memory amount; i = tulipType(name); amount = utilityBedHarvest(i); for(i = 0; i < 3; i++){ if(amount[i] > 0){ _token[i].contractMint(msg.sender, amount[i]); _totalGrown[i] = _totalGrown[i].add(amount[i].div(_decimalConverter)); emit RewardPaid(msg.sender, amount[i].div(_decimalConverter)); } if(amount[i + 3] > 0){ _token[i].contractBurn(address(this), amount[i + 3]); //_totalGrowing[i] = _totalGrowing[i].sub(amount[i + 3].div(_decimalConverter)); _totalBurnt[i] = _totalBurnt[i].add(amount[i + 3].div(_decimalConverter)); } } } function decompose(string memory name, uint8 garden, uint256 amount) public { uint8 i = tulipType(name); //require(amount >= 1, "291");//Cannot stake less than 1 require(_tulipToken[i][garden].planted[msg.sender] == 0 && (_tulipToken[i][garden].periodFinish[msg.sender] == 0 || now > _tulipToken[i][garden].periodFinish[msg.sender]), "293");//Claim your last decomposing reward! require(i > 0, "310");//Cannot decompose a seed! _token[i].safeTransferFrom(msg.sender, address(this), amount.mul(_decimalConverter)); _totalSupply[i] = _totalSupply[i].add(amount); _tulipToken[i][garden].planted[msg.sender] = amount; _tulipToken[i][garden].periodFinish[msg.sender] = now.add(1 * _timeScale); _tulipToken[i][garden].isDecomposing[msg.sender] = true; emit Decomposing(msg.sender, amount); } // test morning function claimDecompose(string memory name, uint8 garden) public { uint8 i = tulipType(name); require(_tulipToken[i][garden].isDecomposing[msg.sender], "308");//This token is not decomposing require(i > 0, "310");//Cannot decompose a seed! //redundant //require(_tulipToken[i][garden].planted[msg.sender] > 0, "311");//Cannot decompose 0 require(now > _tulipToken[i][garden].periodFinish[msg.sender], "312");//Cannot claim decomposition! uint256 amount = _tulipToken[i][garden].planted[msg.sender].mul(_decimalConverter); uint256 subAmount; uint8 scalingCoef; // Checks if token is pink (i = 1) or reds if(i == 1){ subAmount = (amount * 4).div(5); scalingCoef = 1; } else{ subAmount = (amount * 9).div(10); scalingCoef = 100; } // Burns 80% or 90% + (50% * leftovers (this is gone forever from ecosystem)) _token[i].contractBurn(address(this), subAmount + (amount - subAmount).div(2)); _totalDecomposed[i - 1] = _totalDecomposed[i - 1].add(amount.div(_decimalConverter)); // Mints the new amount of seeds to owners account _token[0].contractMint(msg.sender, subAmount.mul(scalingCoef)); _totalGrown[0] = _totalGrown[0].add(amount.div(_decimalConverter).mul(scalingCoef)); _token[i].safeTransfer(_benefitiaryAddress, (amount - subAmount).div(2)); _tulipToken[i][garden].planted[msg.sender] = 0; _totalSupply[i] = _totalSupply[i].sub(amount.div(_decimalConverter)); _tulipToken[i][garden].isDecomposing[msg.sender] = false; emit ClaimedDecomposing(msg.sender, subAmount); } /* ========== RESTRICTED FUNCTIONS ========== */ /* ========== internal functions ========== */ function addTokenOwner(address _tokenAddress, address _newOwner) external onlyOwner { TulipToken tempToken = TulipToken(_tokenAddress); tempToken.addOwner(_newOwner); } function renounceTokenOwner(address _tokenAddress) external onlyOwner { TulipToken tempToken = TulipToken(_tokenAddress); tempToken.renounceOwner(); } function changeOwner(address _newOwner) external onlyOwner { transferOwnership(_newOwner); } function changeBenefitiary(address _newOwner) external onlyOwner { _benefitiaryAddress = _newOwner; } /* ========== HELPER FUNCTIONS ========== */ function tulipType(string memory name) internal pure returns (uint8) { if (keccak256(abi.encodePacked(name)) == keccak256(abi.encodePacked("sTLP"))) { return 0; } if (keccak256(abi.encodePacked(name)) == keccak256(abi.encodePacked("pTLP"))) { return 1; } if (keccak256(abi.encodePacked(name)) == keccak256(abi.encodePacked("rTLP"))) { return 2; } else { return 99; } } function setTimeStamp(uint8 i, uint8 garden) internal{ if (i == 0) { setRewardDurationSeeds(garden); } if (i == 1) { _tulipToken[1][garden].periodFinish[msg.sender] = now.add(30 * _timeScale); } if (i == 2) { _tulipToken[2][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); } } function zeroHoldings(uint8 i, uint8 garden) internal{ _totalSupply[i] = _totalSupply[i] - _tulipToken[i][garden].planted[msg.sender]; _tulipToken[i][garden].planted[msg.sender] = 0; _tulipToken[i][garden].periodFinish[msg.sender] = 0; } function operationBurnMint(uint8 token, uint8 garden, uint256 amount) internal{ _token[token].contractBurn(address(this), _tulipToken[token][garden].planted[msg.sender].mul(_decimalConverter)); _totalBurnt[token] = _totalBurnt[token].add(_tulipToken[token][garden].planted[msg.sender]); //_totalGrowing[token] = _totalGrowing[token].sub(_tulipToken[token][garden].planted[msg.sender]); _token[token + 1].contractMint(msg.sender, amount.mul(_decimalConverter)); _totalGrown[token + 1] = _totalGrown[token + 1].add(amount); } function utilityBedHarvest(uint8 token) internal returns(uint256[6] memory){ uint256[6] memory amount; for(uint8 k; k < _tulipToken[0].length; k++){ if(!_tulipToken[token][k].isDecomposing[msg.sender]) { if (_tulipToken[token][k].planted[msg.sender] > 0 && now > _tulipToken[token][k].periodFinish[msg.sender]){ /* rTLP harvest condition */ if (token == 2) { amount[0] = amount[0] + redTulipRewardAmount(k); _tulipToken[token][k].periodFinish[msg.sender] = now.add(7 * _timeScale); } else { /* pTLP harvest condition */ if(token == 1){ if(_tulipToken[token][k].forSeeds[msg.sender]){ amount[0] = amount[0] + pinkTulipRewardAmount(k); _tulipToken[token][k].periodFinish[msg.sender] = now.add(7 * _timeScale); } else{ amount[token + 1] = amount[token + 1] + _tulipToken[token][k].planted[msg.sender].mul(_decimalConverter).div(100); amount[token + 3] = amount[token + 3] + _tulipToken[token][k].planted[msg.sender].mul(_decimalConverter); zeroHoldings(token, k); } } /* sTLP harvest condition */ else{ amount[token + 1] = amount[token + 1] + _tulipToken[token][k].planted[msg.sender].mul(_decimalConverter); amount[token + 3] = amount[token + 3] + _tulipToken[token][k].planted[msg.sender].mul(_decimalConverter); zeroHoldings(token, k); } } } } } return(amount); } function harvestHelper(string memory name, uint8 garden, bool withdrawing) internal { uint8 i = tulipType(name); if(!withdrawing){ require(_tulipToken[i][garden].planted[msg.sender] > 0, "464"); //Cannot harvest 0 require(now > _tulipToken[i][garden].periodFinish[msg.sender], "465");//Cannot harvest until bloomed! } uint256 tempAmount; /* rTLP harvest condition */ if (i == 2) { tempAmount = redTulipRewardAmount(garden); _token[0].contractMint(msg.sender, tempAmount); _tulipToken[i][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); _totalGrown[0] = _totalGrown[0].add(tempAmount.div(_decimalConverter)); } else { /* pTLP harvest condition */ if(i == 1){ if(_tulipToken[i][garden].forSeeds[msg.sender]){ tempAmount = pinkTulipRewardAmount(garden); _token[0].contractMint(msg.sender, tempAmount); _tulipToken[i][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); _totalGrown[0] = _totalGrown[0].add(tempAmount.div(_decimalConverter)); } else{ tempAmount = _tulipToken[i][garden].planted[msg.sender].div(100); operationBurnMint(i, garden, tempAmount); zeroHoldings(i, garden); } } /* sTLP harvest condition */ else{ tempAmount = _tulipToken[i][garden].planted[msg.sender]; operationBurnMint(i, garden, tempAmount); zeroHoldings(i, garden); } } //_totalGrowing[i] = _totalGrowing[i].sub(_tulipToken[i][garden].planted[msg.sender]); emit RewardPaid(msg.sender, tempAmount); } /* ========== REAL FUNCTIONS ========== */ function setRewardDurationSeeds(uint8 garden) internal returns (bool) { uint256 timeSinceEpoch = ((now - _epochBlockStart) / 60 / 60 / 24 / 30) + 1; if (timeSinceEpoch >= 7) { _tulipToken[0][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); return true; } else { _tulipToken[0][garden].periodFinish[msg.sender] = now.add( timeSinceEpoch.mul(1 * _timeScale) ); return true; } } function redTulipRewardAmount(uint8 garden) internal view returns (uint256) { uint256 timeSinceEpoch = (now - _tulipToken[2][garden].periodFinish[msg.sender].sub(7 * _timeScale)).div(60).div(60).div(24); //uint256 timeSinceEpoch = (now - _tulipToken[2][garden].periodFinish[msg.sender].sub(7 * _timeScale)); uint256 amountWeeks = timeSinceEpoch.div(7); uint256 value; for (uint256 i = amountWeeks; i != 0; i--) { uint256 tokens = 10; value = value.add(tokens.mul(_decimalConverter)); } return value * _tulipToken[2][garden].planted[msg.sender]; } /***************************ONLY WHEN forSeeds is TRUE*****************************8*/ function pinkTulipRewardAmount(uint8 garden) internal view returns (uint256) { uint256 timeSinceEpoch = (now - _tulipToken[1][garden].periodFinish[msg.sender].sub(7 * _timeScale)).div(60).div(60).div(24); //uint256 timeSinceEpoch = (now - _tulipToken[1][garden].periodFinish[msg.sender].sub(7 * _timeScale)); uint256 amountWeeks = timeSinceEpoch.div(7); uint256 value; for (uint256 i = amountWeeks; i != 0; i--) { uint256 tokens = 10; value = value.add(tokens.mul(_decimalConverter).div(500)); } return value * _tulipToken[1][garden].planted[msg.sender]; } /* ========== EVENTS ========== */ event Staked(address indexed user, uint256 amount); //add timestamps event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event Decomposing(address indexed user, uint256 amount); event ClaimedDecomposing(address indexed user, uint256 reward); }
tulipType
function tulipType(string memory name) internal pure returns (uint8) { if (keccak256(abi.encodePacked(name)) == keccak256(abi.encodePacked("sTLP"))) { return 0; } if (keccak256(abi.encodePacked(name)) == keccak256(abi.encodePacked("pTLP"))) { return 1; } if (keccak256(abi.encodePacked(name)) == keccak256(abi.encodePacked("rTLP"))) { return 2; } else { return 99; } }
/* ========== HELPER FUNCTIONS ========== */
Comment
v0.5.16+commit.9c3226ce
MIT
bzzr://3d4f4967b66dbf4f029b44a5b8fd6f0310cc8965cc7b2664cde35fa8aa468deb
{ "func_code_index": [ 10865, 11302 ] }
7,681
GardenContractV2
contracts/GardenContractV2.sol
0x1d6efde41748bc14ec13202f2fcf68a726a21c50
Solidity
GardenContractV2
contract GardenContractV2 is Ownable { using SafeMath for uint256; using SafeERC20 for TulipToken; using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ address internal _benefitiaryAddress = 0x68c1A22aD90f168aa19F800bFB115fB4D52F4AD9; //Founder Address uint256 internal _epochBlockStart = 1600610400; uint256 internal _timeScale = (1 days); //uint256 internal _timeScale = (1 seconds); //uint8 private _pinkTulipDivider = 100; uint256 private _decimalConverter = 10**9; //uint256[3] internal _totalGrowing; uint256[3] internal _totalGrown; /* REMEMBER THE DIFFERENCE */ uint256[3] internal _totalBurnt; uint256[2] internal _totalDecomposed; TulipToken[3] private _token; uint256[3] private _totalSupply; struct tulipToken{ mapping(address => bool) forSeeds; mapping(address => uint256) planted; mapping(address => uint256) periodFinish; //combine with decomposing mapping(address => bool) isDecomposing; } tulipToken[10][3] private _tulipToken; /* ========== CONSTRUCTOR ========== */ constructor(address _seedToken, address _basicTulipToken, address _advTulipToken) public Ownable() { _token[0] = TulipToken(_seedToken); _token[1] = TulipToken(_basicTulipToken); _token[2] = TulipToken(_advTulipToken); } /* ========== VIEWS ========== */ /* ========== internal ========== */ function totalGardenSupply(string calldata name) external view returns (uint256) { uint8 i = tulipType(name); return _totalSupply[i] ; } function totalBedSupply(string calldata name, uint8 garden) external view returns (uint256, bool, bool) { uint8 i = tulipType(name); return (_tulipToken[i][garden].planted[msg.sender], _tulipToken[i][garden].isDecomposing[msg.sender], _tulipToken[i][garden].forSeeds[msg.sender]); } /*function totalTLPGrowing(string calldata name) external view returns (uint256) { uint8 i = tulipType(name); return _totalGrowing[i]; }*/ function totalTLPDecomposed(string calldata name) external view returns (uint256) { uint8 i = tulipType(name) - 1; return _totalDecomposed[i]; } function totalTLPGrown(string calldata name) external view returns (uint256) { uint8 i = tulipType(name); return _totalGrown[i]; } function totalTLPBurnt(string calldata name) external view returns (uint256) { uint8 i = tulipType(name); return _totalBurnt[i]; } function growthRemaining(address account, string calldata name, uint8 garden) external view returns (uint256) { uint8 i = tulipType(name); //return _tulipToken[i][garden].periodFinish[account].sub(now); return _tulipToken[i][garden].periodFinish[account]; } function timeUntilNextTLP(string calldata name, uint8 garden) external view returns (uint256) { uint256 plantTimeSeconds = _tulipToken[tulipType(name)][garden].periodFinish[msg.sender].sub(7 * _timeScale); uint256 secondsDifference = now - plantTimeSeconds; uint256 weeksSincePlanting = (secondsDifference).div(60).div(60).div(24).div(7); //uint256 weeksSincePlanting = (secondsDifference).div(7); if((((secondsDifference).div(60).div(60).div(24)) % 7) > 0){ //if((((secondsDifference)) % 7) > 0){ weeksSincePlanting = weeksSincePlanting.add(1); return plantTimeSeconds.add(weeksSincePlanting.mul(7 * _timeScale)).sub(secondsDifference); } else{ return 0; } } function balanceOf(address account, string calldata name) external view returns (uint256) { uint8 i = tulipType(name); uint256 total; for(uint8 k; k < _tulipToken[0].length; k++){ total = total + _tulipToken[i][k].planted[account]; } return total; } function getTotalrTLPHarvest(uint8 garden) external view returns (uint256){ uint256 total; total = redTulipRewardAmount(garden); return total; } function getTotalpTLPHarvest(uint8 garden) external view returns (uint256[2] memory){ uint256[2] memory total; if(_tulipToken[1][garden].forSeeds[msg.sender]){ total[1] = pinkTulipRewardAmount(garden); } else{ total[0] = _tulipToken[1][garden].planted[msg.sender]; } return total; } /*function getTotalsTLPHarvest(uint8 garden) external view returns (uint256){ uint256 total; total = _tulipToken[0][garden].planted[msg.sender]; return total; } */ /* ========== MUTATIVE FUNCTIONS ========== */ /* ========== internal garden ========== */ function plant(uint256 amount, string calldata name, uint8 garden, bool forSeeds) external { uint8 i = tulipType(name); //require(amount >= 1, "199");//Cannot stake less than 1 require(_tulipToken[i][garden].planted[msg.sender] == 0 && now > _tulipToken[i][garden].periodFinish[msg.sender], "201");//You must withdraw or harvest the previous crop if(i == 1 && !forSeeds){ require((amount % 100) == 0, "203");//Has to be multiple of 100 } _token[i].safeTransferFrom(msg.sender, address(this), amount.mul(_decimalConverter)); _totalSupply[i] = _totalSupply[i].add(amount); _tulipToken[i][garden].planted[msg.sender] = _tulipToken[i][garden].planted[msg.sender].add(amount); //_totalGrowing[i] = _totalGrowing[i] + amount; if(forSeeds && i != 0){ _tulipToken[i][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); _tulipToken[i][garden].forSeeds[msg.sender] = true; } else{ setTimeStamp(i, garden); } emit Staked(msg.sender, amount); } function withdraw(string memory name, uint8 garden) public { uint8 i = tulipType(name); require(!_tulipToken[i][garden].isDecomposing[msg.sender], "226");//Cannot withdraw a decomposing bed if(now > _tulipToken[i][garden].periodFinish[msg.sender] && _tulipToken[i][garden].periodFinish[msg.sender] > 0 && _tulipToken[i][garden].forSeeds[msg.sender]){ harvestHelper(name, garden, true); } /*else{ _totalGrowing[i] = _totalGrowing[i].sub(_tulipToken[i][garden].planted[msg.sender]); }*/ _token[i].safeTransfer(msg.sender, _tulipToken[i][garden].planted[msg.sender].mul(_decimalConverter)); _tulipToken[i][garden].forSeeds[msg.sender] = false; emit Withdrawn(msg.sender, _tulipToken[i][garden].planted[msg.sender]); zeroHoldings(i, garden); } function harvest(string memory name, uint8 garden) public { require(!_tulipToken[tulipType(name)][garden].isDecomposing[msg.sender], "245");//Cannot withdraw a decomposing bed harvestHelper(name, garden, false); } function harvestAllBeds(string memory name) public { uint8 i; uint256[6] memory amount; i = tulipType(name); amount = utilityBedHarvest(i); for(i = 0; i < 3; i++){ if(amount[i] > 0){ _token[i].contractMint(msg.sender, amount[i]); _totalGrown[i] = _totalGrown[i].add(amount[i].div(_decimalConverter)); emit RewardPaid(msg.sender, amount[i].div(_decimalConverter)); } if(amount[i + 3] > 0){ _token[i].contractBurn(address(this), amount[i + 3]); //_totalGrowing[i] = _totalGrowing[i].sub(amount[i + 3].div(_decimalConverter)); _totalBurnt[i] = _totalBurnt[i].add(amount[i + 3].div(_decimalConverter)); } } } function decompose(string memory name, uint8 garden, uint256 amount) public { uint8 i = tulipType(name); //require(amount >= 1, "291");//Cannot stake less than 1 require(_tulipToken[i][garden].planted[msg.sender] == 0 && (_tulipToken[i][garden].periodFinish[msg.sender] == 0 || now > _tulipToken[i][garden].periodFinish[msg.sender]), "293");//Claim your last decomposing reward! require(i > 0, "310");//Cannot decompose a seed! _token[i].safeTransferFrom(msg.sender, address(this), amount.mul(_decimalConverter)); _totalSupply[i] = _totalSupply[i].add(amount); _tulipToken[i][garden].planted[msg.sender] = amount; _tulipToken[i][garden].periodFinish[msg.sender] = now.add(1 * _timeScale); _tulipToken[i][garden].isDecomposing[msg.sender] = true; emit Decomposing(msg.sender, amount); } // test morning function claimDecompose(string memory name, uint8 garden) public { uint8 i = tulipType(name); require(_tulipToken[i][garden].isDecomposing[msg.sender], "308");//This token is not decomposing require(i > 0, "310");//Cannot decompose a seed! //redundant //require(_tulipToken[i][garden].planted[msg.sender] > 0, "311");//Cannot decompose 0 require(now > _tulipToken[i][garden].periodFinish[msg.sender], "312");//Cannot claim decomposition! uint256 amount = _tulipToken[i][garden].planted[msg.sender].mul(_decimalConverter); uint256 subAmount; uint8 scalingCoef; // Checks if token is pink (i = 1) or reds if(i == 1){ subAmount = (amount * 4).div(5); scalingCoef = 1; } else{ subAmount = (amount * 9).div(10); scalingCoef = 100; } // Burns 80% or 90% + (50% * leftovers (this is gone forever from ecosystem)) _token[i].contractBurn(address(this), subAmount + (amount - subAmount).div(2)); _totalDecomposed[i - 1] = _totalDecomposed[i - 1].add(amount.div(_decimalConverter)); // Mints the new amount of seeds to owners account _token[0].contractMint(msg.sender, subAmount.mul(scalingCoef)); _totalGrown[0] = _totalGrown[0].add(amount.div(_decimalConverter).mul(scalingCoef)); _token[i].safeTransfer(_benefitiaryAddress, (amount - subAmount).div(2)); _tulipToken[i][garden].planted[msg.sender] = 0; _totalSupply[i] = _totalSupply[i].sub(amount.div(_decimalConverter)); _tulipToken[i][garden].isDecomposing[msg.sender] = false; emit ClaimedDecomposing(msg.sender, subAmount); } /* ========== RESTRICTED FUNCTIONS ========== */ /* ========== internal functions ========== */ function addTokenOwner(address _tokenAddress, address _newOwner) external onlyOwner { TulipToken tempToken = TulipToken(_tokenAddress); tempToken.addOwner(_newOwner); } function renounceTokenOwner(address _tokenAddress) external onlyOwner { TulipToken tempToken = TulipToken(_tokenAddress); tempToken.renounceOwner(); } function changeOwner(address _newOwner) external onlyOwner { transferOwnership(_newOwner); } function changeBenefitiary(address _newOwner) external onlyOwner { _benefitiaryAddress = _newOwner; } /* ========== HELPER FUNCTIONS ========== */ function tulipType(string memory name) internal pure returns (uint8) { if (keccak256(abi.encodePacked(name)) == keccak256(abi.encodePacked("sTLP"))) { return 0; } if (keccak256(abi.encodePacked(name)) == keccak256(abi.encodePacked("pTLP"))) { return 1; } if (keccak256(abi.encodePacked(name)) == keccak256(abi.encodePacked("rTLP"))) { return 2; } else { return 99; } } function setTimeStamp(uint8 i, uint8 garden) internal{ if (i == 0) { setRewardDurationSeeds(garden); } if (i == 1) { _tulipToken[1][garden].periodFinish[msg.sender] = now.add(30 * _timeScale); } if (i == 2) { _tulipToken[2][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); } } function zeroHoldings(uint8 i, uint8 garden) internal{ _totalSupply[i] = _totalSupply[i] - _tulipToken[i][garden].planted[msg.sender]; _tulipToken[i][garden].planted[msg.sender] = 0; _tulipToken[i][garden].periodFinish[msg.sender] = 0; } function operationBurnMint(uint8 token, uint8 garden, uint256 amount) internal{ _token[token].contractBurn(address(this), _tulipToken[token][garden].planted[msg.sender].mul(_decimalConverter)); _totalBurnt[token] = _totalBurnt[token].add(_tulipToken[token][garden].planted[msg.sender]); //_totalGrowing[token] = _totalGrowing[token].sub(_tulipToken[token][garden].planted[msg.sender]); _token[token + 1].contractMint(msg.sender, amount.mul(_decimalConverter)); _totalGrown[token + 1] = _totalGrown[token + 1].add(amount); } function utilityBedHarvest(uint8 token) internal returns(uint256[6] memory){ uint256[6] memory amount; for(uint8 k; k < _tulipToken[0].length; k++){ if(!_tulipToken[token][k].isDecomposing[msg.sender]) { if (_tulipToken[token][k].planted[msg.sender] > 0 && now > _tulipToken[token][k].periodFinish[msg.sender]){ /* rTLP harvest condition */ if (token == 2) { amount[0] = amount[0] + redTulipRewardAmount(k); _tulipToken[token][k].periodFinish[msg.sender] = now.add(7 * _timeScale); } else { /* pTLP harvest condition */ if(token == 1){ if(_tulipToken[token][k].forSeeds[msg.sender]){ amount[0] = amount[0] + pinkTulipRewardAmount(k); _tulipToken[token][k].periodFinish[msg.sender] = now.add(7 * _timeScale); } else{ amount[token + 1] = amount[token + 1] + _tulipToken[token][k].planted[msg.sender].mul(_decimalConverter).div(100); amount[token + 3] = amount[token + 3] + _tulipToken[token][k].planted[msg.sender].mul(_decimalConverter); zeroHoldings(token, k); } } /* sTLP harvest condition */ else{ amount[token + 1] = amount[token + 1] + _tulipToken[token][k].planted[msg.sender].mul(_decimalConverter); amount[token + 3] = amount[token + 3] + _tulipToken[token][k].planted[msg.sender].mul(_decimalConverter); zeroHoldings(token, k); } } } } } return(amount); } function harvestHelper(string memory name, uint8 garden, bool withdrawing) internal { uint8 i = tulipType(name); if(!withdrawing){ require(_tulipToken[i][garden].planted[msg.sender] > 0, "464"); //Cannot harvest 0 require(now > _tulipToken[i][garden].periodFinish[msg.sender], "465");//Cannot harvest until bloomed! } uint256 tempAmount; /* rTLP harvest condition */ if (i == 2) { tempAmount = redTulipRewardAmount(garden); _token[0].contractMint(msg.sender, tempAmount); _tulipToken[i][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); _totalGrown[0] = _totalGrown[0].add(tempAmount.div(_decimalConverter)); } else { /* pTLP harvest condition */ if(i == 1){ if(_tulipToken[i][garden].forSeeds[msg.sender]){ tempAmount = pinkTulipRewardAmount(garden); _token[0].contractMint(msg.sender, tempAmount); _tulipToken[i][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); _totalGrown[0] = _totalGrown[0].add(tempAmount.div(_decimalConverter)); } else{ tempAmount = _tulipToken[i][garden].planted[msg.sender].div(100); operationBurnMint(i, garden, tempAmount); zeroHoldings(i, garden); } } /* sTLP harvest condition */ else{ tempAmount = _tulipToken[i][garden].planted[msg.sender]; operationBurnMint(i, garden, tempAmount); zeroHoldings(i, garden); } } //_totalGrowing[i] = _totalGrowing[i].sub(_tulipToken[i][garden].planted[msg.sender]); emit RewardPaid(msg.sender, tempAmount); } /* ========== REAL FUNCTIONS ========== */ function setRewardDurationSeeds(uint8 garden) internal returns (bool) { uint256 timeSinceEpoch = ((now - _epochBlockStart) / 60 / 60 / 24 / 30) + 1; if (timeSinceEpoch >= 7) { _tulipToken[0][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); return true; } else { _tulipToken[0][garden].periodFinish[msg.sender] = now.add( timeSinceEpoch.mul(1 * _timeScale) ); return true; } } function redTulipRewardAmount(uint8 garden) internal view returns (uint256) { uint256 timeSinceEpoch = (now - _tulipToken[2][garden].periodFinish[msg.sender].sub(7 * _timeScale)).div(60).div(60).div(24); //uint256 timeSinceEpoch = (now - _tulipToken[2][garden].periodFinish[msg.sender].sub(7 * _timeScale)); uint256 amountWeeks = timeSinceEpoch.div(7); uint256 value; for (uint256 i = amountWeeks; i != 0; i--) { uint256 tokens = 10; value = value.add(tokens.mul(_decimalConverter)); } return value * _tulipToken[2][garden].planted[msg.sender]; } /***************************ONLY WHEN forSeeds is TRUE*****************************8*/ function pinkTulipRewardAmount(uint8 garden) internal view returns (uint256) { uint256 timeSinceEpoch = (now - _tulipToken[1][garden].periodFinish[msg.sender].sub(7 * _timeScale)).div(60).div(60).div(24); //uint256 timeSinceEpoch = (now - _tulipToken[1][garden].periodFinish[msg.sender].sub(7 * _timeScale)); uint256 amountWeeks = timeSinceEpoch.div(7); uint256 value; for (uint256 i = amountWeeks; i != 0; i--) { uint256 tokens = 10; value = value.add(tokens.mul(_decimalConverter).div(500)); } return value * _tulipToken[1][garden].planted[msg.sender]; } /* ========== EVENTS ========== */ event Staked(address indexed user, uint256 amount); //add timestamps event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event Decomposing(address indexed user, uint256 amount); event ClaimedDecomposing(address indexed user, uint256 reward); }
setRewardDurationSeeds
function setRewardDurationSeeds(uint8 garden) internal returns (bool) { uint256 timeSinceEpoch = ((now - _epochBlockStart) / 60 / 60 / 24 / 30) + 1; if (timeSinceEpoch >= 7) { _tulipToken[0][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); return true; } else { _tulipToken[0][garden].periodFinish[msg.sender] = now.add( timeSinceEpoch.mul(1 * _timeScale) ); return true; } }
/* ========== REAL FUNCTIONS ========== */
Comment
v0.5.16+commit.9c3226ce
MIT
bzzr://3d4f4967b66dbf4f029b44a5b8fd6f0310cc8965cc7b2664cde35fa8aa468deb
{ "func_code_index": [ 16004, 16462 ] }
7,682
GardenContractV2
contracts/GardenContractV2.sol
0x1d6efde41748bc14ec13202f2fcf68a726a21c50
Solidity
GardenContractV2
contract GardenContractV2 is Ownable { using SafeMath for uint256; using SafeERC20 for TulipToken; using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ address internal _benefitiaryAddress = 0x68c1A22aD90f168aa19F800bFB115fB4D52F4AD9; //Founder Address uint256 internal _epochBlockStart = 1600610400; uint256 internal _timeScale = (1 days); //uint256 internal _timeScale = (1 seconds); //uint8 private _pinkTulipDivider = 100; uint256 private _decimalConverter = 10**9; //uint256[3] internal _totalGrowing; uint256[3] internal _totalGrown; /* REMEMBER THE DIFFERENCE */ uint256[3] internal _totalBurnt; uint256[2] internal _totalDecomposed; TulipToken[3] private _token; uint256[3] private _totalSupply; struct tulipToken{ mapping(address => bool) forSeeds; mapping(address => uint256) planted; mapping(address => uint256) periodFinish; //combine with decomposing mapping(address => bool) isDecomposing; } tulipToken[10][3] private _tulipToken; /* ========== CONSTRUCTOR ========== */ constructor(address _seedToken, address _basicTulipToken, address _advTulipToken) public Ownable() { _token[0] = TulipToken(_seedToken); _token[1] = TulipToken(_basicTulipToken); _token[2] = TulipToken(_advTulipToken); } /* ========== VIEWS ========== */ /* ========== internal ========== */ function totalGardenSupply(string calldata name) external view returns (uint256) { uint8 i = tulipType(name); return _totalSupply[i] ; } function totalBedSupply(string calldata name, uint8 garden) external view returns (uint256, bool, bool) { uint8 i = tulipType(name); return (_tulipToken[i][garden].planted[msg.sender], _tulipToken[i][garden].isDecomposing[msg.sender], _tulipToken[i][garden].forSeeds[msg.sender]); } /*function totalTLPGrowing(string calldata name) external view returns (uint256) { uint8 i = tulipType(name); return _totalGrowing[i]; }*/ function totalTLPDecomposed(string calldata name) external view returns (uint256) { uint8 i = tulipType(name) - 1; return _totalDecomposed[i]; } function totalTLPGrown(string calldata name) external view returns (uint256) { uint8 i = tulipType(name); return _totalGrown[i]; } function totalTLPBurnt(string calldata name) external view returns (uint256) { uint8 i = tulipType(name); return _totalBurnt[i]; } function growthRemaining(address account, string calldata name, uint8 garden) external view returns (uint256) { uint8 i = tulipType(name); //return _tulipToken[i][garden].periodFinish[account].sub(now); return _tulipToken[i][garden].periodFinish[account]; } function timeUntilNextTLP(string calldata name, uint8 garden) external view returns (uint256) { uint256 plantTimeSeconds = _tulipToken[tulipType(name)][garden].periodFinish[msg.sender].sub(7 * _timeScale); uint256 secondsDifference = now - plantTimeSeconds; uint256 weeksSincePlanting = (secondsDifference).div(60).div(60).div(24).div(7); //uint256 weeksSincePlanting = (secondsDifference).div(7); if((((secondsDifference).div(60).div(60).div(24)) % 7) > 0){ //if((((secondsDifference)) % 7) > 0){ weeksSincePlanting = weeksSincePlanting.add(1); return plantTimeSeconds.add(weeksSincePlanting.mul(7 * _timeScale)).sub(secondsDifference); } else{ return 0; } } function balanceOf(address account, string calldata name) external view returns (uint256) { uint8 i = tulipType(name); uint256 total; for(uint8 k; k < _tulipToken[0].length; k++){ total = total + _tulipToken[i][k].planted[account]; } return total; } function getTotalrTLPHarvest(uint8 garden) external view returns (uint256){ uint256 total; total = redTulipRewardAmount(garden); return total; } function getTotalpTLPHarvest(uint8 garden) external view returns (uint256[2] memory){ uint256[2] memory total; if(_tulipToken[1][garden].forSeeds[msg.sender]){ total[1] = pinkTulipRewardAmount(garden); } else{ total[0] = _tulipToken[1][garden].planted[msg.sender]; } return total; } /*function getTotalsTLPHarvest(uint8 garden) external view returns (uint256){ uint256 total; total = _tulipToken[0][garden].planted[msg.sender]; return total; } */ /* ========== MUTATIVE FUNCTIONS ========== */ /* ========== internal garden ========== */ function plant(uint256 amount, string calldata name, uint8 garden, bool forSeeds) external { uint8 i = tulipType(name); //require(amount >= 1, "199");//Cannot stake less than 1 require(_tulipToken[i][garden].planted[msg.sender] == 0 && now > _tulipToken[i][garden].periodFinish[msg.sender], "201");//You must withdraw or harvest the previous crop if(i == 1 && !forSeeds){ require((amount % 100) == 0, "203");//Has to be multiple of 100 } _token[i].safeTransferFrom(msg.sender, address(this), amount.mul(_decimalConverter)); _totalSupply[i] = _totalSupply[i].add(amount); _tulipToken[i][garden].planted[msg.sender] = _tulipToken[i][garden].planted[msg.sender].add(amount); //_totalGrowing[i] = _totalGrowing[i] + amount; if(forSeeds && i != 0){ _tulipToken[i][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); _tulipToken[i][garden].forSeeds[msg.sender] = true; } else{ setTimeStamp(i, garden); } emit Staked(msg.sender, amount); } function withdraw(string memory name, uint8 garden) public { uint8 i = tulipType(name); require(!_tulipToken[i][garden].isDecomposing[msg.sender], "226");//Cannot withdraw a decomposing bed if(now > _tulipToken[i][garden].periodFinish[msg.sender] && _tulipToken[i][garden].periodFinish[msg.sender] > 0 && _tulipToken[i][garden].forSeeds[msg.sender]){ harvestHelper(name, garden, true); } /*else{ _totalGrowing[i] = _totalGrowing[i].sub(_tulipToken[i][garden].planted[msg.sender]); }*/ _token[i].safeTransfer(msg.sender, _tulipToken[i][garden].planted[msg.sender].mul(_decimalConverter)); _tulipToken[i][garden].forSeeds[msg.sender] = false; emit Withdrawn(msg.sender, _tulipToken[i][garden].planted[msg.sender]); zeroHoldings(i, garden); } function harvest(string memory name, uint8 garden) public { require(!_tulipToken[tulipType(name)][garden].isDecomposing[msg.sender], "245");//Cannot withdraw a decomposing bed harvestHelper(name, garden, false); } function harvestAllBeds(string memory name) public { uint8 i; uint256[6] memory amount; i = tulipType(name); amount = utilityBedHarvest(i); for(i = 0; i < 3; i++){ if(amount[i] > 0){ _token[i].contractMint(msg.sender, amount[i]); _totalGrown[i] = _totalGrown[i].add(amount[i].div(_decimalConverter)); emit RewardPaid(msg.sender, amount[i].div(_decimalConverter)); } if(amount[i + 3] > 0){ _token[i].contractBurn(address(this), amount[i + 3]); //_totalGrowing[i] = _totalGrowing[i].sub(amount[i + 3].div(_decimalConverter)); _totalBurnt[i] = _totalBurnt[i].add(amount[i + 3].div(_decimalConverter)); } } } function decompose(string memory name, uint8 garden, uint256 amount) public { uint8 i = tulipType(name); //require(amount >= 1, "291");//Cannot stake less than 1 require(_tulipToken[i][garden].planted[msg.sender] == 0 && (_tulipToken[i][garden].periodFinish[msg.sender] == 0 || now > _tulipToken[i][garden].periodFinish[msg.sender]), "293");//Claim your last decomposing reward! require(i > 0, "310");//Cannot decompose a seed! _token[i].safeTransferFrom(msg.sender, address(this), amount.mul(_decimalConverter)); _totalSupply[i] = _totalSupply[i].add(amount); _tulipToken[i][garden].planted[msg.sender] = amount; _tulipToken[i][garden].periodFinish[msg.sender] = now.add(1 * _timeScale); _tulipToken[i][garden].isDecomposing[msg.sender] = true; emit Decomposing(msg.sender, amount); } // test morning function claimDecompose(string memory name, uint8 garden) public { uint8 i = tulipType(name); require(_tulipToken[i][garden].isDecomposing[msg.sender], "308");//This token is not decomposing require(i > 0, "310");//Cannot decompose a seed! //redundant //require(_tulipToken[i][garden].planted[msg.sender] > 0, "311");//Cannot decompose 0 require(now > _tulipToken[i][garden].periodFinish[msg.sender], "312");//Cannot claim decomposition! uint256 amount = _tulipToken[i][garden].planted[msg.sender].mul(_decimalConverter); uint256 subAmount; uint8 scalingCoef; // Checks if token is pink (i = 1) or reds if(i == 1){ subAmount = (amount * 4).div(5); scalingCoef = 1; } else{ subAmount = (amount * 9).div(10); scalingCoef = 100; } // Burns 80% or 90% + (50% * leftovers (this is gone forever from ecosystem)) _token[i].contractBurn(address(this), subAmount + (amount - subAmount).div(2)); _totalDecomposed[i - 1] = _totalDecomposed[i - 1].add(amount.div(_decimalConverter)); // Mints the new amount of seeds to owners account _token[0].contractMint(msg.sender, subAmount.mul(scalingCoef)); _totalGrown[0] = _totalGrown[0].add(amount.div(_decimalConverter).mul(scalingCoef)); _token[i].safeTransfer(_benefitiaryAddress, (amount - subAmount).div(2)); _tulipToken[i][garden].planted[msg.sender] = 0; _totalSupply[i] = _totalSupply[i].sub(amount.div(_decimalConverter)); _tulipToken[i][garden].isDecomposing[msg.sender] = false; emit ClaimedDecomposing(msg.sender, subAmount); } /* ========== RESTRICTED FUNCTIONS ========== */ /* ========== internal functions ========== */ function addTokenOwner(address _tokenAddress, address _newOwner) external onlyOwner { TulipToken tempToken = TulipToken(_tokenAddress); tempToken.addOwner(_newOwner); } function renounceTokenOwner(address _tokenAddress) external onlyOwner { TulipToken tempToken = TulipToken(_tokenAddress); tempToken.renounceOwner(); } function changeOwner(address _newOwner) external onlyOwner { transferOwnership(_newOwner); } function changeBenefitiary(address _newOwner) external onlyOwner { _benefitiaryAddress = _newOwner; } /* ========== HELPER FUNCTIONS ========== */ function tulipType(string memory name) internal pure returns (uint8) { if (keccak256(abi.encodePacked(name)) == keccak256(abi.encodePacked("sTLP"))) { return 0; } if (keccak256(abi.encodePacked(name)) == keccak256(abi.encodePacked("pTLP"))) { return 1; } if (keccak256(abi.encodePacked(name)) == keccak256(abi.encodePacked("rTLP"))) { return 2; } else { return 99; } } function setTimeStamp(uint8 i, uint8 garden) internal{ if (i == 0) { setRewardDurationSeeds(garden); } if (i == 1) { _tulipToken[1][garden].periodFinish[msg.sender] = now.add(30 * _timeScale); } if (i == 2) { _tulipToken[2][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); } } function zeroHoldings(uint8 i, uint8 garden) internal{ _totalSupply[i] = _totalSupply[i] - _tulipToken[i][garden].planted[msg.sender]; _tulipToken[i][garden].planted[msg.sender] = 0; _tulipToken[i][garden].periodFinish[msg.sender] = 0; } function operationBurnMint(uint8 token, uint8 garden, uint256 amount) internal{ _token[token].contractBurn(address(this), _tulipToken[token][garden].planted[msg.sender].mul(_decimalConverter)); _totalBurnt[token] = _totalBurnt[token].add(_tulipToken[token][garden].planted[msg.sender]); //_totalGrowing[token] = _totalGrowing[token].sub(_tulipToken[token][garden].planted[msg.sender]); _token[token + 1].contractMint(msg.sender, amount.mul(_decimalConverter)); _totalGrown[token + 1] = _totalGrown[token + 1].add(amount); } function utilityBedHarvest(uint8 token) internal returns(uint256[6] memory){ uint256[6] memory amount; for(uint8 k; k < _tulipToken[0].length; k++){ if(!_tulipToken[token][k].isDecomposing[msg.sender]) { if (_tulipToken[token][k].planted[msg.sender] > 0 && now > _tulipToken[token][k].periodFinish[msg.sender]){ /* rTLP harvest condition */ if (token == 2) { amount[0] = amount[0] + redTulipRewardAmount(k); _tulipToken[token][k].periodFinish[msg.sender] = now.add(7 * _timeScale); } else { /* pTLP harvest condition */ if(token == 1){ if(_tulipToken[token][k].forSeeds[msg.sender]){ amount[0] = amount[0] + pinkTulipRewardAmount(k); _tulipToken[token][k].periodFinish[msg.sender] = now.add(7 * _timeScale); } else{ amount[token + 1] = amount[token + 1] + _tulipToken[token][k].planted[msg.sender].mul(_decimalConverter).div(100); amount[token + 3] = amount[token + 3] + _tulipToken[token][k].planted[msg.sender].mul(_decimalConverter); zeroHoldings(token, k); } } /* sTLP harvest condition */ else{ amount[token + 1] = amount[token + 1] + _tulipToken[token][k].planted[msg.sender].mul(_decimalConverter); amount[token + 3] = amount[token + 3] + _tulipToken[token][k].planted[msg.sender].mul(_decimalConverter); zeroHoldings(token, k); } } } } } return(amount); } function harvestHelper(string memory name, uint8 garden, bool withdrawing) internal { uint8 i = tulipType(name); if(!withdrawing){ require(_tulipToken[i][garden].planted[msg.sender] > 0, "464"); //Cannot harvest 0 require(now > _tulipToken[i][garden].periodFinish[msg.sender], "465");//Cannot harvest until bloomed! } uint256 tempAmount; /* rTLP harvest condition */ if (i == 2) { tempAmount = redTulipRewardAmount(garden); _token[0].contractMint(msg.sender, tempAmount); _tulipToken[i][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); _totalGrown[0] = _totalGrown[0].add(tempAmount.div(_decimalConverter)); } else { /* pTLP harvest condition */ if(i == 1){ if(_tulipToken[i][garden].forSeeds[msg.sender]){ tempAmount = pinkTulipRewardAmount(garden); _token[0].contractMint(msg.sender, tempAmount); _tulipToken[i][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); _totalGrown[0] = _totalGrown[0].add(tempAmount.div(_decimalConverter)); } else{ tempAmount = _tulipToken[i][garden].planted[msg.sender].div(100); operationBurnMint(i, garden, tempAmount); zeroHoldings(i, garden); } } /* sTLP harvest condition */ else{ tempAmount = _tulipToken[i][garden].planted[msg.sender]; operationBurnMint(i, garden, tempAmount); zeroHoldings(i, garden); } } //_totalGrowing[i] = _totalGrowing[i].sub(_tulipToken[i][garden].planted[msg.sender]); emit RewardPaid(msg.sender, tempAmount); } /* ========== REAL FUNCTIONS ========== */ function setRewardDurationSeeds(uint8 garden) internal returns (bool) { uint256 timeSinceEpoch = ((now - _epochBlockStart) / 60 / 60 / 24 / 30) + 1; if (timeSinceEpoch >= 7) { _tulipToken[0][garden].periodFinish[msg.sender] = now.add(7 * _timeScale); return true; } else { _tulipToken[0][garden].periodFinish[msg.sender] = now.add( timeSinceEpoch.mul(1 * _timeScale) ); return true; } } function redTulipRewardAmount(uint8 garden) internal view returns (uint256) { uint256 timeSinceEpoch = (now - _tulipToken[2][garden].periodFinish[msg.sender].sub(7 * _timeScale)).div(60).div(60).div(24); //uint256 timeSinceEpoch = (now - _tulipToken[2][garden].periodFinish[msg.sender].sub(7 * _timeScale)); uint256 amountWeeks = timeSinceEpoch.div(7); uint256 value; for (uint256 i = amountWeeks; i != 0; i--) { uint256 tokens = 10; value = value.add(tokens.mul(_decimalConverter)); } return value * _tulipToken[2][garden].planted[msg.sender]; } /***************************ONLY WHEN forSeeds is TRUE*****************************8*/ function pinkTulipRewardAmount(uint8 garden) internal view returns (uint256) { uint256 timeSinceEpoch = (now - _tulipToken[1][garden].periodFinish[msg.sender].sub(7 * _timeScale)).div(60).div(60).div(24); //uint256 timeSinceEpoch = (now - _tulipToken[1][garden].periodFinish[msg.sender].sub(7 * _timeScale)); uint256 amountWeeks = timeSinceEpoch.div(7); uint256 value; for (uint256 i = amountWeeks; i != 0; i--) { uint256 tokens = 10; value = value.add(tokens.mul(_decimalConverter).div(500)); } return value * _tulipToken[1][garden].planted[msg.sender]; } /* ========== EVENTS ========== */ event Staked(address indexed user, uint256 amount); //add timestamps event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event Decomposing(address indexed user, uint256 amount); event ClaimedDecomposing(address indexed user, uint256 reward); }
pinkTulipRewardAmount
function pinkTulipRewardAmount(uint8 garden) internal view returns (uint256) { uint256 timeSinceEpoch = (now - _tulipToken[1][garden].periodFinish[msg.sender].sub(7 * _timeScale)).div(60).div(60).div(24); //uint256 timeSinceEpoch = (now - _tulipToken[1][garden].periodFinish[msg.sender].sub(7 * _timeScale)); uint256 amountWeeks = timeSinceEpoch.div(7); uint256 value; for (uint256 i = amountWeeks; i != 0; i--) { uint256 tokens = 10; value = value.add(tokens.mul(_decimalConverter).div(500)); } return value * _tulipToken[1][garden].planted[msg.sender]; }
/***************************ONLY WHEN forSeeds is TRUE*****************************8*/
NatSpecMultiLine
v0.5.16+commit.9c3226ce
MIT
bzzr://3d4f4967b66dbf4f029b44a5b8fd6f0310cc8965cc7b2664cde35fa8aa468deb
{ "func_code_index": [ 17169, 17790 ] }
7,683
VTO
VTO.sol
0x02b66106c712ae79715f62be30a787cdfbcd79b2
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } }
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-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; }
/** * @dev Multiplies two unsigned integers, reverts on overflow. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://b9179b633af1618d26883bc5623b55668f46bcbbd49aa5f18ea67376d9c5bced
{ "func_code_index": [ 104, 542 ] }
7,684
VTO
VTO.sol
0x02b66106c712ae79715f62be30a787cdfbcd79b2
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } }
div
function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; }
/** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://b9179b633af1618d26883bc5623b55668f46bcbbd49aa5f18ea67376d9c5bced
{ "func_code_index": [ 670, 978 ] }
7,685
VTO
VTO.sol
0x02b66106c712ae79715f62be30a787cdfbcd79b2
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } }
sub
function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; }
/** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://b9179b633af1618d26883bc5623b55668f46bcbbd49aa5f18ea67376d9c5bced
{ "func_code_index": [ 1109, 1264 ] }
7,686
VTO
VTO.sol
0x02b66106c712ae79715f62be30a787cdfbcd79b2
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } }
add
function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; }
/** * @dev Adds two unsigned integers, reverts on overflow. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://b9179b633af1618d26883bc5623b55668f46bcbbd49aa5f18ea67376d9c5bced
{ "func_code_index": [ 1345, 1500 ] }
7,687
VTO
VTO.sol
0x02b66106c712ae79715f62be30a787cdfbcd79b2
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } }
mod
function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; }
/** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://b9179b633af1618d26883bc5623b55668f46bcbbd49aa5f18ea67376d9c5bced
{ "func_code_index": [ 1653, 1782 ] }
7,688
VTO
VTO.sol
0x02b66106c712ae79715f62be30a787cdfbcd79b2
Solidity
Roles
library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } }
add
function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; }
/** * @dev give an account access to this role */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://b9179b633af1618d26883bc5623b55668f46bcbbd49aa5f18ea67376d9c5bced
{ "func_code_index": [ 155, 346 ] }
7,689
VTO
VTO.sol
0x02b66106c712ae79715f62be30a787cdfbcd79b2
Solidity
Roles
library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } }
remove
function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; }
/** * @dev remove an account's access to this role */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://b9179b633af1618d26883bc5623b55668f46bcbbd49aa5f18ea67376d9c5bced
{ "func_code_index": [ 420, 614 ] }
7,690
VTO
VTO.sol
0x02b66106c712ae79715f62be30a787cdfbcd79b2
Solidity
Roles
library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } }
has
function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; }
/** * @dev check if an account has this role * @return bool */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://b9179b633af1618d26883bc5623b55668f46bcbbd49aa5f18ea67376d9c5bced
{ "func_code_index": [ 703, 873 ] }
7,691
VTO
VTO.sol
0x02b66106c712ae79715f62be30a787cdfbcd79b2
Solidity
Pausable
contract Pausable is PauserRole { event Paused(address account); event Unpaused(address account); bool private _paused; constructor () internal { _paused = false; } /** * @return true if the contract is paused, false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } }
paused
function paused() public view returns (bool) { return _paused; }
/** * @return true if the contract is paused, false otherwise. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://b9179b633af1618d26883bc5623b55668f46bcbbd49aa5f18ea67376d9c5bced
{ "func_code_index": [ 289, 372 ] }
7,692
VTO
VTO.sol
0x02b66106c712ae79715f62be30a787cdfbcd79b2
Solidity
Pausable
contract Pausable is PauserRole { event Paused(address account); event Unpaused(address account); bool private _paused; constructor () internal { _paused = false; } /** * @return true if the contract is paused, false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } }
pause
function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); }
/** * @dev called by the owner to pause, triggers stopped state */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://b9179b633af1618d26883bc5623b55668f46bcbbd49aa5f18ea67376d9c5bced
{ "func_code_index": [ 825, 946 ] }
7,693
VTO
VTO.sol
0x02b66106c712ae79715f62be30a787cdfbcd79b2
Solidity
Pausable
contract Pausable is PauserRole { event Paused(address account); event Unpaused(address account); bool private _paused; constructor () internal { _paused = false; } /** * @return true if the contract is paused, false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } }
unpause
function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); }
/** * @dev called by the owner to unpause, returns to normal state */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://b9179b633af1618d26883bc5623b55668f46bcbbd49aa5f18ea67376d9c5bced
{ "func_code_index": [ 1036, 1159 ] }
7,694
VTO
VTO.sol
0x02b66106c712ae79715f62be30a787cdfbcd79b2
Solidity
ERC20
contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev 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 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) { _transfer(msg.sender, 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) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @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) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); 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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); } }
totalSupply
function totalSupply() public view returns (uint256) { return _totalSupply; }
/** * @dev Total number of tokens in existence */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://b9179b633af1618d26883bc5623b55668f46bcbbd49aa5f18ea67376d9c5bced
{ "func_code_index": [ 297, 393 ] }
7,695
VTO
VTO.sol
0x02b66106c712ae79715f62be30a787cdfbcd79b2
Solidity
ERC20
contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev 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 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) { _transfer(msg.sender, 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) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @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) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); 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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); } }
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 balance of. * @return An uint256 representing the amount owned by the passed address. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://b9179b633af1618d26883bc5623b55668f46bcbbd49aa5f18ea67376d9c5bced
{ "func_code_index": [ 604, 715 ] }
7,696
VTO
VTO.sol
0x02b66106c712ae79715f62be30a787cdfbcd79b2
Solidity
ERC20
contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev 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 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) { _transfer(msg.sender, 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) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @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) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); 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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); } }
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.5.17+commit.d19bba13
None
bzzr://b9179b633af1618d26883bc5623b55668f46bcbbd49aa5f18ea67376d9c5bced
{ "func_code_index": [ 1049, 1185 ] }
7,697
VTO
VTO.sol
0x02b66106c712ae79715f62be30a787cdfbcd79b2
Solidity
ERC20
contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev 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 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) { _transfer(msg.sender, 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) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @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) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); 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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); } }
transfer
function transfer(address to, uint256 value) public returns (bool) { _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.5.17+commit.d19bba13
None
bzzr://b9179b633af1618d26883bc5623b55668f46bcbbd49aa5f18ea67376d9c5bced
{ "func_code_index": [ 1351, 1496 ] }
7,698
VTO
VTO.sol
0x02b66106c712ae79715f62be30a787cdfbcd79b2
Solidity
ERC20
contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev 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 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) { _transfer(msg.sender, 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) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @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) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); 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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); } }
approve
function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _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.5.17+commit.d19bba13
None
bzzr://b9179b633af1618d26883bc5623b55668f46bcbbd49aa5f18ea67376d9c5bced
{ "func_code_index": [ 2138, 2387 ] }
7,699
VTO
VTO.sol
0x02b66106c712ae79715f62be30a787cdfbcd79b2
Solidity
ERC20
contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev 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 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) { _transfer(msg.sender, 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) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @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) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); 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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); } }
transferFrom
function transferFrom(address from, address to, uint256 value) public returns (bool) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); return true; }
/** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @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.5.17+commit.d19bba13
None
bzzr://b9179b633af1618d26883bc5623b55668f46bcbbd49aa5f18ea67376d9c5bced
{ "func_code_index": [ 2855, 3159 ] }
7,700
VTO
VTO.sol
0x02b66106c712ae79715f62be30a787cdfbcd79b2
Solidity
ERC20
contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev 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 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) { _transfer(msg.sender, 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) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @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) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); 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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); } }
increaseAllowance
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://b9179b633af1618d26883bc5623b55668f46bcbbd49aa5f18ea67376d9c5bced
{ "func_code_index": [ 3669, 3997 ] }
7,701
VTO
VTO.sol
0x02b66106c712ae79715f62be30a787cdfbcd79b2
Solidity
ERC20
contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev 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 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) { _transfer(msg.sender, 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) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @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) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); 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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); } }
decreaseAllowance
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://b9179b633af1618d26883bc5623b55668f46bcbbd49aa5f18ea67376d9c5bced
{ "func_code_index": [ 4512, 4850 ] }
7,702
VTO
VTO.sol
0x02b66106c712ae79715f62be30a787cdfbcd79b2
Solidity
ERC20
contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev 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 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) { _transfer(msg.sender, 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) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @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) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); 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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); } }
_transfer
function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); }
/** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://b9179b633af1618d26883bc5623b55668f46bcbbd49aa5f18ea67376d9c5bced
{ "func_code_index": [ 5067, 5334 ] }
7,703
VTO
VTO.sol
0x02b66106c712ae79715f62be30a787cdfbcd79b2
Solidity
ERC20
contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev 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 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) { _transfer(msg.sender, 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) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @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) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); 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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); } }
_mint
function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); }
/** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://b9179b633af1618d26883bc5623b55668f46bcbbd49aa5f18ea67376d9c5bced
{ "func_code_index": [ 5681, 5955 ] }
7,704
VTO
VTO.sol
0x02b66106c712ae79715f62be30a787cdfbcd79b2
Solidity
ERC20
contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev 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 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) { _transfer(msg.sender, 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) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @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) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); 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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); } }
_burn
function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); }
/** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://b9179b633af1618d26883bc5623b55668f46bcbbd49aa5f18ea67376d9c5bced
{ "func_code_index": [ 6184, 6458 ] }
7,705
VTO
VTO.sol
0x02b66106c712ae79715f62be30a787cdfbcd79b2
Solidity
ERC20
contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev 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 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) { _transfer(msg.sender, 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) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @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) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); 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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); } }
_burnFrom
function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); }
/** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://b9179b633af1618d26883bc5623b55668f46bcbbd49aa5f18ea67376d9c5bced
{ "func_code_index": [ 6852, 7116 ] }
7,706