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
UniV3LiquidityAMO_V2
contracts/Misc_AMOs/UniV3LiquidityAMO_V2.sol
0xc91bb4b0696e3b48c0c501b4ce8e7244fc363a79
Solidity
UniV3LiquidityAMO_V2
contract UniV3LiquidityAMO_V2 is Owned { using SafeMath for uint256; using SafeERC20 for ERC20; /* ========== STATE VARIABLES ========== */ // Core FRAXStablecoin private FRAX; FRAXShares private FXS; IFraxAMOMinter private amo_minter; ERC20 private giveback_collateral; address public giveback_collateral_address; uint256 public missing_decimals_giveback_collat; address public timelock_address; address public custodian_address; // Uniswap v3 IUniswapV3Factory public univ3_factory; INonfungiblePositionManager public univ3_positions; ISwapRouter public univ3_router; // Price constants uint256 private constant PRICE_PRECISION = 1e6; // Wildcat AMO // Details about the AMO's uniswap positions struct Position { uint256 token_id; address collateral_address; uint128 liquidity; // the liquidity of the position int24 tickLower; // the tick range of the position int24 tickUpper; uint24 fee_tier; } // Array of all Uni v3 NFT positions held by the AMO Position[] public positions_array; // List of all collaterals address[] public collateral_addresses; mapping(address => bool) public allowed_collaterals; // Mapping is also used for faster verification mapping(address => OracleLike) public oracles; // Mapping of oracles (if oracle == address(0) the collateral is assumed to be pegged to 1usd) // Map token_id to Position mapping(uint256 => Position) public positions_mapping; /* ========== CONSTRUCTOR ========== */ constructor( address _creator_address, address _giveback_collateral_address, address _amo_minter_address ) Owned(_creator_address) { FRAX = FRAXStablecoin(0x853d955aCEf822Db058eb8505911ED77F175b99e); FXS = FRAXShares(0x3432B6A60D23Ca0dFCa7761B7ab56459D9C964D0); giveback_collateral_address = _giveback_collateral_address; giveback_collateral = ERC20(_giveback_collateral_address); missing_decimals_giveback_collat = uint(18).sub(giveback_collateral.decimals()); collateral_addresses.push(_giveback_collateral_address); allowed_collaterals[_giveback_collateral_address] = true; univ3_factory = IUniswapV3Factory(0x1F98431c8aD98523631AE4a59f267346ea31F984); univ3_positions = INonfungiblePositionManager(0xC36442b4a4522E871399CD717aBDD847Ab11FE88); univ3_router = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564); // Initialize the minter amo_minter = IFraxAMOMinter(_amo_minter_address); // Get the custodian and timelock addresses from the minter custodian_address = amo_minter.custodian_address(); timelock_address = amo_minter.timelock_address(); } /* ========== MODIFIERS ========== */ modifier onlyByOwnGov() { require(msg.sender == timelock_address || msg.sender == owner, "Not owner or timelock"); _; } modifier onlyByOwnGovCust() { require(msg.sender == timelock_address || msg.sender == owner || msg.sender == custodian_address, "Not owner, tlck, or custd"); _; } modifier onlyByMinter() { require(msg.sender == address(amo_minter), "Not minter"); _; } /* ========== VIEWS ========== */ function showAllocations() public view returns (uint256[4] memory allocations) { // All numbers given are in FRAX unless otherwise stated // Unallocated FRAX allocations[0] = FRAX.balanceOf(address(this)); // Unallocated Collateral Dollar Value (E18) allocations[1] = freeColDolVal(); // Sum of Uni v3 Positions liquidity, if it was all in FRAX allocations[2] = TotalLiquidityFrax(); // Total Value allocations[3] = allocations[0].add(allocations[1]).add(allocations[2]); } // E18 Collateral dollar value function freeColDolVal() public view returns (uint256) { uint256 value_tally_e18 = 0; for (uint i = 0; i < collateral_addresses.length; i++){ ERC20 thisCollateral = ERC20(collateral_addresses[i]); uint256 missing_decs = uint256(18).sub(thisCollateral.decimals()); uint256 col_bal_e18 = thisCollateral.balanceOf(address(this)).mul(10 ** missing_decs); uint256 col_usd_value_e18 = collatDolarValue(oracles[collateral_addresses[i]], col_bal_e18); value_tally_e18 = value_tally_e18.add(col_usd_value_e18); } return value_tally_e18; } // Convert collateral to dolar. If no oracle assumes pegged to 1USD. Both oracle, balance and return are E18 function collatDolarValue(OracleLike oracle, uint256 balance) public view returns (uint256) { if (address(oracle) == address(0)) return balance; return balance.mul(oracle.read()).div(1 ether); } // Needed for the Frax contract to function function collatDollarBalance() public view returns (uint256) { // Get the allocations uint256[4] memory allocations = showAllocations(); // Get the collateral and FRAX portions uint256 collat_portion = allocations[1]; uint256 frax_portion = (allocations[0]).add(allocations[2]); // Assumes worst case scenario if FRAX slips out of range. // Otherwise, it would only be half that is multiplied by the CR frax_portion = frax_portion.mul(FRAX.global_collateral_ratio()).div(PRICE_PRECISION); return (collat_portion).add(frax_portion); } function dollarBalances() public view returns (uint256 frax_val_e18, uint256 collat_val_e18) { frax_val_e18 = showAllocations()[3]; collat_val_e18 = collatDollarBalance(); } function TotalLiquidityFrax() public view returns (uint256) { uint256 frax_tally = 0; Position memory thisPosition; for (uint256 i = 0; i < positions_array.length; i++) { thisPosition = positions_array[i]; uint128 this_liq = thisPosition.liquidity; if (this_liq > 0){ uint160 sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(thisPosition.tickLower); uint160 sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(thisPosition.tickUpper); if (thisPosition.collateral_address > 0x853d955aCEf822Db058eb8505911ED77F175b99e){ // if address(FRAX) < collateral_address, then FRAX is token0 frax_tally = frax_tally.add(LiquidityAmounts.getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, this_liq)); } else { frax_tally = frax_tally.add(LiquidityAmounts.getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, this_liq)); } } } // Return the sum of all the positions' balances of FRAX, if the price fell off the range towards that side return frax_tally; } // Returns this contract's liquidity in a specific [FRAX]-[collateral] uni v3 pool function liquidityInPool(address _collateral_address, int24 _tickLower, int24 _tickUpper, uint24 _fee) public view returns (uint128) { IUniswapV3Pool get_pool = IUniswapV3Pool(univ3_factory.getPool(address(FRAX), _collateral_address, _fee)); // goes into the pool's positions mapping, and grabs this address's liquidity (uint128 liquidity, , , , ) = get_pool.positions(keccak256(abi.encodePacked(address(this), _tickLower, _tickUpper))); return liquidity; } // Backwards compatibility function mintedBalance() public view returns (int256) { return amo_minter.frax_mint_balances(address(this)); } // Backwards compatibility function collateralBalance() public view returns (int256) { return amo_minter.collat_borrowed_balances(address(this)); } // Only counts non-withdrawn positions function numPositions() public view returns (uint256) { return positions_array.length; } function allCollateralAddresses() external view returns (address[] memory) { return collateral_addresses; } /* ========== RESTRICTED FUNCTIONS, BUT CUSTODIAN CAN CALL ========== */ // Iterate through all positions and collect fees accumulated function collectFees() external onlyByOwnGovCust { for (uint i = 0; i < positions_array.length; i++){ Position memory current_position = positions_array[i]; INonfungiblePositionManager.CollectParams memory collect_params = INonfungiblePositionManager.CollectParams( current_position.token_id, custodian_address, type(uint128).max, type(uint128).max ); // Send to custodian address univ3_positions.collect(collect_params); } } /* ---------------------------------------------------- */ /* ---------------------- Uni v3 ---------------------- */ /* ---------------------------------------------------- */ function approveTarget(address _target, address _token, uint256 _amount, bool use_safe_approve) public onlyByOwnGov { if (use_safe_approve) { // safeApprove needed for USDT and others for the first approval // You need to approve 0 every time beforehand for USDT: it resets TransferHelper.safeApprove(_token, _target, _amount); } else { ERC20(_token).approve(_target, _amount); } } // IUniswapV3Pool public current_uni_pool; // only used for mint callback; is set and accessed during execution of addLiquidity() function addLiquidity(address _tokenA, address _tokenB, int24 _tickLower, int24 _tickUpper, uint24 _fee, uint256 _amount0Desired, uint256 _amount1Desired, uint256 _amount0Min, uint256 _amount1Min) public onlyByOwnGov { // Make sure the collateral is allowed require(allowed_collaterals[_tokenA] || _tokenA == address(FRAX), "TokenA not allowed"); require(allowed_collaterals[_tokenB] || _tokenB == address(FRAX), "TokenB not allowed"); ERC20(_tokenA).transferFrom(msg.sender, address(this), _amount0Desired); ERC20(_tokenB).transferFrom(msg.sender, address(this), _amount1Desired); ERC20(_tokenA).approve(address(univ3_positions), _amount0Desired); ERC20(_tokenB).approve(address(univ3_positions), _amount1Desired); INonfungiblePositionManager.MintParams memory params = INonfungiblePositionManager.MintParams( _tokenA, _tokenB, _fee, _tickLower, _tickUpper, _amount0Desired, _amount1Desired, _amount0Min, _amount1Min, address(this), block.timestamp ); (uint256 tokenId, uint128 amountLiquidity,,) = univ3_positions.mint(params); Position memory pos = Position( tokenId, _tokenA == address(FRAX) ? _tokenB : _tokenA, amountLiquidity, _tickLower, _tickUpper, _fee ); positions_array.push(pos); positions_mapping[tokenId] = pos; } /* ** burn tokenAmount from the recipient and send tokens to the receipient */ event log(uint); function removeLiquidity(uint256 positionIndex) public onlyByOwnGov { Position memory pos = positions_array[positionIndex]; INonfungiblePositionManager.CollectParams memory collect_params = INonfungiblePositionManager.CollectParams( pos.token_id, custodian_address, type(uint128).max, type(uint128).max ); univ3_positions.collect(collect_params); univ3_positions.burn(pos.token_id); positions_array[positionIndex] = positions_array[positions_array.length -1]; positions_array.pop(); delete positions_mapping[pos.token_id]; emit log(positions_array.length); emit log(positions_mapping[pos.token_id].token_id); } // Swap tokenA into tokenB using univ3_router.ExactInputSingle() // Uni V3 only function swap(address _tokenA, address _tokenB, uint24 _fee_tier, uint256 _amountAtoB, uint256 _amountOutMinimum, uint160 _sqrtPriceLimitX96) public onlyByOwnGov returns (uint256) { // Make sure the collateral is allowed require(allowed_collaterals[_tokenA] || _tokenA == address(FRAX), "TokenA not allowed"); require(allowed_collaterals[_tokenB] || _tokenB == address(FRAX), "TokenB not allowed"); ISwapRouter.ExactInputSingleParams memory swap_params = ISwapRouter.ExactInputSingleParams( _tokenA, _tokenB, _fee_tier, address(this), 2105300114, // Expiration: a long time from now _amountAtoB, _amountOutMinimum, _sqrtPriceLimitX96 ); // Approval TransferHelper.safeApprove(_tokenA, address(univ3_router), _amountAtoB); uint256 amountOut = univ3_router.exactInputSingle(swap_params); return amountOut; } /* ========== Burns and givebacks ========== */ // Give USDC profits back. Goes through the minter function giveCollatBack(uint256 collat_amount) external onlyByOwnGovCust { giveback_collateral.approve(address(amo_minter), collat_amount); amo_minter.receiveCollatFromAMO(collat_amount); } // Burn unneeded or excess FRAX. Goes through the minter function burnFRAX(uint256 frax_amount) public onlyByOwnGovCust { FRAX.approve(address(amo_minter), frax_amount); amo_minter.burnFraxFromAMO(frax_amount); } // Burn unneeded FXS. Goes through the minter function burnFXS(uint256 fxs_amount) public onlyByOwnGovCust { FXS.approve(address(amo_minter), fxs_amount); amo_minter.burnFxsFromAMO(fxs_amount); } /* ========== OWNER / GOVERNANCE FUNCTIONS ONLY ========== */ // Only owner or timelock can call, to limit risk // Adds collateral addresses supported. Needed to make sure dollarBalances is correct function addCollateral(address collat_addr) public onlyByOwnGov { require(collat_addr != address(0), "Zero address detected"); require(collat_addr != address(FRAX), "FRAX is not collateral"); require(allowed_collaterals[collat_addr] == false, "Address already exists"); allowed_collaterals[collat_addr] = true; collateral_addresses.push(collat_addr); } // Adds oracle for collateral. Optional for 1usd pegged coins. function addOracle(address collat_addr, address oracle) public onlyByOwnGov { require(collat_addr != address(0), "Zero address detected"); require(collat_addr != address(FRAX), "FRAX is not collateral"); oracles[collat_addr] = OracleLike(oracle); } function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov { // Can only be triggered by owner or governance, not custodian // Tokens are sent to the custodian, as a sort of safeguard TransferHelper.safeTransfer(tokenAddress, custodian_address, tokenAmount); emit RecoveredERC20(tokenAddress, tokenAmount); } function recoverERC721(address tokenAddress, uint256 token_id) external onlyByOwnGov { // Only the owner address can ever receive the recovery withdrawal // INonfungiblePositionManager inherits IERC721 so the latter does not need to be imported INonfungiblePositionManager(tokenAddress).safeTransferFrom( address(this), custodian_address, token_id); emit RecoveredERC721(tokenAddress, token_id); } // Generic proxy function execute( address _to, uint256 _value, bytes calldata _data ) external onlyByOwnGov returns (bool, bytes memory) { (bool success, bytes memory result) = _to.call{value:_value}(_data); return (success, result); } /* ========== EVENTS ========== */ event RecoveredERC20(address token, uint256 amount); event RecoveredERC721(address token, uint256 id); }
mintedBalance
function mintedBalance() public view returns (int256) { return amo_minter.frax_mint_balances(address(this)); }
// Backwards compatibility
LineComment
v0.8.6+commit.11564f7e
{ "func_code_index": [ 7564, 7690 ] }
800
UniV3LiquidityAMO_V2
contracts/Misc_AMOs/UniV3LiquidityAMO_V2.sol
0xc91bb4b0696e3b48c0c501b4ce8e7244fc363a79
Solidity
UniV3LiquidityAMO_V2
contract UniV3LiquidityAMO_V2 is Owned { using SafeMath for uint256; using SafeERC20 for ERC20; /* ========== STATE VARIABLES ========== */ // Core FRAXStablecoin private FRAX; FRAXShares private FXS; IFraxAMOMinter private amo_minter; ERC20 private giveback_collateral; address public giveback_collateral_address; uint256 public missing_decimals_giveback_collat; address public timelock_address; address public custodian_address; // Uniswap v3 IUniswapV3Factory public univ3_factory; INonfungiblePositionManager public univ3_positions; ISwapRouter public univ3_router; // Price constants uint256 private constant PRICE_PRECISION = 1e6; // Wildcat AMO // Details about the AMO's uniswap positions struct Position { uint256 token_id; address collateral_address; uint128 liquidity; // the liquidity of the position int24 tickLower; // the tick range of the position int24 tickUpper; uint24 fee_tier; } // Array of all Uni v3 NFT positions held by the AMO Position[] public positions_array; // List of all collaterals address[] public collateral_addresses; mapping(address => bool) public allowed_collaterals; // Mapping is also used for faster verification mapping(address => OracleLike) public oracles; // Mapping of oracles (if oracle == address(0) the collateral is assumed to be pegged to 1usd) // Map token_id to Position mapping(uint256 => Position) public positions_mapping; /* ========== CONSTRUCTOR ========== */ constructor( address _creator_address, address _giveback_collateral_address, address _amo_minter_address ) Owned(_creator_address) { FRAX = FRAXStablecoin(0x853d955aCEf822Db058eb8505911ED77F175b99e); FXS = FRAXShares(0x3432B6A60D23Ca0dFCa7761B7ab56459D9C964D0); giveback_collateral_address = _giveback_collateral_address; giveback_collateral = ERC20(_giveback_collateral_address); missing_decimals_giveback_collat = uint(18).sub(giveback_collateral.decimals()); collateral_addresses.push(_giveback_collateral_address); allowed_collaterals[_giveback_collateral_address] = true; univ3_factory = IUniswapV3Factory(0x1F98431c8aD98523631AE4a59f267346ea31F984); univ3_positions = INonfungiblePositionManager(0xC36442b4a4522E871399CD717aBDD847Ab11FE88); univ3_router = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564); // Initialize the minter amo_minter = IFraxAMOMinter(_amo_minter_address); // Get the custodian and timelock addresses from the minter custodian_address = amo_minter.custodian_address(); timelock_address = amo_minter.timelock_address(); } /* ========== MODIFIERS ========== */ modifier onlyByOwnGov() { require(msg.sender == timelock_address || msg.sender == owner, "Not owner or timelock"); _; } modifier onlyByOwnGovCust() { require(msg.sender == timelock_address || msg.sender == owner || msg.sender == custodian_address, "Not owner, tlck, or custd"); _; } modifier onlyByMinter() { require(msg.sender == address(amo_minter), "Not minter"); _; } /* ========== VIEWS ========== */ function showAllocations() public view returns (uint256[4] memory allocations) { // All numbers given are in FRAX unless otherwise stated // Unallocated FRAX allocations[0] = FRAX.balanceOf(address(this)); // Unallocated Collateral Dollar Value (E18) allocations[1] = freeColDolVal(); // Sum of Uni v3 Positions liquidity, if it was all in FRAX allocations[2] = TotalLiquidityFrax(); // Total Value allocations[3] = allocations[0].add(allocations[1]).add(allocations[2]); } // E18 Collateral dollar value function freeColDolVal() public view returns (uint256) { uint256 value_tally_e18 = 0; for (uint i = 0; i < collateral_addresses.length; i++){ ERC20 thisCollateral = ERC20(collateral_addresses[i]); uint256 missing_decs = uint256(18).sub(thisCollateral.decimals()); uint256 col_bal_e18 = thisCollateral.balanceOf(address(this)).mul(10 ** missing_decs); uint256 col_usd_value_e18 = collatDolarValue(oracles[collateral_addresses[i]], col_bal_e18); value_tally_e18 = value_tally_e18.add(col_usd_value_e18); } return value_tally_e18; } // Convert collateral to dolar. If no oracle assumes pegged to 1USD. Both oracle, balance and return are E18 function collatDolarValue(OracleLike oracle, uint256 balance) public view returns (uint256) { if (address(oracle) == address(0)) return balance; return balance.mul(oracle.read()).div(1 ether); } // Needed for the Frax contract to function function collatDollarBalance() public view returns (uint256) { // Get the allocations uint256[4] memory allocations = showAllocations(); // Get the collateral and FRAX portions uint256 collat_portion = allocations[1]; uint256 frax_portion = (allocations[0]).add(allocations[2]); // Assumes worst case scenario if FRAX slips out of range. // Otherwise, it would only be half that is multiplied by the CR frax_portion = frax_portion.mul(FRAX.global_collateral_ratio()).div(PRICE_PRECISION); return (collat_portion).add(frax_portion); } function dollarBalances() public view returns (uint256 frax_val_e18, uint256 collat_val_e18) { frax_val_e18 = showAllocations()[3]; collat_val_e18 = collatDollarBalance(); } function TotalLiquidityFrax() public view returns (uint256) { uint256 frax_tally = 0; Position memory thisPosition; for (uint256 i = 0; i < positions_array.length; i++) { thisPosition = positions_array[i]; uint128 this_liq = thisPosition.liquidity; if (this_liq > 0){ uint160 sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(thisPosition.tickLower); uint160 sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(thisPosition.tickUpper); if (thisPosition.collateral_address > 0x853d955aCEf822Db058eb8505911ED77F175b99e){ // if address(FRAX) < collateral_address, then FRAX is token0 frax_tally = frax_tally.add(LiquidityAmounts.getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, this_liq)); } else { frax_tally = frax_tally.add(LiquidityAmounts.getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, this_liq)); } } } // Return the sum of all the positions' balances of FRAX, if the price fell off the range towards that side return frax_tally; } // Returns this contract's liquidity in a specific [FRAX]-[collateral] uni v3 pool function liquidityInPool(address _collateral_address, int24 _tickLower, int24 _tickUpper, uint24 _fee) public view returns (uint128) { IUniswapV3Pool get_pool = IUniswapV3Pool(univ3_factory.getPool(address(FRAX), _collateral_address, _fee)); // goes into the pool's positions mapping, and grabs this address's liquidity (uint128 liquidity, , , , ) = get_pool.positions(keccak256(abi.encodePacked(address(this), _tickLower, _tickUpper))); return liquidity; } // Backwards compatibility function mintedBalance() public view returns (int256) { return amo_minter.frax_mint_balances(address(this)); } // Backwards compatibility function collateralBalance() public view returns (int256) { return amo_minter.collat_borrowed_balances(address(this)); } // Only counts non-withdrawn positions function numPositions() public view returns (uint256) { return positions_array.length; } function allCollateralAddresses() external view returns (address[] memory) { return collateral_addresses; } /* ========== RESTRICTED FUNCTIONS, BUT CUSTODIAN CAN CALL ========== */ // Iterate through all positions and collect fees accumulated function collectFees() external onlyByOwnGovCust { for (uint i = 0; i < positions_array.length; i++){ Position memory current_position = positions_array[i]; INonfungiblePositionManager.CollectParams memory collect_params = INonfungiblePositionManager.CollectParams( current_position.token_id, custodian_address, type(uint128).max, type(uint128).max ); // Send to custodian address univ3_positions.collect(collect_params); } } /* ---------------------------------------------------- */ /* ---------------------- Uni v3 ---------------------- */ /* ---------------------------------------------------- */ function approveTarget(address _target, address _token, uint256 _amount, bool use_safe_approve) public onlyByOwnGov { if (use_safe_approve) { // safeApprove needed for USDT and others for the first approval // You need to approve 0 every time beforehand for USDT: it resets TransferHelper.safeApprove(_token, _target, _amount); } else { ERC20(_token).approve(_target, _amount); } } // IUniswapV3Pool public current_uni_pool; // only used for mint callback; is set and accessed during execution of addLiquidity() function addLiquidity(address _tokenA, address _tokenB, int24 _tickLower, int24 _tickUpper, uint24 _fee, uint256 _amount0Desired, uint256 _amount1Desired, uint256 _amount0Min, uint256 _amount1Min) public onlyByOwnGov { // Make sure the collateral is allowed require(allowed_collaterals[_tokenA] || _tokenA == address(FRAX), "TokenA not allowed"); require(allowed_collaterals[_tokenB] || _tokenB == address(FRAX), "TokenB not allowed"); ERC20(_tokenA).transferFrom(msg.sender, address(this), _amount0Desired); ERC20(_tokenB).transferFrom(msg.sender, address(this), _amount1Desired); ERC20(_tokenA).approve(address(univ3_positions), _amount0Desired); ERC20(_tokenB).approve(address(univ3_positions), _amount1Desired); INonfungiblePositionManager.MintParams memory params = INonfungiblePositionManager.MintParams( _tokenA, _tokenB, _fee, _tickLower, _tickUpper, _amount0Desired, _amount1Desired, _amount0Min, _amount1Min, address(this), block.timestamp ); (uint256 tokenId, uint128 amountLiquidity,,) = univ3_positions.mint(params); Position memory pos = Position( tokenId, _tokenA == address(FRAX) ? _tokenB : _tokenA, amountLiquidity, _tickLower, _tickUpper, _fee ); positions_array.push(pos); positions_mapping[tokenId] = pos; } /* ** burn tokenAmount from the recipient and send tokens to the receipient */ event log(uint); function removeLiquidity(uint256 positionIndex) public onlyByOwnGov { Position memory pos = positions_array[positionIndex]; INonfungiblePositionManager.CollectParams memory collect_params = INonfungiblePositionManager.CollectParams( pos.token_id, custodian_address, type(uint128).max, type(uint128).max ); univ3_positions.collect(collect_params); univ3_positions.burn(pos.token_id); positions_array[positionIndex] = positions_array[positions_array.length -1]; positions_array.pop(); delete positions_mapping[pos.token_id]; emit log(positions_array.length); emit log(positions_mapping[pos.token_id].token_id); } // Swap tokenA into tokenB using univ3_router.ExactInputSingle() // Uni V3 only function swap(address _tokenA, address _tokenB, uint24 _fee_tier, uint256 _amountAtoB, uint256 _amountOutMinimum, uint160 _sqrtPriceLimitX96) public onlyByOwnGov returns (uint256) { // Make sure the collateral is allowed require(allowed_collaterals[_tokenA] || _tokenA == address(FRAX), "TokenA not allowed"); require(allowed_collaterals[_tokenB] || _tokenB == address(FRAX), "TokenB not allowed"); ISwapRouter.ExactInputSingleParams memory swap_params = ISwapRouter.ExactInputSingleParams( _tokenA, _tokenB, _fee_tier, address(this), 2105300114, // Expiration: a long time from now _amountAtoB, _amountOutMinimum, _sqrtPriceLimitX96 ); // Approval TransferHelper.safeApprove(_tokenA, address(univ3_router), _amountAtoB); uint256 amountOut = univ3_router.exactInputSingle(swap_params); return amountOut; } /* ========== Burns and givebacks ========== */ // Give USDC profits back. Goes through the minter function giveCollatBack(uint256 collat_amount) external onlyByOwnGovCust { giveback_collateral.approve(address(amo_minter), collat_amount); amo_minter.receiveCollatFromAMO(collat_amount); } // Burn unneeded or excess FRAX. Goes through the minter function burnFRAX(uint256 frax_amount) public onlyByOwnGovCust { FRAX.approve(address(amo_minter), frax_amount); amo_minter.burnFraxFromAMO(frax_amount); } // Burn unneeded FXS. Goes through the minter function burnFXS(uint256 fxs_amount) public onlyByOwnGovCust { FXS.approve(address(amo_minter), fxs_amount); amo_minter.burnFxsFromAMO(fxs_amount); } /* ========== OWNER / GOVERNANCE FUNCTIONS ONLY ========== */ // Only owner or timelock can call, to limit risk // Adds collateral addresses supported. Needed to make sure dollarBalances is correct function addCollateral(address collat_addr) public onlyByOwnGov { require(collat_addr != address(0), "Zero address detected"); require(collat_addr != address(FRAX), "FRAX is not collateral"); require(allowed_collaterals[collat_addr] == false, "Address already exists"); allowed_collaterals[collat_addr] = true; collateral_addresses.push(collat_addr); } // Adds oracle for collateral. Optional for 1usd pegged coins. function addOracle(address collat_addr, address oracle) public onlyByOwnGov { require(collat_addr != address(0), "Zero address detected"); require(collat_addr != address(FRAX), "FRAX is not collateral"); oracles[collat_addr] = OracleLike(oracle); } function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov { // Can only be triggered by owner or governance, not custodian // Tokens are sent to the custodian, as a sort of safeguard TransferHelper.safeTransfer(tokenAddress, custodian_address, tokenAmount); emit RecoveredERC20(tokenAddress, tokenAmount); } function recoverERC721(address tokenAddress, uint256 token_id) external onlyByOwnGov { // Only the owner address can ever receive the recovery withdrawal // INonfungiblePositionManager inherits IERC721 so the latter does not need to be imported INonfungiblePositionManager(tokenAddress).safeTransferFrom( address(this), custodian_address, token_id); emit RecoveredERC721(tokenAddress, token_id); } // Generic proxy function execute( address _to, uint256 _value, bytes calldata _data ) external onlyByOwnGov returns (bool, bytes memory) { (bool success, bytes memory result) = _to.call{value:_value}(_data); return (success, result); } /* ========== EVENTS ========== */ event RecoveredERC20(address token, uint256 amount); event RecoveredERC721(address token, uint256 id); }
collateralBalance
function collateralBalance() public view returns (int256) { return amo_minter.collat_borrowed_balances(address(this)); }
// Backwards compatibility
LineComment
v0.8.6+commit.11564f7e
{ "func_code_index": [ 7723, 7859 ] }
801
UniV3LiquidityAMO_V2
contracts/Misc_AMOs/UniV3LiquidityAMO_V2.sol
0xc91bb4b0696e3b48c0c501b4ce8e7244fc363a79
Solidity
UniV3LiquidityAMO_V2
contract UniV3LiquidityAMO_V2 is Owned { using SafeMath for uint256; using SafeERC20 for ERC20; /* ========== STATE VARIABLES ========== */ // Core FRAXStablecoin private FRAX; FRAXShares private FXS; IFraxAMOMinter private amo_minter; ERC20 private giveback_collateral; address public giveback_collateral_address; uint256 public missing_decimals_giveback_collat; address public timelock_address; address public custodian_address; // Uniswap v3 IUniswapV3Factory public univ3_factory; INonfungiblePositionManager public univ3_positions; ISwapRouter public univ3_router; // Price constants uint256 private constant PRICE_PRECISION = 1e6; // Wildcat AMO // Details about the AMO's uniswap positions struct Position { uint256 token_id; address collateral_address; uint128 liquidity; // the liquidity of the position int24 tickLower; // the tick range of the position int24 tickUpper; uint24 fee_tier; } // Array of all Uni v3 NFT positions held by the AMO Position[] public positions_array; // List of all collaterals address[] public collateral_addresses; mapping(address => bool) public allowed_collaterals; // Mapping is also used for faster verification mapping(address => OracleLike) public oracles; // Mapping of oracles (if oracle == address(0) the collateral is assumed to be pegged to 1usd) // Map token_id to Position mapping(uint256 => Position) public positions_mapping; /* ========== CONSTRUCTOR ========== */ constructor( address _creator_address, address _giveback_collateral_address, address _amo_minter_address ) Owned(_creator_address) { FRAX = FRAXStablecoin(0x853d955aCEf822Db058eb8505911ED77F175b99e); FXS = FRAXShares(0x3432B6A60D23Ca0dFCa7761B7ab56459D9C964D0); giveback_collateral_address = _giveback_collateral_address; giveback_collateral = ERC20(_giveback_collateral_address); missing_decimals_giveback_collat = uint(18).sub(giveback_collateral.decimals()); collateral_addresses.push(_giveback_collateral_address); allowed_collaterals[_giveback_collateral_address] = true; univ3_factory = IUniswapV3Factory(0x1F98431c8aD98523631AE4a59f267346ea31F984); univ3_positions = INonfungiblePositionManager(0xC36442b4a4522E871399CD717aBDD847Ab11FE88); univ3_router = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564); // Initialize the minter amo_minter = IFraxAMOMinter(_amo_minter_address); // Get the custodian and timelock addresses from the minter custodian_address = amo_minter.custodian_address(); timelock_address = amo_minter.timelock_address(); } /* ========== MODIFIERS ========== */ modifier onlyByOwnGov() { require(msg.sender == timelock_address || msg.sender == owner, "Not owner or timelock"); _; } modifier onlyByOwnGovCust() { require(msg.sender == timelock_address || msg.sender == owner || msg.sender == custodian_address, "Not owner, tlck, or custd"); _; } modifier onlyByMinter() { require(msg.sender == address(amo_minter), "Not minter"); _; } /* ========== VIEWS ========== */ function showAllocations() public view returns (uint256[4] memory allocations) { // All numbers given are in FRAX unless otherwise stated // Unallocated FRAX allocations[0] = FRAX.balanceOf(address(this)); // Unallocated Collateral Dollar Value (E18) allocations[1] = freeColDolVal(); // Sum of Uni v3 Positions liquidity, if it was all in FRAX allocations[2] = TotalLiquidityFrax(); // Total Value allocations[3] = allocations[0].add(allocations[1]).add(allocations[2]); } // E18 Collateral dollar value function freeColDolVal() public view returns (uint256) { uint256 value_tally_e18 = 0; for (uint i = 0; i < collateral_addresses.length; i++){ ERC20 thisCollateral = ERC20(collateral_addresses[i]); uint256 missing_decs = uint256(18).sub(thisCollateral.decimals()); uint256 col_bal_e18 = thisCollateral.balanceOf(address(this)).mul(10 ** missing_decs); uint256 col_usd_value_e18 = collatDolarValue(oracles[collateral_addresses[i]], col_bal_e18); value_tally_e18 = value_tally_e18.add(col_usd_value_e18); } return value_tally_e18; } // Convert collateral to dolar. If no oracle assumes pegged to 1USD. Both oracle, balance and return are E18 function collatDolarValue(OracleLike oracle, uint256 balance) public view returns (uint256) { if (address(oracle) == address(0)) return balance; return balance.mul(oracle.read()).div(1 ether); } // Needed for the Frax contract to function function collatDollarBalance() public view returns (uint256) { // Get the allocations uint256[4] memory allocations = showAllocations(); // Get the collateral and FRAX portions uint256 collat_portion = allocations[1]; uint256 frax_portion = (allocations[0]).add(allocations[2]); // Assumes worst case scenario if FRAX slips out of range. // Otherwise, it would only be half that is multiplied by the CR frax_portion = frax_portion.mul(FRAX.global_collateral_ratio()).div(PRICE_PRECISION); return (collat_portion).add(frax_portion); } function dollarBalances() public view returns (uint256 frax_val_e18, uint256 collat_val_e18) { frax_val_e18 = showAllocations()[3]; collat_val_e18 = collatDollarBalance(); } function TotalLiquidityFrax() public view returns (uint256) { uint256 frax_tally = 0; Position memory thisPosition; for (uint256 i = 0; i < positions_array.length; i++) { thisPosition = positions_array[i]; uint128 this_liq = thisPosition.liquidity; if (this_liq > 0){ uint160 sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(thisPosition.tickLower); uint160 sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(thisPosition.tickUpper); if (thisPosition.collateral_address > 0x853d955aCEf822Db058eb8505911ED77F175b99e){ // if address(FRAX) < collateral_address, then FRAX is token0 frax_tally = frax_tally.add(LiquidityAmounts.getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, this_liq)); } else { frax_tally = frax_tally.add(LiquidityAmounts.getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, this_liq)); } } } // Return the sum of all the positions' balances of FRAX, if the price fell off the range towards that side return frax_tally; } // Returns this contract's liquidity in a specific [FRAX]-[collateral] uni v3 pool function liquidityInPool(address _collateral_address, int24 _tickLower, int24 _tickUpper, uint24 _fee) public view returns (uint128) { IUniswapV3Pool get_pool = IUniswapV3Pool(univ3_factory.getPool(address(FRAX), _collateral_address, _fee)); // goes into the pool's positions mapping, and grabs this address's liquidity (uint128 liquidity, , , , ) = get_pool.positions(keccak256(abi.encodePacked(address(this), _tickLower, _tickUpper))); return liquidity; } // Backwards compatibility function mintedBalance() public view returns (int256) { return amo_minter.frax_mint_balances(address(this)); } // Backwards compatibility function collateralBalance() public view returns (int256) { return amo_minter.collat_borrowed_balances(address(this)); } // Only counts non-withdrawn positions function numPositions() public view returns (uint256) { return positions_array.length; } function allCollateralAddresses() external view returns (address[] memory) { return collateral_addresses; } /* ========== RESTRICTED FUNCTIONS, BUT CUSTODIAN CAN CALL ========== */ // Iterate through all positions and collect fees accumulated function collectFees() external onlyByOwnGovCust { for (uint i = 0; i < positions_array.length; i++){ Position memory current_position = positions_array[i]; INonfungiblePositionManager.CollectParams memory collect_params = INonfungiblePositionManager.CollectParams( current_position.token_id, custodian_address, type(uint128).max, type(uint128).max ); // Send to custodian address univ3_positions.collect(collect_params); } } /* ---------------------------------------------------- */ /* ---------------------- Uni v3 ---------------------- */ /* ---------------------------------------------------- */ function approveTarget(address _target, address _token, uint256 _amount, bool use_safe_approve) public onlyByOwnGov { if (use_safe_approve) { // safeApprove needed for USDT and others for the first approval // You need to approve 0 every time beforehand for USDT: it resets TransferHelper.safeApprove(_token, _target, _amount); } else { ERC20(_token).approve(_target, _amount); } } // IUniswapV3Pool public current_uni_pool; // only used for mint callback; is set and accessed during execution of addLiquidity() function addLiquidity(address _tokenA, address _tokenB, int24 _tickLower, int24 _tickUpper, uint24 _fee, uint256 _amount0Desired, uint256 _amount1Desired, uint256 _amount0Min, uint256 _amount1Min) public onlyByOwnGov { // Make sure the collateral is allowed require(allowed_collaterals[_tokenA] || _tokenA == address(FRAX), "TokenA not allowed"); require(allowed_collaterals[_tokenB] || _tokenB == address(FRAX), "TokenB not allowed"); ERC20(_tokenA).transferFrom(msg.sender, address(this), _amount0Desired); ERC20(_tokenB).transferFrom(msg.sender, address(this), _amount1Desired); ERC20(_tokenA).approve(address(univ3_positions), _amount0Desired); ERC20(_tokenB).approve(address(univ3_positions), _amount1Desired); INonfungiblePositionManager.MintParams memory params = INonfungiblePositionManager.MintParams( _tokenA, _tokenB, _fee, _tickLower, _tickUpper, _amount0Desired, _amount1Desired, _amount0Min, _amount1Min, address(this), block.timestamp ); (uint256 tokenId, uint128 amountLiquidity,,) = univ3_positions.mint(params); Position memory pos = Position( tokenId, _tokenA == address(FRAX) ? _tokenB : _tokenA, amountLiquidity, _tickLower, _tickUpper, _fee ); positions_array.push(pos); positions_mapping[tokenId] = pos; } /* ** burn tokenAmount from the recipient and send tokens to the receipient */ event log(uint); function removeLiquidity(uint256 positionIndex) public onlyByOwnGov { Position memory pos = positions_array[positionIndex]; INonfungiblePositionManager.CollectParams memory collect_params = INonfungiblePositionManager.CollectParams( pos.token_id, custodian_address, type(uint128).max, type(uint128).max ); univ3_positions.collect(collect_params); univ3_positions.burn(pos.token_id); positions_array[positionIndex] = positions_array[positions_array.length -1]; positions_array.pop(); delete positions_mapping[pos.token_id]; emit log(positions_array.length); emit log(positions_mapping[pos.token_id].token_id); } // Swap tokenA into tokenB using univ3_router.ExactInputSingle() // Uni V3 only function swap(address _tokenA, address _tokenB, uint24 _fee_tier, uint256 _amountAtoB, uint256 _amountOutMinimum, uint160 _sqrtPriceLimitX96) public onlyByOwnGov returns (uint256) { // Make sure the collateral is allowed require(allowed_collaterals[_tokenA] || _tokenA == address(FRAX), "TokenA not allowed"); require(allowed_collaterals[_tokenB] || _tokenB == address(FRAX), "TokenB not allowed"); ISwapRouter.ExactInputSingleParams memory swap_params = ISwapRouter.ExactInputSingleParams( _tokenA, _tokenB, _fee_tier, address(this), 2105300114, // Expiration: a long time from now _amountAtoB, _amountOutMinimum, _sqrtPriceLimitX96 ); // Approval TransferHelper.safeApprove(_tokenA, address(univ3_router), _amountAtoB); uint256 amountOut = univ3_router.exactInputSingle(swap_params); return amountOut; } /* ========== Burns and givebacks ========== */ // Give USDC profits back. Goes through the minter function giveCollatBack(uint256 collat_amount) external onlyByOwnGovCust { giveback_collateral.approve(address(amo_minter), collat_amount); amo_minter.receiveCollatFromAMO(collat_amount); } // Burn unneeded or excess FRAX. Goes through the minter function burnFRAX(uint256 frax_amount) public onlyByOwnGovCust { FRAX.approve(address(amo_minter), frax_amount); amo_minter.burnFraxFromAMO(frax_amount); } // Burn unneeded FXS. Goes through the minter function burnFXS(uint256 fxs_amount) public onlyByOwnGovCust { FXS.approve(address(amo_minter), fxs_amount); amo_minter.burnFxsFromAMO(fxs_amount); } /* ========== OWNER / GOVERNANCE FUNCTIONS ONLY ========== */ // Only owner or timelock can call, to limit risk // Adds collateral addresses supported. Needed to make sure dollarBalances is correct function addCollateral(address collat_addr) public onlyByOwnGov { require(collat_addr != address(0), "Zero address detected"); require(collat_addr != address(FRAX), "FRAX is not collateral"); require(allowed_collaterals[collat_addr] == false, "Address already exists"); allowed_collaterals[collat_addr] = true; collateral_addresses.push(collat_addr); } // Adds oracle for collateral. Optional for 1usd pegged coins. function addOracle(address collat_addr, address oracle) public onlyByOwnGov { require(collat_addr != address(0), "Zero address detected"); require(collat_addr != address(FRAX), "FRAX is not collateral"); oracles[collat_addr] = OracleLike(oracle); } function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov { // Can only be triggered by owner or governance, not custodian // Tokens are sent to the custodian, as a sort of safeguard TransferHelper.safeTransfer(tokenAddress, custodian_address, tokenAmount); emit RecoveredERC20(tokenAddress, tokenAmount); } function recoverERC721(address tokenAddress, uint256 token_id) external onlyByOwnGov { // Only the owner address can ever receive the recovery withdrawal // INonfungiblePositionManager inherits IERC721 so the latter does not need to be imported INonfungiblePositionManager(tokenAddress).safeTransferFrom( address(this), custodian_address, token_id); emit RecoveredERC721(tokenAddress, token_id); } // Generic proxy function execute( address _to, uint256 _value, bytes calldata _data ) external onlyByOwnGov returns (bool, bytes memory) { (bool success, bytes memory result) = _to.call{value:_value}(_data); return (success, result); } /* ========== EVENTS ========== */ event RecoveredERC20(address token, uint256 amount); event RecoveredERC721(address token, uint256 id); }
numPositions
function numPositions() public view returns (uint256) { return positions_array.length; }
// Only counts non-withdrawn positions
LineComment
v0.8.6+commit.11564f7e
{ "func_code_index": [ 7904, 8008 ] }
802
UniV3LiquidityAMO_V2
contracts/Misc_AMOs/UniV3LiquidityAMO_V2.sol
0xc91bb4b0696e3b48c0c501b4ce8e7244fc363a79
Solidity
UniV3LiquidityAMO_V2
contract UniV3LiquidityAMO_V2 is Owned { using SafeMath for uint256; using SafeERC20 for ERC20; /* ========== STATE VARIABLES ========== */ // Core FRAXStablecoin private FRAX; FRAXShares private FXS; IFraxAMOMinter private amo_minter; ERC20 private giveback_collateral; address public giveback_collateral_address; uint256 public missing_decimals_giveback_collat; address public timelock_address; address public custodian_address; // Uniswap v3 IUniswapV3Factory public univ3_factory; INonfungiblePositionManager public univ3_positions; ISwapRouter public univ3_router; // Price constants uint256 private constant PRICE_PRECISION = 1e6; // Wildcat AMO // Details about the AMO's uniswap positions struct Position { uint256 token_id; address collateral_address; uint128 liquidity; // the liquidity of the position int24 tickLower; // the tick range of the position int24 tickUpper; uint24 fee_tier; } // Array of all Uni v3 NFT positions held by the AMO Position[] public positions_array; // List of all collaterals address[] public collateral_addresses; mapping(address => bool) public allowed_collaterals; // Mapping is also used for faster verification mapping(address => OracleLike) public oracles; // Mapping of oracles (if oracle == address(0) the collateral is assumed to be pegged to 1usd) // Map token_id to Position mapping(uint256 => Position) public positions_mapping; /* ========== CONSTRUCTOR ========== */ constructor( address _creator_address, address _giveback_collateral_address, address _amo_minter_address ) Owned(_creator_address) { FRAX = FRAXStablecoin(0x853d955aCEf822Db058eb8505911ED77F175b99e); FXS = FRAXShares(0x3432B6A60D23Ca0dFCa7761B7ab56459D9C964D0); giveback_collateral_address = _giveback_collateral_address; giveback_collateral = ERC20(_giveback_collateral_address); missing_decimals_giveback_collat = uint(18).sub(giveback_collateral.decimals()); collateral_addresses.push(_giveback_collateral_address); allowed_collaterals[_giveback_collateral_address] = true; univ3_factory = IUniswapV3Factory(0x1F98431c8aD98523631AE4a59f267346ea31F984); univ3_positions = INonfungiblePositionManager(0xC36442b4a4522E871399CD717aBDD847Ab11FE88); univ3_router = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564); // Initialize the minter amo_minter = IFraxAMOMinter(_amo_minter_address); // Get the custodian and timelock addresses from the minter custodian_address = amo_minter.custodian_address(); timelock_address = amo_minter.timelock_address(); } /* ========== MODIFIERS ========== */ modifier onlyByOwnGov() { require(msg.sender == timelock_address || msg.sender == owner, "Not owner or timelock"); _; } modifier onlyByOwnGovCust() { require(msg.sender == timelock_address || msg.sender == owner || msg.sender == custodian_address, "Not owner, tlck, or custd"); _; } modifier onlyByMinter() { require(msg.sender == address(amo_minter), "Not minter"); _; } /* ========== VIEWS ========== */ function showAllocations() public view returns (uint256[4] memory allocations) { // All numbers given are in FRAX unless otherwise stated // Unallocated FRAX allocations[0] = FRAX.balanceOf(address(this)); // Unallocated Collateral Dollar Value (E18) allocations[1] = freeColDolVal(); // Sum of Uni v3 Positions liquidity, if it was all in FRAX allocations[2] = TotalLiquidityFrax(); // Total Value allocations[3] = allocations[0].add(allocations[1]).add(allocations[2]); } // E18 Collateral dollar value function freeColDolVal() public view returns (uint256) { uint256 value_tally_e18 = 0; for (uint i = 0; i < collateral_addresses.length; i++){ ERC20 thisCollateral = ERC20(collateral_addresses[i]); uint256 missing_decs = uint256(18).sub(thisCollateral.decimals()); uint256 col_bal_e18 = thisCollateral.balanceOf(address(this)).mul(10 ** missing_decs); uint256 col_usd_value_e18 = collatDolarValue(oracles[collateral_addresses[i]], col_bal_e18); value_tally_e18 = value_tally_e18.add(col_usd_value_e18); } return value_tally_e18; } // Convert collateral to dolar. If no oracle assumes pegged to 1USD. Both oracle, balance and return are E18 function collatDolarValue(OracleLike oracle, uint256 balance) public view returns (uint256) { if (address(oracle) == address(0)) return balance; return balance.mul(oracle.read()).div(1 ether); } // Needed for the Frax contract to function function collatDollarBalance() public view returns (uint256) { // Get the allocations uint256[4] memory allocations = showAllocations(); // Get the collateral and FRAX portions uint256 collat_portion = allocations[1]; uint256 frax_portion = (allocations[0]).add(allocations[2]); // Assumes worst case scenario if FRAX slips out of range. // Otherwise, it would only be half that is multiplied by the CR frax_portion = frax_portion.mul(FRAX.global_collateral_ratio()).div(PRICE_PRECISION); return (collat_portion).add(frax_portion); } function dollarBalances() public view returns (uint256 frax_val_e18, uint256 collat_val_e18) { frax_val_e18 = showAllocations()[3]; collat_val_e18 = collatDollarBalance(); } function TotalLiquidityFrax() public view returns (uint256) { uint256 frax_tally = 0; Position memory thisPosition; for (uint256 i = 0; i < positions_array.length; i++) { thisPosition = positions_array[i]; uint128 this_liq = thisPosition.liquidity; if (this_liq > 0){ uint160 sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(thisPosition.tickLower); uint160 sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(thisPosition.tickUpper); if (thisPosition.collateral_address > 0x853d955aCEf822Db058eb8505911ED77F175b99e){ // if address(FRAX) < collateral_address, then FRAX is token0 frax_tally = frax_tally.add(LiquidityAmounts.getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, this_liq)); } else { frax_tally = frax_tally.add(LiquidityAmounts.getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, this_liq)); } } } // Return the sum of all the positions' balances of FRAX, if the price fell off the range towards that side return frax_tally; } // Returns this contract's liquidity in a specific [FRAX]-[collateral] uni v3 pool function liquidityInPool(address _collateral_address, int24 _tickLower, int24 _tickUpper, uint24 _fee) public view returns (uint128) { IUniswapV3Pool get_pool = IUniswapV3Pool(univ3_factory.getPool(address(FRAX), _collateral_address, _fee)); // goes into the pool's positions mapping, and grabs this address's liquidity (uint128 liquidity, , , , ) = get_pool.positions(keccak256(abi.encodePacked(address(this), _tickLower, _tickUpper))); return liquidity; } // Backwards compatibility function mintedBalance() public view returns (int256) { return amo_minter.frax_mint_balances(address(this)); } // Backwards compatibility function collateralBalance() public view returns (int256) { return amo_minter.collat_borrowed_balances(address(this)); } // Only counts non-withdrawn positions function numPositions() public view returns (uint256) { return positions_array.length; } function allCollateralAddresses() external view returns (address[] memory) { return collateral_addresses; } /* ========== RESTRICTED FUNCTIONS, BUT CUSTODIAN CAN CALL ========== */ // Iterate through all positions and collect fees accumulated function collectFees() external onlyByOwnGovCust { for (uint i = 0; i < positions_array.length; i++){ Position memory current_position = positions_array[i]; INonfungiblePositionManager.CollectParams memory collect_params = INonfungiblePositionManager.CollectParams( current_position.token_id, custodian_address, type(uint128).max, type(uint128).max ); // Send to custodian address univ3_positions.collect(collect_params); } } /* ---------------------------------------------------- */ /* ---------------------- Uni v3 ---------------------- */ /* ---------------------------------------------------- */ function approveTarget(address _target, address _token, uint256 _amount, bool use_safe_approve) public onlyByOwnGov { if (use_safe_approve) { // safeApprove needed for USDT and others for the first approval // You need to approve 0 every time beforehand for USDT: it resets TransferHelper.safeApprove(_token, _target, _amount); } else { ERC20(_token).approve(_target, _amount); } } // IUniswapV3Pool public current_uni_pool; // only used for mint callback; is set and accessed during execution of addLiquidity() function addLiquidity(address _tokenA, address _tokenB, int24 _tickLower, int24 _tickUpper, uint24 _fee, uint256 _amount0Desired, uint256 _amount1Desired, uint256 _amount0Min, uint256 _amount1Min) public onlyByOwnGov { // Make sure the collateral is allowed require(allowed_collaterals[_tokenA] || _tokenA == address(FRAX), "TokenA not allowed"); require(allowed_collaterals[_tokenB] || _tokenB == address(FRAX), "TokenB not allowed"); ERC20(_tokenA).transferFrom(msg.sender, address(this), _amount0Desired); ERC20(_tokenB).transferFrom(msg.sender, address(this), _amount1Desired); ERC20(_tokenA).approve(address(univ3_positions), _amount0Desired); ERC20(_tokenB).approve(address(univ3_positions), _amount1Desired); INonfungiblePositionManager.MintParams memory params = INonfungiblePositionManager.MintParams( _tokenA, _tokenB, _fee, _tickLower, _tickUpper, _amount0Desired, _amount1Desired, _amount0Min, _amount1Min, address(this), block.timestamp ); (uint256 tokenId, uint128 amountLiquidity,,) = univ3_positions.mint(params); Position memory pos = Position( tokenId, _tokenA == address(FRAX) ? _tokenB : _tokenA, amountLiquidity, _tickLower, _tickUpper, _fee ); positions_array.push(pos); positions_mapping[tokenId] = pos; } /* ** burn tokenAmount from the recipient and send tokens to the receipient */ event log(uint); function removeLiquidity(uint256 positionIndex) public onlyByOwnGov { Position memory pos = positions_array[positionIndex]; INonfungiblePositionManager.CollectParams memory collect_params = INonfungiblePositionManager.CollectParams( pos.token_id, custodian_address, type(uint128).max, type(uint128).max ); univ3_positions.collect(collect_params); univ3_positions.burn(pos.token_id); positions_array[positionIndex] = positions_array[positions_array.length -1]; positions_array.pop(); delete positions_mapping[pos.token_id]; emit log(positions_array.length); emit log(positions_mapping[pos.token_id].token_id); } // Swap tokenA into tokenB using univ3_router.ExactInputSingle() // Uni V3 only function swap(address _tokenA, address _tokenB, uint24 _fee_tier, uint256 _amountAtoB, uint256 _amountOutMinimum, uint160 _sqrtPriceLimitX96) public onlyByOwnGov returns (uint256) { // Make sure the collateral is allowed require(allowed_collaterals[_tokenA] || _tokenA == address(FRAX), "TokenA not allowed"); require(allowed_collaterals[_tokenB] || _tokenB == address(FRAX), "TokenB not allowed"); ISwapRouter.ExactInputSingleParams memory swap_params = ISwapRouter.ExactInputSingleParams( _tokenA, _tokenB, _fee_tier, address(this), 2105300114, // Expiration: a long time from now _amountAtoB, _amountOutMinimum, _sqrtPriceLimitX96 ); // Approval TransferHelper.safeApprove(_tokenA, address(univ3_router), _amountAtoB); uint256 amountOut = univ3_router.exactInputSingle(swap_params); return amountOut; } /* ========== Burns and givebacks ========== */ // Give USDC profits back. Goes through the minter function giveCollatBack(uint256 collat_amount) external onlyByOwnGovCust { giveback_collateral.approve(address(amo_minter), collat_amount); amo_minter.receiveCollatFromAMO(collat_amount); } // Burn unneeded or excess FRAX. Goes through the minter function burnFRAX(uint256 frax_amount) public onlyByOwnGovCust { FRAX.approve(address(amo_minter), frax_amount); amo_minter.burnFraxFromAMO(frax_amount); } // Burn unneeded FXS. Goes through the minter function burnFXS(uint256 fxs_amount) public onlyByOwnGovCust { FXS.approve(address(amo_minter), fxs_amount); amo_minter.burnFxsFromAMO(fxs_amount); } /* ========== OWNER / GOVERNANCE FUNCTIONS ONLY ========== */ // Only owner or timelock can call, to limit risk // Adds collateral addresses supported. Needed to make sure dollarBalances is correct function addCollateral(address collat_addr) public onlyByOwnGov { require(collat_addr != address(0), "Zero address detected"); require(collat_addr != address(FRAX), "FRAX is not collateral"); require(allowed_collaterals[collat_addr] == false, "Address already exists"); allowed_collaterals[collat_addr] = true; collateral_addresses.push(collat_addr); } // Adds oracle for collateral. Optional for 1usd pegged coins. function addOracle(address collat_addr, address oracle) public onlyByOwnGov { require(collat_addr != address(0), "Zero address detected"); require(collat_addr != address(FRAX), "FRAX is not collateral"); oracles[collat_addr] = OracleLike(oracle); } function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov { // Can only be triggered by owner or governance, not custodian // Tokens are sent to the custodian, as a sort of safeguard TransferHelper.safeTransfer(tokenAddress, custodian_address, tokenAmount); emit RecoveredERC20(tokenAddress, tokenAmount); } function recoverERC721(address tokenAddress, uint256 token_id) external onlyByOwnGov { // Only the owner address can ever receive the recovery withdrawal // INonfungiblePositionManager inherits IERC721 so the latter does not need to be imported INonfungiblePositionManager(tokenAddress).safeTransferFrom( address(this), custodian_address, token_id); emit RecoveredERC721(tokenAddress, token_id); } // Generic proxy function execute( address _to, uint256 _value, bytes calldata _data ) external onlyByOwnGov returns (bool, bytes memory) { (bool success, bytes memory result) = _to.call{value:_value}(_data); return (success, result); } /* ========== EVENTS ========== */ event RecoveredERC20(address token, uint256 amount); event RecoveredERC721(address token, uint256 id); }
collectFees
function collectFees() external onlyByOwnGovCust { for (uint i = 0; i < positions_array.length; i++){ Position memory current_position = positions_array[i]; INonfungiblePositionManager.CollectParams memory collect_params = INonfungiblePositionManager.CollectParams( current_position.token_id, custodian_address, type(uint128).max, type(uint128).max ); // Send to custodian address univ3_positions.collect(collect_params); } }
// Iterate through all positions and collect fees accumulated
LineComment
v0.8.6+commit.11564f7e
{ "func_code_index": [ 8279, 8853 ] }
803
UniV3LiquidityAMO_V2
contracts/Misc_AMOs/UniV3LiquidityAMO_V2.sol
0xc91bb4b0696e3b48c0c501b4ce8e7244fc363a79
Solidity
UniV3LiquidityAMO_V2
contract UniV3LiquidityAMO_V2 is Owned { using SafeMath for uint256; using SafeERC20 for ERC20; /* ========== STATE VARIABLES ========== */ // Core FRAXStablecoin private FRAX; FRAXShares private FXS; IFraxAMOMinter private amo_minter; ERC20 private giveback_collateral; address public giveback_collateral_address; uint256 public missing_decimals_giveback_collat; address public timelock_address; address public custodian_address; // Uniswap v3 IUniswapV3Factory public univ3_factory; INonfungiblePositionManager public univ3_positions; ISwapRouter public univ3_router; // Price constants uint256 private constant PRICE_PRECISION = 1e6; // Wildcat AMO // Details about the AMO's uniswap positions struct Position { uint256 token_id; address collateral_address; uint128 liquidity; // the liquidity of the position int24 tickLower; // the tick range of the position int24 tickUpper; uint24 fee_tier; } // Array of all Uni v3 NFT positions held by the AMO Position[] public positions_array; // List of all collaterals address[] public collateral_addresses; mapping(address => bool) public allowed_collaterals; // Mapping is also used for faster verification mapping(address => OracleLike) public oracles; // Mapping of oracles (if oracle == address(0) the collateral is assumed to be pegged to 1usd) // Map token_id to Position mapping(uint256 => Position) public positions_mapping; /* ========== CONSTRUCTOR ========== */ constructor( address _creator_address, address _giveback_collateral_address, address _amo_minter_address ) Owned(_creator_address) { FRAX = FRAXStablecoin(0x853d955aCEf822Db058eb8505911ED77F175b99e); FXS = FRAXShares(0x3432B6A60D23Ca0dFCa7761B7ab56459D9C964D0); giveback_collateral_address = _giveback_collateral_address; giveback_collateral = ERC20(_giveback_collateral_address); missing_decimals_giveback_collat = uint(18).sub(giveback_collateral.decimals()); collateral_addresses.push(_giveback_collateral_address); allowed_collaterals[_giveback_collateral_address] = true; univ3_factory = IUniswapV3Factory(0x1F98431c8aD98523631AE4a59f267346ea31F984); univ3_positions = INonfungiblePositionManager(0xC36442b4a4522E871399CD717aBDD847Ab11FE88); univ3_router = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564); // Initialize the minter amo_minter = IFraxAMOMinter(_amo_minter_address); // Get the custodian and timelock addresses from the minter custodian_address = amo_minter.custodian_address(); timelock_address = amo_minter.timelock_address(); } /* ========== MODIFIERS ========== */ modifier onlyByOwnGov() { require(msg.sender == timelock_address || msg.sender == owner, "Not owner or timelock"); _; } modifier onlyByOwnGovCust() { require(msg.sender == timelock_address || msg.sender == owner || msg.sender == custodian_address, "Not owner, tlck, or custd"); _; } modifier onlyByMinter() { require(msg.sender == address(amo_minter), "Not minter"); _; } /* ========== VIEWS ========== */ function showAllocations() public view returns (uint256[4] memory allocations) { // All numbers given are in FRAX unless otherwise stated // Unallocated FRAX allocations[0] = FRAX.balanceOf(address(this)); // Unallocated Collateral Dollar Value (E18) allocations[1] = freeColDolVal(); // Sum of Uni v3 Positions liquidity, if it was all in FRAX allocations[2] = TotalLiquidityFrax(); // Total Value allocations[3] = allocations[0].add(allocations[1]).add(allocations[2]); } // E18 Collateral dollar value function freeColDolVal() public view returns (uint256) { uint256 value_tally_e18 = 0; for (uint i = 0; i < collateral_addresses.length; i++){ ERC20 thisCollateral = ERC20(collateral_addresses[i]); uint256 missing_decs = uint256(18).sub(thisCollateral.decimals()); uint256 col_bal_e18 = thisCollateral.balanceOf(address(this)).mul(10 ** missing_decs); uint256 col_usd_value_e18 = collatDolarValue(oracles[collateral_addresses[i]], col_bal_e18); value_tally_e18 = value_tally_e18.add(col_usd_value_e18); } return value_tally_e18; } // Convert collateral to dolar. If no oracle assumes pegged to 1USD. Both oracle, balance and return are E18 function collatDolarValue(OracleLike oracle, uint256 balance) public view returns (uint256) { if (address(oracle) == address(0)) return balance; return balance.mul(oracle.read()).div(1 ether); } // Needed for the Frax contract to function function collatDollarBalance() public view returns (uint256) { // Get the allocations uint256[4] memory allocations = showAllocations(); // Get the collateral and FRAX portions uint256 collat_portion = allocations[1]; uint256 frax_portion = (allocations[0]).add(allocations[2]); // Assumes worst case scenario if FRAX slips out of range. // Otherwise, it would only be half that is multiplied by the CR frax_portion = frax_portion.mul(FRAX.global_collateral_ratio()).div(PRICE_PRECISION); return (collat_portion).add(frax_portion); } function dollarBalances() public view returns (uint256 frax_val_e18, uint256 collat_val_e18) { frax_val_e18 = showAllocations()[3]; collat_val_e18 = collatDollarBalance(); } function TotalLiquidityFrax() public view returns (uint256) { uint256 frax_tally = 0; Position memory thisPosition; for (uint256 i = 0; i < positions_array.length; i++) { thisPosition = positions_array[i]; uint128 this_liq = thisPosition.liquidity; if (this_liq > 0){ uint160 sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(thisPosition.tickLower); uint160 sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(thisPosition.tickUpper); if (thisPosition.collateral_address > 0x853d955aCEf822Db058eb8505911ED77F175b99e){ // if address(FRAX) < collateral_address, then FRAX is token0 frax_tally = frax_tally.add(LiquidityAmounts.getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, this_liq)); } else { frax_tally = frax_tally.add(LiquidityAmounts.getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, this_liq)); } } } // Return the sum of all the positions' balances of FRAX, if the price fell off the range towards that side return frax_tally; } // Returns this contract's liquidity in a specific [FRAX]-[collateral] uni v3 pool function liquidityInPool(address _collateral_address, int24 _tickLower, int24 _tickUpper, uint24 _fee) public view returns (uint128) { IUniswapV3Pool get_pool = IUniswapV3Pool(univ3_factory.getPool(address(FRAX), _collateral_address, _fee)); // goes into the pool's positions mapping, and grabs this address's liquidity (uint128 liquidity, , , , ) = get_pool.positions(keccak256(abi.encodePacked(address(this), _tickLower, _tickUpper))); return liquidity; } // Backwards compatibility function mintedBalance() public view returns (int256) { return amo_minter.frax_mint_balances(address(this)); } // Backwards compatibility function collateralBalance() public view returns (int256) { return amo_minter.collat_borrowed_balances(address(this)); } // Only counts non-withdrawn positions function numPositions() public view returns (uint256) { return positions_array.length; } function allCollateralAddresses() external view returns (address[] memory) { return collateral_addresses; } /* ========== RESTRICTED FUNCTIONS, BUT CUSTODIAN CAN CALL ========== */ // Iterate through all positions and collect fees accumulated function collectFees() external onlyByOwnGovCust { for (uint i = 0; i < positions_array.length; i++){ Position memory current_position = positions_array[i]; INonfungiblePositionManager.CollectParams memory collect_params = INonfungiblePositionManager.CollectParams( current_position.token_id, custodian_address, type(uint128).max, type(uint128).max ); // Send to custodian address univ3_positions.collect(collect_params); } } /* ---------------------------------------------------- */ /* ---------------------- Uni v3 ---------------------- */ /* ---------------------------------------------------- */ function approveTarget(address _target, address _token, uint256 _amount, bool use_safe_approve) public onlyByOwnGov { if (use_safe_approve) { // safeApprove needed for USDT and others for the first approval // You need to approve 0 every time beforehand for USDT: it resets TransferHelper.safeApprove(_token, _target, _amount); } else { ERC20(_token).approve(_target, _amount); } } // IUniswapV3Pool public current_uni_pool; // only used for mint callback; is set and accessed during execution of addLiquidity() function addLiquidity(address _tokenA, address _tokenB, int24 _tickLower, int24 _tickUpper, uint24 _fee, uint256 _amount0Desired, uint256 _amount1Desired, uint256 _amount0Min, uint256 _amount1Min) public onlyByOwnGov { // Make sure the collateral is allowed require(allowed_collaterals[_tokenA] || _tokenA == address(FRAX), "TokenA not allowed"); require(allowed_collaterals[_tokenB] || _tokenB == address(FRAX), "TokenB not allowed"); ERC20(_tokenA).transferFrom(msg.sender, address(this), _amount0Desired); ERC20(_tokenB).transferFrom(msg.sender, address(this), _amount1Desired); ERC20(_tokenA).approve(address(univ3_positions), _amount0Desired); ERC20(_tokenB).approve(address(univ3_positions), _amount1Desired); INonfungiblePositionManager.MintParams memory params = INonfungiblePositionManager.MintParams( _tokenA, _tokenB, _fee, _tickLower, _tickUpper, _amount0Desired, _amount1Desired, _amount0Min, _amount1Min, address(this), block.timestamp ); (uint256 tokenId, uint128 amountLiquidity,,) = univ3_positions.mint(params); Position memory pos = Position( tokenId, _tokenA == address(FRAX) ? _tokenB : _tokenA, amountLiquidity, _tickLower, _tickUpper, _fee ); positions_array.push(pos); positions_mapping[tokenId] = pos; } /* ** burn tokenAmount from the recipient and send tokens to the receipient */ event log(uint); function removeLiquidity(uint256 positionIndex) public onlyByOwnGov { Position memory pos = positions_array[positionIndex]; INonfungiblePositionManager.CollectParams memory collect_params = INonfungiblePositionManager.CollectParams( pos.token_id, custodian_address, type(uint128).max, type(uint128).max ); univ3_positions.collect(collect_params); univ3_positions.burn(pos.token_id); positions_array[positionIndex] = positions_array[positions_array.length -1]; positions_array.pop(); delete positions_mapping[pos.token_id]; emit log(positions_array.length); emit log(positions_mapping[pos.token_id].token_id); } // Swap tokenA into tokenB using univ3_router.ExactInputSingle() // Uni V3 only function swap(address _tokenA, address _tokenB, uint24 _fee_tier, uint256 _amountAtoB, uint256 _amountOutMinimum, uint160 _sqrtPriceLimitX96) public onlyByOwnGov returns (uint256) { // Make sure the collateral is allowed require(allowed_collaterals[_tokenA] || _tokenA == address(FRAX), "TokenA not allowed"); require(allowed_collaterals[_tokenB] || _tokenB == address(FRAX), "TokenB not allowed"); ISwapRouter.ExactInputSingleParams memory swap_params = ISwapRouter.ExactInputSingleParams( _tokenA, _tokenB, _fee_tier, address(this), 2105300114, // Expiration: a long time from now _amountAtoB, _amountOutMinimum, _sqrtPriceLimitX96 ); // Approval TransferHelper.safeApprove(_tokenA, address(univ3_router), _amountAtoB); uint256 amountOut = univ3_router.exactInputSingle(swap_params); return amountOut; } /* ========== Burns and givebacks ========== */ // Give USDC profits back. Goes through the minter function giveCollatBack(uint256 collat_amount) external onlyByOwnGovCust { giveback_collateral.approve(address(amo_minter), collat_amount); amo_minter.receiveCollatFromAMO(collat_amount); } // Burn unneeded or excess FRAX. Goes through the minter function burnFRAX(uint256 frax_amount) public onlyByOwnGovCust { FRAX.approve(address(amo_minter), frax_amount); amo_minter.burnFraxFromAMO(frax_amount); } // Burn unneeded FXS. Goes through the minter function burnFXS(uint256 fxs_amount) public onlyByOwnGovCust { FXS.approve(address(amo_minter), fxs_amount); amo_minter.burnFxsFromAMO(fxs_amount); } /* ========== OWNER / GOVERNANCE FUNCTIONS ONLY ========== */ // Only owner or timelock can call, to limit risk // Adds collateral addresses supported. Needed to make sure dollarBalances is correct function addCollateral(address collat_addr) public onlyByOwnGov { require(collat_addr != address(0), "Zero address detected"); require(collat_addr != address(FRAX), "FRAX is not collateral"); require(allowed_collaterals[collat_addr] == false, "Address already exists"); allowed_collaterals[collat_addr] = true; collateral_addresses.push(collat_addr); } // Adds oracle for collateral. Optional for 1usd pegged coins. function addOracle(address collat_addr, address oracle) public onlyByOwnGov { require(collat_addr != address(0), "Zero address detected"); require(collat_addr != address(FRAX), "FRAX is not collateral"); oracles[collat_addr] = OracleLike(oracle); } function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov { // Can only be triggered by owner or governance, not custodian // Tokens are sent to the custodian, as a sort of safeguard TransferHelper.safeTransfer(tokenAddress, custodian_address, tokenAmount); emit RecoveredERC20(tokenAddress, tokenAmount); } function recoverERC721(address tokenAddress, uint256 token_id) external onlyByOwnGov { // Only the owner address can ever receive the recovery withdrawal // INonfungiblePositionManager inherits IERC721 so the latter does not need to be imported INonfungiblePositionManager(tokenAddress).safeTransferFrom( address(this), custodian_address, token_id); emit RecoveredERC721(tokenAddress, token_id); } // Generic proxy function execute( address _to, uint256 _value, bytes calldata _data ) external onlyByOwnGov returns (bool, bytes memory) { (bool success, bytes memory result) = _to.call{value:_value}(_data); return (success, result); } /* ========== EVENTS ========== */ event RecoveredERC20(address token, uint256 amount); event RecoveredERC721(address token, uint256 id); }
approveTarget
function approveTarget(address _target, address _token, uint256 _amount, bool use_safe_approve) public onlyByOwnGov { if (use_safe_approve) { // safeApprove needed for USDT and others for the first approval // You need to approve 0 every time beforehand for USDT: it resets TransferHelper.safeApprove(_token, _target, _amount); } else { ERC20(_token).approve(_target, _amount); } }
/* ---------------------------------------------------- */
Comment
v0.8.6+commit.11564f7e
{ "func_code_index": [ 9046, 9515 ] }
804
UniV3LiquidityAMO_V2
contracts/Misc_AMOs/UniV3LiquidityAMO_V2.sol
0xc91bb4b0696e3b48c0c501b4ce8e7244fc363a79
Solidity
UniV3LiquidityAMO_V2
contract UniV3LiquidityAMO_V2 is Owned { using SafeMath for uint256; using SafeERC20 for ERC20; /* ========== STATE VARIABLES ========== */ // Core FRAXStablecoin private FRAX; FRAXShares private FXS; IFraxAMOMinter private amo_minter; ERC20 private giveback_collateral; address public giveback_collateral_address; uint256 public missing_decimals_giveback_collat; address public timelock_address; address public custodian_address; // Uniswap v3 IUniswapV3Factory public univ3_factory; INonfungiblePositionManager public univ3_positions; ISwapRouter public univ3_router; // Price constants uint256 private constant PRICE_PRECISION = 1e6; // Wildcat AMO // Details about the AMO's uniswap positions struct Position { uint256 token_id; address collateral_address; uint128 liquidity; // the liquidity of the position int24 tickLower; // the tick range of the position int24 tickUpper; uint24 fee_tier; } // Array of all Uni v3 NFT positions held by the AMO Position[] public positions_array; // List of all collaterals address[] public collateral_addresses; mapping(address => bool) public allowed_collaterals; // Mapping is also used for faster verification mapping(address => OracleLike) public oracles; // Mapping of oracles (if oracle == address(0) the collateral is assumed to be pegged to 1usd) // Map token_id to Position mapping(uint256 => Position) public positions_mapping; /* ========== CONSTRUCTOR ========== */ constructor( address _creator_address, address _giveback_collateral_address, address _amo_minter_address ) Owned(_creator_address) { FRAX = FRAXStablecoin(0x853d955aCEf822Db058eb8505911ED77F175b99e); FXS = FRAXShares(0x3432B6A60D23Ca0dFCa7761B7ab56459D9C964D0); giveback_collateral_address = _giveback_collateral_address; giveback_collateral = ERC20(_giveback_collateral_address); missing_decimals_giveback_collat = uint(18).sub(giveback_collateral.decimals()); collateral_addresses.push(_giveback_collateral_address); allowed_collaterals[_giveback_collateral_address] = true; univ3_factory = IUniswapV3Factory(0x1F98431c8aD98523631AE4a59f267346ea31F984); univ3_positions = INonfungiblePositionManager(0xC36442b4a4522E871399CD717aBDD847Ab11FE88); univ3_router = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564); // Initialize the minter amo_minter = IFraxAMOMinter(_amo_minter_address); // Get the custodian and timelock addresses from the minter custodian_address = amo_minter.custodian_address(); timelock_address = amo_minter.timelock_address(); } /* ========== MODIFIERS ========== */ modifier onlyByOwnGov() { require(msg.sender == timelock_address || msg.sender == owner, "Not owner or timelock"); _; } modifier onlyByOwnGovCust() { require(msg.sender == timelock_address || msg.sender == owner || msg.sender == custodian_address, "Not owner, tlck, or custd"); _; } modifier onlyByMinter() { require(msg.sender == address(amo_minter), "Not minter"); _; } /* ========== VIEWS ========== */ function showAllocations() public view returns (uint256[4] memory allocations) { // All numbers given are in FRAX unless otherwise stated // Unallocated FRAX allocations[0] = FRAX.balanceOf(address(this)); // Unallocated Collateral Dollar Value (E18) allocations[1] = freeColDolVal(); // Sum of Uni v3 Positions liquidity, if it was all in FRAX allocations[2] = TotalLiquidityFrax(); // Total Value allocations[3] = allocations[0].add(allocations[1]).add(allocations[2]); } // E18 Collateral dollar value function freeColDolVal() public view returns (uint256) { uint256 value_tally_e18 = 0; for (uint i = 0; i < collateral_addresses.length; i++){ ERC20 thisCollateral = ERC20(collateral_addresses[i]); uint256 missing_decs = uint256(18).sub(thisCollateral.decimals()); uint256 col_bal_e18 = thisCollateral.balanceOf(address(this)).mul(10 ** missing_decs); uint256 col_usd_value_e18 = collatDolarValue(oracles[collateral_addresses[i]], col_bal_e18); value_tally_e18 = value_tally_e18.add(col_usd_value_e18); } return value_tally_e18; } // Convert collateral to dolar. If no oracle assumes pegged to 1USD. Both oracle, balance and return are E18 function collatDolarValue(OracleLike oracle, uint256 balance) public view returns (uint256) { if (address(oracle) == address(0)) return balance; return balance.mul(oracle.read()).div(1 ether); } // Needed for the Frax contract to function function collatDollarBalance() public view returns (uint256) { // Get the allocations uint256[4] memory allocations = showAllocations(); // Get the collateral and FRAX portions uint256 collat_portion = allocations[1]; uint256 frax_portion = (allocations[0]).add(allocations[2]); // Assumes worst case scenario if FRAX slips out of range. // Otherwise, it would only be half that is multiplied by the CR frax_portion = frax_portion.mul(FRAX.global_collateral_ratio()).div(PRICE_PRECISION); return (collat_portion).add(frax_portion); } function dollarBalances() public view returns (uint256 frax_val_e18, uint256 collat_val_e18) { frax_val_e18 = showAllocations()[3]; collat_val_e18 = collatDollarBalance(); } function TotalLiquidityFrax() public view returns (uint256) { uint256 frax_tally = 0; Position memory thisPosition; for (uint256 i = 0; i < positions_array.length; i++) { thisPosition = positions_array[i]; uint128 this_liq = thisPosition.liquidity; if (this_liq > 0){ uint160 sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(thisPosition.tickLower); uint160 sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(thisPosition.tickUpper); if (thisPosition.collateral_address > 0x853d955aCEf822Db058eb8505911ED77F175b99e){ // if address(FRAX) < collateral_address, then FRAX is token0 frax_tally = frax_tally.add(LiquidityAmounts.getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, this_liq)); } else { frax_tally = frax_tally.add(LiquidityAmounts.getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, this_liq)); } } } // Return the sum of all the positions' balances of FRAX, if the price fell off the range towards that side return frax_tally; } // Returns this contract's liquidity in a specific [FRAX]-[collateral] uni v3 pool function liquidityInPool(address _collateral_address, int24 _tickLower, int24 _tickUpper, uint24 _fee) public view returns (uint128) { IUniswapV3Pool get_pool = IUniswapV3Pool(univ3_factory.getPool(address(FRAX), _collateral_address, _fee)); // goes into the pool's positions mapping, and grabs this address's liquidity (uint128 liquidity, , , , ) = get_pool.positions(keccak256(abi.encodePacked(address(this), _tickLower, _tickUpper))); return liquidity; } // Backwards compatibility function mintedBalance() public view returns (int256) { return amo_minter.frax_mint_balances(address(this)); } // Backwards compatibility function collateralBalance() public view returns (int256) { return amo_minter.collat_borrowed_balances(address(this)); } // Only counts non-withdrawn positions function numPositions() public view returns (uint256) { return positions_array.length; } function allCollateralAddresses() external view returns (address[] memory) { return collateral_addresses; } /* ========== RESTRICTED FUNCTIONS, BUT CUSTODIAN CAN CALL ========== */ // Iterate through all positions and collect fees accumulated function collectFees() external onlyByOwnGovCust { for (uint i = 0; i < positions_array.length; i++){ Position memory current_position = positions_array[i]; INonfungiblePositionManager.CollectParams memory collect_params = INonfungiblePositionManager.CollectParams( current_position.token_id, custodian_address, type(uint128).max, type(uint128).max ); // Send to custodian address univ3_positions.collect(collect_params); } } /* ---------------------------------------------------- */ /* ---------------------- Uni v3 ---------------------- */ /* ---------------------------------------------------- */ function approveTarget(address _target, address _token, uint256 _amount, bool use_safe_approve) public onlyByOwnGov { if (use_safe_approve) { // safeApprove needed for USDT and others for the first approval // You need to approve 0 every time beforehand for USDT: it resets TransferHelper.safeApprove(_token, _target, _amount); } else { ERC20(_token).approve(_target, _amount); } } // IUniswapV3Pool public current_uni_pool; // only used for mint callback; is set and accessed during execution of addLiquidity() function addLiquidity(address _tokenA, address _tokenB, int24 _tickLower, int24 _tickUpper, uint24 _fee, uint256 _amount0Desired, uint256 _amount1Desired, uint256 _amount0Min, uint256 _amount1Min) public onlyByOwnGov { // Make sure the collateral is allowed require(allowed_collaterals[_tokenA] || _tokenA == address(FRAX), "TokenA not allowed"); require(allowed_collaterals[_tokenB] || _tokenB == address(FRAX), "TokenB not allowed"); ERC20(_tokenA).transferFrom(msg.sender, address(this), _amount0Desired); ERC20(_tokenB).transferFrom(msg.sender, address(this), _amount1Desired); ERC20(_tokenA).approve(address(univ3_positions), _amount0Desired); ERC20(_tokenB).approve(address(univ3_positions), _amount1Desired); INonfungiblePositionManager.MintParams memory params = INonfungiblePositionManager.MintParams( _tokenA, _tokenB, _fee, _tickLower, _tickUpper, _amount0Desired, _amount1Desired, _amount0Min, _amount1Min, address(this), block.timestamp ); (uint256 tokenId, uint128 amountLiquidity,,) = univ3_positions.mint(params); Position memory pos = Position( tokenId, _tokenA == address(FRAX) ? _tokenB : _tokenA, amountLiquidity, _tickLower, _tickUpper, _fee ); positions_array.push(pos); positions_mapping[tokenId] = pos; } /* ** burn tokenAmount from the recipient and send tokens to the receipient */ event log(uint); function removeLiquidity(uint256 positionIndex) public onlyByOwnGov { Position memory pos = positions_array[positionIndex]; INonfungiblePositionManager.CollectParams memory collect_params = INonfungiblePositionManager.CollectParams( pos.token_id, custodian_address, type(uint128).max, type(uint128).max ); univ3_positions.collect(collect_params); univ3_positions.burn(pos.token_id); positions_array[positionIndex] = positions_array[positions_array.length -1]; positions_array.pop(); delete positions_mapping[pos.token_id]; emit log(positions_array.length); emit log(positions_mapping[pos.token_id].token_id); } // Swap tokenA into tokenB using univ3_router.ExactInputSingle() // Uni V3 only function swap(address _tokenA, address _tokenB, uint24 _fee_tier, uint256 _amountAtoB, uint256 _amountOutMinimum, uint160 _sqrtPriceLimitX96) public onlyByOwnGov returns (uint256) { // Make sure the collateral is allowed require(allowed_collaterals[_tokenA] || _tokenA == address(FRAX), "TokenA not allowed"); require(allowed_collaterals[_tokenB] || _tokenB == address(FRAX), "TokenB not allowed"); ISwapRouter.ExactInputSingleParams memory swap_params = ISwapRouter.ExactInputSingleParams( _tokenA, _tokenB, _fee_tier, address(this), 2105300114, // Expiration: a long time from now _amountAtoB, _amountOutMinimum, _sqrtPriceLimitX96 ); // Approval TransferHelper.safeApprove(_tokenA, address(univ3_router), _amountAtoB); uint256 amountOut = univ3_router.exactInputSingle(swap_params); return amountOut; } /* ========== Burns and givebacks ========== */ // Give USDC profits back. Goes through the minter function giveCollatBack(uint256 collat_amount) external onlyByOwnGovCust { giveback_collateral.approve(address(amo_minter), collat_amount); amo_minter.receiveCollatFromAMO(collat_amount); } // Burn unneeded or excess FRAX. Goes through the minter function burnFRAX(uint256 frax_amount) public onlyByOwnGovCust { FRAX.approve(address(amo_minter), frax_amount); amo_minter.burnFraxFromAMO(frax_amount); } // Burn unneeded FXS. Goes through the minter function burnFXS(uint256 fxs_amount) public onlyByOwnGovCust { FXS.approve(address(amo_minter), fxs_amount); amo_minter.burnFxsFromAMO(fxs_amount); } /* ========== OWNER / GOVERNANCE FUNCTIONS ONLY ========== */ // Only owner or timelock can call, to limit risk // Adds collateral addresses supported. Needed to make sure dollarBalances is correct function addCollateral(address collat_addr) public onlyByOwnGov { require(collat_addr != address(0), "Zero address detected"); require(collat_addr != address(FRAX), "FRAX is not collateral"); require(allowed_collaterals[collat_addr] == false, "Address already exists"); allowed_collaterals[collat_addr] = true; collateral_addresses.push(collat_addr); } // Adds oracle for collateral. Optional for 1usd pegged coins. function addOracle(address collat_addr, address oracle) public onlyByOwnGov { require(collat_addr != address(0), "Zero address detected"); require(collat_addr != address(FRAX), "FRAX is not collateral"); oracles[collat_addr] = OracleLike(oracle); } function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov { // Can only be triggered by owner or governance, not custodian // Tokens are sent to the custodian, as a sort of safeguard TransferHelper.safeTransfer(tokenAddress, custodian_address, tokenAmount); emit RecoveredERC20(tokenAddress, tokenAmount); } function recoverERC721(address tokenAddress, uint256 token_id) external onlyByOwnGov { // Only the owner address can ever receive the recovery withdrawal // INonfungiblePositionManager inherits IERC721 so the latter does not need to be imported INonfungiblePositionManager(tokenAddress).safeTransferFrom( address(this), custodian_address, token_id); emit RecoveredERC721(tokenAddress, token_id); } // Generic proxy function execute( address _to, uint256 _value, bytes calldata _data ) external onlyByOwnGov returns (bool, bytes memory) { (bool success, bytes memory result) = _to.call{value:_value}(_data); return (success, result); } /* ========== EVENTS ========== */ event RecoveredERC20(address token, uint256 amount); event RecoveredERC721(address token, uint256 id); }
addLiquidity
function addLiquidity(address _tokenA, address _tokenB, int24 _tickLower, int24 _tickUpper, uint24 _fee, uint256 _amount0Desired, uint256 _amount1Desired, uint256 _amount0Min, uint256 _amount1Min) public onlyByOwnGov { // Make sure the collateral is allowed require(allowed_collaterals[_tokenA] || _tokenA == address(FRAX), "TokenA not allowed"); require(allowed_collaterals[_tokenB] || _tokenB == address(FRAX), "TokenB not allowed"); ERC20(_tokenA).transferFrom(msg.sender, address(this), _amount0Desired); ERC20(_tokenB).transferFrom(msg.sender, address(this), _amount1Desired); ERC20(_tokenA).approve(address(univ3_positions), _amount0Desired); ERC20(_tokenB).approve(address(univ3_positions), _amount1Desired); INonfungiblePositionManager.MintParams memory params = INonfungiblePositionManager.MintParams( _tokenA, _tokenB, _fee, _tickLower, _tickUpper, _amount0Desired, _amount1Desired, _amount0Min, _amount1Min, address(this), block.timestamp ); (uint256 tokenId, uint128 amountLiquidity,,) = univ3_positions.mint(params); Position memory pos = Position( tokenId, _tokenA == address(FRAX) ? _tokenB : _tokenA, amountLiquidity, _tickLower, _tickUpper, _fee ); positions_array.push(pos); positions_mapping[tokenId] = pos; }
// IUniswapV3Pool public current_uni_pool; // only used for mint callback; is set and accessed during execution of addLiquidity()
LineComment
v0.8.6+commit.11564f7e
{ "func_code_index": [ 9651, 11208 ] }
805
UniV3LiquidityAMO_V2
contracts/Misc_AMOs/UniV3LiquidityAMO_V2.sol
0xc91bb4b0696e3b48c0c501b4ce8e7244fc363a79
Solidity
UniV3LiquidityAMO_V2
contract UniV3LiquidityAMO_V2 is Owned { using SafeMath for uint256; using SafeERC20 for ERC20; /* ========== STATE VARIABLES ========== */ // Core FRAXStablecoin private FRAX; FRAXShares private FXS; IFraxAMOMinter private amo_minter; ERC20 private giveback_collateral; address public giveback_collateral_address; uint256 public missing_decimals_giveback_collat; address public timelock_address; address public custodian_address; // Uniswap v3 IUniswapV3Factory public univ3_factory; INonfungiblePositionManager public univ3_positions; ISwapRouter public univ3_router; // Price constants uint256 private constant PRICE_PRECISION = 1e6; // Wildcat AMO // Details about the AMO's uniswap positions struct Position { uint256 token_id; address collateral_address; uint128 liquidity; // the liquidity of the position int24 tickLower; // the tick range of the position int24 tickUpper; uint24 fee_tier; } // Array of all Uni v3 NFT positions held by the AMO Position[] public positions_array; // List of all collaterals address[] public collateral_addresses; mapping(address => bool) public allowed_collaterals; // Mapping is also used for faster verification mapping(address => OracleLike) public oracles; // Mapping of oracles (if oracle == address(0) the collateral is assumed to be pegged to 1usd) // Map token_id to Position mapping(uint256 => Position) public positions_mapping; /* ========== CONSTRUCTOR ========== */ constructor( address _creator_address, address _giveback_collateral_address, address _amo_minter_address ) Owned(_creator_address) { FRAX = FRAXStablecoin(0x853d955aCEf822Db058eb8505911ED77F175b99e); FXS = FRAXShares(0x3432B6A60D23Ca0dFCa7761B7ab56459D9C964D0); giveback_collateral_address = _giveback_collateral_address; giveback_collateral = ERC20(_giveback_collateral_address); missing_decimals_giveback_collat = uint(18).sub(giveback_collateral.decimals()); collateral_addresses.push(_giveback_collateral_address); allowed_collaterals[_giveback_collateral_address] = true; univ3_factory = IUniswapV3Factory(0x1F98431c8aD98523631AE4a59f267346ea31F984); univ3_positions = INonfungiblePositionManager(0xC36442b4a4522E871399CD717aBDD847Ab11FE88); univ3_router = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564); // Initialize the minter amo_minter = IFraxAMOMinter(_amo_minter_address); // Get the custodian and timelock addresses from the minter custodian_address = amo_minter.custodian_address(); timelock_address = amo_minter.timelock_address(); } /* ========== MODIFIERS ========== */ modifier onlyByOwnGov() { require(msg.sender == timelock_address || msg.sender == owner, "Not owner or timelock"); _; } modifier onlyByOwnGovCust() { require(msg.sender == timelock_address || msg.sender == owner || msg.sender == custodian_address, "Not owner, tlck, or custd"); _; } modifier onlyByMinter() { require(msg.sender == address(amo_minter), "Not minter"); _; } /* ========== VIEWS ========== */ function showAllocations() public view returns (uint256[4] memory allocations) { // All numbers given are in FRAX unless otherwise stated // Unallocated FRAX allocations[0] = FRAX.balanceOf(address(this)); // Unallocated Collateral Dollar Value (E18) allocations[1] = freeColDolVal(); // Sum of Uni v3 Positions liquidity, if it was all in FRAX allocations[2] = TotalLiquidityFrax(); // Total Value allocations[3] = allocations[0].add(allocations[1]).add(allocations[2]); } // E18 Collateral dollar value function freeColDolVal() public view returns (uint256) { uint256 value_tally_e18 = 0; for (uint i = 0; i < collateral_addresses.length; i++){ ERC20 thisCollateral = ERC20(collateral_addresses[i]); uint256 missing_decs = uint256(18).sub(thisCollateral.decimals()); uint256 col_bal_e18 = thisCollateral.balanceOf(address(this)).mul(10 ** missing_decs); uint256 col_usd_value_e18 = collatDolarValue(oracles[collateral_addresses[i]], col_bal_e18); value_tally_e18 = value_tally_e18.add(col_usd_value_e18); } return value_tally_e18; } // Convert collateral to dolar. If no oracle assumes pegged to 1USD. Both oracle, balance and return are E18 function collatDolarValue(OracleLike oracle, uint256 balance) public view returns (uint256) { if (address(oracle) == address(0)) return balance; return balance.mul(oracle.read()).div(1 ether); } // Needed for the Frax contract to function function collatDollarBalance() public view returns (uint256) { // Get the allocations uint256[4] memory allocations = showAllocations(); // Get the collateral and FRAX portions uint256 collat_portion = allocations[1]; uint256 frax_portion = (allocations[0]).add(allocations[2]); // Assumes worst case scenario if FRAX slips out of range. // Otherwise, it would only be half that is multiplied by the CR frax_portion = frax_portion.mul(FRAX.global_collateral_ratio()).div(PRICE_PRECISION); return (collat_portion).add(frax_portion); } function dollarBalances() public view returns (uint256 frax_val_e18, uint256 collat_val_e18) { frax_val_e18 = showAllocations()[3]; collat_val_e18 = collatDollarBalance(); } function TotalLiquidityFrax() public view returns (uint256) { uint256 frax_tally = 0; Position memory thisPosition; for (uint256 i = 0; i < positions_array.length; i++) { thisPosition = positions_array[i]; uint128 this_liq = thisPosition.liquidity; if (this_liq > 0){ uint160 sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(thisPosition.tickLower); uint160 sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(thisPosition.tickUpper); if (thisPosition.collateral_address > 0x853d955aCEf822Db058eb8505911ED77F175b99e){ // if address(FRAX) < collateral_address, then FRAX is token0 frax_tally = frax_tally.add(LiquidityAmounts.getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, this_liq)); } else { frax_tally = frax_tally.add(LiquidityAmounts.getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, this_liq)); } } } // Return the sum of all the positions' balances of FRAX, if the price fell off the range towards that side return frax_tally; } // Returns this contract's liquidity in a specific [FRAX]-[collateral] uni v3 pool function liquidityInPool(address _collateral_address, int24 _tickLower, int24 _tickUpper, uint24 _fee) public view returns (uint128) { IUniswapV3Pool get_pool = IUniswapV3Pool(univ3_factory.getPool(address(FRAX), _collateral_address, _fee)); // goes into the pool's positions mapping, and grabs this address's liquidity (uint128 liquidity, , , , ) = get_pool.positions(keccak256(abi.encodePacked(address(this), _tickLower, _tickUpper))); return liquidity; } // Backwards compatibility function mintedBalance() public view returns (int256) { return amo_minter.frax_mint_balances(address(this)); } // Backwards compatibility function collateralBalance() public view returns (int256) { return amo_minter.collat_borrowed_balances(address(this)); } // Only counts non-withdrawn positions function numPositions() public view returns (uint256) { return positions_array.length; } function allCollateralAddresses() external view returns (address[] memory) { return collateral_addresses; } /* ========== RESTRICTED FUNCTIONS, BUT CUSTODIAN CAN CALL ========== */ // Iterate through all positions and collect fees accumulated function collectFees() external onlyByOwnGovCust { for (uint i = 0; i < positions_array.length; i++){ Position memory current_position = positions_array[i]; INonfungiblePositionManager.CollectParams memory collect_params = INonfungiblePositionManager.CollectParams( current_position.token_id, custodian_address, type(uint128).max, type(uint128).max ); // Send to custodian address univ3_positions.collect(collect_params); } } /* ---------------------------------------------------- */ /* ---------------------- Uni v3 ---------------------- */ /* ---------------------------------------------------- */ function approveTarget(address _target, address _token, uint256 _amount, bool use_safe_approve) public onlyByOwnGov { if (use_safe_approve) { // safeApprove needed for USDT and others for the first approval // You need to approve 0 every time beforehand for USDT: it resets TransferHelper.safeApprove(_token, _target, _amount); } else { ERC20(_token).approve(_target, _amount); } } // IUniswapV3Pool public current_uni_pool; // only used for mint callback; is set and accessed during execution of addLiquidity() function addLiquidity(address _tokenA, address _tokenB, int24 _tickLower, int24 _tickUpper, uint24 _fee, uint256 _amount0Desired, uint256 _amount1Desired, uint256 _amount0Min, uint256 _amount1Min) public onlyByOwnGov { // Make sure the collateral is allowed require(allowed_collaterals[_tokenA] || _tokenA == address(FRAX), "TokenA not allowed"); require(allowed_collaterals[_tokenB] || _tokenB == address(FRAX), "TokenB not allowed"); ERC20(_tokenA).transferFrom(msg.sender, address(this), _amount0Desired); ERC20(_tokenB).transferFrom(msg.sender, address(this), _amount1Desired); ERC20(_tokenA).approve(address(univ3_positions), _amount0Desired); ERC20(_tokenB).approve(address(univ3_positions), _amount1Desired); INonfungiblePositionManager.MintParams memory params = INonfungiblePositionManager.MintParams( _tokenA, _tokenB, _fee, _tickLower, _tickUpper, _amount0Desired, _amount1Desired, _amount0Min, _amount1Min, address(this), block.timestamp ); (uint256 tokenId, uint128 amountLiquidity,,) = univ3_positions.mint(params); Position memory pos = Position( tokenId, _tokenA == address(FRAX) ? _tokenB : _tokenA, amountLiquidity, _tickLower, _tickUpper, _fee ); positions_array.push(pos); positions_mapping[tokenId] = pos; } /* ** burn tokenAmount from the recipient and send tokens to the receipient */ event log(uint); function removeLiquidity(uint256 positionIndex) public onlyByOwnGov { Position memory pos = positions_array[positionIndex]; INonfungiblePositionManager.CollectParams memory collect_params = INonfungiblePositionManager.CollectParams( pos.token_id, custodian_address, type(uint128).max, type(uint128).max ); univ3_positions.collect(collect_params); univ3_positions.burn(pos.token_id); positions_array[positionIndex] = positions_array[positions_array.length -1]; positions_array.pop(); delete positions_mapping[pos.token_id]; emit log(positions_array.length); emit log(positions_mapping[pos.token_id].token_id); } // Swap tokenA into tokenB using univ3_router.ExactInputSingle() // Uni V3 only function swap(address _tokenA, address _tokenB, uint24 _fee_tier, uint256 _amountAtoB, uint256 _amountOutMinimum, uint160 _sqrtPriceLimitX96) public onlyByOwnGov returns (uint256) { // Make sure the collateral is allowed require(allowed_collaterals[_tokenA] || _tokenA == address(FRAX), "TokenA not allowed"); require(allowed_collaterals[_tokenB] || _tokenB == address(FRAX), "TokenB not allowed"); ISwapRouter.ExactInputSingleParams memory swap_params = ISwapRouter.ExactInputSingleParams( _tokenA, _tokenB, _fee_tier, address(this), 2105300114, // Expiration: a long time from now _amountAtoB, _amountOutMinimum, _sqrtPriceLimitX96 ); // Approval TransferHelper.safeApprove(_tokenA, address(univ3_router), _amountAtoB); uint256 amountOut = univ3_router.exactInputSingle(swap_params); return amountOut; } /* ========== Burns and givebacks ========== */ // Give USDC profits back. Goes through the minter function giveCollatBack(uint256 collat_amount) external onlyByOwnGovCust { giveback_collateral.approve(address(amo_minter), collat_amount); amo_minter.receiveCollatFromAMO(collat_amount); } // Burn unneeded or excess FRAX. Goes through the minter function burnFRAX(uint256 frax_amount) public onlyByOwnGovCust { FRAX.approve(address(amo_minter), frax_amount); amo_minter.burnFraxFromAMO(frax_amount); } // Burn unneeded FXS. Goes through the minter function burnFXS(uint256 fxs_amount) public onlyByOwnGovCust { FXS.approve(address(amo_minter), fxs_amount); amo_minter.burnFxsFromAMO(fxs_amount); } /* ========== OWNER / GOVERNANCE FUNCTIONS ONLY ========== */ // Only owner or timelock can call, to limit risk // Adds collateral addresses supported. Needed to make sure dollarBalances is correct function addCollateral(address collat_addr) public onlyByOwnGov { require(collat_addr != address(0), "Zero address detected"); require(collat_addr != address(FRAX), "FRAX is not collateral"); require(allowed_collaterals[collat_addr] == false, "Address already exists"); allowed_collaterals[collat_addr] = true; collateral_addresses.push(collat_addr); } // Adds oracle for collateral. Optional for 1usd pegged coins. function addOracle(address collat_addr, address oracle) public onlyByOwnGov { require(collat_addr != address(0), "Zero address detected"); require(collat_addr != address(FRAX), "FRAX is not collateral"); oracles[collat_addr] = OracleLike(oracle); } function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov { // Can only be triggered by owner or governance, not custodian // Tokens are sent to the custodian, as a sort of safeguard TransferHelper.safeTransfer(tokenAddress, custodian_address, tokenAmount); emit RecoveredERC20(tokenAddress, tokenAmount); } function recoverERC721(address tokenAddress, uint256 token_id) external onlyByOwnGov { // Only the owner address can ever receive the recovery withdrawal // INonfungiblePositionManager inherits IERC721 so the latter does not need to be imported INonfungiblePositionManager(tokenAddress).safeTransferFrom( address(this), custodian_address, token_id); emit RecoveredERC721(tokenAddress, token_id); } // Generic proxy function execute( address _to, uint256 _value, bytes calldata _data ) external onlyByOwnGov returns (bool, bytes memory) { (bool success, bytes memory result) = _to.call{value:_value}(_data); return (success, result); } /* ========== EVENTS ========== */ event RecoveredERC20(address token, uint256 amount); event RecoveredERC721(address token, uint256 id); }
swap
function swap(address _tokenA, address _tokenB, uint24 _fee_tier, uint256 _amountAtoB, uint256 _amountOutMinimum, uint160 _sqrtPriceLimitX96) public onlyByOwnGov returns (uint256) { // Make sure the collateral is allowed require(allowed_collaterals[_tokenA] || _tokenA == address(FRAX), "TokenA not allowed"); require(allowed_collaterals[_tokenB] || _tokenB == address(FRAX), "TokenB not allowed"); ISwapRouter.ExactInputSingleParams memory swap_params = ISwapRouter.ExactInputSingleParams( _tokenA, _tokenB, _fee_tier, address(this), 2105300114, // Expiration: a long time from now _amountAtoB, _amountOutMinimum, _sqrtPriceLimitX96 ); // Approval TransferHelper.safeApprove(_tokenA, address(univ3_router), _amountAtoB); uint256 amountOut = univ3_router.exactInputSingle(swap_params); return amountOut; }
// Swap tokenA into tokenB using univ3_router.ExactInputSingle() // Uni V3 only
LineComment
v0.8.6+commit.11564f7e
{ "func_code_index": [ 12218, 13202 ] }
806
UniV3LiquidityAMO_V2
contracts/Misc_AMOs/UniV3LiquidityAMO_V2.sol
0xc91bb4b0696e3b48c0c501b4ce8e7244fc363a79
Solidity
UniV3LiquidityAMO_V2
contract UniV3LiquidityAMO_V2 is Owned { using SafeMath for uint256; using SafeERC20 for ERC20; /* ========== STATE VARIABLES ========== */ // Core FRAXStablecoin private FRAX; FRAXShares private FXS; IFraxAMOMinter private amo_minter; ERC20 private giveback_collateral; address public giveback_collateral_address; uint256 public missing_decimals_giveback_collat; address public timelock_address; address public custodian_address; // Uniswap v3 IUniswapV3Factory public univ3_factory; INonfungiblePositionManager public univ3_positions; ISwapRouter public univ3_router; // Price constants uint256 private constant PRICE_PRECISION = 1e6; // Wildcat AMO // Details about the AMO's uniswap positions struct Position { uint256 token_id; address collateral_address; uint128 liquidity; // the liquidity of the position int24 tickLower; // the tick range of the position int24 tickUpper; uint24 fee_tier; } // Array of all Uni v3 NFT positions held by the AMO Position[] public positions_array; // List of all collaterals address[] public collateral_addresses; mapping(address => bool) public allowed_collaterals; // Mapping is also used for faster verification mapping(address => OracleLike) public oracles; // Mapping of oracles (if oracle == address(0) the collateral is assumed to be pegged to 1usd) // Map token_id to Position mapping(uint256 => Position) public positions_mapping; /* ========== CONSTRUCTOR ========== */ constructor( address _creator_address, address _giveback_collateral_address, address _amo_minter_address ) Owned(_creator_address) { FRAX = FRAXStablecoin(0x853d955aCEf822Db058eb8505911ED77F175b99e); FXS = FRAXShares(0x3432B6A60D23Ca0dFCa7761B7ab56459D9C964D0); giveback_collateral_address = _giveback_collateral_address; giveback_collateral = ERC20(_giveback_collateral_address); missing_decimals_giveback_collat = uint(18).sub(giveback_collateral.decimals()); collateral_addresses.push(_giveback_collateral_address); allowed_collaterals[_giveback_collateral_address] = true; univ3_factory = IUniswapV3Factory(0x1F98431c8aD98523631AE4a59f267346ea31F984); univ3_positions = INonfungiblePositionManager(0xC36442b4a4522E871399CD717aBDD847Ab11FE88); univ3_router = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564); // Initialize the minter amo_minter = IFraxAMOMinter(_amo_minter_address); // Get the custodian and timelock addresses from the minter custodian_address = amo_minter.custodian_address(); timelock_address = amo_minter.timelock_address(); } /* ========== MODIFIERS ========== */ modifier onlyByOwnGov() { require(msg.sender == timelock_address || msg.sender == owner, "Not owner or timelock"); _; } modifier onlyByOwnGovCust() { require(msg.sender == timelock_address || msg.sender == owner || msg.sender == custodian_address, "Not owner, tlck, or custd"); _; } modifier onlyByMinter() { require(msg.sender == address(amo_minter), "Not minter"); _; } /* ========== VIEWS ========== */ function showAllocations() public view returns (uint256[4] memory allocations) { // All numbers given are in FRAX unless otherwise stated // Unallocated FRAX allocations[0] = FRAX.balanceOf(address(this)); // Unallocated Collateral Dollar Value (E18) allocations[1] = freeColDolVal(); // Sum of Uni v3 Positions liquidity, if it was all in FRAX allocations[2] = TotalLiquidityFrax(); // Total Value allocations[3] = allocations[0].add(allocations[1]).add(allocations[2]); } // E18 Collateral dollar value function freeColDolVal() public view returns (uint256) { uint256 value_tally_e18 = 0; for (uint i = 0; i < collateral_addresses.length; i++){ ERC20 thisCollateral = ERC20(collateral_addresses[i]); uint256 missing_decs = uint256(18).sub(thisCollateral.decimals()); uint256 col_bal_e18 = thisCollateral.balanceOf(address(this)).mul(10 ** missing_decs); uint256 col_usd_value_e18 = collatDolarValue(oracles[collateral_addresses[i]], col_bal_e18); value_tally_e18 = value_tally_e18.add(col_usd_value_e18); } return value_tally_e18; } // Convert collateral to dolar. If no oracle assumes pegged to 1USD. Both oracle, balance and return are E18 function collatDolarValue(OracleLike oracle, uint256 balance) public view returns (uint256) { if (address(oracle) == address(0)) return balance; return balance.mul(oracle.read()).div(1 ether); } // Needed for the Frax contract to function function collatDollarBalance() public view returns (uint256) { // Get the allocations uint256[4] memory allocations = showAllocations(); // Get the collateral and FRAX portions uint256 collat_portion = allocations[1]; uint256 frax_portion = (allocations[0]).add(allocations[2]); // Assumes worst case scenario if FRAX slips out of range. // Otherwise, it would only be half that is multiplied by the CR frax_portion = frax_portion.mul(FRAX.global_collateral_ratio()).div(PRICE_PRECISION); return (collat_portion).add(frax_portion); } function dollarBalances() public view returns (uint256 frax_val_e18, uint256 collat_val_e18) { frax_val_e18 = showAllocations()[3]; collat_val_e18 = collatDollarBalance(); } function TotalLiquidityFrax() public view returns (uint256) { uint256 frax_tally = 0; Position memory thisPosition; for (uint256 i = 0; i < positions_array.length; i++) { thisPosition = positions_array[i]; uint128 this_liq = thisPosition.liquidity; if (this_liq > 0){ uint160 sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(thisPosition.tickLower); uint160 sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(thisPosition.tickUpper); if (thisPosition.collateral_address > 0x853d955aCEf822Db058eb8505911ED77F175b99e){ // if address(FRAX) < collateral_address, then FRAX is token0 frax_tally = frax_tally.add(LiquidityAmounts.getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, this_liq)); } else { frax_tally = frax_tally.add(LiquidityAmounts.getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, this_liq)); } } } // Return the sum of all the positions' balances of FRAX, if the price fell off the range towards that side return frax_tally; } // Returns this contract's liquidity in a specific [FRAX]-[collateral] uni v3 pool function liquidityInPool(address _collateral_address, int24 _tickLower, int24 _tickUpper, uint24 _fee) public view returns (uint128) { IUniswapV3Pool get_pool = IUniswapV3Pool(univ3_factory.getPool(address(FRAX), _collateral_address, _fee)); // goes into the pool's positions mapping, and grabs this address's liquidity (uint128 liquidity, , , , ) = get_pool.positions(keccak256(abi.encodePacked(address(this), _tickLower, _tickUpper))); return liquidity; } // Backwards compatibility function mintedBalance() public view returns (int256) { return amo_minter.frax_mint_balances(address(this)); } // Backwards compatibility function collateralBalance() public view returns (int256) { return amo_minter.collat_borrowed_balances(address(this)); } // Only counts non-withdrawn positions function numPositions() public view returns (uint256) { return positions_array.length; } function allCollateralAddresses() external view returns (address[] memory) { return collateral_addresses; } /* ========== RESTRICTED FUNCTIONS, BUT CUSTODIAN CAN CALL ========== */ // Iterate through all positions and collect fees accumulated function collectFees() external onlyByOwnGovCust { for (uint i = 0; i < positions_array.length; i++){ Position memory current_position = positions_array[i]; INonfungiblePositionManager.CollectParams memory collect_params = INonfungiblePositionManager.CollectParams( current_position.token_id, custodian_address, type(uint128).max, type(uint128).max ); // Send to custodian address univ3_positions.collect(collect_params); } } /* ---------------------------------------------------- */ /* ---------------------- Uni v3 ---------------------- */ /* ---------------------------------------------------- */ function approveTarget(address _target, address _token, uint256 _amount, bool use_safe_approve) public onlyByOwnGov { if (use_safe_approve) { // safeApprove needed for USDT and others for the first approval // You need to approve 0 every time beforehand for USDT: it resets TransferHelper.safeApprove(_token, _target, _amount); } else { ERC20(_token).approve(_target, _amount); } } // IUniswapV3Pool public current_uni_pool; // only used for mint callback; is set and accessed during execution of addLiquidity() function addLiquidity(address _tokenA, address _tokenB, int24 _tickLower, int24 _tickUpper, uint24 _fee, uint256 _amount0Desired, uint256 _amount1Desired, uint256 _amount0Min, uint256 _amount1Min) public onlyByOwnGov { // Make sure the collateral is allowed require(allowed_collaterals[_tokenA] || _tokenA == address(FRAX), "TokenA not allowed"); require(allowed_collaterals[_tokenB] || _tokenB == address(FRAX), "TokenB not allowed"); ERC20(_tokenA).transferFrom(msg.sender, address(this), _amount0Desired); ERC20(_tokenB).transferFrom(msg.sender, address(this), _amount1Desired); ERC20(_tokenA).approve(address(univ3_positions), _amount0Desired); ERC20(_tokenB).approve(address(univ3_positions), _amount1Desired); INonfungiblePositionManager.MintParams memory params = INonfungiblePositionManager.MintParams( _tokenA, _tokenB, _fee, _tickLower, _tickUpper, _amount0Desired, _amount1Desired, _amount0Min, _amount1Min, address(this), block.timestamp ); (uint256 tokenId, uint128 amountLiquidity,,) = univ3_positions.mint(params); Position memory pos = Position( tokenId, _tokenA == address(FRAX) ? _tokenB : _tokenA, amountLiquidity, _tickLower, _tickUpper, _fee ); positions_array.push(pos); positions_mapping[tokenId] = pos; } /* ** burn tokenAmount from the recipient and send tokens to the receipient */ event log(uint); function removeLiquidity(uint256 positionIndex) public onlyByOwnGov { Position memory pos = positions_array[positionIndex]; INonfungiblePositionManager.CollectParams memory collect_params = INonfungiblePositionManager.CollectParams( pos.token_id, custodian_address, type(uint128).max, type(uint128).max ); univ3_positions.collect(collect_params); univ3_positions.burn(pos.token_id); positions_array[positionIndex] = positions_array[positions_array.length -1]; positions_array.pop(); delete positions_mapping[pos.token_id]; emit log(positions_array.length); emit log(positions_mapping[pos.token_id].token_id); } // Swap tokenA into tokenB using univ3_router.ExactInputSingle() // Uni V3 only function swap(address _tokenA, address _tokenB, uint24 _fee_tier, uint256 _amountAtoB, uint256 _amountOutMinimum, uint160 _sqrtPriceLimitX96) public onlyByOwnGov returns (uint256) { // Make sure the collateral is allowed require(allowed_collaterals[_tokenA] || _tokenA == address(FRAX), "TokenA not allowed"); require(allowed_collaterals[_tokenB] || _tokenB == address(FRAX), "TokenB not allowed"); ISwapRouter.ExactInputSingleParams memory swap_params = ISwapRouter.ExactInputSingleParams( _tokenA, _tokenB, _fee_tier, address(this), 2105300114, // Expiration: a long time from now _amountAtoB, _amountOutMinimum, _sqrtPriceLimitX96 ); // Approval TransferHelper.safeApprove(_tokenA, address(univ3_router), _amountAtoB); uint256 amountOut = univ3_router.exactInputSingle(swap_params); return amountOut; } /* ========== Burns and givebacks ========== */ // Give USDC profits back. Goes through the minter function giveCollatBack(uint256 collat_amount) external onlyByOwnGovCust { giveback_collateral.approve(address(amo_minter), collat_amount); amo_minter.receiveCollatFromAMO(collat_amount); } // Burn unneeded or excess FRAX. Goes through the minter function burnFRAX(uint256 frax_amount) public onlyByOwnGovCust { FRAX.approve(address(amo_minter), frax_amount); amo_minter.burnFraxFromAMO(frax_amount); } // Burn unneeded FXS. Goes through the minter function burnFXS(uint256 fxs_amount) public onlyByOwnGovCust { FXS.approve(address(amo_minter), fxs_amount); amo_minter.burnFxsFromAMO(fxs_amount); } /* ========== OWNER / GOVERNANCE FUNCTIONS ONLY ========== */ // Only owner or timelock can call, to limit risk // Adds collateral addresses supported. Needed to make sure dollarBalances is correct function addCollateral(address collat_addr) public onlyByOwnGov { require(collat_addr != address(0), "Zero address detected"); require(collat_addr != address(FRAX), "FRAX is not collateral"); require(allowed_collaterals[collat_addr] == false, "Address already exists"); allowed_collaterals[collat_addr] = true; collateral_addresses.push(collat_addr); } // Adds oracle for collateral. Optional for 1usd pegged coins. function addOracle(address collat_addr, address oracle) public onlyByOwnGov { require(collat_addr != address(0), "Zero address detected"); require(collat_addr != address(FRAX), "FRAX is not collateral"); oracles[collat_addr] = OracleLike(oracle); } function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov { // Can only be triggered by owner or governance, not custodian // Tokens are sent to the custodian, as a sort of safeguard TransferHelper.safeTransfer(tokenAddress, custodian_address, tokenAmount); emit RecoveredERC20(tokenAddress, tokenAmount); } function recoverERC721(address tokenAddress, uint256 token_id) external onlyByOwnGov { // Only the owner address can ever receive the recovery withdrawal // INonfungiblePositionManager inherits IERC721 so the latter does not need to be imported INonfungiblePositionManager(tokenAddress).safeTransferFrom( address(this), custodian_address, token_id); emit RecoveredERC721(tokenAddress, token_id); } // Generic proxy function execute( address _to, uint256 _value, bytes calldata _data ) external onlyByOwnGov returns (bool, bytes memory) { (bool success, bytes memory result) = _to.call{value:_value}(_data); return (success, result); } /* ========== EVENTS ========== */ event RecoveredERC20(address token, uint256 amount); event RecoveredERC721(address token, uint256 id); }
giveCollatBack
function giveCollatBack(uint256 collat_amount) external onlyByOwnGovCust { giveback_collateral.approve(address(amo_minter), collat_amount); amo_minter.receiveCollatFromAMO(collat_amount); }
// Give USDC profits back. Goes through the minter
LineComment
v0.8.6+commit.11564f7e
{ "func_code_index": [ 13312, 13525 ] }
807
UniV3LiquidityAMO_V2
contracts/Misc_AMOs/UniV3LiquidityAMO_V2.sol
0xc91bb4b0696e3b48c0c501b4ce8e7244fc363a79
Solidity
UniV3LiquidityAMO_V2
contract UniV3LiquidityAMO_V2 is Owned { using SafeMath for uint256; using SafeERC20 for ERC20; /* ========== STATE VARIABLES ========== */ // Core FRAXStablecoin private FRAX; FRAXShares private FXS; IFraxAMOMinter private amo_minter; ERC20 private giveback_collateral; address public giveback_collateral_address; uint256 public missing_decimals_giveback_collat; address public timelock_address; address public custodian_address; // Uniswap v3 IUniswapV3Factory public univ3_factory; INonfungiblePositionManager public univ3_positions; ISwapRouter public univ3_router; // Price constants uint256 private constant PRICE_PRECISION = 1e6; // Wildcat AMO // Details about the AMO's uniswap positions struct Position { uint256 token_id; address collateral_address; uint128 liquidity; // the liquidity of the position int24 tickLower; // the tick range of the position int24 tickUpper; uint24 fee_tier; } // Array of all Uni v3 NFT positions held by the AMO Position[] public positions_array; // List of all collaterals address[] public collateral_addresses; mapping(address => bool) public allowed_collaterals; // Mapping is also used for faster verification mapping(address => OracleLike) public oracles; // Mapping of oracles (if oracle == address(0) the collateral is assumed to be pegged to 1usd) // Map token_id to Position mapping(uint256 => Position) public positions_mapping; /* ========== CONSTRUCTOR ========== */ constructor( address _creator_address, address _giveback_collateral_address, address _amo_minter_address ) Owned(_creator_address) { FRAX = FRAXStablecoin(0x853d955aCEf822Db058eb8505911ED77F175b99e); FXS = FRAXShares(0x3432B6A60D23Ca0dFCa7761B7ab56459D9C964D0); giveback_collateral_address = _giveback_collateral_address; giveback_collateral = ERC20(_giveback_collateral_address); missing_decimals_giveback_collat = uint(18).sub(giveback_collateral.decimals()); collateral_addresses.push(_giveback_collateral_address); allowed_collaterals[_giveback_collateral_address] = true; univ3_factory = IUniswapV3Factory(0x1F98431c8aD98523631AE4a59f267346ea31F984); univ3_positions = INonfungiblePositionManager(0xC36442b4a4522E871399CD717aBDD847Ab11FE88); univ3_router = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564); // Initialize the minter amo_minter = IFraxAMOMinter(_amo_minter_address); // Get the custodian and timelock addresses from the minter custodian_address = amo_minter.custodian_address(); timelock_address = amo_minter.timelock_address(); } /* ========== MODIFIERS ========== */ modifier onlyByOwnGov() { require(msg.sender == timelock_address || msg.sender == owner, "Not owner or timelock"); _; } modifier onlyByOwnGovCust() { require(msg.sender == timelock_address || msg.sender == owner || msg.sender == custodian_address, "Not owner, tlck, or custd"); _; } modifier onlyByMinter() { require(msg.sender == address(amo_minter), "Not minter"); _; } /* ========== VIEWS ========== */ function showAllocations() public view returns (uint256[4] memory allocations) { // All numbers given are in FRAX unless otherwise stated // Unallocated FRAX allocations[0] = FRAX.balanceOf(address(this)); // Unallocated Collateral Dollar Value (E18) allocations[1] = freeColDolVal(); // Sum of Uni v3 Positions liquidity, if it was all in FRAX allocations[2] = TotalLiquidityFrax(); // Total Value allocations[3] = allocations[0].add(allocations[1]).add(allocations[2]); } // E18 Collateral dollar value function freeColDolVal() public view returns (uint256) { uint256 value_tally_e18 = 0; for (uint i = 0; i < collateral_addresses.length; i++){ ERC20 thisCollateral = ERC20(collateral_addresses[i]); uint256 missing_decs = uint256(18).sub(thisCollateral.decimals()); uint256 col_bal_e18 = thisCollateral.balanceOf(address(this)).mul(10 ** missing_decs); uint256 col_usd_value_e18 = collatDolarValue(oracles[collateral_addresses[i]], col_bal_e18); value_tally_e18 = value_tally_e18.add(col_usd_value_e18); } return value_tally_e18; } // Convert collateral to dolar. If no oracle assumes pegged to 1USD. Both oracle, balance and return are E18 function collatDolarValue(OracleLike oracle, uint256 balance) public view returns (uint256) { if (address(oracle) == address(0)) return balance; return balance.mul(oracle.read()).div(1 ether); } // Needed for the Frax contract to function function collatDollarBalance() public view returns (uint256) { // Get the allocations uint256[4] memory allocations = showAllocations(); // Get the collateral and FRAX portions uint256 collat_portion = allocations[1]; uint256 frax_portion = (allocations[0]).add(allocations[2]); // Assumes worst case scenario if FRAX slips out of range. // Otherwise, it would only be half that is multiplied by the CR frax_portion = frax_portion.mul(FRAX.global_collateral_ratio()).div(PRICE_PRECISION); return (collat_portion).add(frax_portion); } function dollarBalances() public view returns (uint256 frax_val_e18, uint256 collat_val_e18) { frax_val_e18 = showAllocations()[3]; collat_val_e18 = collatDollarBalance(); } function TotalLiquidityFrax() public view returns (uint256) { uint256 frax_tally = 0; Position memory thisPosition; for (uint256 i = 0; i < positions_array.length; i++) { thisPosition = positions_array[i]; uint128 this_liq = thisPosition.liquidity; if (this_liq > 0){ uint160 sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(thisPosition.tickLower); uint160 sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(thisPosition.tickUpper); if (thisPosition.collateral_address > 0x853d955aCEf822Db058eb8505911ED77F175b99e){ // if address(FRAX) < collateral_address, then FRAX is token0 frax_tally = frax_tally.add(LiquidityAmounts.getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, this_liq)); } else { frax_tally = frax_tally.add(LiquidityAmounts.getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, this_liq)); } } } // Return the sum of all the positions' balances of FRAX, if the price fell off the range towards that side return frax_tally; } // Returns this contract's liquidity in a specific [FRAX]-[collateral] uni v3 pool function liquidityInPool(address _collateral_address, int24 _tickLower, int24 _tickUpper, uint24 _fee) public view returns (uint128) { IUniswapV3Pool get_pool = IUniswapV3Pool(univ3_factory.getPool(address(FRAX), _collateral_address, _fee)); // goes into the pool's positions mapping, and grabs this address's liquidity (uint128 liquidity, , , , ) = get_pool.positions(keccak256(abi.encodePacked(address(this), _tickLower, _tickUpper))); return liquidity; } // Backwards compatibility function mintedBalance() public view returns (int256) { return amo_minter.frax_mint_balances(address(this)); } // Backwards compatibility function collateralBalance() public view returns (int256) { return amo_minter.collat_borrowed_balances(address(this)); } // Only counts non-withdrawn positions function numPositions() public view returns (uint256) { return positions_array.length; } function allCollateralAddresses() external view returns (address[] memory) { return collateral_addresses; } /* ========== RESTRICTED FUNCTIONS, BUT CUSTODIAN CAN CALL ========== */ // Iterate through all positions and collect fees accumulated function collectFees() external onlyByOwnGovCust { for (uint i = 0; i < positions_array.length; i++){ Position memory current_position = positions_array[i]; INonfungiblePositionManager.CollectParams memory collect_params = INonfungiblePositionManager.CollectParams( current_position.token_id, custodian_address, type(uint128).max, type(uint128).max ); // Send to custodian address univ3_positions.collect(collect_params); } } /* ---------------------------------------------------- */ /* ---------------------- Uni v3 ---------------------- */ /* ---------------------------------------------------- */ function approveTarget(address _target, address _token, uint256 _amount, bool use_safe_approve) public onlyByOwnGov { if (use_safe_approve) { // safeApprove needed for USDT and others for the first approval // You need to approve 0 every time beforehand for USDT: it resets TransferHelper.safeApprove(_token, _target, _amount); } else { ERC20(_token).approve(_target, _amount); } } // IUniswapV3Pool public current_uni_pool; // only used for mint callback; is set and accessed during execution of addLiquidity() function addLiquidity(address _tokenA, address _tokenB, int24 _tickLower, int24 _tickUpper, uint24 _fee, uint256 _amount0Desired, uint256 _amount1Desired, uint256 _amount0Min, uint256 _amount1Min) public onlyByOwnGov { // Make sure the collateral is allowed require(allowed_collaterals[_tokenA] || _tokenA == address(FRAX), "TokenA not allowed"); require(allowed_collaterals[_tokenB] || _tokenB == address(FRAX), "TokenB not allowed"); ERC20(_tokenA).transferFrom(msg.sender, address(this), _amount0Desired); ERC20(_tokenB).transferFrom(msg.sender, address(this), _amount1Desired); ERC20(_tokenA).approve(address(univ3_positions), _amount0Desired); ERC20(_tokenB).approve(address(univ3_positions), _amount1Desired); INonfungiblePositionManager.MintParams memory params = INonfungiblePositionManager.MintParams( _tokenA, _tokenB, _fee, _tickLower, _tickUpper, _amount0Desired, _amount1Desired, _amount0Min, _amount1Min, address(this), block.timestamp ); (uint256 tokenId, uint128 amountLiquidity,,) = univ3_positions.mint(params); Position memory pos = Position( tokenId, _tokenA == address(FRAX) ? _tokenB : _tokenA, amountLiquidity, _tickLower, _tickUpper, _fee ); positions_array.push(pos); positions_mapping[tokenId] = pos; } /* ** burn tokenAmount from the recipient and send tokens to the receipient */ event log(uint); function removeLiquidity(uint256 positionIndex) public onlyByOwnGov { Position memory pos = positions_array[positionIndex]; INonfungiblePositionManager.CollectParams memory collect_params = INonfungiblePositionManager.CollectParams( pos.token_id, custodian_address, type(uint128).max, type(uint128).max ); univ3_positions.collect(collect_params); univ3_positions.burn(pos.token_id); positions_array[positionIndex] = positions_array[positions_array.length -1]; positions_array.pop(); delete positions_mapping[pos.token_id]; emit log(positions_array.length); emit log(positions_mapping[pos.token_id].token_id); } // Swap tokenA into tokenB using univ3_router.ExactInputSingle() // Uni V3 only function swap(address _tokenA, address _tokenB, uint24 _fee_tier, uint256 _amountAtoB, uint256 _amountOutMinimum, uint160 _sqrtPriceLimitX96) public onlyByOwnGov returns (uint256) { // Make sure the collateral is allowed require(allowed_collaterals[_tokenA] || _tokenA == address(FRAX), "TokenA not allowed"); require(allowed_collaterals[_tokenB] || _tokenB == address(FRAX), "TokenB not allowed"); ISwapRouter.ExactInputSingleParams memory swap_params = ISwapRouter.ExactInputSingleParams( _tokenA, _tokenB, _fee_tier, address(this), 2105300114, // Expiration: a long time from now _amountAtoB, _amountOutMinimum, _sqrtPriceLimitX96 ); // Approval TransferHelper.safeApprove(_tokenA, address(univ3_router), _amountAtoB); uint256 amountOut = univ3_router.exactInputSingle(swap_params); return amountOut; } /* ========== Burns and givebacks ========== */ // Give USDC profits back. Goes through the minter function giveCollatBack(uint256 collat_amount) external onlyByOwnGovCust { giveback_collateral.approve(address(amo_minter), collat_amount); amo_minter.receiveCollatFromAMO(collat_amount); } // Burn unneeded or excess FRAX. Goes through the minter function burnFRAX(uint256 frax_amount) public onlyByOwnGovCust { FRAX.approve(address(amo_minter), frax_amount); amo_minter.burnFraxFromAMO(frax_amount); } // Burn unneeded FXS. Goes through the minter function burnFXS(uint256 fxs_amount) public onlyByOwnGovCust { FXS.approve(address(amo_minter), fxs_amount); amo_minter.burnFxsFromAMO(fxs_amount); } /* ========== OWNER / GOVERNANCE FUNCTIONS ONLY ========== */ // Only owner or timelock can call, to limit risk // Adds collateral addresses supported. Needed to make sure dollarBalances is correct function addCollateral(address collat_addr) public onlyByOwnGov { require(collat_addr != address(0), "Zero address detected"); require(collat_addr != address(FRAX), "FRAX is not collateral"); require(allowed_collaterals[collat_addr] == false, "Address already exists"); allowed_collaterals[collat_addr] = true; collateral_addresses.push(collat_addr); } // Adds oracle for collateral. Optional for 1usd pegged coins. function addOracle(address collat_addr, address oracle) public onlyByOwnGov { require(collat_addr != address(0), "Zero address detected"); require(collat_addr != address(FRAX), "FRAX is not collateral"); oracles[collat_addr] = OracleLike(oracle); } function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov { // Can only be triggered by owner or governance, not custodian // Tokens are sent to the custodian, as a sort of safeguard TransferHelper.safeTransfer(tokenAddress, custodian_address, tokenAmount); emit RecoveredERC20(tokenAddress, tokenAmount); } function recoverERC721(address tokenAddress, uint256 token_id) external onlyByOwnGov { // Only the owner address can ever receive the recovery withdrawal // INonfungiblePositionManager inherits IERC721 so the latter does not need to be imported INonfungiblePositionManager(tokenAddress).safeTransferFrom( address(this), custodian_address, token_id); emit RecoveredERC721(tokenAddress, token_id); } // Generic proxy function execute( address _to, uint256 _value, bytes calldata _data ) external onlyByOwnGov returns (bool, bytes memory) { (bool success, bytes memory result) = _to.call{value:_value}(_data); return (success, result); } /* ========== EVENTS ========== */ event RecoveredERC20(address token, uint256 amount); event RecoveredERC721(address token, uint256 id); }
burnFRAX
function burnFRAX(uint256 frax_amount) public onlyByOwnGovCust { FRAX.approve(address(amo_minter), frax_amount); amo_minter.burnFraxFromAMO(frax_amount); }
// Burn unneeded or excess FRAX. Goes through the minter
LineComment
v0.8.6+commit.11564f7e
{ "func_code_index": [ 13588, 13767 ] }
808
UniV3LiquidityAMO_V2
contracts/Misc_AMOs/UniV3LiquidityAMO_V2.sol
0xc91bb4b0696e3b48c0c501b4ce8e7244fc363a79
Solidity
UniV3LiquidityAMO_V2
contract UniV3LiquidityAMO_V2 is Owned { using SafeMath for uint256; using SafeERC20 for ERC20; /* ========== STATE VARIABLES ========== */ // Core FRAXStablecoin private FRAX; FRAXShares private FXS; IFraxAMOMinter private amo_minter; ERC20 private giveback_collateral; address public giveback_collateral_address; uint256 public missing_decimals_giveback_collat; address public timelock_address; address public custodian_address; // Uniswap v3 IUniswapV3Factory public univ3_factory; INonfungiblePositionManager public univ3_positions; ISwapRouter public univ3_router; // Price constants uint256 private constant PRICE_PRECISION = 1e6; // Wildcat AMO // Details about the AMO's uniswap positions struct Position { uint256 token_id; address collateral_address; uint128 liquidity; // the liquidity of the position int24 tickLower; // the tick range of the position int24 tickUpper; uint24 fee_tier; } // Array of all Uni v3 NFT positions held by the AMO Position[] public positions_array; // List of all collaterals address[] public collateral_addresses; mapping(address => bool) public allowed_collaterals; // Mapping is also used for faster verification mapping(address => OracleLike) public oracles; // Mapping of oracles (if oracle == address(0) the collateral is assumed to be pegged to 1usd) // Map token_id to Position mapping(uint256 => Position) public positions_mapping; /* ========== CONSTRUCTOR ========== */ constructor( address _creator_address, address _giveback_collateral_address, address _amo_minter_address ) Owned(_creator_address) { FRAX = FRAXStablecoin(0x853d955aCEf822Db058eb8505911ED77F175b99e); FXS = FRAXShares(0x3432B6A60D23Ca0dFCa7761B7ab56459D9C964D0); giveback_collateral_address = _giveback_collateral_address; giveback_collateral = ERC20(_giveback_collateral_address); missing_decimals_giveback_collat = uint(18).sub(giveback_collateral.decimals()); collateral_addresses.push(_giveback_collateral_address); allowed_collaterals[_giveback_collateral_address] = true; univ3_factory = IUniswapV3Factory(0x1F98431c8aD98523631AE4a59f267346ea31F984); univ3_positions = INonfungiblePositionManager(0xC36442b4a4522E871399CD717aBDD847Ab11FE88); univ3_router = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564); // Initialize the minter amo_minter = IFraxAMOMinter(_amo_minter_address); // Get the custodian and timelock addresses from the minter custodian_address = amo_minter.custodian_address(); timelock_address = amo_minter.timelock_address(); } /* ========== MODIFIERS ========== */ modifier onlyByOwnGov() { require(msg.sender == timelock_address || msg.sender == owner, "Not owner or timelock"); _; } modifier onlyByOwnGovCust() { require(msg.sender == timelock_address || msg.sender == owner || msg.sender == custodian_address, "Not owner, tlck, or custd"); _; } modifier onlyByMinter() { require(msg.sender == address(amo_minter), "Not minter"); _; } /* ========== VIEWS ========== */ function showAllocations() public view returns (uint256[4] memory allocations) { // All numbers given are in FRAX unless otherwise stated // Unallocated FRAX allocations[0] = FRAX.balanceOf(address(this)); // Unallocated Collateral Dollar Value (E18) allocations[1] = freeColDolVal(); // Sum of Uni v3 Positions liquidity, if it was all in FRAX allocations[2] = TotalLiquidityFrax(); // Total Value allocations[3] = allocations[0].add(allocations[1]).add(allocations[2]); } // E18 Collateral dollar value function freeColDolVal() public view returns (uint256) { uint256 value_tally_e18 = 0; for (uint i = 0; i < collateral_addresses.length; i++){ ERC20 thisCollateral = ERC20(collateral_addresses[i]); uint256 missing_decs = uint256(18).sub(thisCollateral.decimals()); uint256 col_bal_e18 = thisCollateral.balanceOf(address(this)).mul(10 ** missing_decs); uint256 col_usd_value_e18 = collatDolarValue(oracles[collateral_addresses[i]], col_bal_e18); value_tally_e18 = value_tally_e18.add(col_usd_value_e18); } return value_tally_e18; } // Convert collateral to dolar. If no oracle assumes pegged to 1USD. Both oracle, balance and return are E18 function collatDolarValue(OracleLike oracle, uint256 balance) public view returns (uint256) { if (address(oracle) == address(0)) return balance; return balance.mul(oracle.read()).div(1 ether); } // Needed for the Frax contract to function function collatDollarBalance() public view returns (uint256) { // Get the allocations uint256[4] memory allocations = showAllocations(); // Get the collateral and FRAX portions uint256 collat_portion = allocations[1]; uint256 frax_portion = (allocations[0]).add(allocations[2]); // Assumes worst case scenario if FRAX slips out of range. // Otherwise, it would only be half that is multiplied by the CR frax_portion = frax_portion.mul(FRAX.global_collateral_ratio()).div(PRICE_PRECISION); return (collat_portion).add(frax_portion); } function dollarBalances() public view returns (uint256 frax_val_e18, uint256 collat_val_e18) { frax_val_e18 = showAllocations()[3]; collat_val_e18 = collatDollarBalance(); } function TotalLiquidityFrax() public view returns (uint256) { uint256 frax_tally = 0; Position memory thisPosition; for (uint256 i = 0; i < positions_array.length; i++) { thisPosition = positions_array[i]; uint128 this_liq = thisPosition.liquidity; if (this_liq > 0){ uint160 sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(thisPosition.tickLower); uint160 sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(thisPosition.tickUpper); if (thisPosition.collateral_address > 0x853d955aCEf822Db058eb8505911ED77F175b99e){ // if address(FRAX) < collateral_address, then FRAX is token0 frax_tally = frax_tally.add(LiquidityAmounts.getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, this_liq)); } else { frax_tally = frax_tally.add(LiquidityAmounts.getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, this_liq)); } } } // Return the sum of all the positions' balances of FRAX, if the price fell off the range towards that side return frax_tally; } // Returns this contract's liquidity in a specific [FRAX]-[collateral] uni v3 pool function liquidityInPool(address _collateral_address, int24 _tickLower, int24 _tickUpper, uint24 _fee) public view returns (uint128) { IUniswapV3Pool get_pool = IUniswapV3Pool(univ3_factory.getPool(address(FRAX), _collateral_address, _fee)); // goes into the pool's positions mapping, and grabs this address's liquidity (uint128 liquidity, , , , ) = get_pool.positions(keccak256(abi.encodePacked(address(this), _tickLower, _tickUpper))); return liquidity; } // Backwards compatibility function mintedBalance() public view returns (int256) { return amo_minter.frax_mint_balances(address(this)); } // Backwards compatibility function collateralBalance() public view returns (int256) { return amo_minter.collat_borrowed_balances(address(this)); } // Only counts non-withdrawn positions function numPositions() public view returns (uint256) { return positions_array.length; } function allCollateralAddresses() external view returns (address[] memory) { return collateral_addresses; } /* ========== RESTRICTED FUNCTIONS, BUT CUSTODIAN CAN CALL ========== */ // Iterate through all positions and collect fees accumulated function collectFees() external onlyByOwnGovCust { for (uint i = 0; i < positions_array.length; i++){ Position memory current_position = positions_array[i]; INonfungiblePositionManager.CollectParams memory collect_params = INonfungiblePositionManager.CollectParams( current_position.token_id, custodian_address, type(uint128).max, type(uint128).max ); // Send to custodian address univ3_positions.collect(collect_params); } } /* ---------------------------------------------------- */ /* ---------------------- Uni v3 ---------------------- */ /* ---------------------------------------------------- */ function approveTarget(address _target, address _token, uint256 _amount, bool use_safe_approve) public onlyByOwnGov { if (use_safe_approve) { // safeApprove needed for USDT and others for the first approval // You need to approve 0 every time beforehand for USDT: it resets TransferHelper.safeApprove(_token, _target, _amount); } else { ERC20(_token).approve(_target, _amount); } } // IUniswapV3Pool public current_uni_pool; // only used for mint callback; is set and accessed during execution of addLiquidity() function addLiquidity(address _tokenA, address _tokenB, int24 _tickLower, int24 _tickUpper, uint24 _fee, uint256 _amount0Desired, uint256 _amount1Desired, uint256 _amount0Min, uint256 _amount1Min) public onlyByOwnGov { // Make sure the collateral is allowed require(allowed_collaterals[_tokenA] || _tokenA == address(FRAX), "TokenA not allowed"); require(allowed_collaterals[_tokenB] || _tokenB == address(FRAX), "TokenB not allowed"); ERC20(_tokenA).transferFrom(msg.sender, address(this), _amount0Desired); ERC20(_tokenB).transferFrom(msg.sender, address(this), _amount1Desired); ERC20(_tokenA).approve(address(univ3_positions), _amount0Desired); ERC20(_tokenB).approve(address(univ3_positions), _amount1Desired); INonfungiblePositionManager.MintParams memory params = INonfungiblePositionManager.MintParams( _tokenA, _tokenB, _fee, _tickLower, _tickUpper, _amount0Desired, _amount1Desired, _amount0Min, _amount1Min, address(this), block.timestamp ); (uint256 tokenId, uint128 amountLiquidity,,) = univ3_positions.mint(params); Position memory pos = Position( tokenId, _tokenA == address(FRAX) ? _tokenB : _tokenA, amountLiquidity, _tickLower, _tickUpper, _fee ); positions_array.push(pos); positions_mapping[tokenId] = pos; } /* ** burn tokenAmount from the recipient and send tokens to the receipient */ event log(uint); function removeLiquidity(uint256 positionIndex) public onlyByOwnGov { Position memory pos = positions_array[positionIndex]; INonfungiblePositionManager.CollectParams memory collect_params = INonfungiblePositionManager.CollectParams( pos.token_id, custodian_address, type(uint128).max, type(uint128).max ); univ3_positions.collect(collect_params); univ3_positions.burn(pos.token_id); positions_array[positionIndex] = positions_array[positions_array.length -1]; positions_array.pop(); delete positions_mapping[pos.token_id]; emit log(positions_array.length); emit log(positions_mapping[pos.token_id].token_id); } // Swap tokenA into tokenB using univ3_router.ExactInputSingle() // Uni V3 only function swap(address _tokenA, address _tokenB, uint24 _fee_tier, uint256 _amountAtoB, uint256 _amountOutMinimum, uint160 _sqrtPriceLimitX96) public onlyByOwnGov returns (uint256) { // Make sure the collateral is allowed require(allowed_collaterals[_tokenA] || _tokenA == address(FRAX), "TokenA not allowed"); require(allowed_collaterals[_tokenB] || _tokenB == address(FRAX), "TokenB not allowed"); ISwapRouter.ExactInputSingleParams memory swap_params = ISwapRouter.ExactInputSingleParams( _tokenA, _tokenB, _fee_tier, address(this), 2105300114, // Expiration: a long time from now _amountAtoB, _amountOutMinimum, _sqrtPriceLimitX96 ); // Approval TransferHelper.safeApprove(_tokenA, address(univ3_router), _amountAtoB); uint256 amountOut = univ3_router.exactInputSingle(swap_params); return amountOut; } /* ========== Burns and givebacks ========== */ // Give USDC profits back. Goes through the minter function giveCollatBack(uint256 collat_amount) external onlyByOwnGovCust { giveback_collateral.approve(address(amo_minter), collat_amount); amo_minter.receiveCollatFromAMO(collat_amount); } // Burn unneeded or excess FRAX. Goes through the minter function burnFRAX(uint256 frax_amount) public onlyByOwnGovCust { FRAX.approve(address(amo_minter), frax_amount); amo_minter.burnFraxFromAMO(frax_amount); } // Burn unneeded FXS. Goes through the minter function burnFXS(uint256 fxs_amount) public onlyByOwnGovCust { FXS.approve(address(amo_minter), fxs_amount); amo_minter.burnFxsFromAMO(fxs_amount); } /* ========== OWNER / GOVERNANCE FUNCTIONS ONLY ========== */ // Only owner or timelock can call, to limit risk // Adds collateral addresses supported. Needed to make sure dollarBalances is correct function addCollateral(address collat_addr) public onlyByOwnGov { require(collat_addr != address(0), "Zero address detected"); require(collat_addr != address(FRAX), "FRAX is not collateral"); require(allowed_collaterals[collat_addr] == false, "Address already exists"); allowed_collaterals[collat_addr] = true; collateral_addresses.push(collat_addr); } // Adds oracle for collateral. Optional for 1usd pegged coins. function addOracle(address collat_addr, address oracle) public onlyByOwnGov { require(collat_addr != address(0), "Zero address detected"); require(collat_addr != address(FRAX), "FRAX is not collateral"); oracles[collat_addr] = OracleLike(oracle); } function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov { // Can only be triggered by owner or governance, not custodian // Tokens are sent to the custodian, as a sort of safeguard TransferHelper.safeTransfer(tokenAddress, custodian_address, tokenAmount); emit RecoveredERC20(tokenAddress, tokenAmount); } function recoverERC721(address tokenAddress, uint256 token_id) external onlyByOwnGov { // Only the owner address can ever receive the recovery withdrawal // INonfungiblePositionManager inherits IERC721 so the latter does not need to be imported INonfungiblePositionManager(tokenAddress).safeTransferFrom( address(this), custodian_address, token_id); emit RecoveredERC721(tokenAddress, token_id); } // Generic proxy function execute( address _to, uint256 _value, bytes calldata _data ) external onlyByOwnGov returns (bool, bytes memory) { (bool success, bytes memory result) = _to.call{value:_value}(_data); return (success, result); } /* ========== EVENTS ========== */ event RecoveredERC20(address token, uint256 amount); event RecoveredERC721(address token, uint256 id); }
burnFXS
function burnFXS(uint256 fxs_amount) public onlyByOwnGovCust { FXS.approve(address(amo_minter), fxs_amount); amo_minter.burnFxsFromAMO(fxs_amount); }
// Burn unneeded FXS. Goes through the minter
LineComment
v0.8.6+commit.11564f7e
{ "func_code_index": [ 13819, 13992 ] }
809
UniV3LiquidityAMO_V2
contracts/Misc_AMOs/UniV3LiquidityAMO_V2.sol
0xc91bb4b0696e3b48c0c501b4ce8e7244fc363a79
Solidity
UniV3LiquidityAMO_V2
contract UniV3LiquidityAMO_V2 is Owned { using SafeMath for uint256; using SafeERC20 for ERC20; /* ========== STATE VARIABLES ========== */ // Core FRAXStablecoin private FRAX; FRAXShares private FXS; IFraxAMOMinter private amo_minter; ERC20 private giveback_collateral; address public giveback_collateral_address; uint256 public missing_decimals_giveback_collat; address public timelock_address; address public custodian_address; // Uniswap v3 IUniswapV3Factory public univ3_factory; INonfungiblePositionManager public univ3_positions; ISwapRouter public univ3_router; // Price constants uint256 private constant PRICE_PRECISION = 1e6; // Wildcat AMO // Details about the AMO's uniswap positions struct Position { uint256 token_id; address collateral_address; uint128 liquidity; // the liquidity of the position int24 tickLower; // the tick range of the position int24 tickUpper; uint24 fee_tier; } // Array of all Uni v3 NFT positions held by the AMO Position[] public positions_array; // List of all collaterals address[] public collateral_addresses; mapping(address => bool) public allowed_collaterals; // Mapping is also used for faster verification mapping(address => OracleLike) public oracles; // Mapping of oracles (if oracle == address(0) the collateral is assumed to be pegged to 1usd) // Map token_id to Position mapping(uint256 => Position) public positions_mapping; /* ========== CONSTRUCTOR ========== */ constructor( address _creator_address, address _giveback_collateral_address, address _amo_minter_address ) Owned(_creator_address) { FRAX = FRAXStablecoin(0x853d955aCEf822Db058eb8505911ED77F175b99e); FXS = FRAXShares(0x3432B6A60D23Ca0dFCa7761B7ab56459D9C964D0); giveback_collateral_address = _giveback_collateral_address; giveback_collateral = ERC20(_giveback_collateral_address); missing_decimals_giveback_collat = uint(18).sub(giveback_collateral.decimals()); collateral_addresses.push(_giveback_collateral_address); allowed_collaterals[_giveback_collateral_address] = true; univ3_factory = IUniswapV3Factory(0x1F98431c8aD98523631AE4a59f267346ea31F984); univ3_positions = INonfungiblePositionManager(0xC36442b4a4522E871399CD717aBDD847Ab11FE88); univ3_router = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564); // Initialize the minter amo_minter = IFraxAMOMinter(_amo_minter_address); // Get the custodian and timelock addresses from the minter custodian_address = amo_minter.custodian_address(); timelock_address = amo_minter.timelock_address(); } /* ========== MODIFIERS ========== */ modifier onlyByOwnGov() { require(msg.sender == timelock_address || msg.sender == owner, "Not owner or timelock"); _; } modifier onlyByOwnGovCust() { require(msg.sender == timelock_address || msg.sender == owner || msg.sender == custodian_address, "Not owner, tlck, or custd"); _; } modifier onlyByMinter() { require(msg.sender == address(amo_minter), "Not minter"); _; } /* ========== VIEWS ========== */ function showAllocations() public view returns (uint256[4] memory allocations) { // All numbers given are in FRAX unless otherwise stated // Unallocated FRAX allocations[0] = FRAX.balanceOf(address(this)); // Unallocated Collateral Dollar Value (E18) allocations[1] = freeColDolVal(); // Sum of Uni v3 Positions liquidity, if it was all in FRAX allocations[2] = TotalLiquidityFrax(); // Total Value allocations[3] = allocations[0].add(allocations[1]).add(allocations[2]); } // E18 Collateral dollar value function freeColDolVal() public view returns (uint256) { uint256 value_tally_e18 = 0; for (uint i = 0; i < collateral_addresses.length; i++){ ERC20 thisCollateral = ERC20(collateral_addresses[i]); uint256 missing_decs = uint256(18).sub(thisCollateral.decimals()); uint256 col_bal_e18 = thisCollateral.balanceOf(address(this)).mul(10 ** missing_decs); uint256 col_usd_value_e18 = collatDolarValue(oracles[collateral_addresses[i]], col_bal_e18); value_tally_e18 = value_tally_e18.add(col_usd_value_e18); } return value_tally_e18; } // Convert collateral to dolar. If no oracle assumes pegged to 1USD. Both oracle, balance and return are E18 function collatDolarValue(OracleLike oracle, uint256 balance) public view returns (uint256) { if (address(oracle) == address(0)) return balance; return balance.mul(oracle.read()).div(1 ether); } // Needed for the Frax contract to function function collatDollarBalance() public view returns (uint256) { // Get the allocations uint256[4] memory allocations = showAllocations(); // Get the collateral and FRAX portions uint256 collat_portion = allocations[1]; uint256 frax_portion = (allocations[0]).add(allocations[2]); // Assumes worst case scenario if FRAX slips out of range. // Otherwise, it would only be half that is multiplied by the CR frax_portion = frax_portion.mul(FRAX.global_collateral_ratio()).div(PRICE_PRECISION); return (collat_portion).add(frax_portion); } function dollarBalances() public view returns (uint256 frax_val_e18, uint256 collat_val_e18) { frax_val_e18 = showAllocations()[3]; collat_val_e18 = collatDollarBalance(); } function TotalLiquidityFrax() public view returns (uint256) { uint256 frax_tally = 0; Position memory thisPosition; for (uint256 i = 0; i < positions_array.length; i++) { thisPosition = positions_array[i]; uint128 this_liq = thisPosition.liquidity; if (this_liq > 0){ uint160 sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(thisPosition.tickLower); uint160 sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(thisPosition.tickUpper); if (thisPosition.collateral_address > 0x853d955aCEf822Db058eb8505911ED77F175b99e){ // if address(FRAX) < collateral_address, then FRAX is token0 frax_tally = frax_tally.add(LiquidityAmounts.getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, this_liq)); } else { frax_tally = frax_tally.add(LiquidityAmounts.getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, this_liq)); } } } // Return the sum of all the positions' balances of FRAX, if the price fell off the range towards that side return frax_tally; } // Returns this contract's liquidity in a specific [FRAX]-[collateral] uni v3 pool function liquidityInPool(address _collateral_address, int24 _tickLower, int24 _tickUpper, uint24 _fee) public view returns (uint128) { IUniswapV3Pool get_pool = IUniswapV3Pool(univ3_factory.getPool(address(FRAX), _collateral_address, _fee)); // goes into the pool's positions mapping, and grabs this address's liquidity (uint128 liquidity, , , , ) = get_pool.positions(keccak256(abi.encodePacked(address(this), _tickLower, _tickUpper))); return liquidity; } // Backwards compatibility function mintedBalance() public view returns (int256) { return amo_minter.frax_mint_balances(address(this)); } // Backwards compatibility function collateralBalance() public view returns (int256) { return amo_minter.collat_borrowed_balances(address(this)); } // Only counts non-withdrawn positions function numPositions() public view returns (uint256) { return positions_array.length; } function allCollateralAddresses() external view returns (address[] memory) { return collateral_addresses; } /* ========== RESTRICTED FUNCTIONS, BUT CUSTODIAN CAN CALL ========== */ // Iterate through all positions and collect fees accumulated function collectFees() external onlyByOwnGovCust { for (uint i = 0; i < positions_array.length; i++){ Position memory current_position = positions_array[i]; INonfungiblePositionManager.CollectParams memory collect_params = INonfungiblePositionManager.CollectParams( current_position.token_id, custodian_address, type(uint128).max, type(uint128).max ); // Send to custodian address univ3_positions.collect(collect_params); } } /* ---------------------------------------------------- */ /* ---------------------- Uni v3 ---------------------- */ /* ---------------------------------------------------- */ function approveTarget(address _target, address _token, uint256 _amount, bool use_safe_approve) public onlyByOwnGov { if (use_safe_approve) { // safeApprove needed for USDT and others for the first approval // You need to approve 0 every time beforehand for USDT: it resets TransferHelper.safeApprove(_token, _target, _amount); } else { ERC20(_token).approve(_target, _amount); } } // IUniswapV3Pool public current_uni_pool; // only used for mint callback; is set and accessed during execution of addLiquidity() function addLiquidity(address _tokenA, address _tokenB, int24 _tickLower, int24 _tickUpper, uint24 _fee, uint256 _amount0Desired, uint256 _amount1Desired, uint256 _amount0Min, uint256 _amount1Min) public onlyByOwnGov { // Make sure the collateral is allowed require(allowed_collaterals[_tokenA] || _tokenA == address(FRAX), "TokenA not allowed"); require(allowed_collaterals[_tokenB] || _tokenB == address(FRAX), "TokenB not allowed"); ERC20(_tokenA).transferFrom(msg.sender, address(this), _amount0Desired); ERC20(_tokenB).transferFrom(msg.sender, address(this), _amount1Desired); ERC20(_tokenA).approve(address(univ3_positions), _amount0Desired); ERC20(_tokenB).approve(address(univ3_positions), _amount1Desired); INonfungiblePositionManager.MintParams memory params = INonfungiblePositionManager.MintParams( _tokenA, _tokenB, _fee, _tickLower, _tickUpper, _amount0Desired, _amount1Desired, _amount0Min, _amount1Min, address(this), block.timestamp ); (uint256 tokenId, uint128 amountLiquidity,,) = univ3_positions.mint(params); Position memory pos = Position( tokenId, _tokenA == address(FRAX) ? _tokenB : _tokenA, amountLiquidity, _tickLower, _tickUpper, _fee ); positions_array.push(pos); positions_mapping[tokenId] = pos; } /* ** burn tokenAmount from the recipient and send tokens to the receipient */ event log(uint); function removeLiquidity(uint256 positionIndex) public onlyByOwnGov { Position memory pos = positions_array[positionIndex]; INonfungiblePositionManager.CollectParams memory collect_params = INonfungiblePositionManager.CollectParams( pos.token_id, custodian_address, type(uint128).max, type(uint128).max ); univ3_positions.collect(collect_params); univ3_positions.burn(pos.token_id); positions_array[positionIndex] = positions_array[positions_array.length -1]; positions_array.pop(); delete positions_mapping[pos.token_id]; emit log(positions_array.length); emit log(positions_mapping[pos.token_id].token_id); } // Swap tokenA into tokenB using univ3_router.ExactInputSingle() // Uni V3 only function swap(address _tokenA, address _tokenB, uint24 _fee_tier, uint256 _amountAtoB, uint256 _amountOutMinimum, uint160 _sqrtPriceLimitX96) public onlyByOwnGov returns (uint256) { // Make sure the collateral is allowed require(allowed_collaterals[_tokenA] || _tokenA == address(FRAX), "TokenA not allowed"); require(allowed_collaterals[_tokenB] || _tokenB == address(FRAX), "TokenB not allowed"); ISwapRouter.ExactInputSingleParams memory swap_params = ISwapRouter.ExactInputSingleParams( _tokenA, _tokenB, _fee_tier, address(this), 2105300114, // Expiration: a long time from now _amountAtoB, _amountOutMinimum, _sqrtPriceLimitX96 ); // Approval TransferHelper.safeApprove(_tokenA, address(univ3_router), _amountAtoB); uint256 amountOut = univ3_router.exactInputSingle(swap_params); return amountOut; } /* ========== Burns and givebacks ========== */ // Give USDC profits back. Goes through the minter function giveCollatBack(uint256 collat_amount) external onlyByOwnGovCust { giveback_collateral.approve(address(amo_minter), collat_amount); amo_minter.receiveCollatFromAMO(collat_amount); } // Burn unneeded or excess FRAX. Goes through the minter function burnFRAX(uint256 frax_amount) public onlyByOwnGovCust { FRAX.approve(address(amo_minter), frax_amount); amo_minter.burnFraxFromAMO(frax_amount); } // Burn unneeded FXS. Goes through the minter function burnFXS(uint256 fxs_amount) public onlyByOwnGovCust { FXS.approve(address(amo_minter), fxs_amount); amo_minter.burnFxsFromAMO(fxs_amount); } /* ========== OWNER / GOVERNANCE FUNCTIONS ONLY ========== */ // Only owner or timelock can call, to limit risk // Adds collateral addresses supported. Needed to make sure dollarBalances is correct function addCollateral(address collat_addr) public onlyByOwnGov { require(collat_addr != address(0), "Zero address detected"); require(collat_addr != address(FRAX), "FRAX is not collateral"); require(allowed_collaterals[collat_addr] == false, "Address already exists"); allowed_collaterals[collat_addr] = true; collateral_addresses.push(collat_addr); } // Adds oracle for collateral. Optional for 1usd pegged coins. function addOracle(address collat_addr, address oracle) public onlyByOwnGov { require(collat_addr != address(0), "Zero address detected"); require(collat_addr != address(FRAX), "FRAX is not collateral"); oracles[collat_addr] = OracleLike(oracle); } function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov { // Can only be triggered by owner or governance, not custodian // Tokens are sent to the custodian, as a sort of safeguard TransferHelper.safeTransfer(tokenAddress, custodian_address, tokenAmount); emit RecoveredERC20(tokenAddress, tokenAmount); } function recoverERC721(address tokenAddress, uint256 token_id) external onlyByOwnGov { // Only the owner address can ever receive the recovery withdrawal // INonfungiblePositionManager inherits IERC721 so the latter does not need to be imported INonfungiblePositionManager(tokenAddress).safeTransferFrom( address(this), custodian_address, token_id); emit RecoveredERC721(tokenAddress, token_id); } // Generic proxy function execute( address _to, uint256 _value, bytes calldata _data ) external onlyByOwnGov returns (bool, bytes memory) { (bool success, bytes memory result) = _to.call{value:_value}(_data); return (success, result); } /* ========== EVENTS ========== */ event RecoveredERC20(address token, uint256 amount); event RecoveredERC721(address token, uint256 id); }
addCollateral
function addCollateral(address collat_addr) public onlyByOwnGov { require(collat_addr != address(0), "Zero address detected"); require(collat_addr != address(FRAX), "FRAX is not collateral"); require(allowed_collaterals[collat_addr] == false, "Address already exists"); allowed_collaterals[collat_addr] = true; collateral_addresses.push(collat_addr); }
// Only owner or timelock can call, to limit risk // Adds collateral addresses supported. Needed to make sure dollarBalances is correct
LineComment
v0.8.6+commit.11564f7e
{ "func_code_index": [ 14205, 14606 ] }
810
UniV3LiquidityAMO_V2
contracts/Misc_AMOs/UniV3LiquidityAMO_V2.sol
0xc91bb4b0696e3b48c0c501b4ce8e7244fc363a79
Solidity
UniV3LiquidityAMO_V2
contract UniV3LiquidityAMO_V2 is Owned { using SafeMath for uint256; using SafeERC20 for ERC20; /* ========== STATE VARIABLES ========== */ // Core FRAXStablecoin private FRAX; FRAXShares private FXS; IFraxAMOMinter private amo_minter; ERC20 private giveback_collateral; address public giveback_collateral_address; uint256 public missing_decimals_giveback_collat; address public timelock_address; address public custodian_address; // Uniswap v3 IUniswapV3Factory public univ3_factory; INonfungiblePositionManager public univ3_positions; ISwapRouter public univ3_router; // Price constants uint256 private constant PRICE_PRECISION = 1e6; // Wildcat AMO // Details about the AMO's uniswap positions struct Position { uint256 token_id; address collateral_address; uint128 liquidity; // the liquidity of the position int24 tickLower; // the tick range of the position int24 tickUpper; uint24 fee_tier; } // Array of all Uni v3 NFT positions held by the AMO Position[] public positions_array; // List of all collaterals address[] public collateral_addresses; mapping(address => bool) public allowed_collaterals; // Mapping is also used for faster verification mapping(address => OracleLike) public oracles; // Mapping of oracles (if oracle == address(0) the collateral is assumed to be pegged to 1usd) // Map token_id to Position mapping(uint256 => Position) public positions_mapping; /* ========== CONSTRUCTOR ========== */ constructor( address _creator_address, address _giveback_collateral_address, address _amo_minter_address ) Owned(_creator_address) { FRAX = FRAXStablecoin(0x853d955aCEf822Db058eb8505911ED77F175b99e); FXS = FRAXShares(0x3432B6A60D23Ca0dFCa7761B7ab56459D9C964D0); giveback_collateral_address = _giveback_collateral_address; giveback_collateral = ERC20(_giveback_collateral_address); missing_decimals_giveback_collat = uint(18).sub(giveback_collateral.decimals()); collateral_addresses.push(_giveback_collateral_address); allowed_collaterals[_giveback_collateral_address] = true; univ3_factory = IUniswapV3Factory(0x1F98431c8aD98523631AE4a59f267346ea31F984); univ3_positions = INonfungiblePositionManager(0xC36442b4a4522E871399CD717aBDD847Ab11FE88); univ3_router = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564); // Initialize the minter amo_minter = IFraxAMOMinter(_amo_minter_address); // Get the custodian and timelock addresses from the minter custodian_address = amo_minter.custodian_address(); timelock_address = amo_minter.timelock_address(); } /* ========== MODIFIERS ========== */ modifier onlyByOwnGov() { require(msg.sender == timelock_address || msg.sender == owner, "Not owner or timelock"); _; } modifier onlyByOwnGovCust() { require(msg.sender == timelock_address || msg.sender == owner || msg.sender == custodian_address, "Not owner, tlck, or custd"); _; } modifier onlyByMinter() { require(msg.sender == address(amo_minter), "Not minter"); _; } /* ========== VIEWS ========== */ function showAllocations() public view returns (uint256[4] memory allocations) { // All numbers given are in FRAX unless otherwise stated // Unallocated FRAX allocations[0] = FRAX.balanceOf(address(this)); // Unallocated Collateral Dollar Value (E18) allocations[1] = freeColDolVal(); // Sum of Uni v3 Positions liquidity, if it was all in FRAX allocations[2] = TotalLiquidityFrax(); // Total Value allocations[3] = allocations[0].add(allocations[1]).add(allocations[2]); } // E18 Collateral dollar value function freeColDolVal() public view returns (uint256) { uint256 value_tally_e18 = 0; for (uint i = 0; i < collateral_addresses.length; i++){ ERC20 thisCollateral = ERC20(collateral_addresses[i]); uint256 missing_decs = uint256(18).sub(thisCollateral.decimals()); uint256 col_bal_e18 = thisCollateral.balanceOf(address(this)).mul(10 ** missing_decs); uint256 col_usd_value_e18 = collatDolarValue(oracles[collateral_addresses[i]], col_bal_e18); value_tally_e18 = value_tally_e18.add(col_usd_value_e18); } return value_tally_e18; } // Convert collateral to dolar. If no oracle assumes pegged to 1USD. Both oracle, balance and return are E18 function collatDolarValue(OracleLike oracle, uint256 balance) public view returns (uint256) { if (address(oracle) == address(0)) return balance; return balance.mul(oracle.read()).div(1 ether); } // Needed for the Frax contract to function function collatDollarBalance() public view returns (uint256) { // Get the allocations uint256[4] memory allocations = showAllocations(); // Get the collateral and FRAX portions uint256 collat_portion = allocations[1]; uint256 frax_portion = (allocations[0]).add(allocations[2]); // Assumes worst case scenario if FRAX slips out of range. // Otherwise, it would only be half that is multiplied by the CR frax_portion = frax_portion.mul(FRAX.global_collateral_ratio()).div(PRICE_PRECISION); return (collat_portion).add(frax_portion); } function dollarBalances() public view returns (uint256 frax_val_e18, uint256 collat_val_e18) { frax_val_e18 = showAllocations()[3]; collat_val_e18 = collatDollarBalance(); } function TotalLiquidityFrax() public view returns (uint256) { uint256 frax_tally = 0; Position memory thisPosition; for (uint256 i = 0; i < positions_array.length; i++) { thisPosition = positions_array[i]; uint128 this_liq = thisPosition.liquidity; if (this_liq > 0){ uint160 sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(thisPosition.tickLower); uint160 sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(thisPosition.tickUpper); if (thisPosition.collateral_address > 0x853d955aCEf822Db058eb8505911ED77F175b99e){ // if address(FRAX) < collateral_address, then FRAX is token0 frax_tally = frax_tally.add(LiquidityAmounts.getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, this_liq)); } else { frax_tally = frax_tally.add(LiquidityAmounts.getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, this_liq)); } } } // Return the sum of all the positions' balances of FRAX, if the price fell off the range towards that side return frax_tally; } // Returns this contract's liquidity in a specific [FRAX]-[collateral] uni v3 pool function liquidityInPool(address _collateral_address, int24 _tickLower, int24 _tickUpper, uint24 _fee) public view returns (uint128) { IUniswapV3Pool get_pool = IUniswapV3Pool(univ3_factory.getPool(address(FRAX), _collateral_address, _fee)); // goes into the pool's positions mapping, and grabs this address's liquidity (uint128 liquidity, , , , ) = get_pool.positions(keccak256(abi.encodePacked(address(this), _tickLower, _tickUpper))); return liquidity; } // Backwards compatibility function mintedBalance() public view returns (int256) { return amo_minter.frax_mint_balances(address(this)); } // Backwards compatibility function collateralBalance() public view returns (int256) { return amo_minter.collat_borrowed_balances(address(this)); } // Only counts non-withdrawn positions function numPositions() public view returns (uint256) { return positions_array.length; } function allCollateralAddresses() external view returns (address[] memory) { return collateral_addresses; } /* ========== RESTRICTED FUNCTIONS, BUT CUSTODIAN CAN CALL ========== */ // Iterate through all positions and collect fees accumulated function collectFees() external onlyByOwnGovCust { for (uint i = 0; i < positions_array.length; i++){ Position memory current_position = positions_array[i]; INonfungiblePositionManager.CollectParams memory collect_params = INonfungiblePositionManager.CollectParams( current_position.token_id, custodian_address, type(uint128).max, type(uint128).max ); // Send to custodian address univ3_positions.collect(collect_params); } } /* ---------------------------------------------------- */ /* ---------------------- Uni v3 ---------------------- */ /* ---------------------------------------------------- */ function approveTarget(address _target, address _token, uint256 _amount, bool use_safe_approve) public onlyByOwnGov { if (use_safe_approve) { // safeApprove needed for USDT and others for the first approval // You need to approve 0 every time beforehand for USDT: it resets TransferHelper.safeApprove(_token, _target, _amount); } else { ERC20(_token).approve(_target, _amount); } } // IUniswapV3Pool public current_uni_pool; // only used for mint callback; is set and accessed during execution of addLiquidity() function addLiquidity(address _tokenA, address _tokenB, int24 _tickLower, int24 _tickUpper, uint24 _fee, uint256 _amount0Desired, uint256 _amount1Desired, uint256 _amount0Min, uint256 _amount1Min) public onlyByOwnGov { // Make sure the collateral is allowed require(allowed_collaterals[_tokenA] || _tokenA == address(FRAX), "TokenA not allowed"); require(allowed_collaterals[_tokenB] || _tokenB == address(FRAX), "TokenB not allowed"); ERC20(_tokenA).transferFrom(msg.sender, address(this), _amount0Desired); ERC20(_tokenB).transferFrom(msg.sender, address(this), _amount1Desired); ERC20(_tokenA).approve(address(univ3_positions), _amount0Desired); ERC20(_tokenB).approve(address(univ3_positions), _amount1Desired); INonfungiblePositionManager.MintParams memory params = INonfungiblePositionManager.MintParams( _tokenA, _tokenB, _fee, _tickLower, _tickUpper, _amount0Desired, _amount1Desired, _amount0Min, _amount1Min, address(this), block.timestamp ); (uint256 tokenId, uint128 amountLiquidity,,) = univ3_positions.mint(params); Position memory pos = Position( tokenId, _tokenA == address(FRAX) ? _tokenB : _tokenA, amountLiquidity, _tickLower, _tickUpper, _fee ); positions_array.push(pos); positions_mapping[tokenId] = pos; } /* ** burn tokenAmount from the recipient and send tokens to the receipient */ event log(uint); function removeLiquidity(uint256 positionIndex) public onlyByOwnGov { Position memory pos = positions_array[positionIndex]; INonfungiblePositionManager.CollectParams memory collect_params = INonfungiblePositionManager.CollectParams( pos.token_id, custodian_address, type(uint128).max, type(uint128).max ); univ3_positions.collect(collect_params); univ3_positions.burn(pos.token_id); positions_array[positionIndex] = positions_array[positions_array.length -1]; positions_array.pop(); delete positions_mapping[pos.token_id]; emit log(positions_array.length); emit log(positions_mapping[pos.token_id].token_id); } // Swap tokenA into tokenB using univ3_router.ExactInputSingle() // Uni V3 only function swap(address _tokenA, address _tokenB, uint24 _fee_tier, uint256 _amountAtoB, uint256 _amountOutMinimum, uint160 _sqrtPriceLimitX96) public onlyByOwnGov returns (uint256) { // Make sure the collateral is allowed require(allowed_collaterals[_tokenA] || _tokenA == address(FRAX), "TokenA not allowed"); require(allowed_collaterals[_tokenB] || _tokenB == address(FRAX), "TokenB not allowed"); ISwapRouter.ExactInputSingleParams memory swap_params = ISwapRouter.ExactInputSingleParams( _tokenA, _tokenB, _fee_tier, address(this), 2105300114, // Expiration: a long time from now _amountAtoB, _amountOutMinimum, _sqrtPriceLimitX96 ); // Approval TransferHelper.safeApprove(_tokenA, address(univ3_router), _amountAtoB); uint256 amountOut = univ3_router.exactInputSingle(swap_params); return amountOut; } /* ========== Burns and givebacks ========== */ // Give USDC profits back. Goes through the minter function giveCollatBack(uint256 collat_amount) external onlyByOwnGovCust { giveback_collateral.approve(address(amo_minter), collat_amount); amo_minter.receiveCollatFromAMO(collat_amount); } // Burn unneeded or excess FRAX. Goes through the minter function burnFRAX(uint256 frax_amount) public onlyByOwnGovCust { FRAX.approve(address(amo_minter), frax_amount); amo_minter.burnFraxFromAMO(frax_amount); } // Burn unneeded FXS. Goes through the minter function burnFXS(uint256 fxs_amount) public onlyByOwnGovCust { FXS.approve(address(amo_minter), fxs_amount); amo_minter.burnFxsFromAMO(fxs_amount); } /* ========== OWNER / GOVERNANCE FUNCTIONS ONLY ========== */ // Only owner or timelock can call, to limit risk // Adds collateral addresses supported. Needed to make sure dollarBalances is correct function addCollateral(address collat_addr) public onlyByOwnGov { require(collat_addr != address(0), "Zero address detected"); require(collat_addr != address(FRAX), "FRAX is not collateral"); require(allowed_collaterals[collat_addr] == false, "Address already exists"); allowed_collaterals[collat_addr] = true; collateral_addresses.push(collat_addr); } // Adds oracle for collateral. Optional for 1usd pegged coins. function addOracle(address collat_addr, address oracle) public onlyByOwnGov { require(collat_addr != address(0), "Zero address detected"); require(collat_addr != address(FRAX), "FRAX is not collateral"); oracles[collat_addr] = OracleLike(oracle); } function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov { // Can only be triggered by owner or governance, not custodian // Tokens are sent to the custodian, as a sort of safeguard TransferHelper.safeTransfer(tokenAddress, custodian_address, tokenAmount); emit RecoveredERC20(tokenAddress, tokenAmount); } function recoverERC721(address tokenAddress, uint256 token_id) external onlyByOwnGov { // Only the owner address can ever receive the recovery withdrawal // INonfungiblePositionManager inherits IERC721 so the latter does not need to be imported INonfungiblePositionManager(tokenAddress).safeTransferFrom( address(this), custodian_address, token_id); emit RecoveredERC721(tokenAddress, token_id); } // Generic proxy function execute( address _to, uint256 _value, bytes calldata _data ) external onlyByOwnGov returns (bool, bytes memory) { (bool success, bytes memory result) = _to.call{value:_value}(_data); return (success, result); } /* ========== EVENTS ========== */ event RecoveredERC20(address token, uint256 amount); event RecoveredERC721(address token, uint256 id); }
addOracle
function addOracle(address collat_addr, address oracle) public onlyByOwnGov { require(collat_addr != address(0), "Zero address detected"); require(collat_addr != address(FRAX), "FRAX is not collateral"); oracles[collat_addr] = OracleLike(oracle); }
// Adds oracle for collateral. Optional for 1usd pegged coins.
LineComment
v0.8.6+commit.11564f7e
{ "func_code_index": [ 14675, 14956 ] }
811
UniV3LiquidityAMO_V2
contracts/Misc_AMOs/UniV3LiquidityAMO_V2.sol
0xc91bb4b0696e3b48c0c501b4ce8e7244fc363a79
Solidity
UniV3LiquidityAMO_V2
contract UniV3LiquidityAMO_V2 is Owned { using SafeMath for uint256; using SafeERC20 for ERC20; /* ========== STATE VARIABLES ========== */ // Core FRAXStablecoin private FRAX; FRAXShares private FXS; IFraxAMOMinter private amo_minter; ERC20 private giveback_collateral; address public giveback_collateral_address; uint256 public missing_decimals_giveback_collat; address public timelock_address; address public custodian_address; // Uniswap v3 IUniswapV3Factory public univ3_factory; INonfungiblePositionManager public univ3_positions; ISwapRouter public univ3_router; // Price constants uint256 private constant PRICE_PRECISION = 1e6; // Wildcat AMO // Details about the AMO's uniswap positions struct Position { uint256 token_id; address collateral_address; uint128 liquidity; // the liquidity of the position int24 tickLower; // the tick range of the position int24 tickUpper; uint24 fee_tier; } // Array of all Uni v3 NFT positions held by the AMO Position[] public positions_array; // List of all collaterals address[] public collateral_addresses; mapping(address => bool) public allowed_collaterals; // Mapping is also used for faster verification mapping(address => OracleLike) public oracles; // Mapping of oracles (if oracle == address(0) the collateral is assumed to be pegged to 1usd) // Map token_id to Position mapping(uint256 => Position) public positions_mapping; /* ========== CONSTRUCTOR ========== */ constructor( address _creator_address, address _giveback_collateral_address, address _amo_minter_address ) Owned(_creator_address) { FRAX = FRAXStablecoin(0x853d955aCEf822Db058eb8505911ED77F175b99e); FXS = FRAXShares(0x3432B6A60D23Ca0dFCa7761B7ab56459D9C964D0); giveback_collateral_address = _giveback_collateral_address; giveback_collateral = ERC20(_giveback_collateral_address); missing_decimals_giveback_collat = uint(18).sub(giveback_collateral.decimals()); collateral_addresses.push(_giveback_collateral_address); allowed_collaterals[_giveback_collateral_address] = true; univ3_factory = IUniswapV3Factory(0x1F98431c8aD98523631AE4a59f267346ea31F984); univ3_positions = INonfungiblePositionManager(0xC36442b4a4522E871399CD717aBDD847Ab11FE88); univ3_router = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564); // Initialize the minter amo_minter = IFraxAMOMinter(_amo_minter_address); // Get the custodian and timelock addresses from the minter custodian_address = amo_minter.custodian_address(); timelock_address = amo_minter.timelock_address(); } /* ========== MODIFIERS ========== */ modifier onlyByOwnGov() { require(msg.sender == timelock_address || msg.sender == owner, "Not owner or timelock"); _; } modifier onlyByOwnGovCust() { require(msg.sender == timelock_address || msg.sender == owner || msg.sender == custodian_address, "Not owner, tlck, or custd"); _; } modifier onlyByMinter() { require(msg.sender == address(amo_minter), "Not minter"); _; } /* ========== VIEWS ========== */ function showAllocations() public view returns (uint256[4] memory allocations) { // All numbers given are in FRAX unless otherwise stated // Unallocated FRAX allocations[0] = FRAX.balanceOf(address(this)); // Unallocated Collateral Dollar Value (E18) allocations[1] = freeColDolVal(); // Sum of Uni v3 Positions liquidity, if it was all in FRAX allocations[2] = TotalLiquidityFrax(); // Total Value allocations[3] = allocations[0].add(allocations[1]).add(allocations[2]); } // E18 Collateral dollar value function freeColDolVal() public view returns (uint256) { uint256 value_tally_e18 = 0; for (uint i = 0; i < collateral_addresses.length; i++){ ERC20 thisCollateral = ERC20(collateral_addresses[i]); uint256 missing_decs = uint256(18).sub(thisCollateral.decimals()); uint256 col_bal_e18 = thisCollateral.balanceOf(address(this)).mul(10 ** missing_decs); uint256 col_usd_value_e18 = collatDolarValue(oracles[collateral_addresses[i]], col_bal_e18); value_tally_e18 = value_tally_e18.add(col_usd_value_e18); } return value_tally_e18; } // Convert collateral to dolar. If no oracle assumes pegged to 1USD. Both oracle, balance and return are E18 function collatDolarValue(OracleLike oracle, uint256 balance) public view returns (uint256) { if (address(oracle) == address(0)) return balance; return balance.mul(oracle.read()).div(1 ether); } // Needed for the Frax contract to function function collatDollarBalance() public view returns (uint256) { // Get the allocations uint256[4] memory allocations = showAllocations(); // Get the collateral and FRAX portions uint256 collat_portion = allocations[1]; uint256 frax_portion = (allocations[0]).add(allocations[2]); // Assumes worst case scenario if FRAX slips out of range. // Otherwise, it would only be half that is multiplied by the CR frax_portion = frax_portion.mul(FRAX.global_collateral_ratio()).div(PRICE_PRECISION); return (collat_portion).add(frax_portion); } function dollarBalances() public view returns (uint256 frax_val_e18, uint256 collat_val_e18) { frax_val_e18 = showAllocations()[3]; collat_val_e18 = collatDollarBalance(); } function TotalLiquidityFrax() public view returns (uint256) { uint256 frax_tally = 0; Position memory thisPosition; for (uint256 i = 0; i < positions_array.length; i++) { thisPosition = positions_array[i]; uint128 this_liq = thisPosition.liquidity; if (this_liq > 0){ uint160 sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(thisPosition.tickLower); uint160 sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(thisPosition.tickUpper); if (thisPosition.collateral_address > 0x853d955aCEf822Db058eb8505911ED77F175b99e){ // if address(FRAX) < collateral_address, then FRAX is token0 frax_tally = frax_tally.add(LiquidityAmounts.getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, this_liq)); } else { frax_tally = frax_tally.add(LiquidityAmounts.getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, this_liq)); } } } // Return the sum of all the positions' balances of FRAX, if the price fell off the range towards that side return frax_tally; } // Returns this contract's liquidity in a specific [FRAX]-[collateral] uni v3 pool function liquidityInPool(address _collateral_address, int24 _tickLower, int24 _tickUpper, uint24 _fee) public view returns (uint128) { IUniswapV3Pool get_pool = IUniswapV3Pool(univ3_factory.getPool(address(FRAX), _collateral_address, _fee)); // goes into the pool's positions mapping, and grabs this address's liquidity (uint128 liquidity, , , , ) = get_pool.positions(keccak256(abi.encodePacked(address(this), _tickLower, _tickUpper))); return liquidity; } // Backwards compatibility function mintedBalance() public view returns (int256) { return amo_minter.frax_mint_balances(address(this)); } // Backwards compatibility function collateralBalance() public view returns (int256) { return amo_minter.collat_borrowed_balances(address(this)); } // Only counts non-withdrawn positions function numPositions() public view returns (uint256) { return positions_array.length; } function allCollateralAddresses() external view returns (address[] memory) { return collateral_addresses; } /* ========== RESTRICTED FUNCTIONS, BUT CUSTODIAN CAN CALL ========== */ // Iterate through all positions and collect fees accumulated function collectFees() external onlyByOwnGovCust { for (uint i = 0; i < positions_array.length; i++){ Position memory current_position = positions_array[i]; INonfungiblePositionManager.CollectParams memory collect_params = INonfungiblePositionManager.CollectParams( current_position.token_id, custodian_address, type(uint128).max, type(uint128).max ); // Send to custodian address univ3_positions.collect(collect_params); } } /* ---------------------------------------------------- */ /* ---------------------- Uni v3 ---------------------- */ /* ---------------------------------------------------- */ function approveTarget(address _target, address _token, uint256 _amount, bool use_safe_approve) public onlyByOwnGov { if (use_safe_approve) { // safeApprove needed for USDT and others for the first approval // You need to approve 0 every time beforehand for USDT: it resets TransferHelper.safeApprove(_token, _target, _amount); } else { ERC20(_token).approve(_target, _amount); } } // IUniswapV3Pool public current_uni_pool; // only used for mint callback; is set and accessed during execution of addLiquidity() function addLiquidity(address _tokenA, address _tokenB, int24 _tickLower, int24 _tickUpper, uint24 _fee, uint256 _amount0Desired, uint256 _amount1Desired, uint256 _amount0Min, uint256 _amount1Min) public onlyByOwnGov { // Make sure the collateral is allowed require(allowed_collaterals[_tokenA] || _tokenA == address(FRAX), "TokenA not allowed"); require(allowed_collaterals[_tokenB] || _tokenB == address(FRAX), "TokenB not allowed"); ERC20(_tokenA).transferFrom(msg.sender, address(this), _amount0Desired); ERC20(_tokenB).transferFrom(msg.sender, address(this), _amount1Desired); ERC20(_tokenA).approve(address(univ3_positions), _amount0Desired); ERC20(_tokenB).approve(address(univ3_positions), _amount1Desired); INonfungiblePositionManager.MintParams memory params = INonfungiblePositionManager.MintParams( _tokenA, _tokenB, _fee, _tickLower, _tickUpper, _amount0Desired, _amount1Desired, _amount0Min, _amount1Min, address(this), block.timestamp ); (uint256 tokenId, uint128 amountLiquidity,,) = univ3_positions.mint(params); Position memory pos = Position( tokenId, _tokenA == address(FRAX) ? _tokenB : _tokenA, amountLiquidity, _tickLower, _tickUpper, _fee ); positions_array.push(pos); positions_mapping[tokenId] = pos; } /* ** burn tokenAmount from the recipient and send tokens to the receipient */ event log(uint); function removeLiquidity(uint256 positionIndex) public onlyByOwnGov { Position memory pos = positions_array[positionIndex]; INonfungiblePositionManager.CollectParams memory collect_params = INonfungiblePositionManager.CollectParams( pos.token_id, custodian_address, type(uint128).max, type(uint128).max ); univ3_positions.collect(collect_params); univ3_positions.burn(pos.token_id); positions_array[positionIndex] = positions_array[positions_array.length -1]; positions_array.pop(); delete positions_mapping[pos.token_id]; emit log(positions_array.length); emit log(positions_mapping[pos.token_id].token_id); } // Swap tokenA into tokenB using univ3_router.ExactInputSingle() // Uni V3 only function swap(address _tokenA, address _tokenB, uint24 _fee_tier, uint256 _amountAtoB, uint256 _amountOutMinimum, uint160 _sqrtPriceLimitX96) public onlyByOwnGov returns (uint256) { // Make sure the collateral is allowed require(allowed_collaterals[_tokenA] || _tokenA == address(FRAX), "TokenA not allowed"); require(allowed_collaterals[_tokenB] || _tokenB == address(FRAX), "TokenB not allowed"); ISwapRouter.ExactInputSingleParams memory swap_params = ISwapRouter.ExactInputSingleParams( _tokenA, _tokenB, _fee_tier, address(this), 2105300114, // Expiration: a long time from now _amountAtoB, _amountOutMinimum, _sqrtPriceLimitX96 ); // Approval TransferHelper.safeApprove(_tokenA, address(univ3_router), _amountAtoB); uint256 amountOut = univ3_router.exactInputSingle(swap_params); return amountOut; } /* ========== Burns and givebacks ========== */ // Give USDC profits back. Goes through the minter function giveCollatBack(uint256 collat_amount) external onlyByOwnGovCust { giveback_collateral.approve(address(amo_minter), collat_amount); amo_minter.receiveCollatFromAMO(collat_amount); } // Burn unneeded or excess FRAX. Goes through the minter function burnFRAX(uint256 frax_amount) public onlyByOwnGovCust { FRAX.approve(address(amo_minter), frax_amount); amo_minter.burnFraxFromAMO(frax_amount); } // Burn unneeded FXS. Goes through the minter function burnFXS(uint256 fxs_amount) public onlyByOwnGovCust { FXS.approve(address(amo_minter), fxs_amount); amo_minter.burnFxsFromAMO(fxs_amount); } /* ========== OWNER / GOVERNANCE FUNCTIONS ONLY ========== */ // Only owner or timelock can call, to limit risk // Adds collateral addresses supported. Needed to make sure dollarBalances is correct function addCollateral(address collat_addr) public onlyByOwnGov { require(collat_addr != address(0), "Zero address detected"); require(collat_addr != address(FRAX), "FRAX is not collateral"); require(allowed_collaterals[collat_addr] == false, "Address already exists"); allowed_collaterals[collat_addr] = true; collateral_addresses.push(collat_addr); } // Adds oracle for collateral. Optional for 1usd pegged coins. function addOracle(address collat_addr, address oracle) public onlyByOwnGov { require(collat_addr != address(0), "Zero address detected"); require(collat_addr != address(FRAX), "FRAX is not collateral"); oracles[collat_addr] = OracleLike(oracle); } function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov { // Can only be triggered by owner or governance, not custodian // Tokens are sent to the custodian, as a sort of safeguard TransferHelper.safeTransfer(tokenAddress, custodian_address, tokenAmount); emit RecoveredERC20(tokenAddress, tokenAmount); } function recoverERC721(address tokenAddress, uint256 token_id) external onlyByOwnGov { // Only the owner address can ever receive the recovery withdrawal // INonfungiblePositionManager inherits IERC721 so the latter does not need to be imported INonfungiblePositionManager(tokenAddress).safeTransferFrom( address(this), custodian_address, token_id); emit RecoveredERC721(tokenAddress, token_id); } // Generic proxy function execute( address _to, uint256 _value, bytes calldata _data ) external onlyByOwnGov returns (bool, bytes memory) { (bool success, bytes memory result) = _to.call{value:_value}(_data); return (success, result); } /* ========== EVENTS ========== */ event RecoveredERC20(address token, uint256 amount); event RecoveredERC721(address token, uint256 id); }
execute
function execute( address _to, uint256 _value, bytes calldata _data ) external onlyByOwnGov returns (bool, bytes memory) { (bool success, bytes memory result) = _to.call{value:_value}(_data); return (success, result); }
// Generic proxy
LineComment
v0.8.6+commit.11564f7e
{ "func_code_index": [ 15797, 16068 ] }
812
ChibiDinosHalloWeen
contracts/ChibiDinosHalloWeen.sol
0x8fba374c20d8f8e837d50748a4a9c2c62ea74f35
Solidity
ChibiDinosHalloWeen
contract ChibiDinosHalloWeen is ERC721Enumerable, Ownable { using Strings for uint256; string public baseURI; string public baseExtension = ".json"; string public notRevealedUri; uint256 public cost = 0.1 ether; uint256 public maxSupply = 3000; uint256 public maxMintAmount = 18; uint256 public nftPerAddressLimit = 18; bool public paused = true; bool public revealed = false; bool public onlyWhitelisted = true; address[] public whitelistedAddresses; mapping(address => uint256) public addressMintedBalance; constructor( string memory _name, string memory _symbol, string memory _initBaseURI, string memory _initNotRevealedUri ) ERC721(_name, _symbol) { setBaseURI(_initBaseURI); setNotRevealedURI(_initNotRevealedUri); } // internal function _baseURI() internal view virtual override returns (string memory) { return baseURI; } // public function mint(uint256 _mintAmount) public payable { require(!paused, "the contract is paused"); uint256 supply = totalSupply(); _mintAmount = _mintAmount * 6; require(_mintAmount > 0, "need to mint at least 1 NFT"); require(_mintAmount <= maxMintAmount, "max mint amount per session exceeded"); require(supply + _mintAmount <= maxSupply, "max NFT limit exceeded"); if (msg.sender != owner()) { if(onlyWhitelisted == true) { require(isWhitelisted(msg.sender), "user is not whitelisted"); uint256 ownerMintedCount = addressMintedBalance[msg.sender]; require(ownerMintedCount + _mintAmount <= nftPerAddressLimit, "max NFT per address exceeded"); } // require(msg.value >= cost * _mintAmount, "insufficient funds"); require(msg.value >= cost , "insufficient funds"); } for (uint256 i = 1; i <= _mintAmount; i++) { addressMintedBalance[msg.sender]++; _safeMint(msg.sender, supply + i); } } function isWhitelisted(address _user) public view returns (bool) { for (uint i = 0; i < whitelistedAddresses.length; i++) { if (whitelistedAddresses[i] == _user) { return true; } } return false; } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); if(revealed == false) { return notRevealedUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } //only owner function reveal() public onlyOwner { revealed = true; } function setNftPerAddressLimit(uint24 _limit) public onlyOwner { nftPerAddressLimit = _limit; } function setCost(uint256 _newCost) public onlyOwner { cost = _newCost; } function setmaxMintAmount(uint24 _newmaxMintAmount) public onlyOwner { maxMintAmount = _newmaxMintAmount; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedUri = _notRevealedURI; } function pause(bool _state) public onlyOwner { paused = _state; } function setOnlyWhitelisted(bool _state) public onlyOwner { onlyWhitelisted = _state; } function whitelistUsers(address[] calldata _users) public onlyOwner { delete whitelistedAddresses; whitelistedAddresses = _users; } function withdraw() public payable onlyOwner { // Do not remove this otherwise you will not be able to withdraw the funds. // ============================================================================= (bool os, ) = payable(owner()).call{value: address(this).balance}(""); require(os); // ============================================================================= } }
_baseURI
function _baseURI() internal view virtual override returns (string memory) { return baseURI; }
// internal
LineComment
v0.8.7+commit.e28d00a7
MIT
ipfs://f45300ce30cc3f4de344a93f0329d9844de31733a00e5211e9005bec86443cc8
{ "func_code_index": [ 823, 928 ] }
813
ChibiDinosHalloWeen
contracts/ChibiDinosHalloWeen.sol
0x8fba374c20d8f8e837d50748a4a9c2c62ea74f35
Solidity
ChibiDinosHalloWeen
contract ChibiDinosHalloWeen is ERC721Enumerable, Ownable { using Strings for uint256; string public baseURI; string public baseExtension = ".json"; string public notRevealedUri; uint256 public cost = 0.1 ether; uint256 public maxSupply = 3000; uint256 public maxMintAmount = 18; uint256 public nftPerAddressLimit = 18; bool public paused = true; bool public revealed = false; bool public onlyWhitelisted = true; address[] public whitelistedAddresses; mapping(address => uint256) public addressMintedBalance; constructor( string memory _name, string memory _symbol, string memory _initBaseURI, string memory _initNotRevealedUri ) ERC721(_name, _symbol) { setBaseURI(_initBaseURI); setNotRevealedURI(_initNotRevealedUri); } // internal function _baseURI() internal view virtual override returns (string memory) { return baseURI; } // public function mint(uint256 _mintAmount) public payable { require(!paused, "the contract is paused"); uint256 supply = totalSupply(); _mintAmount = _mintAmount * 6; require(_mintAmount > 0, "need to mint at least 1 NFT"); require(_mintAmount <= maxMintAmount, "max mint amount per session exceeded"); require(supply + _mintAmount <= maxSupply, "max NFT limit exceeded"); if (msg.sender != owner()) { if(onlyWhitelisted == true) { require(isWhitelisted(msg.sender), "user is not whitelisted"); uint256 ownerMintedCount = addressMintedBalance[msg.sender]; require(ownerMintedCount + _mintAmount <= nftPerAddressLimit, "max NFT per address exceeded"); } // require(msg.value >= cost * _mintAmount, "insufficient funds"); require(msg.value >= cost , "insufficient funds"); } for (uint256 i = 1; i <= _mintAmount; i++) { addressMintedBalance[msg.sender]++; _safeMint(msg.sender, supply + i); } } function isWhitelisted(address _user) public view returns (bool) { for (uint i = 0; i < whitelistedAddresses.length; i++) { if (whitelistedAddresses[i] == _user) { return true; } } return false; } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); if(revealed == false) { return notRevealedUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } //only owner function reveal() public onlyOwner { revealed = true; } function setNftPerAddressLimit(uint24 _limit) public onlyOwner { nftPerAddressLimit = _limit; } function setCost(uint256 _newCost) public onlyOwner { cost = _newCost; } function setmaxMintAmount(uint24 _newmaxMintAmount) public onlyOwner { maxMintAmount = _newmaxMintAmount; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedUri = _notRevealedURI; } function pause(bool _state) public onlyOwner { paused = _state; } function setOnlyWhitelisted(bool _state) public onlyOwner { onlyWhitelisted = _state; } function whitelistUsers(address[] calldata _users) public onlyOwner { delete whitelistedAddresses; whitelistedAddresses = _users; } function withdraw() public payable onlyOwner { // Do not remove this otherwise you will not be able to withdraw the funds. // ============================================================================= (bool os, ) = payable(owner()).call{value: address(this).balance}(""); require(os); // ============================================================================= } }
mint
function mint(uint256 _mintAmount) public payable { require(!paused, "the contract is paused"); uint256 supply = totalSupply(); _mintAmount = _mintAmount * 6; require(_mintAmount > 0, "need to mint at least 1 NFT"); require(_mintAmount <= maxMintAmount, "max mint amount per session exceeded"); require(supply + _mintAmount <= maxSupply, "max NFT limit exceeded"); if (msg.sender != owner()) { if(onlyWhitelisted == true) { require(isWhitelisted(msg.sender), "user is not whitelisted"); uint256 ownerMintedCount = addressMintedBalance[msg.sender]; require(ownerMintedCount + _mintAmount <= nftPerAddressLimit, "max NFT per address exceeded"); } // require(msg.value >= cost * _mintAmount, "insufficient funds"); require(msg.value >= cost , "insufficient funds"); } for (uint256 i = 1; i <= _mintAmount; i++) { addressMintedBalance[msg.sender]++; _safeMint(msg.sender, supply + i); } }
// public
LineComment
v0.8.7+commit.e28d00a7
MIT
ipfs://f45300ce30cc3f4de344a93f0329d9844de31733a00e5211e9005bec86443cc8
{ "func_code_index": [ 944, 1977 ] }
814
ChibiDinosHalloWeen
contracts/ChibiDinosHalloWeen.sol
0x8fba374c20d8f8e837d50748a4a9c2c62ea74f35
Solidity
ChibiDinosHalloWeen
contract ChibiDinosHalloWeen is ERC721Enumerable, Ownable { using Strings for uint256; string public baseURI; string public baseExtension = ".json"; string public notRevealedUri; uint256 public cost = 0.1 ether; uint256 public maxSupply = 3000; uint256 public maxMintAmount = 18; uint256 public nftPerAddressLimit = 18; bool public paused = true; bool public revealed = false; bool public onlyWhitelisted = true; address[] public whitelistedAddresses; mapping(address => uint256) public addressMintedBalance; constructor( string memory _name, string memory _symbol, string memory _initBaseURI, string memory _initNotRevealedUri ) ERC721(_name, _symbol) { setBaseURI(_initBaseURI); setNotRevealedURI(_initNotRevealedUri); } // internal function _baseURI() internal view virtual override returns (string memory) { return baseURI; } // public function mint(uint256 _mintAmount) public payable { require(!paused, "the contract is paused"); uint256 supply = totalSupply(); _mintAmount = _mintAmount * 6; require(_mintAmount > 0, "need to mint at least 1 NFT"); require(_mintAmount <= maxMintAmount, "max mint amount per session exceeded"); require(supply + _mintAmount <= maxSupply, "max NFT limit exceeded"); if (msg.sender != owner()) { if(onlyWhitelisted == true) { require(isWhitelisted(msg.sender), "user is not whitelisted"); uint256 ownerMintedCount = addressMintedBalance[msg.sender]; require(ownerMintedCount + _mintAmount <= nftPerAddressLimit, "max NFT per address exceeded"); } // require(msg.value >= cost * _mintAmount, "insufficient funds"); require(msg.value >= cost , "insufficient funds"); } for (uint256 i = 1; i <= _mintAmount; i++) { addressMintedBalance[msg.sender]++; _safeMint(msg.sender, supply + i); } } function isWhitelisted(address _user) public view returns (bool) { for (uint i = 0; i < whitelistedAddresses.length; i++) { if (whitelistedAddresses[i] == _user) { return true; } } return false; } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); if(revealed == false) { return notRevealedUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } //only owner function reveal() public onlyOwner { revealed = true; } function setNftPerAddressLimit(uint24 _limit) public onlyOwner { nftPerAddressLimit = _limit; } function setCost(uint256 _newCost) public onlyOwner { cost = _newCost; } function setmaxMintAmount(uint24 _newmaxMintAmount) public onlyOwner { maxMintAmount = _newmaxMintAmount; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedUri = _notRevealedURI; } function pause(bool _state) public onlyOwner { paused = _state; } function setOnlyWhitelisted(bool _state) public onlyOwner { onlyWhitelisted = _state; } function whitelistUsers(address[] calldata _users) public onlyOwner { delete whitelistedAddresses; whitelistedAddresses = _users; } function withdraw() public payable onlyOwner { // Do not remove this otherwise you will not be able to withdraw the funds. // ============================================================================= (bool os, ) = payable(owner()).call{value: address(this).balance}(""); require(os); // ============================================================================= } }
reveal
function reveal() public onlyOwner { revealed = true; }
//only owner
LineComment
v0.8.7+commit.e28d00a7
MIT
ipfs://f45300ce30cc3f4de344a93f0329d9844de31733a00e5211e9005bec86443cc8
{ "func_code_index": [ 3100, 3168 ] }
815
EmblemVault
browser/EmblemVault_v2.sol
0x82c7a8f707110f5fbb16184a5933e9f78a34c6ab
Solidity
EmblemVault
contract EmblemVault is NFTokenEnumerableMetadata, Ownable { /** * @dev Contract constructor. Sets metadata extension `name` and `symbol`. */ constructor() public { nftName = "Emblem Vault V2"; nftSymbol = "Emblem.pro"; } function changeName(string calldata name, string calldata symbol) external onlyOwner { nftName = name; nftSymbol = symbol; } /** * @dev Mints a new NFT. * @param _to The address that will own the minted NFT. * @param _tokenId of the NFT to be minted by the msg.sender. * @param _uri String representing RFC 3986 URI. */ function mint( address _to, uint256 _tokenId, string calldata _uri, string calldata _payload) external onlyOwner { super._mint(_to, _tokenId); super._setTokenUri(_tokenId, _uri); super._setTokenPayload(_tokenId, _payload); } function burn(uint256 _tokenId) external canTransfer(_tokenId) { super._burn(_tokenId); } function contractURI() public view returns (string memory) { return nftContractMetadataUri; } event UpdatedContractURI(string _from, string _to); function updateContractURI(string memory uri) public onlyOwner { emit UpdatedContractURI(nftContractMetadataUri, uri); nftContractMetadataUri = uri; } function getOwnerNFTCount(address _owner) public view returns (uint256) { return NFTokenEnumerableMetadata._getOwnerNFTCount(_owner); } function updateTokenUri( uint256 _tokenId, string memory _uri ) public validNFToken(_tokenId) onlyOwner { idToUri[_tokenId] = _uri; } }
/** * @dev This is an example contract implementation of NFToken with metadata extension. */
NatSpecMultiLine
mint
function mint( address _to, uint256 _tokenId, string calldata _uri, string calldata _payload) external onlyOwner { super._mint(_to, _tokenId); super._setTokenUri(_tokenId, _uri); super._setTokenPayload(_tokenId, _payload); }
/** * @dev Mints a new NFT. * @param _to The address that will own the minted NFT. * @param _tokenId of the NFT to be minted by the msg.sender. * @param _uri String representing RFC 3986 URI. */
NatSpecMultiLine
v0.6.2+commit.bacdbe57
MIT
ipfs://6626fd920334c84d658057cbe16dd3b47b41fc7475707238fefa241a53c0a511
{ "func_code_index": [ 628, 873 ] }
816
MightierThanTheSword
MightierThanTheSword.sol
0x8d10111af48659c1d8537f01880ce5995b5a6ec1
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } }
transfer
function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; }
/** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
None
bzzr://25736f9b52887ae20065dca6812b9001537be6fba8d4cb8dd0dad9b011784055
{ "func_code_index": [ 268, 664 ] }
817
MightierThanTheSword
MightierThanTheSword.sol
0x8d10111af48659c1d8537f01880ce5995b5a6ec1
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } }
balanceOf
function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; }
/** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
None
bzzr://25736f9b52887ae20065dca6812b9001537be6fba8d4cb8dd0dad9b011784055
{ "func_code_index": [ 870, 986 ] }
818
MightierThanTheSword
MightierThanTheSword.sol
0x8d10111af48659c1d8537f01880ce5995b5a6ec1
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } }
transferFrom
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; }
/** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
None
bzzr://25736f9b52887ae20065dca6812b9001537be6fba8d4cb8dd0dad9b011784055
{ "func_code_index": [ 401, 858 ] }
819
MightierThanTheSword
MightierThanTheSword.sol
0x8d10111af48659c1d8537f01880ce5995b5a6ec1
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } }
approve
function approve(address _spender, uint256 _value) public returns (bool) { require((_value == 0) || (allowed[msg.sender][_spender] == 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.4.26+commit.4563c3fc
None
bzzr://25736f9b52887ae20065dca6812b9001537be6fba8d4cb8dd0dad9b011784055
{ "func_code_index": [ 1490, 1754 ] }
820
MightierThanTheSword
MightierThanTheSword.sol
0x8d10111af48659c1d8537f01880ce5995b5a6ec1
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } }
allowance
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; }
/** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
None
bzzr://25736f9b52887ae20065dca6812b9001537be6fba8d4cb8dd0dad9b011784055
{ "func_code_index": [ 2078, 2223 ] }
821
Inke
Inke.sol
0x5301a786c6d68bf3fb97e13cb2c71e671f6fa69e
Solidity
InkeGold
contract InkeGold is ERC20Interface, Administration, SafeMath { event GoldTransfer(address indexed from, address indexed to, uint tokens); string public goldSymbol; string public goldName; uint8 public goldDecimals; uint public _goldTotalSupply; mapping(address => uint) goldBalances; mapping(address => bool) goldFreezed; mapping(address => uint) goldFreezeAmount; mapping(address => uint) goldUnlockTime; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { goldSymbol = "IKG"; goldName = "Inke Gold"; goldDecimals = 0; _goldTotalSupply = 45000; goldBalances[CEOAddress] = _goldTotalSupply; emit GoldTransfer(address(0), CEOAddress, _goldTotalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function goldTotalSupply() public constant returns (uint) { return _goldTotalSupply - goldBalances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function goldBalanceOf(address tokenOwner) public constant returns (uint balance) { return goldBalances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function goldTransfer(address to, uint tokens) public whenNotPaused returns (bool success) { if(goldFreezed[msg.sender] == false){ goldBalances[msg.sender] = safeSub(goldBalances[msg.sender], tokens); goldBalances[to] = safeAdd(goldBalances[to], tokens); emit GoldTransfer(msg.sender, to, tokens); } else { if(goldBalances[msg.sender] > goldFreezeAmount[msg.sender]) { require(tokens <= safeSub(goldBalances[msg.sender], goldFreezeAmount[msg.sender])); goldBalances[msg.sender] = safeSub(goldBalances[msg.sender], tokens); goldBalances[to] = safeAdd(goldBalances[to], tokens); emit GoldTransfer(msg.sender, to, tokens); } } return true; } // ------------------------------------------------------------------------ // Mint Tokens // ------------------------------------------------------------------------ function mintGold(uint amount) public onlyCEO { goldBalances[msg.sender] = safeAdd(goldBalances[msg.sender], amount); _goldTotalSupply = safeAdd(_goldTotalSupply, amount); } // ------------------------------------------------------------------------ // Burn Tokens // ------------------------------------------------------------------------ function burnGold(uint amount) public onlyCEO { goldBalances[msg.sender] = safeSub(goldBalances[msg.sender], amount); _goldTotalSupply = safeSub(_goldTotalSupply, amount); } // ------------------------------------------------------------------------ // Freeze Tokens // ------------------------------------------------------------------------ function goldFreeze(address user, uint amount, uint period) public onlyAdmin { require(goldBalances[user] >= amount); goldFreezed[user] = true; goldUnlockTime[user] = uint(now) + period; goldFreezeAmount[user] = amount; } function _goldFreeze(uint amount) internal { require(goldFreezed[msg.sender] == false); require(goldBalances[msg.sender] >= amount); goldFreezed[msg.sender] = true; goldUnlockTime[msg.sender] = uint(-1); goldFreezeAmount[msg.sender] = amount; } // ------------------------------------------------------------------------ // UnFreeze Tokens // ------------------------------------------------------------------------ function goldUnFreeze() public whenNotPaused { require(goldFreezed[msg.sender] == true); require(goldUnlockTime[msg.sender] < uint(now)); goldFreezed[msg.sender] = false; goldFreezeAmount[msg.sender] = 0; } function _goldUnFreeze(uint _amount) internal { require(goldFreezed[msg.sender] == true); goldUnlockTime[msg.sender] = 0; goldFreezed[msg.sender] = false; goldFreezeAmount[msg.sender] = safeSub(goldFreezeAmount[msg.sender], _amount); } function goldIfFreeze(address user) public view returns ( bool check, uint amount, uint timeLeft ) { check = goldFreezed[user]; amount = goldFreezeAmount[user]; timeLeft = goldUnlockTime[user] - uint(now); } }
goldTotalSupply
function goldTotalSupply() public constant returns (uint) { return _goldTotalSupply - goldBalances[address(0)]; }
// ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------
LineComment
v0.4.24+commit.e67f0147
bzzr://1d50d33bcacbc79c72c404b9ba3e0da98cc33b209a6a2c04acb355c1e24613c0
{ "func_code_index": [ 1115, 1248 ] }
822
Inke
Inke.sol
0x5301a786c6d68bf3fb97e13cb2c71e671f6fa69e
Solidity
InkeGold
contract InkeGold is ERC20Interface, Administration, SafeMath { event GoldTransfer(address indexed from, address indexed to, uint tokens); string public goldSymbol; string public goldName; uint8 public goldDecimals; uint public _goldTotalSupply; mapping(address => uint) goldBalances; mapping(address => bool) goldFreezed; mapping(address => uint) goldFreezeAmount; mapping(address => uint) goldUnlockTime; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { goldSymbol = "IKG"; goldName = "Inke Gold"; goldDecimals = 0; _goldTotalSupply = 45000; goldBalances[CEOAddress] = _goldTotalSupply; emit GoldTransfer(address(0), CEOAddress, _goldTotalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function goldTotalSupply() public constant returns (uint) { return _goldTotalSupply - goldBalances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function goldBalanceOf(address tokenOwner) public constant returns (uint balance) { return goldBalances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function goldTransfer(address to, uint tokens) public whenNotPaused returns (bool success) { if(goldFreezed[msg.sender] == false){ goldBalances[msg.sender] = safeSub(goldBalances[msg.sender], tokens); goldBalances[to] = safeAdd(goldBalances[to], tokens); emit GoldTransfer(msg.sender, to, tokens); } else { if(goldBalances[msg.sender] > goldFreezeAmount[msg.sender]) { require(tokens <= safeSub(goldBalances[msg.sender], goldFreezeAmount[msg.sender])); goldBalances[msg.sender] = safeSub(goldBalances[msg.sender], tokens); goldBalances[to] = safeAdd(goldBalances[to], tokens); emit GoldTransfer(msg.sender, to, tokens); } } return true; } // ------------------------------------------------------------------------ // Mint Tokens // ------------------------------------------------------------------------ function mintGold(uint amount) public onlyCEO { goldBalances[msg.sender] = safeAdd(goldBalances[msg.sender], amount); _goldTotalSupply = safeAdd(_goldTotalSupply, amount); } // ------------------------------------------------------------------------ // Burn Tokens // ------------------------------------------------------------------------ function burnGold(uint amount) public onlyCEO { goldBalances[msg.sender] = safeSub(goldBalances[msg.sender], amount); _goldTotalSupply = safeSub(_goldTotalSupply, amount); } // ------------------------------------------------------------------------ // Freeze Tokens // ------------------------------------------------------------------------ function goldFreeze(address user, uint amount, uint period) public onlyAdmin { require(goldBalances[user] >= amount); goldFreezed[user] = true; goldUnlockTime[user] = uint(now) + period; goldFreezeAmount[user] = amount; } function _goldFreeze(uint amount) internal { require(goldFreezed[msg.sender] == false); require(goldBalances[msg.sender] >= amount); goldFreezed[msg.sender] = true; goldUnlockTime[msg.sender] = uint(-1); goldFreezeAmount[msg.sender] = amount; } // ------------------------------------------------------------------------ // UnFreeze Tokens // ------------------------------------------------------------------------ function goldUnFreeze() public whenNotPaused { require(goldFreezed[msg.sender] == true); require(goldUnlockTime[msg.sender] < uint(now)); goldFreezed[msg.sender] = false; goldFreezeAmount[msg.sender] = 0; } function _goldUnFreeze(uint _amount) internal { require(goldFreezed[msg.sender] == true); goldUnlockTime[msg.sender] = 0; goldFreezed[msg.sender] = false; goldFreezeAmount[msg.sender] = safeSub(goldFreezeAmount[msg.sender], _amount); } function goldIfFreeze(address user) public view returns ( bool check, uint amount, uint timeLeft ) { check = goldFreezed[user]; amount = goldFreezeAmount[user]; timeLeft = goldUnlockTime[user] - uint(now); } }
goldBalanceOf
function goldBalanceOf(address tokenOwner) public constant returns (uint balance) { return goldBalances[tokenOwner]; }
// ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------
LineComment
v0.4.24+commit.e67f0147
bzzr://1d50d33bcacbc79c72c404b9ba3e0da98cc33b209a6a2c04acb355c1e24613c0
{ "func_code_index": [ 1468, 1605 ] }
823
Inke
Inke.sol
0x5301a786c6d68bf3fb97e13cb2c71e671f6fa69e
Solidity
InkeGold
contract InkeGold is ERC20Interface, Administration, SafeMath { event GoldTransfer(address indexed from, address indexed to, uint tokens); string public goldSymbol; string public goldName; uint8 public goldDecimals; uint public _goldTotalSupply; mapping(address => uint) goldBalances; mapping(address => bool) goldFreezed; mapping(address => uint) goldFreezeAmount; mapping(address => uint) goldUnlockTime; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { goldSymbol = "IKG"; goldName = "Inke Gold"; goldDecimals = 0; _goldTotalSupply = 45000; goldBalances[CEOAddress] = _goldTotalSupply; emit GoldTransfer(address(0), CEOAddress, _goldTotalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function goldTotalSupply() public constant returns (uint) { return _goldTotalSupply - goldBalances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function goldBalanceOf(address tokenOwner) public constant returns (uint balance) { return goldBalances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function goldTransfer(address to, uint tokens) public whenNotPaused returns (bool success) { if(goldFreezed[msg.sender] == false){ goldBalances[msg.sender] = safeSub(goldBalances[msg.sender], tokens); goldBalances[to] = safeAdd(goldBalances[to], tokens); emit GoldTransfer(msg.sender, to, tokens); } else { if(goldBalances[msg.sender] > goldFreezeAmount[msg.sender]) { require(tokens <= safeSub(goldBalances[msg.sender], goldFreezeAmount[msg.sender])); goldBalances[msg.sender] = safeSub(goldBalances[msg.sender], tokens); goldBalances[to] = safeAdd(goldBalances[to], tokens); emit GoldTransfer(msg.sender, to, tokens); } } return true; } // ------------------------------------------------------------------------ // Mint Tokens // ------------------------------------------------------------------------ function mintGold(uint amount) public onlyCEO { goldBalances[msg.sender] = safeAdd(goldBalances[msg.sender], amount); _goldTotalSupply = safeAdd(_goldTotalSupply, amount); } // ------------------------------------------------------------------------ // Burn Tokens // ------------------------------------------------------------------------ function burnGold(uint amount) public onlyCEO { goldBalances[msg.sender] = safeSub(goldBalances[msg.sender], amount); _goldTotalSupply = safeSub(_goldTotalSupply, amount); } // ------------------------------------------------------------------------ // Freeze Tokens // ------------------------------------------------------------------------ function goldFreeze(address user, uint amount, uint period) public onlyAdmin { require(goldBalances[user] >= amount); goldFreezed[user] = true; goldUnlockTime[user] = uint(now) + period; goldFreezeAmount[user] = amount; } function _goldFreeze(uint amount) internal { require(goldFreezed[msg.sender] == false); require(goldBalances[msg.sender] >= amount); goldFreezed[msg.sender] = true; goldUnlockTime[msg.sender] = uint(-1); goldFreezeAmount[msg.sender] = amount; } // ------------------------------------------------------------------------ // UnFreeze Tokens // ------------------------------------------------------------------------ function goldUnFreeze() public whenNotPaused { require(goldFreezed[msg.sender] == true); require(goldUnlockTime[msg.sender] < uint(now)); goldFreezed[msg.sender] = false; goldFreezeAmount[msg.sender] = 0; } function _goldUnFreeze(uint _amount) internal { require(goldFreezed[msg.sender] == true); goldUnlockTime[msg.sender] = 0; goldFreezed[msg.sender] = false; goldFreezeAmount[msg.sender] = safeSub(goldFreezeAmount[msg.sender], _amount); } function goldIfFreeze(address user) public view returns ( bool check, uint amount, uint timeLeft ) { check = goldFreezed[user]; amount = goldFreezeAmount[user]; timeLeft = goldUnlockTime[user] - uint(now); } }
goldTransfer
function goldTransfer(address to, uint tokens) public whenNotPaused returns (bool success) { if(goldFreezed[msg.sender] == false){ goldBalances[msg.sender] = safeSub(goldBalances[msg.sender], tokens); goldBalances[to] = safeAdd(goldBalances[to], tokens); emit GoldTransfer(msg.sender, to, tokens); } else { if(goldBalances[msg.sender] > goldFreezeAmount[msg.sender]) { require(tokens <= safeSub(goldBalances[msg.sender], goldFreezeAmount[msg.sender])); goldBalances[msg.sender] = safeSub(goldBalances[msg.sender], tokens); goldBalances[to] = safeAdd(goldBalances[to], tokens); emit GoldTransfer(msg.sender, to, tokens); } } return true; }
// ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------
LineComment
v0.4.24+commit.e67f0147
bzzr://1d50d33bcacbc79c72c404b9ba3e0da98cc33b209a6a2c04acb355c1e24613c0
{ "func_code_index": [ 1949, 2780 ] }
824
Inke
Inke.sol
0x5301a786c6d68bf3fb97e13cb2c71e671f6fa69e
Solidity
InkeGold
contract InkeGold is ERC20Interface, Administration, SafeMath { event GoldTransfer(address indexed from, address indexed to, uint tokens); string public goldSymbol; string public goldName; uint8 public goldDecimals; uint public _goldTotalSupply; mapping(address => uint) goldBalances; mapping(address => bool) goldFreezed; mapping(address => uint) goldFreezeAmount; mapping(address => uint) goldUnlockTime; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { goldSymbol = "IKG"; goldName = "Inke Gold"; goldDecimals = 0; _goldTotalSupply = 45000; goldBalances[CEOAddress] = _goldTotalSupply; emit GoldTransfer(address(0), CEOAddress, _goldTotalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function goldTotalSupply() public constant returns (uint) { return _goldTotalSupply - goldBalances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function goldBalanceOf(address tokenOwner) public constant returns (uint balance) { return goldBalances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function goldTransfer(address to, uint tokens) public whenNotPaused returns (bool success) { if(goldFreezed[msg.sender] == false){ goldBalances[msg.sender] = safeSub(goldBalances[msg.sender], tokens); goldBalances[to] = safeAdd(goldBalances[to], tokens); emit GoldTransfer(msg.sender, to, tokens); } else { if(goldBalances[msg.sender] > goldFreezeAmount[msg.sender]) { require(tokens <= safeSub(goldBalances[msg.sender], goldFreezeAmount[msg.sender])); goldBalances[msg.sender] = safeSub(goldBalances[msg.sender], tokens); goldBalances[to] = safeAdd(goldBalances[to], tokens); emit GoldTransfer(msg.sender, to, tokens); } } return true; } // ------------------------------------------------------------------------ // Mint Tokens // ------------------------------------------------------------------------ function mintGold(uint amount) public onlyCEO { goldBalances[msg.sender] = safeAdd(goldBalances[msg.sender], amount); _goldTotalSupply = safeAdd(_goldTotalSupply, amount); } // ------------------------------------------------------------------------ // Burn Tokens // ------------------------------------------------------------------------ function burnGold(uint amount) public onlyCEO { goldBalances[msg.sender] = safeSub(goldBalances[msg.sender], amount); _goldTotalSupply = safeSub(_goldTotalSupply, amount); } // ------------------------------------------------------------------------ // Freeze Tokens // ------------------------------------------------------------------------ function goldFreeze(address user, uint amount, uint period) public onlyAdmin { require(goldBalances[user] >= amount); goldFreezed[user] = true; goldUnlockTime[user] = uint(now) + period; goldFreezeAmount[user] = amount; } function _goldFreeze(uint amount) internal { require(goldFreezed[msg.sender] == false); require(goldBalances[msg.sender] >= amount); goldFreezed[msg.sender] = true; goldUnlockTime[msg.sender] = uint(-1); goldFreezeAmount[msg.sender] = amount; } // ------------------------------------------------------------------------ // UnFreeze Tokens // ------------------------------------------------------------------------ function goldUnFreeze() public whenNotPaused { require(goldFreezed[msg.sender] == true); require(goldUnlockTime[msg.sender] < uint(now)); goldFreezed[msg.sender] = false; goldFreezeAmount[msg.sender] = 0; } function _goldUnFreeze(uint _amount) internal { require(goldFreezed[msg.sender] == true); goldUnlockTime[msg.sender] = 0; goldFreezed[msg.sender] = false; goldFreezeAmount[msg.sender] = safeSub(goldFreezeAmount[msg.sender], _amount); } function goldIfFreeze(address user) public view returns ( bool check, uint amount, uint timeLeft ) { check = goldFreezed[user]; amount = goldFreezeAmount[user]; timeLeft = goldUnlockTime[user] - uint(now); } }
mintGold
function mintGold(uint amount) public onlyCEO { goldBalances[msg.sender] = safeAdd(goldBalances[msg.sender], amount); _goldTotalSupply = safeAdd(_goldTotalSupply, amount); }
// ------------------------------------------------------------------------ // Mint Tokens // ------------------------------------------------------------------------
LineComment
v0.4.24+commit.e67f0147
bzzr://1d50d33bcacbc79c72c404b9ba3e0da98cc33b209a6a2c04acb355c1e24613c0
{ "func_code_index": [ 2965, 3166 ] }
825
Inke
Inke.sol
0x5301a786c6d68bf3fb97e13cb2c71e671f6fa69e
Solidity
InkeGold
contract InkeGold is ERC20Interface, Administration, SafeMath { event GoldTransfer(address indexed from, address indexed to, uint tokens); string public goldSymbol; string public goldName; uint8 public goldDecimals; uint public _goldTotalSupply; mapping(address => uint) goldBalances; mapping(address => bool) goldFreezed; mapping(address => uint) goldFreezeAmount; mapping(address => uint) goldUnlockTime; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { goldSymbol = "IKG"; goldName = "Inke Gold"; goldDecimals = 0; _goldTotalSupply = 45000; goldBalances[CEOAddress] = _goldTotalSupply; emit GoldTransfer(address(0), CEOAddress, _goldTotalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function goldTotalSupply() public constant returns (uint) { return _goldTotalSupply - goldBalances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function goldBalanceOf(address tokenOwner) public constant returns (uint balance) { return goldBalances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function goldTransfer(address to, uint tokens) public whenNotPaused returns (bool success) { if(goldFreezed[msg.sender] == false){ goldBalances[msg.sender] = safeSub(goldBalances[msg.sender], tokens); goldBalances[to] = safeAdd(goldBalances[to], tokens); emit GoldTransfer(msg.sender, to, tokens); } else { if(goldBalances[msg.sender] > goldFreezeAmount[msg.sender]) { require(tokens <= safeSub(goldBalances[msg.sender], goldFreezeAmount[msg.sender])); goldBalances[msg.sender] = safeSub(goldBalances[msg.sender], tokens); goldBalances[to] = safeAdd(goldBalances[to], tokens); emit GoldTransfer(msg.sender, to, tokens); } } return true; } // ------------------------------------------------------------------------ // Mint Tokens // ------------------------------------------------------------------------ function mintGold(uint amount) public onlyCEO { goldBalances[msg.sender] = safeAdd(goldBalances[msg.sender], amount); _goldTotalSupply = safeAdd(_goldTotalSupply, amount); } // ------------------------------------------------------------------------ // Burn Tokens // ------------------------------------------------------------------------ function burnGold(uint amount) public onlyCEO { goldBalances[msg.sender] = safeSub(goldBalances[msg.sender], amount); _goldTotalSupply = safeSub(_goldTotalSupply, amount); } // ------------------------------------------------------------------------ // Freeze Tokens // ------------------------------------------------------------------------ function goldFreeze(address user, uint amount, uint period) public onlyAdmin { require(goldBalances[user] >= amount); goldFreezed[user] = true; goldUnlockTime[user] = uint(now) + period; goldFreezeAmount[user] = amount; } function _goldFreeze(uint amount) internal { require(goldFreezed[msg.sender] == false); require(goldBalances[msg.sender] >= amount); goldFreezed[msg.sender] = true; goldUnlockTime[msg.sender] = uint(-1); goldFreezeAmount[msg.sender] = amount; } // ------------------------------------------------------------------------ // UnFreeze Tokens // ------------------------------------------------------------------------ function goldUnFreeze() public whenNotPaused { require(goldFreezed[msg.sender] == true); require(goldUnlockTime[msg.sender] < uint(now)); goldFreezed[msg.sender] = false; goldFreezeAmount[msg.sender] = 0; } function _goldUnFreeze(uint _amount) internal { require(goldFreezed[msg.sender] == true); goldUnlockTime[msg.sender] = 0; goldFreezed[msg.sender] = false; goldFreezeAmount[msg.sender] = safeSub(goldFreezeAmount[msg.sender], _amount); } function goldIfFreeze(address user) public view returns ( bool check, uint amount, uint timeLeft ) { check = goldFreezed[user]; amount = goldFreezeAmount[user]; timeLeft = goldUnlockTime[user] - uint(now); } }
burnGold
function burnGold(uint amount) public onlyCEO { goldBalances[msg.sender] = safeSub(goldBalances[msg.sender], amount); _goldTotalSupply = safeSub(_goldTotalSupply, amount); }
// ------------------------------------------------------------------------ // Burn Tokens // ------------------------------------------------------------------------
LineComment
v0.4.24+commit.e67f0147
bzzr://1d50d33bcacbc79c72c404b9ba3e0da98cc33b209a6a2c04acb355c1e24613c0
{ "func_code_index": [ 3351, 3552 ] }
826
Inke
Inke.sol
0x5301a786c6d68bf3fb97e13cb2c71e671f6fa69e
Solidity
InkeGold
contract InkeGold is ERC20Interface, Administration, SafeMath { event GoldTransfer(address indexed from, address indexed to, uint tokens); string public goldSymbol; string public goldName; uint8 public goldDecimals; uint public _goldTotalSupply; mapping(address => uint) goldBalances; mapping(address => bool) goldFreezed; mapping(address => uint) goldFreezeAmount; mapping(address => uint) goldUnlockTime; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { goldSymbol = "IKG"; goldName = "Inke Gold"; goldDecimals = 0; _goldTotalSupply = 45000; goldBalances[CEOAddress] = _goldTotalSupply; emit GoldTransfer(address(0), CEOAddress, _goldTotalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function goldTotalSupply() public constant returns (uint) { return _goldTotalSupply - goldBalances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function goldBalanceOf(address tokenOwner) public constant returns (uint balance) { return goldBalances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function goldTransfer(address to, uint tokens) public whenNotPaused returns (bool success) { if(goldFreezed[msg.sender] == false){ goldBalances[msg.sender] = safeSub(goldBalances[msg.sender], tokens); goldBalances[to] = safeAdd(goldBalances[to], tokens); emit GoldTransfer(msg.sender, to, tokens); } else { if(goldBalances[msg.sender] > goldFreezeAmount[msg.sender]) { require(tokens <= safeSub(goldBalances[msg.sender], goldFreezeAmount[msg.sender])); goldBalances[msg.sender] = safeSub(goldBalances[msg.sender], tokens); goldBalances[to] = safeAdd(goldBalances[to], tokens); emit GoldTransfer(msg.sender, to, tokens); } } return true; } // ------------------------------------------------------------------------ // Mint Tokens // ------------------------------------------------------------------------ function mintGold(uint amount) public onlyCEO { goldBalances[msg.sender] = safeAdd(goldBalances[msg.sender], amount); _goldTotalSupply = safeAdd(_goldTotalSupply, amount); } // ------------------------------------------------------------------------ // Burn Tokens // ------------------------------------------------------------------------ function burnGold(uint amount) public onlyCEO { goldBalances[msg.sender] = safeSub(goldBalances[msg.sender], amount); _goldTotalSupply = safeSub(_goldTotalSupply, amount); } // ------------------------------------------------------------------------ // Freeze Tokens // ------------------------------------------------------------------------ function goldFreeze(address user, uint amount, uint period) public onlyAdmin { require(goldBalances[user] >= amount); goldFreezed[user] = true; goldUnlockTime[user] = uint(now) + period; goldFreezeAmount[user] = amount; } function _goldFreeze(uint amount) internal { require(goldFreezed[msg.sender] == false); require(goldBalances[msg.sender] >= amount); goldFreezed[msg.sender] = true; goldUnlockTime[msg.sender] = uint(-1); goldFreezeAmount[msg.sender] = amount; } // ------------------------------------------------------------------------ // UnFreeze Tokens // ------------------------------------------------------------------------ function goldUnFreeze() public whenNotPaused { require(goldFreezed[msg.sender] == true); require(goldUnlockTime[msg.sender] < uint(now)); goldFreezed[msg.sender] = false; goldFreezeAmount[msg.sender] = 0; } function _goldUnFreeze(uint _amount) internal { require(goldFreezed[msg.sender] == true); goldUnlockTime[msg.sender] = 0; goldFreezed[msg.sender] = false; goldFreezeAmount[msg.sender] = safeSub(goldFreezeAmount[msg.sender], _amount); } function goldIfFreeze(address user) public view returns ( bool check, uint amount, uint timeLeft ) { check = goldFreezed[user]; amount = goldFreezeAmount[user]; timeLeft = goldUnlockTime[user] - uint(now); } }
goldFreeze
function goldFreeze(address user, uint amount, uint period) public onlyAdmin { require(goldBalances[user] >= amount); goldFreezed[user] = true; goldUnlockTime[user] = uint(now) + period; goldFreezeAmount[user] = amount; }
// ------------------------------------------------------------------------ // Freeze Tokens // ------------------------------------------------------------------------
LineComment
v0.4.24+commit.e67f0147
bzzr://1d50d33bcacbc79c72c404b9ba3e0da98cc33b209a6a2c04acb355c1e24613c0
{ "func_code_index": [ 3743, 4010 ] }
827
Inke
Inke.sol
0x5301a786c6d68bf3fb97e13cb2c71e671f6fa69e
Solidity
InkeGold
contract InkeGold is ERC20Interface, Administration, SafeMath { event GoldTransfer(address indexed from, address indexed to, uint tokens); string public goldSymbol; string public goldName; uint8 public goldDecimals; uint public _goldTotalSupply; mapping(address => uint) goldBalances; mapping(address => bool) goldFreezed; mapping(address => uint) goldFreezeAmount; mapping(address => uint) goldUnlockTime; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { goldSymbol = "IKG"; goldName = "Inke Gold"; goldDecimals = 0; _goldTotalSupply = 45000; goldBalances[CEOAddress] = _goldTotalSupply; emit GoldTransfer(address(0), CEOAddress, _goldTotalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function goldTotalSupply() public constant returns (uint) { return _goldTotalSupply - goldBalances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function goldBalanceOf(address tokenOwner) public constant returns (uint balance) { return goldBalances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function goldTransfer(address to, uint tokens) public whenNotPaused returns (bool success) { if(goldFreezed[msg.sender] == false){ goldBalances[msg.sender] = safeSub(goldBalances[msg.sender], tokens); goldBalances[to] = safeAdd(goldBalances[to], tokens); emit GoldTransfer(msg.sender, to, tokens); } else { if(goldBalances[msg.sender] > goldFreezeAmount[msg.sender]) { require(tokens <= safeSub(goldBalances[msg.sender], goldFreezeAmount[msg.sender])); goldBalances[msg.sender] = safeSub(goldBalances[msg.sender], tokens); goldBalances[to] = safeAdd(goldBalances[to], tokens); emit GoldTransfer(msg.sender, to, tokens); } } return true; } // ------------------------------------------------------------------------ // Mint Tokens // ------------------------------------------------------------------------ function mintGold(uint amount) public onlyCEO { goldBalances[msg.sender] = safeAdd(goldBalances[msg.sender], amount); _goldTotalSupply = safeAdd(_goldTotalSupply, amount); } // ------------------------------------------------------------------------ // Burn Tokens // ------------------------------------------------------------------------ function burnGold(uint amount) public onlyCEO { goldBalances[msg.sender] = safeSub(goldBalances[msg.sender], amount); _goldTotalSupply = safeSub(_goldTotalSupply, amount); } // ------------------------------------------------------------------------ // Freeze Tokens // ------------------------------------------------------------------------ function goldFreeze(address user, uint amount, uint period) public onlyAdmin { require(goldBalances[user] >= amount); goldFreezed[user] = true; goldUnlockTime[user] = uint(now) + period; goldFreezeAmount[user] = amount; } function _goldFreeze(uint amount) internal { require(goldFreezed[msg.sender] == false); require(goldBalances[msg.sender] >= amount); goldFreezed[msg.sender] = true; goldUnlockTime[msg.sender] = uint(-1); goldFreezeAmount[msg.sender] = amount; } // ------------------------------------------------------------------------ // UnFreeze Tokens // ------------------------------------------------------------------------ function goldUnFreeze() public whenNotPaused { require(goldFreezed[msg.sender] == true); require(goldUnlockTime[msg.sender] < uint(now)); goldFreezed[msg.sender] = false; goldFreezeAmount[msg.sender] = 0; } function _goldUnFreeze(uint _amount) internal { require(goldFreezed[msg.sender] == true); goldUnlockTime[msg.sender] = 0; goldFreezed[msg.sender] = false; goldFreezeAmount[msg.sender] = safeSub(goldFreezeAmount[msg.sender], _amount); } function goldIfFreeze(address user) public view returns ( bool check, uint amount, uint timeLeft ) { check = goldFreezed[user]; amount = goldFreezeAmount[user]; timeLeft = goldUnlockTime[user] - uint(now); } }
goldUnFreeze
function goldUnFreeze() public whenNotPaused { require(goldFreezed[msg.sender] == true); require(goldUnlockTime[msg.sender] < uint(now)); goldFreezed[msg.sender] = false; goldFreezeAmount[msg.sender] = 0; }
// ------------------------------------------------------------------------ // UnFreeze Tokens // ------------------------------------------------------------------------
LineComment
v0.4.24+commit.e67f0147
bzzr://1d50d33bcacbc79c72c404b9ba3e0da98cc33b209a6a2c04acb355c1e24613c0
{ "func_code_index": [ 4505, 4757 ] }
828
Inke
Inke.sol
0x5301a786c6d68bf3fb97e13cb2c71e671f6fa69e
Solidity
InkeToken
contract InkeToken is InkeGold { event PartnerCreated(uint indexed partnerId, address indexed partner, uint indexed amount, uint singleTrans, uint durance); event RewardDistribute(uint indexed postId, uint partnerId, address indexed user, uint indexed amount); event VipAgreementSign(uint indexed vipId, address indexed vip, uint durance, uint frequence, uint salar); event SalaryReceived(uint indexed vipId, address indexed vip, uint salary, uint indexed timestamp); string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public minePool; // 60% uint public fundPool; // 30% struct Partner { address admin; uint tokenPool; uint singleTrans; uint timestamp; uint durance; } struct Poster { address poster; bytes32 hashData; uint reward; } struct Vip { address vip; uint durance; uint frequence; uint salary; uint timestamp; } Partner[] partners; Vip[] vips; modifier onlyPartner(uint _partnerId) { require(partners[_partnerId].admin == msg.sender); require(partners[_partnerId].tokenPool > uint(0)); uint deadline = safeAdd(partners[_partnerId].timestamp, partners[_partnerId].durance); require(deadline > now); _; } modifier onlyVip(uint _vipId) { require(vips[_vipId].vip == msg.sender); require(vips[_vipId].durance > now); require(vips[_vipId].timestamp < now); _; } mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; mapping(address => bool) freezed; mapping(address => uint) freezeAmount; mapping(address => uint) unlockTime; mapping(uint => Poster[]) PartnerIdToPosterList; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "Inke"; name = "Inke Token"; decimals = 18; _totalSupply = 10000000000000000000000000000; minePool = 60000000000000000000000000000; fundPool = 30000000000000000000000000000; balances[CEOAddress] = _totalSupply; emit Transfer(address(0), CEOAddress, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { if(freezed[msg.sender] == false){ balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); } else { if(balances[msg.sender] > freezeAmount[msg.sender]) { require(tokens <= safeSub(balances[msg.sender], freezeAmount[msg.sender])); balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); } } return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { require(freezed[msg.sender] != true); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { require(freezed[msg.sender] != true); return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { require(freezed[msg.sender] != true); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Mint Tokens // ------------------------------------------------------------------------ function _mine(uint amount, address receiver) internal { require(minePool >= amount); minePool = safeSub(minePool, amount); _totalSupply = safeAdd(_totalSupply, amount); balances[receiver] = safeAdd(balances[receiver], amount); emit Transfer(address(0), receiver, amount); } function _fund(uint amount, address receiver) internal { require(fundPool >= amount); fundPool = safeSub(fundPool, amount); _totalSupply = safeAdd(_totalSupply, amount); balances[receiver] = safeAdd(balances[receiver], amount); emit Transfer(address(0), receiver, amount); } function mint(uint amount) public onlyAdmin { _fund(amount, msg.sender); } function burn(uint amount) public onlyAdmin { require(_totalSupply >= amount); balances[msg.sender] = safeSub(balances[msg.sender], amount); _totalSupply = safeSub(_totalSupply, amount); } // ------------------------------------------------------------------------ // Freeze Tokens // ------------------------------------------------------------------------ function freeze(address user, uint amount, uint period) public onlyAdmin { require(balances[user] >= amount); freezed[user] = true; unlockTime[user] = uint(now) + period; freezeAmount[user] = amount; } // ------------------------------------------------------------------------ // UnFreeze Tokens // ------------------------------------------------------------------------ function unFreeze() public whenNotPaused { require(freezed[msg.sender] == true); require(unlockTime[msg.sender] < uint(now)); freezed[msg.sender] = false; freezeAmount[msg.sender] = 0; } function ifFreeze(address user) public view returns ( bool check, uint amount, uint timeLeft ) { check = freezed[user]; amount = freezeAmount[user]; timeLeft = unlockTime[user] - uint(now); } // ------------------------------------------------------------------------ // Partner Authorization // ------------------------------------------------------------------------ function createPartner(address _partner, uint _amount, uint _singleTrans, uint _durance) public onlyAdmin returns (uint) { Partner memory _Partner = Partner({ admin: _partner, tokenPool: _amount, singleTrans: _singleTrans, timestamp: uint(now), durance: _durance }); uint newPartnerId = partners.push(_Partner) - 1; emit PartnerCreated(newPartnerId, _partner, _amount, _singleTrans, _durance); return newPartnerId; } function partnerTransfer(uint _partnerId, bytes32 _data, address _to, uint _amount) public onlyPartner(_partnerId) whenNotPaused returns (bool) { require(_amount <= partners[_partnerId].singleTrans); partners[_partnerId].tokenPool = safeSub(partners[_partnerId].tokenPool, _amount); Poster memory _Poster = Poster ({ poster: _to, hashData: _data, reward: _amount }); uint newPostId = PartnerIdToPosterList[_partnerId].push(_Poster) - 1; _fund(_amount, _to); emit RewardDistribute(newPostId, _partnerId, _to, _amount); return true; } function setPartnerPool(uint _partnerId, uint _amount) public onlyAdmin { partners[_partnerId].tokenPool = _amount; } function setPartnerDurance(uint _partnerId, uint _durance) public onlyAdmin { partners[_partnerId].durance = uint(now) + _durance; } function getPartnerInfo(uint _partnerId) public view returns ( address admin, uint tokenPool, uint timeLeft ) { Partner memory _Partner = partners[_partnerId]; admin = _Partner.admin; tokenPool = _Partner.tokenPool; if (_Partner.timestamp + _Partner.durance > uint(now)) { timeLeft = _Partner.timestamp + _Partner.durance - uint(now); } else { timeLeft = 0; } } function getPosterInfo(uint _partnerId, uint _posterId) public view returns ( address poster, bytes32 hashData, uint reward ) { Poster memory _Poster = PartnerIdToPosterList[_partnerId][_posterId]; poster = _Poster.poster; hashData = _Poster.hashData; reward = _Poster.reward; } // ------------------------------------------------------------------------ // Vip Agreement // ------------------------------------------------------------------------ function createVip(address _vip, uint _durance, uint _frequence, uint _salary) public onlyAdmin returns (uint) { Vip memory _Vip = Vip ({ vip: _vip, durance: uint(now) + _durance, frequence: _frequence, salary: _salary, timestamp: now + _frequence }); uint newVipId = vips.push(_Vip) - 1; emit VipAgreementSign(newVipId, _vip, _durance, _frequence, _salary); return newVipId; } function mineSalary(uint _vipId) public onlyVip(_vipId) whenNotPaused returns (bool) { Vip storage _Vip = vips[_vipId]; _fund(_Vip.salary, _Vip.vip); _Vip.timestamp = safeAdd(_Vip.timestamp, _Vip.frequence); emit SalaryReceived(_vipId, _Vip.vip, _Vip.salary, _Vip.timestamp); return true; } function deleteVip(uint _vipId) public onlyAdmin { delete vips[_vipId]; } function getVipInfo(uint _vipId) public view returns ( address vip, uint durance, uint frequence, uint salary, uint nextSalary, string log ) { Vip memory _Vip = vips[_vipId]; vip = _Vip.vip; durance = _Vip.durance; frequence = _Vip.frequence; salary = _Vip.salary; if(_Vip.timestamp >= uint(now)) { nextSalary = safeSub(_Vip.timestamp, uint(now)); log = "Please Wait"; } else { nextSalary = 0; log = "Pick Up Your Salary Now"; } } // ------------------------------------------------------------------------ // Accept ETH // ------------------------------------------------------------------------ function () public payable { } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyAdmin returns (bool success) { return ERC20Interface(tokenAddress).transfer(CEOAddress, tokens); } }
totalSupply
function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; }
// ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------
LineComment
v0.4.24+commit.e67f0147
bzzr://1d50d33bcacbc79c72c404b9ba3e0da98cc33b209a6a2c04acb355c1e24613c0
{ "func_code_index": [ 2713, 2834 ] }
829
Inke
Inke.sol
0x5301a786c6d68bf3fb97e13cb2c71e671f6fa69e
Solidity
InkeToken
contract InkeToken is InkeGold { event PartnerCreated(uint indexed partnerId, address indexed partner, uint indexed amount, uint singleTrans, uint durance); event RewardDistribute(uint indexed postId, uint partnerId, address indexed user, uint indexed amount); event VipAgreementSign(uint indexed vipId, address indexed vip, uint durance, uint frequence, uint salar); event SalaryReceived(uint indexed vipId, address indexed vip, uint salary, uint indexed timestamp); string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public minePool; // 60% uint public fundPool; // 30% struct Partner { address admin; uint tokenPool; uint singleTrans; uint timestamp; uint durance; } struct Poster { address poster; bytes32 hashData; uint reward; } struct Vip { address vip; uint durance; uint frequence; uint salary; uint timestamp; } Partner[] partners; Vip[] vips; modifier onlyPartner(uint _partnerId) { require(partners[_partnerId].admin == msg.sender); require(partners[_partnerId].tokenPool > uint(0)); uint deadline = safeAdd(partners[_partnerId].timestamp, partners[_partnerId].durance); require(deadline > now); _; } modifier onlyVip(uint _vipId) { require(vips[_vipId].vip == msg.sender); require(vips[_vipId].durance > now); require(vips[_vipId].timestamp < now); _; } mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; mapping(address => bool) freezed; mapping(address => uint) freezeAmount; mapping(address => uint) unlockTime; mapping(uint => Poster[]) PartnerIdToPosterList; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "Inke"; name = "Inke Token"; decimals = 18; _totalSupply = 10000000000000000000000000000; minePool = 60000000000000000000000000000; fundPool = 30000000000000000000000000000; balances[CEOAddress] = _totalSupply; emit Transfer(address(0), CEOAddress, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { if(freezed[msg.sender] == false){ balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); } else { if(balances[msg.sender] > freezeAmount[msg.sender]) { require(tokens <= safeSub(balances[msg.sender], freezeAmount[msg.sender])); balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); } } return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { require(freezed[msg.sender] != true); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { require(freezed[msg.sender] != true); return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { require(freezed[msg.sender] != true); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Mint Tokens // ------------------------------------------------------------------------ function _mine(uint amount, address receiver) internal { require(minePool >= amount); minePool = safeSub(minePool, amount); _totalSupply = safeAdd(_totalSupply, amount); balances[receiver] = safeAdd(balances[receiver], amount); emit Transfer(address(0), receiver, amount); } function _fund(uint amount, address receiver) internal { require(fundPool >= amount); fundPool = safeSub(fundPool, amount); _totalSupply = safeAdd(_totalSupply, amount); balances[receiver] = safeAdd(balances[receiver], amount); emit Transfer(address(0), receiver, amount); } function mint(uint amount) public onlyAdmin { _fund(amount, msg.sender); } function burn(uint amount) public onlyAdmin { require(_totalSupply >= amount); balances[msg.sender] = safeSub(balances[msg.sender], amount); _totalSupply = safeSub(_totalSupply, amount); } // ------------------------------------------------------------------------ // Freeze Tokens // ------------------------------------------------------------------------ function freeze(address user, uint amount, uint period) public onlyAdmin { require(balances[user] >= amount); freezed[user] = true; unlockTime[user] = uint(now) + period; freezeAmount[user] = amount; } // ------------------------------------------------------------------------ // UnFreeze Tokens // ------------------------------------------------------------------------ function unFreeze() public whenNotPaused { require(freezed[msg.sender] == true); require(unlockTime[msg.sender] < uint(now)); freezed[msg.sender] = false; freezeAmount[msg.sender] = 0; } function ifFreeze(address user) public view returns ( bool check, uint amount, uint timeLeft ) { check = freezed[user]; amount = freezeAmount[user]; timeLeft = unlockTime[user] - uint(now); } // ------------------------------------------------------------------------ // Partner Authorization // ------------------------------------------------------------------------ function createPartner(address _partner, uint _amount, uint _singleTrans, uint _durance) public onlyAdmin returns (uint) { Partner memory _Partner = Partner({ admin: _partner, tokenPool: _amount, singleTrans: _singleTrans, timestamp: uint(now), durance: _durance }); uint newPartnerId = partners.push(_Partner) - 1; emit PartnerCreated(newPartnerId, _partner, _amount, _singleTrans, _durance); return newPartnerId; } function partnerTransfer(uint _partnerId, bytes32 _data, address _to, uint _amount) public onlyPartner(_partnerId) whenNotPaused returns (bool) { require(_amount <= partners[_partnerId].singleTrans); partners[_partnerId].tokenPool = safeSub(partners[_partnerId].tokenPool, _amount); Poster memory _Poster = Poster ({ poster: _to, hashData: _data, reward: _amount }); uint newPostId = PartnerIdToPosterList[_partnerId].push(_Poster) - 1; _fund(_amount, _to); emit RewardDistribute(newPostId, _partnerId, _to, _amount); return true; } function setPartnerPool(uint _partnerId, uint _amount) public onlyAdmin { partners[_partnerId].tokenPool = _amount; } function setPartnerDurance(uint _partnerId, uint _durance) public onlyAdmin { partners[_partnerId].durance = uint(now) + _durance; } function getPartnerInfo(uint _partnerId) public view returns ( address admin, uint tokenPool, uint timeLeft ) { Partner memory _Partner = partners[_partnerId]; admin = _Partner.admin; tokenPool = _Partner.tokenPool; if (_Partner.timestamp + _Partner.durance > uint(now)) { timeLeft = _Partner.timestamp + _Partner.durance - uint(now); } else { timeLeft = 0; } } function getPosterInfo(uint _partnerId, uint _posterId) public view returns ( address poster, bytes32 hashData, uint reward ) { Poster memory _Poster = PartnerIdToPosterList[_partnerId][_posterId]; poster = _Poster.poster; hashData = _Poster.hashData; reward = _Poster.reward; } // ------------------------------------------------------------------------ // Vip Agreement // ------------------------------------------------------------------------ function createVip(address _vip, uint _durance, uint _frequence, uint _salary) public onlyAdmin returns (uint) { Vip memory _Vip = Vip ({ vip: _vip, durance: uint(now) + _durance, frequence: _frequence, salary: _salary, timestamp: now + _frequence }); uint newVipId = vips.push(_Vip) - 1; emit VipAgreementSign(newVipId, _vip, _durance, _frequence, _salary); return newVipId; } function mineSalary(uint _vipId) public onlyVip(_vipId) whenNotPaused returns (bool) { Vip storage _Vip = vips[_vipId]; _fund(_Vip.salary, _Vip.vip); _Vip.timestamp = safeAdd(_Vip.timestamp, _Vip.frequence); emit SalaryReceived(_vipId, _Vip.vip, _Vip.salary, _Vip.timestamp); return true; } function deleteVip(uint _vipId) public onlyAdmin { delete vips[_vipId]; } function getVipInfo(uint _vipId) public view returns ( address vip, uint durance, uint frequence, uint salary, uint nextSalary, string log ) { Vip memory _Vip = vips[_vipId]; vip = _Vip.vip; durance = _Vip.durance; frequence = _Vip.frequence; salary = _Vip.salary; if(_Vip.timestamp >= uint(now)) { nextSalary = safeSub(_Vip.timestamp, uint(now)); log = "Please Wait"; } else { nextSalary = 0; log = "Pick Up Your Salary Now"; } } // ------------------------------------------------------------------------ // Accept ETH // ------------------------------------------------------------------------ function () public payable { } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyAdmin returns (bool success) { return ERC20Interface(tokenAddress).transfer(CEOAddress, tokens); } }
balanceOf
function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; }
// ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------
LineComment
v0.4.24+commit.e67f0147
bzzr://1d50d33bcacbc79c72c404b9ba3e0da98cc33b209a6a2c04acb355c1e24613c0
{ "func_code_index": [ 3054, 3183 ] }
830
Inke
Inke.sol
0x5301a786c6d68bf3fb97e13cb2c71e671f6fa69e
Solidity
InkeToken
contract InkeToken is InkeGold { event PartnerCreated(uint indexed partnerId, address indexed partner, uint indexed amount, uint singleTrans, uint durance); event RewardDistribute(uint indexed postId, uint partnerId, address indexed user, uint indexed amount); event VipAgreementSign(uint indexed vipId, address indexed vip, uint durance, uint frequence, uint salar); event SalaryReceived(uint indexed vipId, address indexed vip, uint salary, uint indexed timestamp); string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public minePool; // 60% uint public fundPool; // 30% struct Partner { address admin; uint tokenPool; uint singleTrans; uint timestamp; uint durance; } struct Poster { address poster; bytes32 hashData; uint reward; } struct Vip { address vip; uint durance; uint frequence; uint salary; uint timestamp; } Partner[] partners; Vip[] vips; modifier onlyPartner(uint _partnerId) { require(partners[_partnerId].admin == msg.sender); require(partners[_partnerId].tokenPool > uint(0)); uint deadline = safeAdd(partners[_partnerId].timestamp, partners[_partnerId].durance); require(deadline > now); _; } modifier onlyVip(uint _vipId) { require(vips[_vipId].vip == msg.sender); require(vips[_vipId].durance > now); require(vips[_vipId].timestamp < now); _; } mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; mapping(address => bool) freezed; mapping(address => uint) freezeAmount; mapping(address => uint) unlockTime; mapping(uint => Poster[]) PartnerIdToPosterList; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "Inke"; name = "Inke Token"; decimals = 18; _totalSupply = 10000000000000000000000000000; minePool = 60000000000000000000000000000; fundPool = 30000000000000000000000000000; balances[CEOAddress] = _totalSupply; emit Transfer(address(0), CEOAddress, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { if(freezed[msg.sender] == false){ balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); } else { if(balances[msg.sender] > freezeAmount[msg.sender]) { require(tokens <= safeSub(balances[msg.sender], freezeAmount[msg.sender])); balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); } } return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { require(freezed[msg.sender] != true); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { require(freezed[msg.sender] != true); return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { require(freezed[msg.sender] != true); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Mint Tokens // ------------------------------------------------------------------------ function _mine(uint amount, address receiver) internal { require(minePool >= amount); minePool = safeSub(minePool, amount); _totalSupply = safeAdd(_totalSupply, amount); balances[receiver] = safeAdd(balances[receiver], amount); emit Transfer(address(0), receiver, amount); } function _fund(uint amount, address receiver) internal { require(fundPool >= amount); fundPool = safeSub(fundPool, amount); _totalSupply = safeAdd(_totalSupply, amount); balances[receiver] = safeAdd(balances[receiver], amount); emit Transfer(address(0), receiver, amount); } function mint(uint amount) public onlyAdmin { _fund(amount, msg.sender); } function burn(uint amount) public onlyAdmin { require(_totalSupply >= amount); balances[msg.sender] = safeSub(balances[msg.sender], amount); _totalSupply = safeSub(_totalSupply, amount); } // ------------------------------------------------------------------------ // Freeze Tokens // ------------------------------------------------------------------------ function freeze(address user, uint amount, uint period) public onlyAdmin { require(balances[user] >= amount); freezed[user] = true; unlockTime[user] = uint(now) + period; freezeAmount[user] = amount; } // ------------------------------------------------------------------------ // UnFreeze Tokens // ------------------------------------------------------------------------ function unFreeze() public whenNotPaused { require(freezed[msg.sender] == true); require(unlockTime[msg.sender] < uint(now)); freezed[msg.sender] = false; freezeAmount[msg.sender] = 0; } function ifFreeze(address user) public view returns ( bool check, uint amount, uint timeLeft ) { check = freezed[user]; amount = freezeAmount[user]; timeLeft = unlockTime[user] - uint(now); } // ------------------------------------------------------------------------ // Partner Authorization // ------------------------------------------------------------------------ function createPartner(address _partner, uint _amount, uint _singleTrans, uint _durance) public onlyAdmin returns (uint) { Partner memory _Partner = Partner({ admin: _partner, tokenPool: _amount, singleTrans: _singleTrans, timestamp: uint(now), durance: _durance }); uint newPartnerId = partners.push(_Partner) - 1; emit PartnerCreated(newPartnerId, _partner, _amount, _singleTrans, _durance); return newPartnerId; } function partnerTransfer(uint _partnerId, bytes32 _data, address _to, uint _amount) public onlyPartner(_partnerId) whenNotPaused returns (bool) { require(_amount <= partners[_partnerId].singleTrans); partners[_partnerId].tokenPool = safeSub(partners[_partnerId].tokenPool, _amount); Poster memory _Poster = Poster ({ poster: _to, hashData: _data, reward: _amount }); uint newPostId = PartnerIdToPosterList[_partnerId].push(_Poster) - 1; _fund(_amount, _to); emit RewardDistribute(newPostId, _partnerId, _to, _amount); return true; } function setPartnerPool(uint _partnerId, uint _amount) public onlyAdmin { partners[_partnerId].tokenPool = _amount; } function setPartnerDurance(uint _partnerId, uint _durance) public onlyAdmin { partners[_partnerId].durance = uint(now) + _durance; } function getPartnerInfo(uint _partnerId) public view returns ( address admin, uint tokenPool, uint timeLeft ) { Partner memory _Partner = partners[_partnerId]; admin = _Partner.admin; tokenPool = _Partner.tokenPool; if (_Partner.timestamp + _Partner.durance > uint(now)) { timeLeft = _Partner.timestamp + _Partner.durance - uint(now); } else { timeLeft = 0; } } function getPosterInfo(uint _partnerId, uint _posterId) public view returns ( address poster, bytes32 hashData, uint reward ) { Poster memory _Poster = PartnerIdToPosterList[_partnerId][_posterId]; poster = _Poster.poster; hashData = _Poster.hashData; reward = _Poster.reward; } // ------------------------------------------------------------------------ // Vip Agreement // ------------------------------------------------------------------------ function createVip(address _vip, uint _durance, uint _frequence, uint _salary) public onlyAdmin returns (uint) { Vip memory _Vip = Vip ({ vip: _vip, durance: uint(now) + _durance, frequence: _frequence, salary: _salary, timestamp: now + _frequence }); uint newVipId = vips.push(_Vip) - 1; emit VipAgreementSign(newVipId, _vip, _durance, _frequence, _salary); return newVipId; } function mineSalary(uint _vipId) public onlyVip(_vipId) whenNotPaused returns (bool) { Vip storage _Vip = vips[_vipId]; _fund(_Vip.salary, _Vip.vip); _Vip.timestamp = safeAdd(_Vip.timestamp, _Vip.frequence); emit SalaryReceived(_vipId, _Vip.vip, _Vip.salary, _Vip.timestamp); return true; } function deleteVip(uint _vipId) public onlyAdmin { delete vips[_vipId]; } function getVipInfo(uint _vipId) public view returns ( address vip, uint durance, uint frequence, uint salary, uint nextSalary, string log ) { Vip memory _Vip = vips[_vipId]; vip = _Vip.vip; durance = _Vip.durance; frequence = _Vip.frequence; salary = _Vip.salary; if(_Vip.timestamp >= uint(now)) { nextSalary = safeSub(_Vip.timestamp, uint(now)); log = "Please Wait"; } else { nextSalary = 0; log = "Pick Up Your Salary Now"; } } // ------------------------------------------------------------------------ // Accept ETH // ------------------------------------------------------------------------ function () public payable { } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyAdmin returns (bool success) { return ERC20Interface(tokenAddress).transfer(CEOAddress, tokens); } }
transfer
function transfer(address to, uint tokens) public returns (bool success) { if(freezed[msg.sender] == false){ balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); } else { if(balances[msg.sender] > freezeAmount[msg.sender]) { require(tokens <= safeSub(balances[msg.sender], freezeAmount[msg.sender])); balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); } } return true; }
// ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------
LineComment
v0.4.24+commit.e67f0147
bzzr://1d50d33bcacbc79c72c404b9ba3e0da98cc33b209a6a2c04acb355c1e24613c0
{ "func_code_index": [ 3527, 4280 ] }
831
Inke
Inke.sol
0x5301a786c6d68bf3fb97e13cb2c71e671f6fa69e
Solidity
InkeToken
contract InkeToken is InkeGold { event PartnerCreated(uint indexed partnerId, address indexed partner, uint indexed amount, uint singleTrans, uint durance); event RewardDistribute(uint indexed postId, uint partnerId, address indexed user, uint indexed amount); event VipAgreementSign(uint indexed vipId, address indexed vip, uint durance, uint frequence, uint salar); event SalaryReceived(uint indexed vipId, address indexed vip, uint salary, uint indexed timestamp); string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public minePool; // 60% uint public fundPool; // 30% struct Partner { address admin; uint tokenPool; uint singleTrans; uint timestamp; uint durance; } struct Poster { address poster; bytes32 hashData; uint reward; } struct Vip { address vip; uint durance; uint frequence; uint salary; uint timestamp; } Partner[] partners; Vip[] vips; modifier onlyPartner(uint _partnerId) { require(partners[_partnerId].admin == msg.sender); require(partners[_partnerId].tokenPool > uint(0)); uint deadline = safeAdd(partners[_partnerId].timestamp, partners[_partnerId].durance); require(deadline > now); _; } modifier onlyVip(uint _vipId) { require(vips[_vipId].vip == msg.sender); require(vips[_vipId].durance > now); require(vips[_vipId].timestamp < now); _; } mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; mapping(address => bool) freezed; mapping(address => uint) freezeAmount; mapping(address => uint) unlockTime; mapping(uint => Poster[]) PartnerIdToPosterList; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "Inke"; name = "Inke Token"; decimals = 18; _totalSupply = 10000000000000000000000000000; minePool = 60000000000000000000000000000; fundPool = 30000000000000000000000000000; balances[CEOAddress] = _totalSupply; emit Transfer(address(0), CEOAddress, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { if(freezed[msg.sender] == false){ balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); } else { if(balances[msg.sender] > freezeAmount[msg.sender]) { require(tokens <= safeSub(balances[msg.sender], freezeAmount[msg.sender])); balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); } } return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { require(freezed[msg.sender] != true); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { require(freezed[msg.sender] != true); return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { require(freezed[msg.sender] != true); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Mint Tokens // ------------------------------------------------------------------------ function _mine(uint amount, address receiver) internal { require(minePool >= amount); minePool = safeSub(minePool, amount); _totalSupply = safeAdd(_totalSupply, amount); balances[receiver] = safeAdd(balances[receiver], amount); emit Transfer(address(0), receiver, amount); } function _fund(uint amount, address receiver) internal { require(fundPool >= amount); fundPool = safeSub(fundPool, amount); _totalSupply = safeAdd(_totalSupply, amount); balances[receiver] = safeAdd(balances[receiver], amount); emit Transfer(address(0), receiver, amount); } function mint(uint amount) public onlyAdmin { _fund(amount, msg.sender); } function burn(uint amount) public onlyAdmin { require(_totalSupply >= amount); balances[msg.sender] = safeSub(balances[msg.sender], amount); _totalSupply = safeSub(_totalSupply, amount); } // ------------------------------------------------------------------------ // Freeze Tokens // ------------------------------------------------------------------------ function freeze(address user, uint amount, uint period) public onlyAdmin { require(balances[user] >= amount); freezed[user] = true; unlockTime[user] = uint(now) + period; freezeAmount[user] = amount; } // ------------------------------------------------------------------------ // UnFreeze Tokens // ------------------------------------------------------------------------ function unFreeze() public whenNotPaused { require(freezed[msg.sender] == true); require(unlockTime[msg.sender] < uint(now)); freezed[msg.sender] = false; freezeAmount[msg.sender] = 0; } function ifFreeze(address user) public view returns ( bool check, uint amount, uint timeLeft ) { check = freezed[user]; amount = freezeAmount[user]; timeLeft = unlockTime[user] - uint(now); } // ------------------------------------------------------------------------ // Partner Authorization // ------------------------------------------------------------------------ function createPartner(address _partner, uint _amount, uint _singleTrans, uint _durance) public onlyAdmin returns (uint) { Partner memory _Partner = Partner({ admin: _partner, tokenPool: _amount, singleTrans: _singleTrans, timestamp: uint(now), durance: _durance }); uint newPartnerId = partners.push(_Partner) - 1; emit PartnerCreated(newPartnerId, _partner, _amount, _singleTrans, _durance); return newPartnerId; } function partnerTransfer(uint _partnerId, bytes32 _data, address _to, uint _amount) public onlyPartner(_partnerId) whenNotPaused returns (bool) { require(_amount <= partners[_partnerId].singleTrans); partners[_partnerId].tokenPool = safeSub(partners[_partnerId].tokenPool, _amount); Poster memory _Poster = Poster ({ poster: _to, hashData: _data, reward: _amount }); uint newPostId = PartnerIdToPosterList[_partnerId].push(_Poster) - 1; _fund(_amount, _to); emit RewardDistribute(newPostId, _partnerId, _to, _amount); return true; } function setPartnerPool(uint _partnerId, uint _amount) public onlyAdmin { partners[_partnerId].tokenPool = _amount; } function setPartnerDurance(uint _partnerId, uint _durance) public onlyAdmin { partners[_partnerId].durance = uint(now) + _durance; } function getPartnerInfo(uint _partnerId) public view returns ( address admin, uint tokenPool, uint timeLeft ) { Partner memory _Partner = partners[_partnerId]; admin = _Partner.admin; tokenPool = _Partner.tokenPool; if (_Partner.timestamp + _Partner.durance > uint(now)) { timeLeft = _Partner.timestamp + _Partner.durance - uint(now); } else { timeLeft = 0; } } function getPosterInfo(uint _partnerId, uint _posterId) public view returns ( address poster, bytes32 hashData, uint reward ) { Poster memory _Poster = PartnerIdToPosterList[_partnerId][_posterId]; poster = _Poster.poster; hashData = _Poster.hashData; reward = _Poster.reward; } // ------------------------------------------------------------------------ // Vip Agreement // ------------------------------------------------------------------------ function createVip(address _vip, uint _durance, uint _frequence, uint _salary) public onlyAdmin returns (uint) { Vip memory _Vip = Vip ({ vip: _vip, durance: uint(now) + _durance, frequence: _frequence, salary: _salary, timestamp: now + _frequence }); uint newVipId = vips.push(_Vip) - 1; emit VipAgreementSign(newVipId, _vip, _durance, _frequence, _salary); return newVipId; } function mineSalary(uint _vipId) public onlyVip(_vipId) whenNotPaused returns (bool) { Vip storage _Vip = vips[_vipId]; _fund(_Vip.salary, _Vip.vip); _Vip.timestamp = safeAdd(_Vip.timestamp, _Vip.frequence); emit SalaryReceived(_vipId, _Vip.vip, _Vip.salary, _Vip.timestamp); return true; } function deleteVip(uint _vipId) public onlyAdmin { delete vips[_vipId]; } function getVipInfo(uint _vipId) public view returns ( address vip, uint durance, uint frequence, uint salary, uint nextSalary, string log ) { Vip memory _Vip = vips[_vipId]; vip = _Vip.vip; durance = _Vip.durance; frequence = _Vip.frequence; salary = _Vip.salary; if(_Vip.timestamp >= uint(now)) { nextSalary = safeSub(_Vip.timestamp, uint(now)); log = "Please Wait"; } else { nextSalary = 0; log = "Pick Up Your Salary Now"; } } // ------------------------------------------------------------------------ // Accept ETH // ------------------------------------------------------------------------ function () public payable { } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyAdmin returns (bool success) { return ERC20Interface(tokenAddress).transfer(CEOAddress, tokens); } }
approve
function approve(address spender, uint tokens) public returns (bool success) { require(freezed[msg.sender] != true); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; }
// ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------
LineComment
v0.4.24+commit.e67f0147
bzzr://1d50d33bcacbc79c72c404b9ba3e0da98cc33b209a6a2c04acb355c1e24613c0
{ "func_code_index": [ 4788, 5048 ] }
832
Inke
Inke.sol
0x5301a786c6d68bf3fb97e13cb2c71e671f6fa69e
Solidity
InkeToken
contract InkeToken is InkeGold { event PartnerCreated(uint indexed partnerId, address indexed partner, uint indexed amount, uint singleTrans, uint durance); event RewardDistribute(uint indexed postId, uint partnerId, address indexed user, uint indexed amount); event VipAgreementSign(uint indexed vipId, address indexed vip, uint durance, uint frequence, uint salar); event SalaryReceived(uint indexed vipId, address indexed vip, uint salary, uint indexed timestamp); string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public minePool; // 60% uint public fundPool; // 30% struct Partner { address admin; uint tokenPool; uint singleTrans; uint timestamp; uint durance; } struct Poster { address poster; bytes32 hashData; uint reward; } struct Vip { address vip; uint durance; uint frequence; uint salary; uint timestamp; } Partner[] partners; Vip[] vips; modifier onlyPartner(uint _partnerId) { require(partners[_partnerId].admin == msg.sender); require(partners[_partnerId].tokenPool > uint(0)); uint deadline = safeAdd(partners[_partnerId].timestamp, partners[_partnerId].durance); require(deadline > now); _; } modifier onlyVip(uint _vipId) { require(vips[_vipId].vip == msg.sender); require(vips[_vipId].durance > now); require(vips[_vipId].timestamp < now); _; } mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; mapping(address => bool) freezed; mapping(address => uint) freezeAmount; mapping(address => uint) unlockTime; mapping(uint => Poster[]) PartnerIdToPosterList; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "Inke"; name = "Inke Token"; decimals = 18; _totalSupply = 10000000000000000000000000000; minePool = 60000000000000000000000000000; fundPool = 30000000000000000000000000000; balances[CEOAddress] = _totalSupply; emit Transfer(address(0), CEOAddress, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { if(freezed[msg.sender] == false){ balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); } else { if(balances[msg.sender] > freezeAmount[msg.sender]) { require(tokens <= safeSub(balances[msg.sender], freezeAmount[msg.sender])); balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); } } return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { require(freezed[msg.sender] != true); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { require(freezed[msg.sender] != true); return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { require(freezed[msg.sender] != true); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Mint Tokens // ------------------------------------------------------------------------ function _mine(uint amount, address receiver) internal { require(minePool >= amount); minePool = safeSub(minePool, amount); _totalSupply = safeAdd(_totalSupply, amount); balances[receiver] = safeAdd(balances[receiver], amount); emit Transfer(address(0), receiver, amount); } function _fund(uint amount, address receiver) internal { require(fundPool >= amount); fundPool = safeSub(fundPool, amount); _totalSupply = safeAdd(_totalSupply, amount); balances[receiver] = safeAdd(balances[receiver], amount); emit Transfer(address(0), receiver, amount); } function mint(uint amount) public onlyAdmin { _fund(amount, msg.sender); } function burn(uint amount) public onlyAdmin { require(_totalSupply >= amount); balances[msg.sender] = safeSub(balances[msg.sender], amount); _totalSupply = safeSub(_totalSupply, amount); } // ------------------------------------------------------------------------ // Freeze Tokens // ------------------------------------------------------------------------ function freeze(address user, uint amount, uint period) public onlyAdmin { require(balances[user] >= amount); freezed[user] = true; unlockTime[user] = uint(now) + period; freezeAmount[user] = amount; } // ------------------------------------------------------------------------ // UnFreeze Tokens // ------------------------------------------------------------------------ function unFreeze() public whenNotPaused { require(freezed[msg.sender] == true); require(unlockTime[msg.sender] < uint(now)); freezed[msg.sender] = false; freezeAmount[msg.sender] = 0; } function ifFreeze(address user) public view returns ( bool check, uint amount, uint timeLeft ) { check = freezed[user]; amount = freezeAmount[user]; timeLeft = unlockTime[user] - uint(now); } // ------------------------------------------------------------------------ // Partner Authorization // ------------------------------------------------------------------------ function createPartner(address _partner, uint _amount, uint _singleTrans, uint _durance) public onlyAdmin returns (uint) { Partner memory _Partner = Partner({ admin: _partner, tokenPool: _amount, singleTrans: _singleTrans, timestamp: uint(now), durance: _durance }); uint newPartnerId = partners.push(_Partner) - 1; emit PartnerCreated(newPartnerId, _partner, _amount, _singleTrans, _durance); return newPartnerId; } function partnerTransfer(uint _partnerId, bytes32 _data, address _to, uint _amount) public onlyPartner(_partnerId) whenNotPaused returns (bool) { require(_amount <= partners[_partnerId].singleTrans); partners[_partnerId].tokenPool = safeSub(partners[_partnerId].tokenPool, _amount); Poster memory _Poster = Poster ({ poster: _to, hashData: _data, reward: _amount }); uint newPostId = PartnerIdToPosterList[_partnerId].push(_Poster) - 1; _fund(_amount, _to); emit RewardDistribute(newPostId, _partnerId, _to, _amount); return true; } function setPartnerPool(uint _partnerId, uint _amount) public onlyAdmin { partners[_partnerId].tokenPool = _amount; } function setPartnerDurance(uint _partnerId, uint _durance) public onlyAdmin { partners[_partnerId].durance = uint(now) + _durance; } function getPartnerInfo(uint _partnerId) public view returns ( address admin, uint tokenPool, uint timeLeft ) { Partner memory _Partner = partners[_partnerId]; admin = _Partner.admin; tokenPool = _Partner.tokenPool; if (_Partner.timestamp + _Partner.durance > uint(now)) { timeLeft = _Partner.timestamp + _Partner.durance - uint(now); } else { timeLeft = 0; } } function getPosterInfo(uint _partnerId, uint _posterId) public view returns ( address poster, bytes32 hashData, uint reward ) { Poster memory _Poster = PartnerIdToPosterList[_partnerId][_posterId]; poster = _Poster.poster; hashData = _Poster.hashData; reward = _Poster.reward; } // ------------------------------------------------------------------------ // Vip Agreement // ------------------------------------------------------------------------ function createVip(address _vip, uint _durance, uint _frequence, uint _salary) public onlyAdmin returns (uint) { Vip memory _Vip = Vip ({ vip: _vip, durance: uint(now) + _durance, frequence: _frequence, salary: _salary, timestamp: now + _frequence }); uint newVipId = vips.push(_Vip) - 1; emit VipAgreementSign(newVipId, _vip, _durance, _frequence, _salary); return newVipId; } function mineSalary(uint _vipId) public onlyVip(_vipId) whenNotPaused returns (bool) { Vip storage _Vip = vips[_vipId]; _fund(_Vip.salary, _Vip.vip); _Vip.timestamp = safeAdd(_Vip.timestamp, _Vip.frequence); emit SalaryReceived(_vipId, _Vip.vip, _Vip.salary, _Vip.timestamp); return true; } function deleteVip(uint _vipId) public onlyAdmin { delete vips[_vipId]; } function getVipInfo(uint _vipId) public view returns ( address vip, uint durance, uint frequence, uint salary, uint nextSalary, string log ) { Vip memory _Vip = vips[_vipId]; vip = _Vip.vip; durance = _Vip.durance; frequence = _Vip.frequence; salary = _Vip.salary; if(_Vip.timestamp >= uint(now)) { nextSalary = safeSub(_Vip.timestamp, uint(now)); log = "Please Wait"; } else { nextSalary = 0; log = "Pick Up Your Salary Now"; } } // ------------------------------------------------------------------------ // Accept ETH // ------------------------------------------------------------------------ function () public payable { } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyAdmin returns (bool success) { return ERC20Interface(tokenAddress).transfer(CEOAddress, tokens); } }
transferFrom
function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; }
// ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------
LineComment
v0.4.24+commit.e67f0147
bzzr://1d50d33bcacbc79c72c404b9ba3e0da98cc33b209a6a2c04acb355c1e24613c0
{ "func_code_index": [ 5579, 5942 ] }
833
Inke
Inke.sol
0x5301a786c6d68bf3fb97e13cb2c71e671f6fa69e
Solidity
InkeToken
contract InkeToken is InkeGold { event PartnerCreated(uint indexed partnerId, address indexed partner, uint indexed amount, uint singleTrans, uint durance); event RewardDistribute(uint indexed postId, uint partnerId, address indexed user, uint indexed amount); event VipAgreementSign(uint indexed vipId, address indexed vip, uint durance, uint frequence, uint salar); event SalaryReceived(uint indexed vipId, address indexed vip, uint salary, uint indexed timestamp); string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public minePool; // 60% uint public fundPool; // 30% struct Partner { address admin; uint tokenPool; uint singleTrans; uint timestamp; uint durance; } struct Poster { address poster; bytes32 hashData; uint reward; } struct Vip { address vip; uint durance; uint frequence; uint salary; uint timestamp; } Partner[] partners; Vip[] vips; modifier onlyPartner(uint _partnerId) { require(partners[_partnerId].admin == msg.sender); require(partners[_partnerId].tokenPool > uint(0)); uint deadline = safeAdd(partners[_partnerId].timestamp, partners[_partnerId].durance); require(deadline > now); _; } modifier onlyVip(uint _vipId) { require(vips[_vipId].vip == msg.sender); require(vips[_vipId].durance > now); require(vips[_vipId].timestamp < now); _; } mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; mapping(address => bool) freezed; mapping(address => uint) freezeAmount; mapping(address => uint) unlockTime; mapping(uint => Poster[]) PartnerIdToPosterList; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "Inke"; name = "Inke Token"; decimals = 18; _totalSupply = 10000000000000000000000000000; minePool = 60000000000000000000000000000; fundPool = 30000000000000000000000000000; balances[CEOAddress] = _totalSupply; emit Transfer(address(0), CEOAddress, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { if(freezed[msg.sender] == false){ balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); } else { if(balances[msg.sender] > freezeAmount[msg.sender]) { require(tokens <= safeSub(balances[msg.sender], freezeAmount[msg.sender])); balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); } } return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { require(freezed[msg.sender] != true); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { require(freezed[msg.sender] != true); return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { require(freezed[msg.sender] != true); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Mint Tokens // ------------------------------------------------------------------------ function _mine(uint amount, address receiver) internal { require(minePool >= amount); minePool = safeSub(minePool, amount); _totalSupply = safeAdd(_totalSupply, amount); balances[receiver] = safeAdd(balances[receiver], amount); emit Transfer(address(0), receiver, amount); } function _fund(uint amount, address receiver) internal { require(fundPool >= amount); fundPool = safeSub(fundPool, amount); _totalSupply = safeAdd(_totalSupply, amount); balances[receiver] = safeAdd(balances[receiver], amount); emit Transfer(address(0), receiver, amount); } function mint(uint amount) public onlyAdmin { _fund(amount, msg.sender); } function burn(uint amount) public onlyAdmin { require(_totalSupply >= amount); balances[msg.sender] = safeSub(balances[msg.sender], amount); _totalSupply = safeSub(_totalSupply, amount); } // ------------------------------------------------------------------------ // Freeze Tokens // ------------------------------------------------------------------------ function freeze(address user, uint amount, uint period) public onlyAdmin { require(balances[user] >= amount); freezed[user] = true; unlockTime[user] = uint(now) + period; freezeAmount[user] = amount; } // ------------------------------------------------------------------------ // UnFreeze Tokens // ------------------------------------------------------------------------ function unFreeze() public whenNotPaused { require(freezed[msg.sender] == true); require(unlockTime[msg.sender] < uint(now)); freezed[msg.sender] = false; freezeAmount[msg.sender] = 0; } function ifFreeze(address user) public view returns ( bool check, uint amount, uint timeLeft ) { check = freezed[user]; amount = freezeAmount[user]; timeLeft = unlockTime[user] - uint(now); } // ------------------------------------------------------------------------ // Partner Authorization // ------------------------------------------------------------------------ function createPartner(address _partner, uint _amount, uint _singleTrans, uint _durance) public onlyAdmin returns (uint) { Partner memory _Partner = Partner({ admin: _partner, tokenPool: _amount, singleTrans: _singleTrans, timestamp: uint(now), durance: _durance }); uint newPartnerId = partners.push(_Partner) - 1; emit PartnerCreated(newPartnerId, _partner, _amount, _singleTrans, _durance); return newPartnerId; } function partnerTransfer(uint _partnerId, bytes32 _data, address _to, uint _amount) public onlyPartner(_partnerId) whenNotPaused returns (bool) { require(_amount <= partners[_partnerId].singleTrans); partners[_partnerId].tokenPool = safeSub(partners[_partnerId].tokenPool, _amount); Poster memory _Poster = Poster ({ poster: _to, hashData: _data, reward: _amount }); uint newPostId = PartnerIdToPosterList[_partnerId].push(_Poster) - 1; _fund(_amount, _to); emit RewardDistribute(newPostId, _partnerId, _to, _amount); return true; } function setPartnerPool(uint _partnerId, uint _amount) public onlyAdmin { partners[_partnerId].tokenPool = _amount; } function setPartnerDurance(uint _partnerId, uint _durance) public onlyAdmin { partners[_partnerId].durance = uint(now) + _durance; } function getPartnerInfo(uint _partnerId) public view returns ( address admin, uint tokenPool, uint timeLeft ) { Partner memory _Partner = partners[_partnerId]; admin = _Partner.admin; tokenPool = _Partner.tokenPool; if (_Partner.timestamp + _Partner.durance > uint(now)) { timeLeft = _Partner.timestamp + _Partner.durance - uint(now); } else { timeLeft = 0; } } function getPosterInfo(uint _partnerId, uint _posterId) public view returns ( address poster, bytes32 hashData, uint reward ) { Poster memory _Poster = PartnerIdToPosterList[_partnerId][_posterId]; poster = _Poster.poster; hashData = _Poster.hashData; reward = _Poster.reward; } // ------------------------------------------------------------------------ // Vip Agreement // ------------------------------------------------------------------------ function createVip(address _vip, uint _durance, uint _frequence, uint _salary) public onlyAdmin returns (uint) { Vip memory _Vip = Vip ({ vip: _vip, durance: uint(now) + _durance, frequence: _frequence, salary: _salary, timestamp: now + _frequence }); uint newVipId = vips.push(_Vip) - 1; emit VipAgreementSign(newVipId, _vip, _durance, _frequence, _salary); return newVipId; } function mineSalary(uint _vipId) public onlyVip(_vipId) whenNotPaused returns (bool) { Vip storage _Vip = vips[_vipId]; _fund(_Vip.salary, _Vip.vip); _Vip.timestamp = safeAdd(_Vip.timestamp, _Vip.frequence); emit SalaryReceived(_vipId, _Vip.vip, _Vip.salary, _Vip.timestamp); return true; } function deleteVip(uint _vipId) public onlyAdmin { delete vips[_vipId]; } function getVipInfo(uint _vipId) public view returns ( address vip, uint durance, uint frequence, uint salary, uint nextSalary, string log ) { Vip memory _Vip = vips[_vipId]; vip = _Vip.vip; durance = _Vip.durance; frequence = _Vip.frequence; salary = _Vip.salary; if(_Vip.timestamp >= uint(now)) { nextSalary = safeSub(_Vip.timestamp, uint(now)); log = "Please Wait"; } else { nextSalary = 0; log = "Pick Up Your Salary Now"; } } // ------------------------------------------------------------------------ // Accept ETH // ------------------------------------------------------------------------ function () public payable { } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyAdmin returns (bool success) { return ERC20Interface(tokenAddress).transfer(CEOAddress, tokens); } }
allowance
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { require(freezed[msg.sender] != true); return allowed[tokenOwner][spender]; }
// ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------
LineComment
v0.4.24+commit.e67f0147
bzzr://1d50d33bcacbc79c72c404b9ba3e0da98cc33b209a6a2c04acb355c1e24613c0
{ "func_code_index": [ 6225, 6428 ] }
834
Inke
Inke.sol
0x5301a786c6d68bf3fb97e13cb2c71e671f6fa69e
Solidity
InkeToken
contract InkeToken is InkeGold { event PartnerCreated(uint indexed partnerId, address indexed partner, uint indexed amount, uint singleTrans, uint durance); event RewardDistribute(uint indexed postId, uint partnerId, address indexed user, uint indexed amount); event VipAgreementSign(uint indexed vipId, address indexed vip, uint durance, uint frequence, uint salar); event SalaryReceived(uint indexed vipId, address indexed vip, uint salary, uint indexed timestamp); string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public minePool; // 60% uint public fundPool; // 30% struct Partner { address admin; uint tokenPool; uint singleTrans; uint timestamp; uint durance; } struct Poster { address poster; bytes32 hashData; uint reward; } struct Vip { address vip; uint durance; uint frequence; uint salary; uint timestamp; } Partner[] partners; Vip[] vips; modifier onlyPartner(uint _partnerId) { require(partners[_partnerId].admin == msg.sender); require(partners[_partnerId].tokenPool > uint(0)); uint deadline = safeAdd(partners[_partnerId].timestamp, partners[_partnerId].durance); require(deadline > now); _; } modifier onlyVip(uint _vipId) { require(vips[_vipId].vip == msg.sender); require(vips[_vipId].durance > now); require(vips[_vipId].timestamp < now); _; } mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; mapping(address => bool) freezed; mapping(address => uint) freezeAmount; mapping(address => uint) unlockTime; mapping(uint => Poster[]) PartnerIdToPosterList; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "Inke"; name = "Inke Token"; decimals = 18; _totalSupply = 10000000000000000000000000000; minePool = 60000000000000000000000000000; fundPool = 30000000000000000000000000000; balances[CEOAddress] = _totalSupply; emit Transfer(address(0), CEOAddress, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { if(freezed[msg.sender] == false){ balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); } else { if(balances[msg.sender] > freezeAmount[msg.sender]) { require(tokens <= safeSub(balances[msg.sender], freezeAmount[msg.sender])); balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); } } return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { require(freezed[msg.sender] != true); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { require(freezed[msg.sender] != true); return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { require(freezed[msg.sender] != true); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Mint Tokens // ------------------------------------------------------------------------ function _mine(uint amount, address receiver) internal { require(minePool >= amount); minePool = safeSub(minePool, amount); _totalSupply = safeAdd(_totalSupply, amount); balances[receiver] = safeAdd(balances[receiver], amount); emit Transfer(address(0), receiver, amount); } function _fund(uint amount, address receiver) internal { require(fundPool >= amount); fundPool = safeSub(fundPool, amount); _totalSupply = safeAdd(_totalSupply, amount); balances[receiver] = safeAdd(balances[receiver], amount); emit Transfer(address(0), receiver, amount); } function mint(uint amount) public onlyAdmin { _fund(amount, msg.sender); } function burn(uint amount) public onlyAdmin { require(_totalSupply >= amount); balances[msg.sender] = safeSub(balances[msg.sender], amount); _totalSupply = safeSub(_totalSupply, amount); } // ------------------------------------------------------------------------ // Freeze Tokens // ------------------------------------------------------------------------ function freeze(address user, uint amount, uint period) public onlyAdmin { require(balances[user] >= amount); freezed[user] = true; unlockTime[user] = uint(now) + period; freezeAmount[user] = amount; } // ------------------------------------------------------------------------ // UnFreeze Tokens // ------------------------------------------------------------------------ function unFreeze() public whenNotPaused { require(freezed[msg.sender] == true); require(unlockTime[msg.sender] < uint(now)); freezed[msg.sender] = false; freezeAmount[msg.sender] = 0; } function ifFreeze(address user) public view returns ( bool check, uint amount, uint timeLeft ) { check = freezed[user]; amount = freezeAmount[user]; timeLeft = unlockTime[user] - uint(now); } // ------------------------------------------------------------------------ // Partner Authorization // ------------------------------------------------------------------------ function createPartner(address _partner, uint _amount, uint _singleTrans, uint _durance) public onlyAdmin returns (uint) { Partner memory _Partner = Partner({ admin: _partner, tokenPool: _amount, singleTrans: _singleTrans, timestamp: uint(now), durance: _durance }); uint newPartnerId = partners.push(_Partner) - 1; emit PartnerCreated(newPartnerId, _partner, _amount, _singleTrans, _durance); return newPartnerId; } function partnerTransfer(uint _partnerId, bytes32 _data, address _to, uint _amount) public onlyPartner(_partnerId) whenNotPaused returns (bool) { require(_amount <= partners[_partnerId].singleTrans); partners[_partnerId].tokenPool = safeSub(partners[_partnerId].tokenPool, _amount); Poster memory _Poster = Poster ({ poster: _to, hashData: _data, reward: _amount }); uint newPostId = PartnerIdToPosterList[_partnerId].push(_Poster) - 1; _fund(_amount, _to); emit RewardDistribute(newPostId, _partnerId, _to, _amount); return true; } function setPartnerPool(uint _partnerId, uint _amount) public onlyAdmin { partners[_partnerId].tokenPool = _amount; } function setPartnerDurance(uint _partnerId, uint _durance) public onlyAdmin { partners[_partnerId].durance = uint(now) + _durance; } function getPartnerInfo(uint _partnerId) public view returns ( address admin, uint tokenPool, uint timeLeft ) { Partner memory _Partner = partners[_partnerId]; admin = _Partner.admin; tokenPool = _Partner.tokenPool; if (_Partner.timestamp + _Partner.durance > uint(now)) { timeLeft = _Partner.timestamp + _Partner.durance - uint(now); } else { timeLeft = 0; } } function getPosterInfo(uint _partnerId, uint _posterId) public view returns ( address poster, bytes32 hashData, uint reward ) { Poster memory _Poster = PartnerIdToPosterList[_partnerId][_posterId]; poster = _Poster.poster; hashData = _Poster.hashData; reward = _Poster.reward; } // ------------------------------------------------------------------------ // Vip Agreement // ------------------------------------------------------------------------ function createVip(address _vip, uint _durance, uint _frequence, uint _salary) public onlyAdmin returns (uint) { Vip memory _Vip = Vip ({ vip: _vip, durance: uint(now) + _durance, frequence: _frequence, salary: _salary, timestamp: now + _frequence }); uint newVipId = vips.push(_Vip) - 1; emit VipAgreementSign(newVipId, _vip, _durance, _frequence, _salary); return newVipId; } function mineSalary(uint _vipId) public onlyVip(_vipId) whenNotPaused returns (bool) { Vip storage _Vip = vips[_vipId]; _fund(_Vip.salary, _Vip.vip); _Vip.timestamp = safeAdd(_Vip.timestamp, _Vip.frequence); emit SalaryReceived(_vipId, _Vip.vip, _Vip.salary, _Vip.timestamp); return true; } function deleteVip(uint _vipId) public onlyAdmin { delete vips[_vipId]; } function getVipInfo(uint _vipId) public view returns ( address vip, uint durance, uint frequence, uint salary, uint nextSalary, string log ) { Vip memory _Vip = vips[_vipId]; vip = _Vip.vip; durance = _Vip.durance; frequence = _Vip.frequence; salary = _Vip.salary; if(_Vip.timestamp >= uint(now)) { nextSalary = safeSub(_Vip.timestamp, uint(now)); log = "Please Wait"; } else { nextSalary = 0; log = "Pick Up Your Salary Now"; } } // ------------------------------------------------------------------------ // Accept ETH // ------------------------------------------------------------------------ function () public payable { } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyAdmin returns (bool success) { return ERC20Interface(tokenAddress).transfer(CEOAddress, tokens); } }
approveAndCall
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { require(freezed[msg.sender] != true); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; }
// ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------
LineComment
v0.4.24+commit.e67f0147
bzzr://1d50d33bcacbc79c72c404b9ba3e0da98cc33b209a6a2c04acb355c1e24613c0
{ "func_code_index": [ 6783, 7152 ] }
835
Inke
Inke.sol
0x5301a786c6d68bf3fb97e13cb2c71e671f6fa69e
Solidity
InkeToken
contract InkeToken is InkeGold { event PartnerCreated(uint indexed partnerId, address indexed partner, uint indexed amount, uint singleTrans, uint durance); event RewardDistribute(uint indexed postId, uint partnerId, address indexed user, uint indexed amount); event VipAgreementSign(uint indexed vipId, address indexed vip, uint durance, uint frequence, uint salar); event SalaryReceived(uint indexed vipId, address indexed vip, uint salary, uint indexed timestamp); string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public minePool; // 60% uint public fundPool; // 30% struct Partner { address admin; uint tokenPool; uint singleTrans; uint timestamp; uint durance; } struct Poster { address poster; bytes32 hashData; uint reward; } struct Vip { address vip; uint durance; uint frequence; uint salary; uint timestamp; } Partner[] partners; Vip[] vips; modifier onlyPartner(uint _partnerId) { require(partners[_partnerId].admin == msg.sender); require(partners[_partnerId].tokenPool > uint(0)); uint deadline = safeAdd(partners[_partnerId].timestamp, partners[_partnerId].durance); require(deadline > now); _; } modifier onlyVip(uint _vipId) { require(vips[_vipId].vip == msg.sender); require(vips[_vipId].durance > now); require(vips[_vipId].timestamp < now); _; } mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; mapping(address => bool) freezed; mapping(address => uint) freezeAmount; mapping(address => uint) unlockTime; mapping(uint => Poster[]) PartnerIdToPosterList; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "Inke"; name = "Inke Token"; decimals = 18; _totalSupply = 10000000000000000000000000000; minePool = 60000000000000000000000000000; fundPool = 30000000000000000000000000000; balances[CEOAddress] = _totalSupply; emit Transfer(address(0), CEOAddress, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { if(freezed[msg.sender] == false){ balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); } else { if(balances[msg.sender] > freezeAmount[msg.sender]) { require(tokens <= safeSub(balances[msg.sender], freezeAmount[msg.sender])); balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); } } return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { require(freezed[msg.sender] != true); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { require(freezed[msg.sender] != true); return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { require(freezed[msg.sender] != true); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Mint Tokens // ------------------------------------------------------------------------ function _mine(uint amount, address receiver) internal { require(minePool >= amount); minePool = safeSub(minePool, amount); _totalSupply = safeAdd(_totalSupply, amount); balances[receiver] = safeAdd(balances[receiver], amount); emit Transfer(address(0), receiver, amount); } function _fund(uint amount, address receiver) internal { require(fundPool >= amount); fundPool = safeSub(fundPool, amount); _totalSupply = safeAdd(_totalSupply, amount); balances[receiver] = safeAdd(balances[receiver], amount); emit Transfer(address(0), receiver, amount); } function mint(uint amount) public onlyAdmin { _fund(amount, msg.sender); } function burn(uint amount) public onlyAdmin { require(_totalSupply >= amount); balances[msg.sender] = safeSub(balances[msg.sender], amount); _totalSupply = safeSub(_totalSupply, amount); } // ------------------------------------------------------------------------ // Freeze Tokens // ------------------------------------------------------------------------ function freeze(address user, uint amount, uint period) public onlyAdmin { require(balances[user] >= amount); freezed[user] = true; unlockTime[user] = uint(now) + period; freezeAmount[user] = amount; } // ------------------------------------------------------------------------ // UnFreeze Tokens // ------------------------------------------------------------------------ function unFreeze() public whenNotPaused { require(freezed[msg.sender] == true); require(unlockTime[msg.sender] < uint(now)); freezed[msg.sender] = false; freezeAmount[msg.sender] = 0; } function ifFreeze(address user) public view returns ( bool check, uint amount, uint timeLeft ) { check = freezed[user]; amount = freezeAmount[user]; timeLeft = unlockTime[user] - uint(now); } // ------------------------------------------------------------------------ // Partner Authorization // ------------------------------------------------------------------------ function createPartner(address _partner, uint _amount, uint _singleTrans, uint _durance) public onlyAdmin returns (uint) { Partner memory _Partner = Partner({ admin: _partner, tokenPool: _amount, singleTrans: _singleTrans, timestamp: uint(now), durance: _durance }); uint newPartnerId = partners.push(_Partner) - 1; emit PartnerCreated(newPartnerId, _partner, _amount, _singleTrans, _durance); return newPartnerId; } function partnerTransfer(uint _partnerId, bytes32 _data, address _to, uint _amount) public onlyPartner(_partnerId) whenNotPaused returns (bool) { require(_amount <= partners[_partnerId].singleTrans); partners[_partnerId].tokenPool = safeSub(partners[_partnerId].tokenPool, _amount); Poster memory _Poster = Poster ({ poster: _to, hashData: _data, reward: _amount }); uint newPostId = PartnerIdToPosterList[_partnerId].push(_Poster) - 1; _fund(_amount, _to); emit RewardDistribute(newPostId, _partnerId, _to, _amount); return true; } function setPartnerPool(uint _partnerId, uint _amount) public onlyAdmin { partners[_partnerId].tokenPool = _amount; } function setPartnerDurance(uint _partnerId, uint _durance) public onlyAdmin { partners[_partnerId].durance = uint(now) + _durance; } function getPartnerInfo(uint _partnerId) public view returns ( address admin, uint tokenPool, uint timeLeft ) { Partner memory _Partner = partners[_partnerId]; admin = _Partner.admin; tokenPool = _Partner.tokenPool; if (_Partner.timestamp + _Partner.durance > uint(now)) { timeLeft = _Partner.timestamp + _Partner.durance - uint(now); } else { timeLeft = 0; } } function getPosterInfo(uint _partnerId, uint _posterId) public view returns ( address poster, bytes32 hashData, uint reward ) { Poster memory _Poster = PartnerIdToPosterList[_partnerId][_posterId]; poster = _Poster.poster; hashData = _Poster.hashData; reward = _Poster.reward; } // ------------------------------------------------------------------------ // Vip Agreement // ------------------------------------------------------------------------ function createVip(address _vip, uint _durance, uint _frequence, uint _salary) public onlyAdmin returns (uint) { Vip memory _Vip = Vip ({ vip: _vip, durance: uint(now) + _durance, frequence: _frequence, salary: _salary, timestamp: now + _frequence }); uint newVipId = vips.push(_Vip) - 1; emit VipAgreementSign(newVipId, _vip, _durance, _frequence, _salary); return newVipId; } function mineSalary(uint _vipId) public onlyVip(_vipId) whenNotPaused returns (bool) { Vip storage _Vip = vips[_vipId]; _fund(_Vip.salary, _Vip.vip); _Vip.timestamp = safeAdd(_Vip.timestamp, _Vip.frequence); emit SalaryReceived(_vipId, _Vip.vip, _Vip.salary, _Vip.timestamp); return true; } function deleteVip(uint _vipId) public onlyAdmin { delete vips[_vipId]; } function getVipInfo(uint _vipId) public view returns ( address vip, uint durance, uint frequence, uint salary, uint nextSalary, string log ) { Vip memory _Vip = vips[_vipId]; vip = _Vip.vip; durance = _Vip.durance; frequence = _Vip.frequence; salary = _Vip.salary; if(_Vip.timestamp >= uint(now)) { nextSalary = safeSub(_Vip.timestamp, uint(now)); log = "Please Wait"; } else { nextSalary = 0; log = "Pick Up Your Salary Now"; } } // ------------------------------------------------------------------------ // Accept ETH // ------------------------------------------------------------------------ function () public payable { } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyAdmin returns (bool success) { return ERC20Interface(tokenAddress).transfer(CEOAddress, tokens); } }
_mine
function _mine(uint amount, address receiver) internal { require(minePool >= amount); minePool = safeSub(minePool, amount); _totalSupply = safeAdd(_totalSupply, amount); balances[receiver] = safeAdd(balances[receiver], amount); emit Transfer(address(0), receiver, amount); }
// ------------------------------------------------------------------------ // Mint Tokens // ------------------------------------------------------------------------
LineComment
v0.4.24+commit.e67f0147
bzzr://1d50d33bcacbc79c72c404b9ba3e0da98cc33b209a6a2c04acb355c1e24613c0
{ "func_code_index": [ 7337, 7666 ] }
836
Inke
Inke.sol
0x5301a786c6d68bf3fb97e13cb2c71e671f6fa69e
Solidity
InkeToken
contract InkeToken is InkeGold { event PartnerCreated(uint indexed partnerId, address indexed partner, uint indexed amount, uint singleTrans, uint durance); event RewardDistribute(uint indexed postId, uint partnerId, address indexed user, uint indexed amount); event VipAgreementSign(uint indexed vipId, address indexed vip, uint durance, uint frequence, uint salar); event SalaryReceived(uint indexed vipId, address indexed vip, uint salary, uint indexed timestamp); string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public minePool; // 60% uint public fundPool; // 30% struct Partner { address admin; uint tokenPool; uint singleTrans; uint timestamp; uint durance; } struct Poster { address poster; bytes32 hashData; uint reward; } struct Vip { address vip; uint durance; uint frequence; uint salary; uint timestamp; } Partner[] partners; Vip[] vips; modifier onlyPartner(uint _partnerId) { require(partners[_partnerId].admin == msg.sender); require(partners[_partnerId].tokenPool > uint(0)); uint deadline = safeAdd(partners[_partnerId].timestamp, partners[_partnerId].durance); require(deadline > now); _; } modifier onlyVip(uint _vipId) { require(vips[_vipId].vip == msg.sender); require(vips[_vipId].durance > now); require(vips[_vipId].timestamp < now); _; } mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; mapping(address => bool) freezed; mapping(address => uint) freezeAmount; mapping(address => uint) unlockTime; mapping(uint => Poster[]) PartnerIdToPosterList; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "Inke"; name = "Inke Token"; decimals = 18; _totalSupply = 10000000000000000000000000000; minePool = 60000000000000000000000000000; fundPool = 30000000000000000000000000000; balances[CEOAddress] = _totalSupply; emit Transfer(address(0), CEOAddress, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { if(freezed[msg.sender] == false){ balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); } else { if(balances[msg.sender] > freezeAmount[msg.sender]) { require(tokens <= safeSub(balances[msg.sender], freezeAmount[msg.sender])); balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); } } return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { require(freezed[msg.sender] != true); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { require(freezed[msg.sender] != true); return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { require(freezed[msg.sender] != true); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Mint Tokens // ------------------------------------------------------------------------ function _mine(uint amount, address receiver) internal { require(minePool >= amount); minePool = safeSub(minePool, amount); _totalSupply = safeAdd(_totalSupply, amount); balances[receiver] = safeAdd(balances[receiver], amount); emit Transfer(address(0), receiver, amount); } function _fund(uint amount, address receiver) internal { require(fundPool >= amount); fundPool = safeSub(fundPool, amount); _totalSupply = safeAdd(_totalSupply, amount); balances[receiver] = safeAdd(balances[receiver], amount); emit Transfer(address(0), receiver, amount); } function mint(uint amount) public onlyAdmin { _fund(amount, msg.sender); } function burn(uint amount) public onlyAdmin { require(_totalSupply >= amount); balances[msg.sender] = safeSub(balances[msg.sender], amount); _totalSupply = safeSub(_totalSupply, amount); } // ------------------------------------------------------------------------ // Freeze Tokens // ------------------------------------------------------------------------ function freeze(address user, uint amount, uint period) public onlyAdmin { require(balances[user] >= amount); freezed[user] = true; unlockTime[user] = uint(now) + period; freezeAmount[user] = amount; } // ------------------------------------------------------------------------ // UnFreeze Tokens // ------------------------------------------------------------------------ function unFreeze() public whenNotPaused { require(freezed[msg.sender] == true); require(unlockTime[msg.sender] < uint(now)); freezed[msg.sender] = false; freezeAmount[msg.sender] = 0; } function ifFreeze(address user) public view returns ( bool check, uint amount, uint timeLeft ) { check = freezed[user]; amount = freezeAmount[user]; timeLeft = unlockTime[user] - uint(now); } // ------------------------------------------------------------------------ // Partner Authorization // ------------------------------------------------------------------------ function createPartner(address _partner, uint _amount, uint _singleTrans, uint _durance) public onlyAdmin returns (uint) { Partner memory _Partner = Partner({ admin: _partner, tokenPool: _amount, singleTrans: _singleTrans, timestamp: uint(now), durance: _durance }); uint newPartnerId = partners.push(_Partner) - 1; emit PartnerCreated(newPartnerId, _partner, _amount, _singleTrans, _durance); return newPartnerId; } function partnerTransfer(uint _partnerId, bytes32 _data, address _to, uint _amount) public onlyPartner(_partnerId) whenNotPaused returns (bool) { require(_amount <= partners[_partnerId].singleTrans); partners[_partnerId].tokenPool = safeSub(partners[_partnerId].tokenPool, _amount); Poster memory _Poster = Poster ({ poster: _to, hashData: _data, reward: _amount }); uint newPostId = PartnerIdToPosterList[_partnerId].push(_Poster) - 1; _fund(_amount, _to); emit RewardDistribute(newPostId, _partnerId, _to, _amount); return true; } function setPartnerPool(uint _partnerId, uint _amount) public onlyAdmin { partners[_partnerId].tokenPool = _amount; } function setPartnerDurance(uint _partnerId, uint _durance) public onlyAdmin { partners[_partnerId].durance = uint(now) + _durance; } function getPartnerInfo(uint _partnerId) public view returns ( address admin, uint tokenPool, uint timeLeft ) { Partner memory _Partner = partners[_partnerId]; admin = _Partner.admin; tokenPool = _Partner.tokenPool; if (_Partner.timestamp + _Partner.durance > uint(now)) { timeLeft = _Partner.timestamp + _Partner.durance - uint(now); } else { timeLeft = 0; } } function getPosterInfo(uint _partnerId, uint _posterId) public view returns ( address poster, bytes32 hashData, uint reward ) { Poster memory _Poster = PartnerIdToPosterList[_partnerId][_posterId]; poster = _Poster.poster; hashData = _Poster.hashData; reward = _Poster.reward; } // ------------------------------------------------------------------------ // Vip Agreement // ------------------------------------------------------------------------ function createVip(address _vip, uint _durance, uint _frequence, uint _salary) public onlyAdmin returns (uint) { Vip memory _Vip = Vip ({ vip: _vip, durance: uint(now) + _durance, frequence: _frequence, salary: _salary, timestamp: now + _frequence }); uint newVipId = vips.push(_Vip) - 1; emit VipAgreementSign(newVipId, _vip, _durance, _frequence, _salary); return newVipId; } function mineSalary(uint _vipId) public onlyVip(_vipId) whenNotPaused returns (bool) { Vip storage _Vip = vips[_vipId]; _fund(_Vip.salary, _Vip.vip); _Vip.timestamp = safeAdd(_Vip.timestamp, _Vip.frequence); emit SalaryReceived(_vipId, _Vip.vip, _Vip.salary, _Vip.timestamp); return true; } function deleteVip(uint _vipId) public onlyAdmin { delete vips[_vipId]; } function getVipInfo(uint _vipId) public view returns ( address vip, uint durance, uint frequence, uint salary, uint nextSalary, string log ) { Vip memory _Vip = vips[_vipId]; vip = _Vip.vip; durance = _Vip.durance; frequence = _Vip.frequence; salary = _Vip.salary; if(_Vip.timestamp >= uint(now)) { nextSalary = safeSub(_Vip.timestamp, uint(now)); log = "Please Wait"; } else { nextSalary = 0; log = "Pick Up Your Salary Now"; } } // ------------------------------------------------------------------------ // Accept ETH // ------------------------------------------------------------------------ function () public payable { } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyAdmin returns (bool success) { return ERC20Interface(tokenAddress).transfer(CEOAddress, tokens); } }
freeze
function freeze(address user, uint amount, uint period) public onlyAdmin { require(balances[user] >= amount); freezed[user] = true; unlockTime[user] = uint(now) + period; freezeAmount[user] = amount; }
// ------------------------------------------------------------------------ // Freeze Tokens // ------------------------------------------------------------------------
LineComment
v0.4.24+commit.e67f0147
bzzr://1d50d33bcacbc79c72c404b9ba3e0da98cc33b209a6a2c04acb355c1e24613c0
{ "func_code_index": [ 8525, 8772 ] }
837
Inke
Inke.sol
0x5301a786c6d68bf3fb97e13cb2c71e671f6fa69e
Solidity
InkeToken
contract InkeToken is InkeGold { event PartnerCreated(uint indexed partnerId, address indexed partner, uint indexed amount, uint singleTrans, uint durance); event RewardDistribute(uint indexed postId, uint partnerId, address indexed user, uint indexed amount); event VipAgreementSign(uint indexed vipId, address indexed vip, uint durance, uint frequence, uint salar); event SalaryReceived(uint indexed vipId, address indexed vip, uint salary, uint indexed timestamp); string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public minePool; // 60% uint public fundPool; // 30% struct Partner { address admin; uint tokenPool; uint singleTrans; uint timestamp; uint durance; } struct Poster { address poster; bytes32 hashData; uint reward; } struct Vip { address vip; uint durance; uint frequence; uint salary; uint timestamp; } Partner[] partners; Vip[] vips; modifier onlyPartner(uint _partnerId) { require(partners[_partnerId].admin == msg.sender); require(partners[_partnerId].tokenPool > uint(0)); uint deadline = safeAdd(partners[_partnerId].timestamp, partners[_partnerId].durance); require(deadline > now); _; } modifier onlyVip(uint _vipId) { require(vips[_vipId].vip == msg.sender); require(vips[_vipId].durance > now); require(vips[_vipId].timestamp < now); _; } mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; mapping(address => bool) freezed; mapping(address => uint) freezeAmount; mapping(address => uint) unlockTime; mapping(uint => Poster[]) PartnerIdToPosterList; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "Inke"; name = "Inke Token"; decimals = 18; _totalSupply = 10000000000000000000000000000; minePool = 60000000000000000000000000000; fundPool = 30000000000000000000000000000; balances[CEOAddress] = _totalSupply; emit Transfer(address(0), CEOAddress, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { if(freezed[msg.sender] == false){ balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); } else { if(balances[msg.sender] > freezeAmount[msg.sender]) { require(tokens <= safeSub(balances[msg.sender], freezeAmount[msg.sender])); balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); } } return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { require(freezed[msg.sender] != true); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { require(freezed[msg.sender] != true); return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { require(freezed[msg.sender] != true); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Mint Tokens // ------------------------------------------------------------------------ function _mine(uint amount, address receiver) internal { require(minePool >= amount); minePool = safeSub(minePool, amount); _totalSupply = safeAdd(_totalSupply, amount); balances[receiver] = safeAdd(balances[receiver], amount); emit Transfer(address(0), receiver, amount); } function _fund(uint amount, address receiver) internal { require(fundPool >= amount); fundPool = safeSub(fundPool, amount); _totalSupply = safeAdd(_totalSupply, amount); balances[receiver] = safeAdd(balances[receiver], amount); emit Transfer(address(0), receiver, amount); } function mint(uint amount) public onlyAdmin { _fund(amount, msg.sender); } function burn(uint amount) public onlyAdmin { require(_totalSupply >= amount); balances[msg.sender] = safeSub(balances[msg.sender], amount); _totalSupply = safeSub(_totalSupply, amount); } // ------------------------------------------------------------------------ // Freeze Tokens // ------------------------------------------------------------------------ function freeze(address user, uint amount, uint period) public onlyAdmin { require(balances[user] >= amount); freezed[user] = true; unlockTime[user] = uint(now) + period; freezeAmount[user] = amount; } // ------------------------------------------------------------------------ // UnFreeze Tokens // ------------------------------------------------------------------------ function unFreeze() public whenNotPaused { require(freezed[msg.sender] == true); require(unlockTime[msg.sender] < uint(now)); freezed[msg.sender] = false; freezeAmount[msg.sender] = 0; } function ifFreeze(address user) public view returns ( bool check, uint amount, uint timeLeft ) { check = freezed[user]; amount = freezeAmount[user]; timeLeft = unlockTime[user] - uint(now); } // ------------------------------------------------------------------------ // Partner Authorization // ------------------------------------------------------------------------ function createPartner(address _partner, uint _amount, uint _singleTrans, uint _durance) public onlyAdmin returns (uint) { Partner memory _Partner = Partner({ admin: _partner, tokenPool: _amount, singleTrans: _singleTrans, timestamp: uint(now), durance: _durance }); uint newPartnerId = partners.push(_Partner) - 1; emit PartnerCreated(newPartnerId, _partner, _amount, _singleTrans, _durance); return newPartnerId; } function partnerTransfer(uint _partnerId, bytes32 _data, address _to, uint _amount) public onlyPartner(_partnerId) whenNotPaused returns (bool) { require(_amount <= partners[_partnerId].singleTrans); partners[_partnerId].tokenPool = safeSub(partners[_partnerId].tokenPool, _amount); Poster memory _Poster = Poster ({ poster: _to, hashData: _data, reward: _amount }); uint newPostId = PartnerIdToPosterList[_partnerId].push(_Poster) - 1; _fund(_amount, _to); emit RewardDistribute(newPostId, _partnerId, _to, _amount); return true; } function setPartnerPool(uint _partnerId, uint _amount) public onlyAdmin { partners[_partnerId].tokenPool = _amount; } function setPartnerDurance(uint _partnerId, uint _durance) public onlyAdmin { partners[_partnerId].durance = uint(now) + _durance; } function getPartnerInfo(uint _partnerId) public view returns ( address admin, uint tokenPool, uint timeLeft ) { Partner memory _Partner = partners[_partnerId]; admin = _Partner.admin; tokenPool = _Partner.tokenPool; if (_Partner.timestamp + _Partner.durance > uint(now)) { timeLeft = _Partner.timestamp + _Partner.durance - uint(now); } else { timeLeft = 0; } } function getPosterInfo(uint _partnerId, uint _posterId) public view returns ( address poster, bytes32 hashData, uint reward ) { Poster memory _Poster = PartnerIdToPosterList[_partnerId][_posterId]; poster = _Poster.poster; hashData = _Poster.hashData; reward = _Poster.reward; } // ------------------------------------------------------------------------ // Vip Agreement // ------------------------------------------------------------------------ function createVip(address _vip, uint _durance, uint _frequence, uint _salary) public onlyAdmin returns (uint) { Vip memory _Vip = Vip ({ vip: _vip, durance: uint(now) + _durance, frequence: _frequence, salary: _salary, timestamp: now + _frequence }); uint newVipId = vips.push(_Vip) - 1; emit VipAgreementSign(newVipId, _vip, _durance, _frequence, _salary); return newVipId; } function mineSalary(uint _vipId) public onlyVip(_vipId) whenNotPaused returns (bool) { Vip storage _Vip = vips[_vipId]; _fund(_Vip.salary, _Vip.vip); _Vip.timestamp = safeAdd(_Vip.timestamp, _Vip.frequence); emit SalaryReceived(_vipId, _Vip.vip, _Vip.salary, _Vip.timestamp); return true; } function deleteVip(uint _vipId) public onlyAdmin { delete vips[_vipId]; } function getVipInfo(uint _vipId) public view returns ( address vip, uint durance, uint frequence, uint salary, uint nextSalary, string log ) { Vip memory _Vip = vips[_vipId]; vip = _Vip.vip; durance = _Vip.durance; frequence = _Vip.frequence; salary = _Vip.salary; if(_Vip.timestamp >= uint(now)) { nextSalary = safeSub(_Vip.timestamp, uint(now)); log = "Please Wait"; } else { nextSalary = 0; log = "Pick Up Your Salary Now"; } } // ------------------------------------------------------------------------ // Accept ETH // ------------------------------------------------------------------------ function () public payable { } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyAdmin returns (bool success) { return ERC20Interface(tokenAddress).transfer(CEOAddress, tokens); } }
unFreeze
function unFreeze() public whenNotPaused { require(freezed[msg.sender] == true); require(unlockTime[msg.sender] < uint(now)); freezed[msg.sender] = false; freezeAmount[msg.sender] = 0; }
// ------------------------------------------------------------------------ // UnFreeze Tokens // ------------------------------------------------------------------------
LineComment
v0.4.24+commit.e67f0147
bzzr://1d50d33bcacbc79c72c404b9ba3e0da98cc33b209a6a2c04acb355c1e24613c0
{ "func_code_index": [ 8961, 9193 ] }
838
Inke
Inke.sol
0x5301a786c6d68bf3fb97e13cb2c71e671f6fa69e
Solidity
InkeToken
contract InkeToken is InkeGold { event PartnerCreated(uint indexed partnerId, address indexed partner, uint indexed amount, uint singleTrans, uint durance); event RewardDistribute(uint indexed postId, uint partnerId, address indexed user, uint indexed amount); event VipAgreementSign(uint indexed vipId, address indexed vip, uint durance, uint frequence, uint salar); event SalaryReceived(uint indexed vipId, address indexed vip, uint salary, uint indexed timestamp); string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public minePool; // 60% uint public fundPool; // 30% struct Partner { address admin; uint tokenPool; uint singleTrans; uint timestamp; uint durance; } struct Poster { address poster; bytes32 hashData; uint reward; } struct Vip { address vip; uint durance; uint frequence; uint salary; uint timestamp; } Partner[] partners; Vip[] vips; modifier onlyPartner(uint _partnerId) { require(partners[_partnerId].admin == msg.sender); require(partners[_partnerId].tokenPool > uint(0)); uint deadline = safeAdd(partners[_partnerId].timestamp, partners[_partnerId].durance); require(deadline > now); _; } modifier onlyVip(uint _vipId) { require(vips[_vipId].vip == msg.sender); require(vips[_vipId].durance > now); require(vips[_vipId].timestamp < now); _; } mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; mapping(address => bool) freezed; mapping(address => uint) freezeAmount; mapping(address => uint) unlockTime; mapping(uint => Poster[]) PartnerIdToPosterList; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "Inke"; name = "Inke Token"; decimals = 18; _totalSupply = 10000000000000000000000000000; minePool = 60000000000000000000000000000; fundPool = 30000000000000000000000000000; balances[CEOAddress] = _totalSupply; emit Transfer(address(0), CEOAddress, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { if(freezed[msg.sender] == false){ balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); } else { if(balances[msg.sender] > freezeAmount[msg.sender]) { require(tokens <= safeSub(balances[msg.sender], freezeAmount[msg.sender])); balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); } } return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { require(freezed[msg.sender] != true); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { require(freezed[msg.sender] != true); return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { require(freezed[msg.sender] != true); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Mint Tokens // ------------------------------------------------------------------------ function _mine(uint amount, address receiver) internal { require(minePool >= amount); minePool = safeSub(minePool, amount); _totalSupply = safeAdd(_totalSupply, amount); balances[receiver] = safeAdd(balances[receiver], amount); emit Transfer(address(0), receiver, amount); } function _fund(uint amount, address receiver) internal { require(fundPool >= amount); fundPool = safeSub(fundPool, amount); _totalSupply = safeAdd(_totalSupply, amount); balances[receiver] = safeAdd(balances[receiver], amount); emit Transfer(address(0), receiver, amount); } function mint(uint amount) public onlyAdmin { _fund(amount, msg.sender); } function burn(uint amount) public onlyAdmin { require(_totalSupply >= amount); balances[msg.sender] = safeSub(balances[msg.sender], amount); _totalSupply = safeSub(_totalSupply, amount); } // ------------------------------------------------------------------------ // Freeze Tokens // ------------------------------------------------------------------------ function freeze(address user, uint amount, uint period) public onlyAdmin { require(balances[user] >= amount); freezed[user] = true; unlockTime[user] = uint(now) + period; freezeAmount[user] = amount; } // ------------------------------------------------------------------------ // UnFreeze Tokens // ------------------------------------------------------------------------ function unFreeze() public whenNotPaused { require(freezed[msg.sender] == true); require(unlockTime[msg.sender] < uint(now)); freezed[msg.sender] = false; freezeAmount[msg.sender] = 0; } function ifFreeze(address user) public view returns ( bool check, uint amount, uint timeLeft ) { check = freezed[user]; amount = freezeAmount[user]; timeLeft = unlockTime[user] - uint(now); } // ------------------------------------------------------------------------ // Partner Authorization // ------------------------------------------------------------------------ function createPartner(address _partner, uint _amount, uint _singleTrans, uint _durance) public onlyAdmin returns (uint) { Partner memory _Partner = Partner({ admin: _partner, tokenPool: _amount, singleTrans: _singleTrans, timestamp: uint(now), durance: _durance }); uint newPartnerId = partners.push(_Partner) - 1; emit PartnerCreated(newPartnerId, _partner, _amount, _singleTrans, _durance); return newPartnerId; } function partnerTransfer(uint _partnerId, bytes32 _data, address _to, uint _amount) public onlyPartner(_partnerId) whenNotPaused returns (bool) { require(_amount <= partners[_partnerId].singleTrans); partners[_partnerId].tokenPool = safeSub(partners[_partnerId].tokenPool, _amount); Poster memory _Poster = Poster ({ poster: _to, hashData: _data, reward: _amount }); uint newPostId = PartnerIdToPosterList[_partnerId].push(_Poster) - 1; _fund(_amount, _to); emit RewardDistribute(newPostId, _partnerId, _to, _amount); return true; } function setPartnerPool(uint _partnerId, uint _amount) public onlyAdmin { partners[_partnerId].tokenPool = _amount; } function setPartnerDurance(uint _partnerId, uint _durance) public onlyAdmin { partners[_partnerId].durance = uint(now) + _durance; } function getPartnerInfo(uint _partnerId) public view returns ( address admin, uint tokenPool, uint timeLeft ) { Partner memory _Partner = partners[_partnerId]; admin = _Partner.admin; tokenPool = _Partner.tokenPool; if (_Partner.timestamp + _Partner.durance > uint(now)) { timeLeft = _Partner.timestamp + _Partner.durance - uint(now); } else { timeLeft = 0; } } function getPosterInfo(uint _partnerId, uint _posterId) public view returns ( address poster, bytes32 hashData, uint reward ) { Poster memory _Poster = PartnerIdToPosterList[_partnerId][_posterId]; poster = _Poster.poster; hashData = _Poster.hashData; reward = _Poster.reward; } // ------------------------------------------------------------------------ // Vip Agreement // ------------------------------------------------------------------------ function createVip(address _vip, uint _durance, uint _frequence, uint _salary) public onlyAdmin returns (uint) { Vip memory _Vip = Vip ({ vip: _vip, durance: uint(now) + _durance, frequence: _frequence, salary: _salary, timestamp: now + _frequence }); uint newVipId = vips.push(_Vip) - 1; emit VipAgreementSign(newVipId, _vip, _durance, _frequence, _salary); return newVipId; } function mineSalary(uint _vipId) public onlyVip(_vipId) whenNotPaused returns (bool) { Vip storage _Vip = vips[_vipId]; _fund(_Vip.salary, _Vip.vip); _Vip.timestamp = safeAdd(_Vip.timestamp, _Vip.frequence); emit SalaryReceived(_vipId, _Vip.vip, _Vip.salary, _Vip.timestamp); return true; } function deleteVip(uint _vipId) public onlyAdmin { delete vips[_vipId]; } function getVipInfo(uint _vipId) public view returns ( address vip, uint durance, uint frequence, uint salary, uint nextSalary, string log ) { Vip memory _Vip = vips[_vipId]; vip = _Vip.vip; durance = _Vip.durance; frequence = _Vip.frequence; salary = _Vip.salary; if(_Vip.timestamp >= uint(now)) { nextSalary = safeSub(_Vip.timestamp, uint(now)); log = "Please Wait"; } else { nextSalary = 0; log = "Pick Up Your Salary Now"; } } // ------------------------------------------------------------------------ // Accept ETH // ------------------------------------------------------------------------ function () public payable { } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyAdmin returns (bool success) { return ERC20Interface(tokenAddress).transfer(CEOAddress, tokens); } }
createPartner
function createPartner(address _partner, uint _amount, uint _singleTrans, uint _durance) public onlyAdmin returns (uint) { Partner memory _Partner = Partner({ admin: _partner, tokenPool: _amount, singleTrans: _singleTrans, timestamp: uint(now), durance: _durance }); uint newPartnerId = partners.push(_Partner) - 1; emit PartnerCreated(newPartnerId, _partner, _amount, _singleTrans, _durance); return newPartnerId; }
// ------------------------------------------------------------------------ // Partner Authorization // ------------------------------------------------------------------------
LineComment
v0.4.24+commit.e67f0147
bzzr://1d50d33bcacbc79c72c404b9ba3e0da98cc33b209a6a2c04acb355c1e24613c0
{ "func_code_index": [ 9661, 10207 ] }
839
Inke
Inke.sol
0x5301a786c6d68bf3fb97e13cb2c71e671f6fa69e
Solidity
InkeToken
contract InkeToken is InkeGold { event PartnerCreated(uint indexed partnerId, address indexed partner, uint indexed amount, uint singleTrans, uint durance); event RewardDistribute(uint indexed postId, uint partnerId, address indexed user, uint indexed amount); event VipAgreementSign(uint indexed vipId, address indexed vip, uint durance, uint frequence, uint salar); event SalaryReceived(uint indexed vipId, address indexed vip, uint salary, uint indexed timestamp); string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public minePool; // 60% uint public fundPool; // 30% struct Partner { address admin; uint tokenPool; uint singleTrans; uint timestamp; uint durance; } struct Poster { address poster; bytes32 hashData; uint reward; } struct Vip { address vip; uint durance; uint frequence; uint salary; uint timestamp; } Partner[] partners; Vip[] vips; modifier onlyPartner(uint _partnerId) { require(partners[_partnerId].admin == msg.sender); require(partners[_partnerId].tokenPool > uint(0)); uint deadline = safeAdd(partners[_partnerId].timestamp, partners[_partnerId].durance); require(deadline > now); _; } modifier onlyVip(uint _vipId) { require(vips[_vipId].vip == msg.sender); require(vips[_vipId].durance > now); require(vips[_vipId].timestamp < now); _; } mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; mapping(address => bool) freezed; mapping(address => uint) freezeAmount; mapping(address => uint) unlockTime; mapping(uint => Poster[]) PartnerIdToPosterList; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "Inke"; name = "Inke Token"; decimals = 18; _totalSupply = 10000000000000000000000000000; minePool = 60000000000000000000000000000; fundPool = 30000000000000000000000000000; balances[CEOAddress] = _totalSupply; emit Transfer(address(0), CEOAddress, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { if(freezed[msg.sender] == false){ balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); } else { if(balances[msg.sender] > freezeAmount[msg.sender]) { require(tokens <= safeSub(balances[msg.sender], freezeAmount[msg.sender])); balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); } } return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { require(freezed[msg.sender] != true); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { require(freezed[msg.sender] != true); return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { require(freezed[msg.sender] != true); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Mint Tokens // ------------------------------------------------------------------------ function _mine(uint amount, address receiver) internal { require(minePool >= amount); minePool = safeSub(minePool, amount); _totalSupply = safeAdd(_totalSupply, amount); balances[receiver] = safeAdd(balances[receiver], amount); emit Transfer(address(0), receiver, amount); } function _fund(uint amount, address receiver) internal { require(fundPool >= amount); fundPool = safeSub(fundPool, amount); _totalSupply = safeAdd(_totalSupply, amount); balances[receiver] = safeAdd(balances[receiver], amount); emit Transfer(address(0), receiver, amount); } function mint(uint amount) public onlyAdmin { _fund(amount, msg.sender); } function burn(uint amount) public onlyAdmin { require(_totalSupply >= amount); balances[msg.sender] = safeSub(balances[msg.sender], amount); _totalSupply = safeSub(_totalSupply, amount); } // ------------------------------------------------------------------------ // Freeze Tokens // ------------------------------------------------------------------------ function freeze(address user, uint amount, uint period) public onlyAdmin { require(balances[user] >= amount); freezed[user] = true; unlockTime[user] = uint(now) + period; freezeAmount[user] = amount; } // ------------------------------------------------------------------------ // UnFreeze Tokens // ------------------------------------------------------------------------ function unFreeze() public whenNotPaused { require(freezed[msg.sender] == true); require(unlockTime[msg.sender] < uint(now)); freezed[msg.sender] = false; freezeAmount[msg.sender] = 0; } function ifFreeze(address user) public view returns ( bool check, uint amount, uint timeLeft ) { check = freezed[user]; amount = freezeAmount[user]; timeLeft = unlockTime[user] - uint(now); } // ------------------------------------------------------------------------ // Partner Authorization // ------------------------------------------------------------------------ function createPartner(address _partner, uint _amount, uint _singleTrans, uint _durance) public onlyAdmin returns (uint) { Partner memory _Partner = Partner({ admin: _partner, tokenPool: _amount, singleTrans: _singleTrans, timestamp: uint(now), durance: _durance }); uint newPartnerId = partners.push(_Partner) - 1; emit PartnerCreated(newPartnerId, _partner, _amount, _singleTrans, _durance); return newPartnerId; } function partnerTransfer(uint _partnerId, bytes32 _data, address _to, uint _amount) public onlyPartner(_partnerId) whenNotPaused returns (bool) { require(_amount <= partners[_partnerId].singleTrans); partners[_partnerId].tokenPool = safeSub(partners[_partnerId].tokenPool, _amount); Poster memory _Poster = Poster ({ poster: _to, hashData: _data, reward: _amount }); uint newPostId = PartnerIdToPosterList[_partnerId].push(_Poster) - 1; _fund(_amount, _to); emit RewardDistribute(newPostId, _partnerId, _to, _amount); return true; } function setPartnerPool(uint _partnerId, uint _amount) public onlyAdmin { partners[_partnerId].tokenPool = _amount; } function setPartnerDurance(uint _partnerId, uint _durance) public onlyAdmin { partners[_partnerId].durance = uint(now) + _durance; } function getPartnerInfo(uint _partnerId) public view returns ( address admin, uint tokenPool, uint timeLeft ) { Partner memory _Partner = partners[_partnerId]; admin = _Partner.admin; tokenPool = _Partner.tokenPool; if (_Partner.timestamp + _Partner.durance > uint(now)) { timeLeft = _Partner.timestamp + _Partner.durance - uint(now); } else { timeLeft = 0; } } function getPosterInfo(uint _partnerId, uint _posterId) public view returns ( address poster, bytes32 hashData, uint reward ) { Poster memory _Poster = PartnerIdToPosterList[_partnerId][_posterId]; poster = _Poster.poster; hashData = _Poster.hashData; reward = _Poster.reward; } // ------------------------------------------------------------------------ // Vip Agreement // ------------------------------------------------------------------------ function createVip(address _vip, uint _durance, uint _frequence, uint _salary) public onlyAdmin returns (uint) { Vip memory _Vip = Vip ({ vip: _vip, durance: uint(now) + _durance, frequence: _frequence, salary: _salary, timestamp: now + _frequence }); uint newVipId = vips.push(_Vip) - 1; emit VipAgreementSign(newVipId, _vip, _durance, _frequence, _salary); return newVipId; } function mineSalary(uint _vipId) public onlyVip(_vipId) whenNotPaused returns (bool) { Vip storage _Vip = vips[_vipId]; _fund(_Vip.salary, _Vip.vip); _Vip.timestamp = safeAdd(_Vip.timestamp, _Vip.frequence); emit SalaryReceived(_vipId, _Vip.vip, _Vip.salary, _Vip.timestamp); return true; } function deleteVip(uint _vipId) public onlyAdmin { delete vips[_vipId]; } function getVipInfo(uint _vipId) public view returns ( address vip, uint durance, uint frequence, uint salary, uint nextSalary, string log ) { Vip memory _Vip = vips[_vipId]; vip = _Vip.vip; durance = _Vip.durance; frequence = _Vip.frequence; salary = _Vip.salary; if(_Vip.timestamp >= uint(now)) { nextSalary = safeSub(_Vip.timestamp, uint(now)); log = "Please Wait"; } else { nextSalary = 0; log = "Pick Up Your Salary Now"; } } // ------------------------------------------------------------------------ // Accept ETH // ------------------------------------------------------------------------ function () public payable { } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyAdmin returns (bool success) { return ERC20Interface(tokenAddress).transfer(CEOAddress, tokens); } }
createVip
function createVip(address _vip, uint _durance, uint _frequence, uint _salary) public onlyAdmin returns (uint) { Vip memory _Vip = Vip ({ vip: _vip, durance: uint(now) + _durance, frequence: _frequence, salary: _salary, timestamp: now + _frequence }); uint newVipId = vips.push(_Vip) - 1; emit VipAgreementSign(newVipId, _vip, _durance, _frequence, _salary); return newVipId; }
// ------------------------------------------------------------------------ // Vip Agreement // ------------------------------------------------------------------------
LineComment
v0.4.24+commit.e67f0147
bzzr://1d50d33bcacbc79c72c404b9ba3e0da98cc33b209a6a2c04acb355c1e24613c0
{ "func_code_index": [ 12211, 12713 ] }
840
Inke
Inke.sol
0x5301a786c6d68bf3fb97e13cb2c71e671f6fa69e
Solidity
InkeToken
contract InkeToken is InkeGold { event PartnerCreated(uint indexed partnerId, address indexed partner, uint indexed amount, uint singleTrans, uint durance); event RewardDistribute(uint indexed postId, uint partnerId, address indexed user, uint indexed amount); event VipAgreementSign(uint indexed vipId, address indexed vip, uint durance, uint frequence, uint salar); event SalaryReceived(uint indexed vipId, address indexed vip, uint salary, uint indexed timestamp); string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public minePool; // 60% uint public fundPool; // 30% struct Partner { address admin; uint tokenPool; uint singleTrans; uint timestamp; uint durance; } struct Poster { address poster; bytes32 hashData; uint reward; } struct Vip { address vip; uint durance; uint frequence; uint salary; uint timestamp; } Partner[] partners; Vip[] vips; modifier onlyPartner(uint _partnerId) { require(partners[_partnerId].admin == msg.sender); require(partners[_partnerId].tokenPool > uint(0)); uint deadline = safeAdd(partners[_partnerId].timestamp, partners[_partnerId].durance); require(deadline > now); _; } modifier onlyVip(uint _vipId) { require(vips[_vipId].vip == msg.sender); require(vips[_vipId].durance > now); require(vips[_vipId].timestamp < now); _; } mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; mapping(address => bool) freezed; mapping(address => uint) freezeAmount; mapping(address => uint) unlockTime; mapping(uint => Poster[]) PartnerIdToPosterList; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "Inke"; name = "Inke Token"; decimals = 18; _totalSupply = 10000000000000000000000000000; minePool = 60000000000000000000000000000; fundPool = 30000000000000000000000000000; balances[CEOAddress] = _totalSupply; emit Transfer(address(0), CEOAddress, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { if(freezed[msg.sender] == false){ balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); } else { if(balances[msg.sender] > freezeAmount[msg.sender]) { require(tokens <= safeSub(balances[msg.sender], freezeAmount[msg.sender])); balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); } } return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { require(freezed[msg.sender] != true); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { require(freezed[msg.sender] != true); return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { require(freezed[msg.sender] != true); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Mint Tokens // ------------------------------------------------------------------------ function _mine(uint amount, address receiver) internal { require(minePool >= amount); minePool = safeSub(minePool, amount); _totalSupply = safeAdd(_totalSupply, amount); balances[receiver] = safeAdd(balances[receiver], amount); emit Transfer(address(0), receiver, amount); } function _fund(uint amount, address receiver) internal { require(fundPool >= amount); fundPool = safeSub(fundPool, amount); _totalSupply = safeAdd(_totalSupply, amount); balances[receiver] = safeAdd(balances[receiver], amount); emit Transfer(address(0), receiver, amount); } function mint(uint amount) public onlyAdmin { _fund(amount, msg.sender); } function burn(uint amount) public onlyAdmin { require(_totalSupply >= amount); balances[msg.sender] = safeSub(balances[msg.sender], amount); _totalSupply = safeSub(_totalSupply, amount); } // ------------------------------------------------------------------------ // Freeze Tokens // ------------------------------------------------------------------------ function freeze(address user, uint amount, uint period) public onlyAdmin { require(balances[user] >= amount); freezed[user] = true; unlockTime[user] = uint(now) + period; freezeAmount[user] = amount; } // ------------------------------------------------------------------------ // UnFreeze Tokens // ------------------------------------------------------------------------ function unFreeze() public whenNotPaused { require(freezed[msg.sender] == true); require(unlockTime[msg.sender] < uint(now)); freezed[msg.sender] = false; freezeAmount[msg.sender] = 0; } function ifFreeze(address user) public view returns ( bool check, uint amount, uint timeLeft ) { check = freezed[user]; amount = freezeAmount[user]; timeLeft = unlockTime[user] - uint(now); } // ------------------------------------------------------------------------ // Partner Authorization // ------------------------------------------------------------------------ function createPartner(address _partner, uint _amount, uint _singleTrans, uint _durance) public onlyAdmin returns (uint) { Partner memory _Partner = Partner({ admin: _partner, tokenPool: _amount, singleTrans: _singleTrans, timestamp: uint(now), durance: _durance }); uint newPartnerId = partners.push(_Partner) - 1; emit PartnerCreated(newPartnerId, _partner, _amount, _singleTrans, _durance); return newPartnerId; } function partnerTransfer(uint _partnerId, bytes32 _data, address _to, uint _amount) public onlyPartner(_partnerId) whenNotPaused returns (bool) { require(_amount <= partners[_partnerId].singleTrans); partners[_partnerId].tokenPool = safeSub(partners[_partnerId].tokenPool, _amount); Poster memory _Poster = Poster ({ poster: _to, hashData: _data, reward: _amount }); uint newPostId = PartnerIdToPosterList[_partnerId].push(_Poster) - 1; _fund(_amount, _to); emit RewardDistribute(newPostId, _partnerId, _to, _amount); return true; } function setPartnerPool(uint _partnerId, uint _amount) public onlyAdmin { partners[_partnerId].tokenPool = _amount; } function setPartnerDurance(uint _partnerId, uint _durance) public onlyAdmin { partners[_partnerId].durance = uint(now) + _durance; } function getPartnerInfo(uint _partnerId) public view returns ( address admin, uint tokenPool, uint timeLeft ) { Partner memory _Partner = partners[_partnerId]; admin = _Partner.admin; tokenPool = _Partner.tokenPool; if (_Partner.timestamp + _Partner.durance > uint(now)) { timeLeft = _Partner.timestamp + _Partner.durance - uint(now); } else { timeLeft = 0; } } function getPosterInfo(uint _partnerId, uint _posterId) public view returns ( address poster, bytes32 hashData, uint reward ) { Poster memory _Poster = PartnerIdToPosterList[_partnerId][_posterId]; poster = _Poster.poster; hashData = _Poster.hashData; reward = _Poster.reward; } // ------------------------------------------------------------------------ // Vip Agreement // ------------------------------------------------------------------------ function createVip(address _vip, uint _durance, uint _frequence, uint _salary) public onlyAdmin returns (uint) { Vip memory _Vip = Vip ({ vip: _vip, durance: uint(now) + _durance, frequence: _frequence, salary: _salary, timestamp: now + _frequence }); uint newVipId = vips.push(_Vip) - 1; emit VipAgreementSign(newVipId, _vip, _durance, _frequence, _salary); return newVipId; } function mineSalary(uint _vipId) public onlyVip(_vipId) whenNotPaused returns (bool) { Vip storage _Vip = vips[_vipId]; _fund(_Vip.salary, _Vip.vip); _Vip.timestamp = safeAdd(_Vip.timestamp, _Vip.frequence); emit SalaryReceived(_vipId, _Vip.vip, _Vip.salary, _Vip.timestamp); return true; } function deleteVip(uint _vipId) public onlyAdmin { delete vips[_vipId]; } function getVipInfo(uint _vipId) public view returns ( address vip, uint durance, uint frequence, uint salary, uint nextSalary, string log ) { Vip memory _Vip = vips[_vipId]; vip = _Vip.vip; durance = _Vip.durance; frequence = _Vip.frequence; salary = _Vip.salary; if(_Vip.timestamp >= uint(now)) { nextSalary = safeSub(_Vip.timestamp, uint(now)); log = "Please Wait"; } else { nextSalary = 0; log = "Pick Up Your Salary Now"; } } // ------------------------------------------------------------------------ // Accept ETH // ------------------------------------------------------------------------ function () public payable { } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyAdmin returns (bool success) { return ERC20Interface(tokenAddress).transfer(CEOAddress, tokens); } }
function () public payable { }
// ------------------------------------------------------------------------ // Accept ETH // ------------------------------------------------------------------------
LineComment
v0.4.24+commit.e67f0147
bzzr://1d50d33bcacbc79c72c404b9ba3e0da98cc33b209a6a2c04acb355c1e24613c0
{ "func_code_index": [ 13988, 14028 ] }
841
Inke
Inke.sol
0x5301a786c6d68bf3fb97e13cb2c71e671f6fa69e
Solidity
InkeToken
contract InkeToken is InkeGold { event PartnerCreated(uint indexed partnerId, address indexed partner, uint indexed amount, uint singleTrans, uint durance); event RewardDistribute(uint indexed postId, uint partnerId, address indexed user, uint indexed amount); event VipAgreementSign(uint indexed vipId, address indexed vip, uint durance, uint frequence, uint salar); event SalaryReceived(uint indexed vipId, address indexed vip, uint salary, uint indexed timestamp); string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public minePool; // 60% uint public fundPool; // 30% struct Partner { address admin; uint tokenPool; uint singleTrans; uint timestamp; uint durance; } struct Poster { address poster; bytes32 hashData; uint reward; } struct Vip { address vip; uint durance; uint frequence; uint salary; uint timestamp; } Partner[] partners; Vip[] vips; modifier onlyPartner(uint _partnerId) { require(partners[_partnerId].admin == msg.sender); require(partners[_partnerId].tokenPool > uint(0)); uint deadline = safeAdd(partners[_partnerId].timestamp, partners[_partnerId].durance); require(deadline > now); _; } modifier onlyVip(uint _vipId) { require(vips[_vipId].vip == msg.sender); require(vips[_vipId].durance > now); require(vips[_vipId].timestamp < now); _; } mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; mapping(address => bool) freezed; mapping(address => uint) freezeAmount; mapping(address => uint) unlockTime; mapping(uint => Poster[]) PartnerIdToPosterList; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "Inke"; name = "Inke Token"; decimals = 18; _totalSupply = 10000000000000000000000000000; minePool = 60000000000000000000000000000; fundPool = 30000000000000000000000000000; balances[CEOAddress] = _totalSupply; emit Transfer(address(0), CEOAddress, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { if(freezed[msg.sender] == false){ balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); } else { if(balances[msg.sender] > freezeAmount[msg.sender]) { require(tokens <= safeSub(balances[msg.sender], freezeAmount[msg.sender])); balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); } } return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { require(freezed[msg.sender] != true); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { require(freezed[msg.sender] != true); return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { require(freezed[msg.sender] != true); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Mint Tokens // ------------------------------------------------------------------------ function _mine(uint amount, address receiver) internal { require(minePool >= amount); minePool = safeSub(minePool, amount); _totalSupply = safeAdd(_totalSupply, amount); balances[receiver] = safeAdd(balances[receiver], amount); emit Transfer(address(0), receiver, amount); } function _fund(uint amount, address receiver) internal { require(fundPool >= amount); fundPool = safeSub(fundPool, amount); _totalSupply = safeAdd(_totalSupply, amount); balances[receiver] = safeAdd(balances[receiver], amount); emit Transfer(address(0), receiver, amount); } function mint(uint amount) public onlyAdmin { _fund(amount, msg.sender); } function burn(uint amount) public onlyAdmin { require(_totalSupply >= amount); balances[msg.sender] = safeSub(balances[msg.sender], amount); _totalSupply = safeSub(_totalSupply, amount); } // ------------------------------------------------------------------------ // Freeze Tokens // ------------------------------------------------------------------------ function freeze(address user, uint amount, uint period) public onlyAdmin { require(balances[user] >= amount); freezed[user] = true; unlockTime[user] = uint(now) + period; freezeAmount[user] = amount; } // ------------------------------------------------------------------------ // UnFreeze Tokens // ------------------------------------------------------------------------ function unFreeze() public whenNotPaused { require(freezed[msg.sender] == true); require(unlockTime[msg.sender] < uint(now)); freezed[msg.sender] = false; freezeAmount[msg.sender] = 0; } function ifFreeze(address user) public view returns ( bool check, uint amount, uint timeLeft ) { check = freezed[user]; amount = freezeAmount[user]; timeLeft = unlockTime[user] - uint(now); } // ------------------------------------------------------------------------ // Partner Authorization // ------------------------------------------------------------------------ function createPartner(address _partner, uint _amount, uint _singleTrans, uint _durance) public onlyAdmin returns (uint) { Partner memory _Partner = Partner({ admin: _partner, tokenPool: _amount, singleTrans: _singleTrans, timestamp: uint(now), durance: _durance }); uint newPartnerId = partners.push(_Partner) - 1; emit PartnerCreated(newPartnerId, _partner, _amount, _singleTrans, _durance); return newPartnerId; } function partnerTransfer(uint _partnerId, bytes32 _data, address _to, uint _amount) public onlyPartner(_partnerId) whenNotPaused returns (bool) { require(_amount <= partners[_partnerId].singleTrans); partners[_partnerId].tokenPool = safeSub(partners[_partnerId].tokenPool, _amount); Poster memory _Poster = Poster ({ poster: _to, hashData: _data, reward: _amount }); uint newPostId = PartnerIdToPosterList[_partnerId].push(_Poster) - 1; _fund(_amount, _to); emit RewardDistribute(newPostId, _partnerId, _to, _amount); return true; } function setPartnerPool(uint _partnerId, uint _amount) public onlyAdmin { partners[_partnerId].tokenPool = _amount; } function setPartnerDurance(uint _partnerId, uint _durance) public onlyAdmin { partners[_partnerId].durance = uint(now) + _durance; } function getPartnerInfo(uint _partnerId) public view returns ( address admin, uint tokenPool, uint timeLeft ) { Partner memory _Partner = partners[_partnerId]; admin = _Partner.admin; tokenPool = _Partner.tokenPool; if (_Partner.timestamp + _Partner.durance > uint(now)) { timeLeft = _Partner.timestamp + _Partner.durance - uint(now); } else { timeLeft = 0; } } function getPosterInfo(uint _partnerId, uint _posterId) public view returns ( address poster, bytes32 hashData, uint reward ) { Poster memory _Poster = PartnerIdToPosterList[_partnerId][_posterId]; poster = _Poster.poster; hashData = _Poster.hashData; reward = _Poster.reward; } // ------------------------------------------------------------------------ // Vip Agreement // ------------------------------------------------------------------------ function createVip(address _vip, uint _durance, uint _frequence, uint _salary) public onlyAdmin returns (uint) { Vip memory _Vip = Vip ({ vip: _vip, durance: uint(now) + _durance, frequence: _frequence, salary: _salary, timestamp: now + _frequence }); uint newVipId = vips.push(_Vip) - 1; emit VipAgreementSign(newVipId, _vip, _durance, _frequence, _salary); return newVipId; } function mineSalary(uint _vipId) public onlyVip(_vipId) whenNotPaused returns (bool) { Vip storage _Vip = vips[_vipId]; _fund(_Vip.salary, _Vip.vip); _Vip.timestamp = safeAdd(_Vip.timestamp, _Vip.frequence); emit SalaryReceived(_vipId, _Vip.vip, _Vip.salary, _Vip.timestamp); return true; } function deleteVip(uint _vipId) public onlyAdmin { delete vips[_vipId]; } function getVipInfo(uint _vipId) public view returns ( address vip, uint durance, uint frequence, uint salary, uint nextSalary, string log ) { Vip memory _Vip = vips[_vipId]; vip = _Vip.vip; durance = _Vip.durance; frequence = _Vip.frequence; salary = _Vip.salary; if(_Vip.timestamp >= uint(now)) { nextSalary = safeSub(_Vip.timestamp, uint(now)); log = "Please Wait"; } else { nextSalary = 0; log = "Pick Up Your Salary Now"; } } // ------------------------------------------------------------------------ // Accept ETH // ------------------------------------------------------------------------ function () public payable { } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyAdmin returns (bool success) { return ERC20Interface(tokenAddress).transfer(CEOAddress, tokens); } }
transferAnyERC20Token
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyAdmin returns (bool success) { return ERC20Interface(tokenAddress).transfer(CEOAddress, tokens); }
// ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------
LineComment
v0.4.24+commit.e67f0147
bzzr://1d50d33bcacbc79c72c404b9ba3e0da98cc33b209a6a2c04acb355c1e24613c0
{ "func_code_index": [ 14259, 14453 ] }
842
Token
/Users/pjh/workspace/chainpartners/cha-contracts/contracts/token/Token.sol
0x07305f5dc6c75e93fed3a10776eb3e92835ef474
Solidity
Token
contract Token is ERC20PresetMinterPauser, ERC20Permit, ERC20OnApprove { bytes32 public constant MINTER_ADMIN_ROLE = keccak256("MINTER_ADMIN_ROLE"); bytes32 public constant PAUSER_ADMIN_ROLE = keccak256("PAUSER_ADMIN_ROLE"); constructor( string memory name_, string memory symbol_, uint256 initialSupply_ ) ERC20PresetMinterPauser(name_, symbol_) ERC20Permit(name_) { _mint(_msgSender(), initialSupply_); _setRoleAdmin(MINTER_ROLE, MINTER_ADMIN_ROLE); _setRoleAdmin(PAUSER_ROLE, PAUSER_ADMIN_ROLE); _setupRole(MINTER_ADMIN_ROLE, _msgSender()); _setupRole(PAUSER_ADMIN_ROLE, _msgSender()); } /** * @dev change DEFAULT_ADMIN_ROLE to `account`. * To revoke DEFAULT_ADMIN_ROLE, use `revokeRole(DEFAULT_ADMIN_ROLE, account)` */ function changeAdminRole(address account) external { require(account != address(0), "Token: zero-address"); changeRole(DEFAULT_ADMIN_ROLE, account); } /** * @dev grant and revoke `role` to `account` */ function changeRole(bytes32 role, address account) public { grantRole(role, account); revokeRole(role, _msgSender()); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override(ERC20, ERC20PresetMinterPauser) { super._beforeTokenTransfer(from, to, amount); } function getChainId() external view returns (uint256) { return block.chainid; } }
changeAdminRole
function changeAdminRole(address account) external { require(account != address(0), "Token: zero-address"); changeRole(DEFAULT_ADMIN_ROLE, account); }
/** * @dev change DEFAULT_ADMIN_ROLE to `account`. * To revoke DEFAULT_ADMIN_ROLE, use `revokeRole(DEFAULT_ADMIN_ROLE, account)` */
NatSpecMultiLine
v0.8.5+commit.a4f2e591
{ "func_code_index": [ 835, 1009 ] }
843
Token
/Users/pjh/workspace/chainpartners/cha-contracts/contracts/token/Token.sol
0x07305f5dc6c75e93fed3a10776eb3e92835ef474
Solidity
Token
contract Token is ERC20PresetMinterPauser, ERC20Permit, ERC20OnApprove { bytes32 public constant MINTER_ADMIN_ROLE = keccak256("MINTER_ADMIN_ROLE"); bytes32 public constant PAUSER_ADMIN_ROLE = keccak256("PAUSER_ADMIN_ROLE"); constructor( string memory name_, string memory symbol_, uint256 initialSupply_ ) ERC20PresetMinterPauser(name_, symbol_) ERC20Permit(name_) { _mint(_msgSender(), initialSupply_); _setRoleAdmin(MINTER_ROLE, MINTER_ADMIN_ROLE); _setRoleAdmin(PAUSER_ROLE, PAUSER_ADMIN_ROLE); _setupRole(MINTER_ADMIN_ROLE, _msgSender()); _setupRole(PAUSER_ADMIN_ROLE, _msgSender()); } /** * @dev change DEFAULT_ADMIN_ROLE to `account`. * To revoke DEFAULT_ADMIN_ROLE, use `revokeRole(DEFAULT_ADMIN_ROLE, account)` */ function changeAdminRole(address account) external { require(account != address(0), "Token: zero-address"); changeRole(DEFAULT_ADMIN_ROLE, account); } /** * @dev grant and revoke `role` to `account` */ function changeRole(bytes32 role, address account) public { grantRole(role, account); revokeRole(role, _msgSender()); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override(ERC20, ERC20PresetMinterPauser) { super._beforeTokenTransfer(from, to, amount); } function getChainId() external view returns (uint256) { return block.chainid; } }
changeRole
function changeRole(bytes32 role, address account) public { grantRole(role, account); revokeRole(role, _msgSender()); }
/** * @dev grant and revoke `role` to `account` */
NatSpecMultiLine
v0.8.5+commit.a4f2e591
{ "func_code_index": [ 1076, 1219 ] }
844
DroneCoin
DroneCoin.sol
0x6f97eff37aa24cf5275ab0d92e5d43cb45d2f3ec
Solidity
ERC20Token
contract ERC20Token is IERC20, Pausable { using SafeMath for uint256; using Address for address; string internal _name; string internal _symbol; uint8 internal _decimals; uint256 internal _totalSupply; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowances; constructor(string memory name, string memory symbol, uint8 decimals, uint256 totalSupply) public { _name = name; _symbol = symbol; _decimals = decimals; _totalSupply = totalSupply; _balances[msg.sender] = totalSupply; emit Transfer(address(0), msg.sender, totalSupply); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256 balance) { return _balances[account]; } // Function that is called when a user or another contract wants to transfer funds . function transfer(address recipient, uint256 amount) public whenNotPaused returns (bool success) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 value) public whenNotPaused returns (bool) { _approve(msg.sender, spender, value); return true; } function transferFrom(address sender, address recipient, uint256 amount) public whenNotPaused returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } function increaseAllowance(address spender, uint256 addedValue) public whenNotPaused returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public whenNotPaused returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } }
transfer
function transfer(address recipient, uint256 amount) public whenNotPaused returns (bool success) { _transfer(msg.sender, recipient, amount); return true; }
// Function that is called when a user or another contract wants to transfer funds .
LineComment
v0.5.0+commit.1d4f565a
None
bzzr://260572514d6ba90bd1d07087d605c3f3eb52e14f4cbf06c196c4f991d65ad02c
{ "func_code_index": [ 1303, 1506 ] }
845
Rapide
Rapide.sol
0xc8035ea3580d5dd63b7535c26687fe18f8284e2f
Solidity
Rapide
contract Rapide { // 변수 선언 string public name; string public symbol; uint8 public decimals = 18; // 18소수 점 이하는 강력하게 제안된 기본 값이므로 변경하지 마십시오. uint256 public totalSupply; // 모든 균형을 갖춘 배열을 생성합니다. mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // 이것은 블록체인에서 클라이언트에게 알려주는 공개 이벤트를 생성합니다 event Transfer(address indexed from, address indexed to, uint256 value); // 소각된 양을 알립니다. event Burn(address indexed from, uint256 value); /** * 생성자 함수 * * 계약서 작성자에게 초기 공급 토큰과의 계약을 초기화합니다. */ function Rapide( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // 총 공급액을 소수로 업데이트합니다. balanceOf[msg.sender] = totalSupply; // 총 발행량 name = tokenName; // 토큰 이름 symbol = tokenSymbol; // 토큰 심볼 (EX: BTC, ETH, LTC) } /** * 내부 전송, 이 계약으로만 호출할 수 있습니다. */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // 발신자 점검 require(balanceOf[_from] >= _value); // 오버플로 확인 require(balanceOf[_to] + _value > balanceOf[_to]); // 미래의 주장을 위해 이것을 저장하십시오 uint previousBalances = balanceOf[_from] + balanceOf[_to]; // 발신자에서 차감 balanceOf[_from] -= _value; // 받는 사람에게 같은 것을 추가하십시오. balanceOf[_to] += _value; Transfer(_from, _to, _value); // 정적 분석을 사용하여 코드에서 버그를 찾을 때 사용합니다. 이 시스템은 실패하지 않습니다. assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * 토큰 전송 * @ _to 받는 사람의 주소에 대한 매개 변수 * @ _value 전송할 금액을 정하다. */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * _from 보낸 사람의 주소 * _to 받는 사람의 주소 * _value 전송할 금액 */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // 허용량 체크 allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * 다른 주소에 대한 허용량 설정 * _spender 지출 할 수있는 주소 * _value 그들이 쓸 수 있는 지출 할 수있는 최대 금액 */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * 다른 주소에 대한 허용치 설정 및 알림 * @param _spender 지출 할 수있는 주소 * @param _value 그들이 쓸 수 있는 지출 할 수있는 최대 금액 * @param _extraData 승인 된 계약서에 보낼 추가 정보 */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * 토큰 파괴 * @param _value 소각되는 금액 */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // 보낸 사람이 충분히 있는지 확인하십시오. balanceOf[msg.sender] -= _value; // 발신자에게서 뺍니다. totalSupply -= _value; // 총 발행량 업데이트 Burn(msg.sender, _value); return true; } /** * 다른 계정에서 토큰 삭제 * @param _from 발신자 주소 * @param _value 소각되는 금액 */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // 목표 잔액이 충분한 지 확인하십시오. require(_value <= allowance[_from][msg.sender]); // 수당 확인 balanceOf[_from] -= _value; // 목표 잔액에서 차감 allowance[_from][msg.sender] -= _value; // 발송인의 허용량에서 차감 totalSupply -= _value; // 총 발행량 업데이트 Burn(_from, _value); return true; } }
Rapide
function Rapide( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // 총 공급액을 소수로 업데이트합니다. balanceOf[msg.sender] = totalSupply; // 총 발행량 name = tokenName; // 토큰 이름 symbol = tokenSymbol; // 토큰 심볼 (EX: BTC, ETH, LTC) }
/** * 생성자 함수 * * 계약서 작성자에게 초기 공급 토큰과의 계약을 초기화합니다. */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
bzzr://06bdab768321bb8adbb90bc85da173de01186c85dc584d117a2de3de80d4133c
{ "func_code_index": [ 660, 1131 ] }
846
Rapide
Rapide.sol
0xc8035ea3580d5dd63b7535c26687fe18f8284e2f
Solidity
Rapide
contract Rapide { // 변수 선언 string public name; string public symbol; uint8 public decimals = 18; // 18소수 점 이하는 강력하게 제안된 기본 값이므로 변경하지 마십시오. uint256 public totalSupply; // 모든 균형을 갖춘 배열을 생성합니다. mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // 이것은 블록체인에서 클라이언트에게 알려주는 공개 이벤트를 생성합니다 event Transfer(address indexed from, address indexed to, uint256 value); // 소각된 양을 알립니다. event Burn(address indexed from, uint256 value); /** * 생성자 함수 * * 계약서 작성자에게 초기 공급 토큰과의 계약을 초기화합니다. */ function Rapide( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // 총 공급액을 소수로 업데이트합니다. balanceOf[msg.sender] = totalSupply; // 총 발행량 name = tokenName; // 토큰 이름 symbol = tokenSymbol; // 토큰 심볼 (EX: BTC, ETH, LTC) } /** * 내부 전송, 이 계약으로만 호출할 수 있습니다. */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // 발신자 점검 require(balanceOf[_from] >= _value); // 오버플로 확인 require(balanceOf[_to] + _value > balanceOf[_to]); // 미래의 주장을 위해 이것을 저장하십시오 uint previousBalances = balanceOf[_from] + balanceOf[_to]; // 발신자에서 차감 balanceOf[_from] -= _value; // 받는 사람에게 같은 것을 추가하십시오. balanceOf[_to] += _value; Transfer(_from, _to, _value); // 정적 분석을 사용하여 코드에서 버그를 찾을 때 사용합니다. 이 시스템은 실패하지 않습니다. assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * 토큰 전송 * @ _to 받는 사람의 주소에 대한 매개 변수 * @ _value 전송할 금액을 정하다. */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * _from 보낸 사람의 주소 * _to 받는 사람의 주소 * _value 전송할 금액 */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // 허용량 체크 allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * 다른 주소에 대한 허용량 설정 * _spender 지출 할 수있는 주소 * _value 그들이 쓸 수 있는 지출 할 수있는 최대 금액 */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * 다른 주소에 대한 허용치 설정 및 알림 * @param _spender 지출 할 수있는 주소 * @param _value 그들이 쓸 수 있는 지출 할 수있는 최대 금액 * @param _extraData 승인 된 계약서에 보낼 추가 정보 */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * 토큰 파괴 * @param _value 소각되는 금액 */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // 보낸 사람이 충분히 있는지 확인하십시오. balanceOf[msg.sender] -= _value; // 발신자에게서 뺍니다. totalSupply -= _value; // 총 발행량 업데이트 Burn(msg.sender, _value); return true; } /** * 다른 계정에서 토큰 삭제 * @param _from 발신자 주소 * @param _value 소각되는 금액 */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // 목표 잔액이 충분한 지 확인하십시오. require(_value <= allowance[_from][msg.sender]); // 수당 확인 balanceOf[_from] -= _value; // 목표 잔액에서 차감 allowance[_from][msg.sender] -= _value; // 발송인의 허용량에서 차감 totalSupply -= _value; // 총 발행량 업데이트 Burn(_from, _value); return true; } }
_transfer
function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // 발신자 점검 require(balanceOf[_from] >= _value); // 오버플로 확인 require(balanceOf[_to] + _value > balanceOf[_to]); // 미래의 주장을 위해 이것을 저장하십시오 uint previousBalances = balanceOf[_from] + balanceOf[_to]; // 발신자에서 차감 balanceOf[_from] -= _value; // 받는 사람에게 같은 것을 추가하십시오. balanceOf[_to] += _value; Transfer(_from, _to, _value); // 정적 분석을 사용하여 코드에서 버그를 찾을 때 사용합니다. 이 시스템은 실패하지 않습니다. assert(balanceOf[_from] + balanceOf[_to] == previousBalances); }
/** * 내부 전송, 이 계약으로만 호출할 수 있습니다. */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
bzzr://06bdab768321bb8adbb90bc85da173de01186c85dc584d117a2de3de80d4133c
{ "func_code_index": [ 1190, 1931 ] }
847
Rapide
Rapide.sol
0xc8035ea3580d5dd63b7535c26687fe18f8284e2f
Solidity
Rapide
contract Rapide { // 변수 선언 string public name; string public symbol; uint8 public decimals = 18; // 18소수 점 이하는 강력하게 제안된 기본 값이므로 변경하지 마십시오. uint256 public totalSupply; // 모든 균형을 갖춘 배열을 생성합니다. mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // 이것은 블록체인에서 클라이언트에게 알려주는 공개 이벤트를 생성합니다 event Transfer(address indexed from, address indexed to, uint256 value); // 소각된 양을 알립니다. event Burn(address indexed from, uint256 value); /** * 생성자 함수 * * 계약서 작성자에게 초기 공급 토큰과의 계약을 초기화합니다. */ function Rapide( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // 총 공급액을 소수로 업데이트합니다. balanceOf[msg.sender] = totalSupply; // 총 발행량 name = tokenName; // 토큰 이름 symbol = tokenSymbol; // 토큰 심볼 (EX: BTC, ETH, LTC) } /** * 내부 전송, 이 계약으로만 호출할 수 있습니다. */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // 발신자 점검 require(balanceOf[_from] >= _value); // 오버플로 확인 require(balanceOf[_to] + _value > balanceOf[_to]); // 미래의 주장을 위해 이것을 저장하십시오 uint previousBalances = balanceOf[_from] + balanceOf[_to]; // 발신자에서 차감 balanceOf[_from] -= _value; // 받는 사람에게 같은 것을 추가하십시오. balanceOf[_to] += _value; Transfer(_from, _to, _value); // 정적 분석을 사용하여 코드에서 버그를 찾을 때 사용합니다. 이 시스템은 실패하지 않습니다. assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * 토큰 전송 * @ _to 받는 사람의 주소에 대한 매개 변수 * @ _value 전송할 금액을 정하다. */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * _from 보낸 사람의 주소 * _to 받는 사람의 주소 * _value 전송할 금액 */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // 허용량 체크 allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * 다른 주소에 대한 허용량 설정 * _spender 지출 할 수있는 주소 * _value 그들이 쓸 수 있는 지출 할 수있는 최대 금액 */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * 다른 주소에 대한 허용치 설정 및 알림 * @param _spender 지출 할 수있는 주소 * @param _value 그들이 쓸 수 있는 지출 할 수있는 최대 금액 * @param _extraData 승인 된 계약서에 보낼 추가 정보 */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * 토큰 파괴 * @param _value 소각되는 금액 */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // 보낸 사람이 충분히 있는지 확인하십시오. balanceOf[msg.sender] -= _value; // 발신자에게서 뺍니다. totalSupply -= _value; // 총 발행량 업데이트 Burn(msg.sender, _value); return true; } /** * 다른 계정에서 토큰 삭제 * @param _from 발신자 주소 * @param _value 소각되는 금액 */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // 목표 잔액이 충분한 지 확인하십시오. require(_value <= allowance[_from][msg.sender]); // 수당 확인 balanceOf[_from] -= _value; // 목표 잔액에서 차감 allowance[_from][msg.sender] -= _value; // 발송인의 허용량에서 차감 totalSupply -= _value; // 총 발행량 업데이트 Burn(_from, _value); return true; } }
transfer
function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); }
/** * 토큰 전송 * @ _to 받는 사람의 주소에 대한 매개 변수 * @ _value 전송할 금액을 정하다. */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
bzzr://06bdab768321bb8adbb90bc85da173de01186c85dc584d117a2de3de80d4133c
{ "func_code_index": [ 2035, 2150 ] }
848
Rapide
Rapide.sol
0xc8035ea3580d5dd63b7535c26687fe18f8284e2f
Solidity
Rapide
contract Rapide { // 변수 선언 string public name; string public symbol; uint8 public decimals = 18; // 18소수 점 이하는 강력하게 제안된 기본 값이므로 변경하지 마십시오. uint256 public totalSupply; // 모든 균형을 갖춘 배열을 생성합니다. mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // 이것은 블록체인에서 클라이언트에게 알려주는 공개 이벤트를 생성합니다 event Transfer(address indexed from, address indexed to, uint256 value); // 소각된 양을 알립니다. event Burn(address indexed from, uint256 value); /** * 생성자 함수 * * 계약서 작성자에게 초기 공급 토큰과의 계약을 초기화합니다. */ function Rapide( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // 총 공급액을 소수로 업데이트합니다. balanceOf[msg.sender] = totalSupply; // 총 발행량 name = tokenName; // 토큰 이름 symbol = tokenSymbol; // 토큰 심볼 (EX: BTC, ETH, LTC) } /** * 내부 전송, 이 계약으로만 호출할 수 있습니다. */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // 발신자 점검 require(balanceOf[_from] >= _value); // 오버플로 확인 require(balanceOf[_to] + _value > balanceOf[_to]); // 미래의 주장을 위해 이것을 저장하십시오 uint previousBalances = balanceOf[_from] + balanceOf[_to]; // 발신자에서 차감 balanceOf[_from] -= _value; // 받는 사람에게 같은 것을 추가하십시오. balanceOf[_to] += _value; Transfer(_from, _to, _value); // 정적 분석을 사용하여 코드에서 버그를 찾을 때 사용합니다. 이 시스템은 실패하지 않습니다. assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * 토큰 전송 * @ _to 받는 사람의 주소에 대한 매개 변수 * @ _value 전송할 금액을 정하다. */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * _from 보낸 사람의 주소 * _to 받는 사람의 주소 * _value 전송할 금액 */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // 허용량 체크 allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * 다른 주소에 대한 허용량 설정 * _spender 지출 할 수있는 주소 * _value 그들이 쓸 수 있는 지출 할 수있는 최대 금액 */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * 다른 주소에 대한 허용치 설정 및 알림 * @param _spender 지출 할 수있는 주소 * @param _value 그들이 쓸 수 있는 지출 할 수있는 최대 금액 * @param _extraData 승인 된 계약서에 보낼 추가 정보 */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * 토큰 파괴 * @param _value 소각되는 금액 */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // 보낸 사람이 충분히 있는지 확인하십시오. balanceOf[msg.sender] -= _value; // 발신자에게서 뺍니다. totalSupply -= _value; // 총 발행량 업데이트 Burn(msg.sender, _value); return true; } /** * 다른 계정에서 토큰 삭제 * @param _from 발신자 주소 * @param _value 소각되는 금액 */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // 목표 잔액이 충분한 지 확인하십시오. require(_value <= allowance[_from][msg.sender]); // 수당 확인 balanceOf[_from] -= _value; // 목표 잔액에서 차감 allowance[_from][msg.sender] -= _value; // 발송인의 허용량에서 차감 totalSupply -= _value; // 총 발행량 업데이트 Burn(_from, _value); return true; } }
transferFrom
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // 허용량 체크 allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; }
/** * _from 보낸 사람의 주소 * _to 받는 사람의 주소 * _value 전송할 금액 */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
bzzr://06bdab768321bb8adbb90bc85da173de01186c85dc584d117a2de3de80d4133c
{ "func_code_index": [ 2248, 2546 ] }
849
Rapide
Rapide.sol
0xc8035ea3580d5dd63b7535c26687fe18f8284e2f
Solidity
Rapide
contract Rapide { // 변수 선언 string public name; string public symbol; uint8 public decimals = 18; // 18소수 점 이하는 강력하게 제안된 기본 값이므로 변경하지 마십시오. uint256 public totalSupply; // 모든 균형을 갖춘 배열을 생성합니다. mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // 이것은 블록체인에서 클라이언트에게 알려주는 공개 이벤트를 생성합니다 event Transfer(address indexed from, address indexed to, uint256 value); // 소각된 양을 알립니다. event Burn(address indexed from, uint256 value); /** * 생성자 함수 * * 계약서 작성자에게 초기 공급 토큰과의 계약을 초기화합니다. */ function Rapide( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // 총 공급액을 소수로 업데이트합니다. balanceOf[msg.sender] = totalSupply; // 총 발행량 name = tokenName; // 토큰 이름 symbol = tokenSymbol; // 토큰 심볼 (EX: BTC, ETH, LTC) } /** * 내부 전송, 이 계약으로만 호출할 수 있습니다. */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // 발신자 점검 require(balanceOf[_from] >= _value); // 오버플로 확인 require(balanceOf[_to] + _value > balanceOf[_to]); // 미래의 주장을 위해 이것을 저장하십시오 uint previousBalances = balanceOf[_from] + balanceOf[_to]; // 발신자에서 차감 balanceOf[_from] -= _value; // 받는 사람에게 같은 것을 추가하십시오. balanceOf[_to] += _value; Transfer(_from, _to, _value); // 정적 분석을 사용하여 코드에서 버그를 찾을 때 사용합니다. 이 시스템은 실패하지 않습니다. assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * 토큰 전송 * @ _to 받는 사람의 주소에 대한 매개 변수 * @ _value 전송할 금액을 정하다. */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * _from 보낸 사람의 주소 * _to 받는 사람의 주소 * _value 전송할 금액 */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // 허용량 체크 allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * 다른 주소에 대한 허용량 설정 * _spender 지출 할 수있는 주소 * _value 그들이 쓸 수 있는 지출 할 수있는 최대 금액 */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * 다른 주소에 대한 허용치 설정 및 알림 * @param _spender 지출 할 수있는 주소 * @param _value 그들이 쓸 수 있는 지출 할 수있는 최대 금액 * @param _extraData 승인 된 계약서에 보낼 추가 정보 */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * 토큰 파괴 * @param _value 소각되는 금액 */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // 보낸 사람이 충분히 있는지 확인하십시오. balanceOf[msg.sender] -= _value; // 발신자에게서 뺍니다. totalSupply -= _value; // 총 발행량 업데이트 Burn(msg.sender, _value); return true; } /** * 다른 계정에서 토큰 삭제 * @param _from 발신자 주소 * @param _value 소각되는 금액 */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // 목표 잔액이 충분한 지 확인하십시오. require(_value <= allowance[_from][msg.sender]); // 수당 확인 balanceOf[_from] -= _value; // 목표 잔액에서 차감 allowance[_from][msg.sender] -= _value; // 발송인의 허용량에서 차감 totalSupply -= _value; // 총 발행량 업데이트 Burn(_from, _value); return true; } }
approve
function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; }
/** * 다른 주소에 대한 허용량 설정 * _spender 지출 할 수있는 주소 * _value 그들이 쓸 수 있는 지출 할 수있는 최대 금액 */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
bzzr://06bdab768321bb8adbb90bc85da173de01186c85dc584d117a2de3de80d4133c
{ "func_code_index": [ 2669, 2850 ] }
850
Rapide
Rapide.sol
0xc8035ea3580d5dd63b7535c26687fe18f8284e2f
Solidity
Rapide
contract Rapide { // 변수 선언 string public name; string public symbol; uint8 public decimals = 18; // 18소수 점 이하는 강력하게 제안된 기본 값이므로 변경하지 마십시오. uint256 public totalSupply; // 모든 균형을 갖춘 배열을 생성합니다. mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // 이것은 블록체인에서 클라이언트에게 알려주는 공개 이벤트를 생성합니다 event Transfer(address indexed from, address indexed to, uint256 value); // 소각된 양을 알립니다. event Burn(address indexed from, uint256 value); /** * 생성자 함수 * * 계약서 작성자에게 초기 공급 토큰과의 계약을 초기화합니다. */ function Rapide( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // 총 공급액을 소수로 업데이트합니다. balanceOf[msg.sender] = totalSupply; // 총 발행량 name = tokenName; // 토큰 이름 symbol = tokenSymbol; // 토큰 심볼 (EX: BTC, ETH, LTC) } /** * 내부 전송, 이 계약으로만 호출할 수 있습니다. */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // 발신자 점검 require(balanceOf[_from] >= _value); // 오버플로 확인 require(balanceOf[_to] + _value > balanceOf[_to]); // 미래의 주장을 위해 이것을 저장하십시오 uint previousBalances = balanceOf[_from] + balanceOf[_to]; // 발신자에서 차감 balanceOf[_from] -= _value; // 받는 사람에게 같은 것을 추가하십시오. balanceOf[_to] += _value; Transfer(_from, _to, _value); // 정적 분석을 사용하여 코드에서 버그를 찾을 때 사용합니다. 이 시스템은 실패하지 않습니다. assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * 토큰 전송 * @ _to 받는 사람의 주소에 대한 매개 변수 * @ _value 전송할 금액을 정하다. */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * _from 보낸 사람의 주소 * _to 받는 사람의 주소 * _value 전송할 금액 */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // 허용량 체크 allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * 다른 주소에 대한 허용량 설정 * _spender 지출 할 수있는 주소 * _value 그들이 쓸 수 있는 지출 할 수있는 최대 금액 */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * 다른 주소에 대한 허용치 설정 및 알림 * @param _spender 지출 할 수있는 주소 * @param _value 그들이 쓸 수 있는 지출 할 수있는 최대 금액 * @param _extraData 승인 된 계약서에 보낼 추가 정보 */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * 토큰 파괴 * @param _value 소각되는 금액 */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // 보낸 사람이 충분히 있는지 확인하십시오. balanceOf[msg.sender] -= _value; // 발신자에게서 뺍니다. totalSupply -= _value; // 총 발행량 업데이트 Burn(msg.sender, _value); return true; } /** * 다른 계정에서 토큰 삭제 * @param _from 발신자 주소 * @param _value 소각되는 금액 */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // 목표 잔액이 충분한 지 확인하십시오. require(_value <= allowance[_from][msg.sender]); // 수당 확인 balanceOf[_from] -= _value; // 목표 잔액에서 차감 allowance[_from][msg.sender] -= _value; // 발송인의 허용량에서 차감 totalSupply -= _value; // 총 발행량 업데이트 Burn(_from, _value); return true; } }
approveAndCall
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } }
/** * 다른 주소에 대한 허용치 설정 및 알림 * @param _spender 지출 할 수있는 주소 * @param _value 그들이 쓸 수 있는 지출 할 수있는 최대 금액 * @param _extraData 승인 된 계약서에 보낼 추가 정보 */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
bzzr://06bdab768321bb8adbb90bc85da173de01186c85dc584d117a2de3de80d4133c
{ "func_code_index": [ 3042, 3403 ] }
851
Rapide
Rapide.sol
0xc8035ea3580d5dd63b7535c26687fe18f8284e2f
Solidity
Rapide
contract Rapide { // 변수 선언 string public name; string public symbol; uint8 public decimals = 18; // 18소수 점 이하는 강력하게 제안된 기본 값이므로 변경하지 마십시오. uint256 public totalSupply; // 모든 균형을 갖춘 배열을 생성합니다. mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // 이것은 블록체인에서 클라이언트에게 알려주는 공개 이벤트를 생성합니다 event Transfer(address indexed from, address indexed to, uint256 value); // 소각된 양을 알립니다. event Burn(address indexed from, uint256 value); /** * 생성자 함수 * * 계약서 작성자에게 초기 공급 토큰과의 계약을 초기화합니다. */ function Rapide( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // 총 공급액을 소수로 업데이트합니다. balanceOf[msg.sender] = totalSupply; // 총 발행량 name = tokenName; // 토큰 이름 symbol = tokenSymbol; // 토큰 심볼 (EX: BTC, ETH, LTC) } /** * 내부 전송, 이 계약으로만 호출할 수 있습니다. */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // 발신자 점검 require(balanceOf[_from] >= _value); // 오버플로 확인 require(balanceOf[_to] + _value > balanceOf[_to]); // 미래의 주장을 위해 이것을 저장하십시오 uint previousBalances = balanceOf[_from] + balanceOf[_to]; // 발신자에서 차감 balanceOf[_from] -= _value; // 받는 사람에게 같은 것을 추가하십시오. balanceOf[_to] += _value; Transfer(_from, _to, _value); // 정적 분석을 사용하여 코드에서 버그를 찾을 때 사용합니다. 이 시스템은 실패하지 않습니다. assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * 토큰 전송 * @ _to 받는 사람의 주소에 대한 매개 변수 * @ _value 전송할 금액을 정하다. */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * _from 보낸 사람의 주소 * _to 받는 사람의 주소 * _value 전송할 금액 */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // 허용량 체크 allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * 다른 주소에 대한 허용량 설정 * _spender 지출 할 수있는 주소 * _value 그들이 쓸 수 있는 지출 할 수있는 최대 금액 */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * 다른 주소에 대한 허용치 설정 및 알림 * @param _spender 지출 할 수있는 주소 * @param _value 그들이 쓸 수 있는 지출 할 수있는 최대 금액 * @param _extraData 승인 된 계약서에 보낼 추가 정보 */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * 토큰 파괴 * @param _value 소각되는 금액 */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // 보낸 사람이 충분히 있는지 확인하십시오. balanceOf[msg.sender] -= _value; // 발신자에게서 뺍니다. totalSupply -= _value; // 총 발행량 업데이트 Burn(msg.sender, _value); return true; } /** * 다른 계정에서 토큰 삭제 * @param _from 발신자 주소 * @param _value 소각되는 금액 */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // 목표 잔액이 충분한 지 확인하십시오. require(_value <= allowance[_from][msg.sender]); // 수당 확인 balanceOf[_from] -= _value; // 목표 잔액에서 차감 allowance[_from][msg.sender] -= _value; // 발송인의 허용량에서 차감 totalSupply -= _value; // 총 발행량 업데이트 Burn(_from, _value); return true; } }
burn
function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // 보낸 사람이 충분히 있는지 확인하십시오. balanceOf[msg.sender] -= _value; // 발신자에게서 뺍니다. totalSupply -= _value; // 총 발행량 업데이트 Burn(msg.sender, _value); return true; }
/** * 토큰 파괴 * @param _value 소각되는 금액 */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
bzzr://06bdab768321bb8adbb90bc85da173de01186c85dc584d117a2de3de80d4133c
{ "func_code_index": [ 3472, 3823 ] }
852
Rapide
Rapide.sol
0xc8035ea3580d5dd63b7535c26687fe18f8284e2f
Solidity
Rapide
contract Rapide { // 변수 선언 string public name; string public symbol; uint8 public decimals = 18; // 18소수 점 이하는 강력하게 제안된 기본 값이므로 변경하지 마십시오. uint256 public totalSupply; // 모든 균형을 갖춘 배열을 생성합니다. mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // 이것은 블록체인에서 클라이언트에게 알려주는 공개 이벤트를 생성합니다 event Transfer(address indexed from, address indexed to, uint256 value); // 소각된 양을 알립니다. event Burn(address indexed from, uint256 value); /** * 생성자 함수 * * 계약서 작성자에게 초기 공급 토큰과의 계약을 초기화합니다. */ function Rapide( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // 총 공급액을 소수로 업데이트합니다. balanceOf[msg.sender] = totalSupply; // 총 발행량 name = tokenName; // 토큰 이름 symbol = tokenSymbol; // 토큰 심볼 (EX: BTC, ETH, LTC) } /** * 내부 전송, 이 계약으로만 호출할 수 있습니다. */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // 발신자 점검 require(balanceOf[_from] >= _value); // 오버플로 확인 require(balanceOf[_to] + _value > balanceOf[_to]); // 미래의 주장을 위해 이것을 저장하십시오 uint previousBalances = balanceOf[_from] + balanceOf[_to]; // 발신자에서 차감 balanceOf[_from] -= _value; // 받는 사람에게 같은 것을 추가하십시오. balanceOf[_to] += _value; Transfer(_from, _to, _value); // 정적 분석을 사용하여 코드에서 버그를 찾을 때 사용합니다. 이 시스템은 실패하지 않습니다. assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * 토큰 전송 * @ _to 받는 사람의 주소에 대한 매개 변수 * @ _value 전송할 금액을 정하다. */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * _from 보낸 사람의 주소 * _to 받는 사람의 주소 * _value 전송할 금액 */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // 허용량 체크 allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * 다른 주소에 대한 허용량 설정 * _spender 지출 할 수있는 주소 * _value 그들이 쓸 수 있는 지출 할 수있는 최대 금액 */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * 다른 주소에 대한 허용치 설정 및 알림 * @param _spender 지출 할 수있는 주소 * @param _value 그들이 쓸 수 있는 지출 할 수있는 최대 금액 * @param _extraData 승인 된 계약서에 보낼 추가 정보 */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * 토큰 파괴 * @param _value 소각되는 금액 */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // 보낸 사람이 충분히 있는지 확인하십시오. balanceOf[msg.sender] -= _value; // 발신자에게서 뺍니다. totalSupply -= _value; // 총 발행량 업데이트 Burn(msg.sender, _value); return true; } /** * 다른 계정에서 토큰 삭제 * @param _from 발신자 주소 * @param _value 소각되는 금액 */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // 목표 잔액이 충분한 지 확인하십시오. require(_value <= allowance[_from][msg.sender]); // 수당 확인 balanceOf[_from] -= _value; // 목표 잔액에서 차감 allowance[_from][msg.sender] -= _value; // 발송인의 허용량에서 차감 totalSupply -= _value; // 총 발행량 업데이트 Burn(_from, _value); return true; } }
burnFrom
function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // 목표 잔액이 충분한 지 확인하십시오. require(_value <= allowance[_from][msg.sender]); // 수당 확인 balanceOf[_from] -= _value; // 목표 잔액에서 차감 allowance[_from][msg.sender] -= _value; // 발송인의 허용량에서 차감 totalSupply -= _value; // 총 발행량 업데이트 Burn(_from, _value); return true; }
/** * 다른 계정에서 토큰 삭제 * @param _from 발신자 주소 * @param _value 소각되는 금액 */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
bzzr://06bdab768321bb8adbb90bc85da173de01186c85dc584d117a2de3de80d4133c
{ "func_code_index": [ 3927, 4463 ] }
853
Constantinople
Constantinople.sol
0xd8d659f062e88f4ed703a15955fa25f0e65e0296
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. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
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.5.10+commit.5a6ea5b1
None
bzzr://0014f0174e94348e903a474184fee9fee5e5a0e4eb3612a16f8f7a4e4b43a2ad
{ "func_code_index": [ 251, 437 ] }
854
Constantinople
Constantinople.sol
0xd8d659f062e88f4ed703a15955fa25f0e65e0296
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. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
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.5.10+commit.5a6ea5b1
None
bzzr://0014f0174e94348e903a474184fee9fee5e5a0e4eb3612a16f8f7a4e4b43a2ad
{ "func_code_index": [ 707, 848 ] }
855
Constantinople
Constantinople.sol
0xd8d659f062e88f4ed703a15955fa25f0e65e0296
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. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
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. * * _Available since v2.4.0._ */
NatSpecMultiLine
v0.5.10+commit.5a6ea5b1
None
bzzr://0014f0174e94348e903a474184fee9fee5e5a0e4eb3612a16f8f7a4e4b43a2ad
{ "func_code_index": [ 1180, 1377 ] }
856
Constantinople
Constantinople.sol
0xd8d659f062e88f4ed703a15955fa25f0e65e0296
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. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
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.5.10+commit.5a6ea5b1
None
bzzr://0014f0174e94348e903a474184fee9fee5e5a0e4eb3612a16f8f7a4e4b43a2ad
{ "func_code_index": [ 1623, 2099 ] }
857
Constantinople
Constantinople.sol
0xd8d659f062e88f4ed703a15955fa25f0e65e0296
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. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
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.5.10+commit.5a6ea5b1
None
bzzr://0014f0174e94348e903a474184fee9fee5e5a0e4eb3612a16f8f7a4e4b43a2ad
{ "func_code_index": [ 2562, 2699 ] }
858
Constantinople
Constantinople.sol
0xd8d659f062e88f4ed703a15955fa25f0e65e0296
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. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
div
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; }
/** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */
NatSpecMultiLine
v0.5.10+commit.5a6ea5b1
None
bzzr://0014f0174e94348e903a474184fee9fee5e5a0e4eb3612a16f8f7a4e4b43a2ad
{ "func_code_index": [ 3224, 3574 ] }
859
Constantinople
Constantinople.sol
0xd8d659f062e88f4ed703a15955fa25f0e65e0296
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. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
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.5.10+commit.5a6ea5b1
None
bzzr://0014f0174e94348e903a474184fee9fee5e5a0e4eb3612a16f8f7a4e4b43a2ad
{ "func_code_index": [ 4026, 4161 ] }
860
Constantinople
Constantinople.sol
0xd8d659f062e88f4ed703a15955fa25f0e65e0296
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. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
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. * * _Available since v2.4.0._ */
NatSpecMultiLine
v0.5.10+commit.5a6ea5b1
None
bzzr://0014f0174e94348e903a474184fee9fee5e5a0e4eb3612a16f8f7a4e4b43a2ad
{ "func_code_index": [ 4675, 4846 ] }
861
SomaIco
SomaIco.sol
0x63b992e6246d88f07fc35a056d2c365e6d441a3d
Solidity
Ownable
contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } }
Ownable
function Ownable() { owner = msg.sender; }
/** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */
NatSpecMultiLine
v0.4.16+commit.d7661dd9
bzzr://5b695bf7b74d7a3f0d9e685a175da87b3a9ba8c5f6eaaf568e54ac49d379d3ab
{ "func_code_index": [ 169, 222 ] }
862
SomaIco
SomaIco.sol
0x63b992e6246d88f07fc35a056d2c365e6d441a3d
Solidity
Ownable
contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } }
transferOwnership
function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } }
/** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */
NatSpecMultiLine
v0.4.16+commit.d7661dd9
bzzr://5b695bf7b74d7a3f0d9e685a175da87b3a9ba8c5f6eaaf568e54ac49d379d3ab
{ "func_code_index": [ 545, 676 ] }
863
SomaIco
SomaIco.sol
0x63b992e6246d88f07fc35a056d2c365e6d441a3d
Solidity
Pausable
contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused returns (bool) { paused = true; Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused returns (bool) { paused = false; Unpause(); return true; } }
pause
function pause() onlyOwner whenNotPaused returns (bool) { paused = true; Pause(); return true; }
/** * @dev called by the owner to pause, triggers stopped state */
NatSpecMultiLine
v0.4.16+commit.d7661dd9
bzzr://5b695bf7b74d7a3f0d9e685a175da87b3a9ba8c5f6eaaf568e54ac49d379d3ab
{ "func_code_index": [ 487, 604 ] }
864
SomaIco
SomaIco.sol
0x63b992e6246d88f07fc35a056d2c365e6d441a3d
Solidity
Pausable
contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused returns (bool) { paused = true; Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused returns (bool) { paused = false; Unpause(); return true; } }
unpause
function unpause() onlyOwner whenPaused returns (bool) { paused = false; Unpause(); return true; }
/** * @dev called by the owner to unpause, returns to normal state */
NatSpecMultiLine
v0.4.16+commit.d7661dd9
bzzr://5b695bf7b74d7a3f0d9e685a175da87b3a9ba8c5f6eaaf568e54ac49d379d3ab
{ "func_code_index": [ 688, 807 ] }
865
SomaIco
SomaIco.sol
0x63b992e6246d88f07fc35a056d2c365e6d441a3d
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } }
transfer
function transfer(address _to, uint256 _value) returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; }
/** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */
NatSpecMultiLine
v0.4.16+commit.d7661dd9
bzzr://5b695bf7b74d7a3f0d9e685a175da87b3a9ba8c5f6eaaf568e54ac49d379d3ab
{ "func_code_index": [ 268, 507 ] }
866
SomaIco
SomaIco.sol
0x63b992e6246d88f07fc35a056d2c365e6d441a3d
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } }
balanceOf
function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; }
/** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */
NatSpecMultiLine
v0.4.16+commit.d7661dd9
bzzr://5b695bf7b74d7a3f0d9e685a175da87b3a9ba8c5f6eaaf568e54ac49d379d3ab
{ "func_code_index": [ 714, 823 ] }
867
SomaIco
SomaIco.sol
0x63b992e6246d88f07fc35a056d2c365e6d441a3d
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } }
transferFrom
function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; }
/** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */
NatSpecMultiLine
v0.4.16+commit.d7661dd9
bzzr://5b695bf7b74d7a3f0d9e685a175da87b3a9ba8c5f6eaaf568e54ac49d379d3ab
{ "func_code_index": [ 390, 893 ] }
868
SomaIco
SomaIco.sol
0x63b992e6246d88f07fc35a056d2c365e6d441a3d
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } }
approve
function approve(address _spender, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; }
/** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */
NatSpecMultiLine
v0.4.16+commit.d7661dd9
bzzr://5b695bf7b74d7a3f0d9e685a175da87b3a9ba8c5f6eaaf568e54ac49d379d3ab
{ "func_code_index": [ 1128, 1676 ] }
869
SomaIco
SomaIco.sol
0x63b992e6246d88f07fc35a056d2c365e6d441a3d
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } }
allowance
function allowance(address _owner, address _spender) constant returns (uint256 remaining) { 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 specifing the amount of tokens still avaible for the spender. */
NatSpecMultiLine
v0.4.16+commit.d7661dd9
bzzr://5b695bf7b74d7a3f0d9e685a175da87b3a9ba8c5f6eaaf568e54ac49d379d3ab
{ "func_code_index": [ 1997, 2135 ] }
870
SomaIco
SomaIco.sol
0x63b992e6246d88f07fc35a056d2c365e6d441a3d
Solidity
SomaIco
contract SomaIco is PausableToken { using SafeMath for uint256; string public name = "Soma Community Token"; string public symbol = "SCT"; uint8 public decimals = 18; address public liquidityReserveWallet; // address where liquidity reserve tokens will be delivered address public wallet; // address where funds are collected address public marketingWallet; // address which controls marketing token pool uint256 public icoStartTimestamp; // ICO start timestamp uint256 public icoEndTimestamp; // ICO end timestamp uint256 public totalRaised = 0; // total amount of money raised in wei uint256 public totalSupply; // total token supply with decimals precisoin uint256 public marketingPool; // marketing pool with decimals precisoin uint256 public tokensSold = 0; // total number of tokens sold bool public halted = false; //the owner address can set this to true to halt the crowdsale due to emergency uint256 public icoEtherMinCap; // should be specified as: 8000 * 1 ether uint256 public icoEtherMaxCap; // should be specified as: 120000 * 1 ether uint256 public rate = 450; // standard SCT/ETH rate event Burn(address indexed burner, uint256 value); function SomaIco( address newWallet, address newMarketingWallet, address newLiquidityReserveWallet, uint256 newIcoEtherMinCap, uint256 newIcoEtherMaxCap, uint256 totalPresaleRaised ) { require(newWallet != 0x0); require(newMarketingWallet != 0x0); require(newLiquidityReserveWallet != 0x0); require(newIcoEtherMinCap <= newIcoEtherMaxCap); require(newIcoEtherMinCap > 0); require(newIcoEtherMaxCap > 0); pause(); icoEtherMinCap = newIcoEtherMinCap; icoEtherMaxCap = newIcoEtherMaxCap; wallet = newWallet; marketingWallet = newMarketingWallet; liquidityReserveWallet = newLiquidityReserveWallet; // calculate marketingPool and totalSupply based on the max cap: // totalSupply = rate * icoEtherMaxCap + marketingPool // marketingPool = 10% * totalSupply // hence: // totalSupply = 10/9 * rate * icoEtherMaxCap totalSupply = icoEtherMaxCap.mul(rate).mul(10).div(9); marketingPool = totalSupply.div(10); // account for the funds raised during the presale totalRaised = totalRaised.add(totalPresaleRaised); // assign marketing pool to marketing wallet assignTokens(marketingWallet, marketingPool); } /// fallback function to buy tokens function () nonHalted nonZeroPurchase acceptsFunds payable { address recipient = msg.sender; uint256 weiAmount = msg.value; uint256 amount = weiAmount.mul(rate); assignTokens(recipient, amount); totalRaised = totalRaised.add(weiAmount); forwardFundsToWallet(); } modifier acceptsFunds() { bool hasStarted = icoStartTimestamp != 0 && now >= icoStartTimestamp; require(hasStarted); // ICO is continued over the end date until the min cap is reached bool isIcoInProgress = now <= icoEndTimestamp || (icoEndTimestamp == 0) // before dates are set || totalRaised < icoEtherMinCap; require(isIcoInProgress); bool isBelowMaxCap = totalRaised < icoEtherMaxCap; require(isBelowMaxCap); _; } modifier nonHalted() { require(!halted); _; } modifier nonZeroPurchase() { require(msg.value > 0); _; } function forwardFundsToWallet() internal { wallet.transfer(msg.value); // immediately send Ether to wallet address, propagates exception if execution fails } function assignTokens(address recipient, uint256 amount) internal { balances[recipient] = balances[recipient].add(amount); tokensSold = tokensSold.add(amount); // sanity safeguard if (tokensSold > totalSupply) { // there is a chance that tokens are sold over the supply: // a) when: total presale bonuses > (maxCap - totalRaised) * rate // b) when: last payment goes over the maxCap totalSupply = tokensSold; } Transfer(0x0, recipient, amount); } function setIcoDates(uint256 newIcoStartTimestamp, uint256 newIcoEndTimestamp) public onlyOwner { require(newIcoStartTimestamp < newIcoEndTimestamp); require(!isIcoFinished()); icoStartTimestamp = newIcoStartTimestamp; icoEndTimestamp = newIcoEndTimestamp; } function setRate(uint256 _rate) public onlyOwner { require(!isIcoFinished()); rate = _rate; } function haltFundraising() public onlyOwner { halted = true; } function unhaltFundraising() public onlyOwner { halted = false; } function isIcoFinished() public constant returns (bool icoFinished) { return (totalRaised >= icoEtherMinCap && icoEndTimestamp != 0 && now > icoEndTimestamp) || (totalRaised >= icoEtherMaxCap); } function prepareLiquidityReserve() public onlyOwner { require(isIcoFinished()); uint256 unsoldTokens = totalSupply.sub(tokensSold); // make sure there are any unsold tokens to be assigned require(unsoldTokens > 0); // try to allocate up to 10% of total sold tokens to Liquidity Reserve fund: uint256 liquidityReserveTokens = tokensSold.div(10); if (liquidityReserveTokens > unsoldTokens) { liquidityReserveTokens = unsoldTokens; } assignTokens(liquidityReserveWallet, liquidityReserveTokens); unsoldTokens = unsoldTokens.sub(liquidityReserveTokens); // if there are still unsold tokens: if (unsoldTokens > 0) { // decrease (burn) total supply by the number of unsold tokens: totalSupply = totalSupply.sub(unsoldTokens); } // make sure there are no tokens left assert(tokensSold == totalSupply); } function manuallyAssignTokens(address recipient, uint256 amount) public onlyOwner { require(tokensSold < totalSupply); assignTokens(recipient, amount); } /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public whenNotPaused { require(_value > 0); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } }
function () nonHalted nonZeroPurchase acceptsFunds payable { address recipient = msg.sender; uint256 weiAmount = msg.value; uint256 amount = weiAmount.mul(rate); assignTokens(recipient, amount); totalRaised = totalRaised.add(weiAmount); forwardFundsToWallet(); }
/// fallback function to buy tokens
NatSpecSingleLine
v0.4.16+commit.d7661dd9
bzzr://5b695bf7b74d7a3f0d9e685a175da87b3a9ba8c5f6eaaf568e54ac49d379d3ab
{ "func_code_index": [ 2684, 3016 ] }
871
SomaIco
SomaIco.sol
0x63b992e6246d88f07fc35a056d2c365e6d441a3d
Solidity
SomaIco
contract SomaIco is PausableToken { using SafeMath for uint256; string public name = "Soma Community Token"; string public symbol = "SCT"; uint8 public decimals = 18; address public liquidityReserveWallet; // address where liquidity reserve tokens will be delivered address public wallet; // address where funds are collected address public marketingWallet; // address which controls marketing token pool uint256 public icoStartTimestamp; // ICO start timestamp uint256 public icoEndTimestamp; // ICO end timestamp uint256 public totalRaised = 0; // total amount of money raised in wei uint256 public totalSupply; // total token supply with decimals precisoin uint256 public marketingPool; // marketing pool with decimals precisoin uint256 public tokensSold = 0; // total number of tokens sold bool public halted = false; //the owner address can set this to true to halt the crowdsale due to emergency uint256 public icoEtherMinCap; // should be specified as: 8000 * 1 ether uint256 public icoEtherMaxCap; // should be specified as: 120000 * 1 ether uint256 public rate = 450; // standard SCT/ETH rate event Burn(address indexed burner, uint256 value); function SomaIco( address newWallet, address newMarketingWallet, address newLiquidityReserveWallet, uint256 newIcoEtherMinCap, uint256 newIcoEtherMaxCap, uint256 totalPresaleRaised ) { require(newWallet != 0x0); require(newMarketingWallet != 0x0); require(newLiquidityReserveWallet != 0x0); require(newIcoEtherMinCap <= newIcoEtherMaxCap); require(newIcoEtherMinCap > 0); require(newIcoEtherMaxCap > 0); pause(); icoEtherMinCap = newIcoEtherMinCap; icoEtherMaxCap = newIcoEtherMaxCap; wallet = newWallet; marketingWallet = newMarketingWallet; liquidityReserveWallet = newLiquidityReserveWallet; // calculate marketingPool and totalSupply based on the max cap: // totalSupply = rate * icoEtherMaxCap + marketingPool // marketingPool = 10% * totalSupply // hence: // totalSupply = 10/9 * rate * icoEtherMaxCap totalSupply = icoEtherMaxCap.mul(rate).mul(10).div(9); marketingPool = totalSupply.div(10); // account for the funds raised during the presale totalRaised = totalRaised.add(totalPresaleRaised); // assign marketing pool to marketing wallet assignTokens(marketingWallet, marketingPool); } /// fallback function to buy tokens function () nonHalted nonZeroPurchase acceptsFunds payable { address recipient = msg.sender; uint256 weiAmount = msg.value; uint256 amount = weiAmount.mul(rate); assignTokens(recipient, amount); totalRaised = totalRaised.add(weiAmount); forwardFundsToWallet(); } modifier acceptsFunds() { bool hasStarted = icoStartTimestamp != 0 && now >= icoStartTimestamp; require(hasStarted); // ICO is continued over the end date until the min cap is reached bool isIcoInProgress = now <= icoEndTimestamp || (icoEndTimestamp == 0) // before dates are set || totalRaised < icoEtherMinCap; require(isIcoInProgress); bool isBelowMaxCap = totalRaised < icoEtherMaxCap; require(isBelowMaxCap); _; } modifier nonHalted() { require(!halted); _; } modifier nonZeroPurchase() { require(msg.value > 0); _; } function forwardFundsToWallet() internal { wallet.transfer(msg.value); // immediately send Ether to wallet address, propagates exception if execution fails } function assignTokens(address recipient, uint256 amount) internal { balances[recipient] = balances[recipient].add(amount); tokensSold = tokensSold.add(amount); // sanity safeguard if (tokensSold > totalSupply) { // there is a chance that tokens are sold over the supply: // a) when: total presale bonuses > (maxCap - totalRaised) * rate // b) when: last payment goes over the maxCap totalSupply = tokensSold; } Transfer(0x0, recipient, amount); } function setIcoDates(uint256 newIcoStartTimestamp, uint256 newIcoEndTimestamp) public onlyOwner { require(newIcoStartTimestamp < newIcoEndTimestamp); require(!isIcoFinished()); icoStartTimestamp = newIcoStartTimestamp; icoEndTimestamp = newIcoEndTimestamp; } function setRate(uint256 _rate) public onlyOwner { require(!isIcoFinished()); rate = _rate; } function haltFundraising() public onlyOwner { halted = true; } function unhaltFundraising() public onlyOwner { halted = false; } function isIcoFinished() public constant returns (bool icoFinished) { return (totalRaised >= icoEtherMinCap && icoEndTimestamp != 0 && now > icoEndTimestamp) || (totalRaised >= icoEtherMaxCap); } function prepareLiquidityReserve() public onlyOwner { require(isIcoFinished()); uint256 unsoldTokens = totalSupply.sub(tokensSold); // make sure there are any unsold tokens to be assigned require(unsoldTokens > 0); // try to allocate up to 10% of total sold tokens to Liquidity Reserve fund: uint256 liquidityReserveTokens = tokensSold.div(10); if (liquidityReserveTokens > unsoldTokens) { liquidityReserveTokens = unsoldTokens; } assignTokens(liquidityReserveWallet, liquidityReserveTokens); unsoldTokens = unsoldTokens.sub(liquidityReserveTokens); // if there are still unsold tokens: if (unsoldTokens > 0) { // decrease (burn) total supply by the number of unsold tokens: totalSupply = totalSupply.sub(unsoldTokens); } // make sure there are no tokens left assert(tokensSold == totalSupply); } function manuallyAssignTokens(address recipient, uint256 amount) public onlyOwner { require(tokensSold < totalSupply); assignTokens(recipient, amount); } /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public whenNotPaused { require(_value > 0); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } }
burn
function burn(uint256 _value) public whenNotPaused { require(_value > 0); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); }
/** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */
NatSpecMultiLine
v0.4.16+commit.d7661dd9
bzzr://5b695bf7b74d7a3f0d9e685a175da87b3a9ba8c5f6eaaf568e54ac49d379d3ab
{ "func_code_index": [ 6615, 6886 ] }
872
EmblemVault
browser/github/0xcert/ethereum-erc721/src/contracts/tokens/nf-token-enumerable-metadata.sol
0x82c7a8f707110f5fbb16184a5933e9f78a34c6ab
Solidity
NFTokenEnumerableMetadata
abstract contract NFTokenEnumerableMetadata is NFToken, ERC721Metadata, ERC721Enumerable { /** * @dev A descriptive name for a collection of NFTs. */ string internal nftName; /** * @dev An abbreviated name for NFTokens. */ string internal nftSymbol; /** * @dev An uri to represent the metadata for this contract. */ string internal nftContractMetadataUri; /** * @dev Mapping from NFT ID to metadata uri. */ mapping (uint256 => string) internal idToUri; /** * @dev Mapping from NFT ID to encrypted value. */ mapping (uint256 => string) internal idToPayload; /** * @dev Contract constructor. * @notice When implementing this contract don't forget to set nftName and nftSymbol. */ constructor() public { supportedInterfaces[0x5b5e139f] = true; // ERC721Metadata supportedInterfaces[0x780e9d63] = true; // ERC721Enumerable } /** * @dev Returns a descriptive name for a collection of NFTokens. * @return _name Representing name. */ function name() external override view returns (string memory _name) { _name = nftName; } /** * @dev Returns an abbreviated name for NFTokens. * @return _symbol Representing symbol. */ function symbol() external override view returns (string memory _symbol) { _symbol = nftSymbol; } /** * @dev A distinct URI (RFC 3986) for a given NFT. * @param _tokenId Id for which we want uri. * @return URI of _tokenId. */ function tokenURI( uint256 _tokenId ) external override view validNFToken(_tokenId) returns (string memory) { return idToUri[_tokenId]; } /** * @dev A distinct URI (RFC 3986) for a given NFT. * @param _tokenId Id for which we want uri. * @return URI of _tokenId. */ function tokenPayload( uint256 _tokenId ) external view validNFToken(_tokenId) returns (string memory) { return idToPayload[_tokenId]; } /** * @dev Set a distinct URI (RFC 3986) for a given NFT ID. * @notice This is an internal function which should be called from user-implemented external * function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _tokenId Id for which we want URI. * @param _uri String representing RFC 3986 URI. */ function _setTokenUri( uint256 _tokenId, string memory _uri ) internal validNFToken(_tokenId) { idToUri[_tokenId] = _uri; } function _setTokenPayload( uint256 _tokenId, string memory _uri ) internal validNFToken(_tokenId) { idToPayload[_tokenId] = _uri; } /** * List of revert message codes. Implementing dApp should handle showing the correct message. * Based on 0xcert framework error codes. */ string constant INVALID_INDEX = "005007"; /** * @dev Array of all NFT IDs. */ uint256[] internal tokens; /** * @dev Mapping from token ID to its index in global tokens array. */ mapping(uint256 => uint256) internal idToIndex; /** * @dev Mapping from owner to list of owned NFT IDs. */ mapping(address => uint256[]) internal ownerToIds; /** * @dev Mapping from NFT ID to its index in the owner tokens list. */ mapping(uint256 => uint256) internal idToOwnerIndex; /** * @dev Returns the count of all existing NFTokens. * @return Total supply of NFTs. */ function totalSupply() external override view returns (uint256) { return tokens.length; } /** * @dev Returns NFT ID by its index. * @param _index A counter less than `totalSupply()`. * @return Token id. */ function tokenByIndex( uint256 _index ) external override view returns (uint256) { require(_index < tokens.length, INVALID_INDEX); return tokens[_index]; } /** * @dev returns the n-th NFT ID from a list of owner's tokens. * @param _owner Token owner's address. * @param _index Index number representing n-th token in owner's list of tokens. * @return Token id. */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) external override view returns (uint256) { require(_index < ownerToIds[_owner].length, INVALID_INDEX); return ownerToIds[_owner][_index]; } /** * @dev Mints a new NFT. * @notice This is an internal function which should be called from user-implemented external * mint function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _to The address that will own the minted NFT. * @param _tokenId of the NFT to be minted by the msg.sender. */ function _mint( address _to, uint256 _tokenId ) internal override virtual { super._mint(_to, _tokenId); tokens.push(_tokenId); idToIndex[_tokenId] = tokens.length - 1; } /** * @dev Burns a NFT. * @notice This is an internal function which should be called from user-implemented external * burn function. Its purpose is to show and properly initialize data structures when using this * implementation. Also, note that this burn implementation allows the minter to re-mint a burned * NFT. * @param _tokenId ID of the NFT to be burned. */ function _burn( uint256 _tokenId ) internal override virtual { super._burn(_tokenId); if (bytes(idToUri[_tokenId]).length != 0) { delete idToUri[_tokenId]; } if (bytes(idToPayload[_tokenId]).length != 0) { delete idToPayload[_tokenId]; } uint256 tokenIndex = idToIndex[_tokenId]; uint256 lastTokenIndex = tokens.length - 1; uint256 lastToken = tokens[lastTokenIndex]; tokens[tokenIndex] = lastToken; tokens.pop(); // This wastes gas if you are burning the last token but saves a little gas if you are not. idToIndex[lastToken] = tokenIndex; idToIndex[_tokenId] = 0; } /** * @dev Removes a NFT from an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _from Address from wich we want to remove the NFT. * @param _tokenId Which NFT we want to remove. */ function _removeNFToken( address _from, uint256 _tokenId ) internal override virtual { require(idToOwner[_tokenId] == _from, NOT_OWNER); delete idToOwner[_tokenId]; uint256 tokenToRemoveIndex = idToOwnerIndex[_tokenId]; uint256 lastTokenIndex = ownerToIds[_from].length - 1; if (lastTokenIndex != tokenToRemoveIndex) { uint256 lastToken = ownerToIds[_from][lastTokenIndex]; ownerToIds[_from][tokenToRemoveIndex] = lastToken; idToOwnerIndex[lastToken] = tokenToRemoveIndex; } ownerToIds[_from].pop(); } /** * @dev Assignes a new NFT to an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _to Address to wich we want to add the NFT. * @param _tokenId Which NFT we want to add. */ function _addNFToken( address _to, uint256 _tokenId ) internal override virtual { require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS); idToOwner[_tokenId] = _to; ownerToIds[_to].push(_tokenId); idToOwnerIndex[_tokenId] = ownerToIds[_to].length - 1; } /** * @dev Helper function that gets NFT count of owner. This is needed for overriding in enumerable * extension to remove double storage(gas optimization) of owner nft count. * @param _owner Address for whom to query the count. * @return Number of _owner NFTs. */ function _getOwnerNFTCount( address _owner ) internal override virtual view returns (uint256) { return ownerToIds[_owner].length; } }
/** * @dev Optional metadata implementation for ERC-721 non-fungible token standard. */
NatSpecMultiLine
name
function name() external override view returns (string memory _name) { _name = nftName; }
/** * @dev Returns a descriptive name for a collection of NFTokens. * @return _name Representing name. */
NatSpecMultiLine
v0.6.2+commit.bacdbe57
MIT
ipfs://6626fd920334c84d658057cbe16dd3b47b41fc7475707238fefa241a53c0a511
{ "func_code_index": [ 1088, 1211 ] }
873
EmblemVault
browser/github/0xcert/ethereum-erc721/src/contracts/tokens/nf-token-enumerable-metadata.sol
0x82c7a8f707110f5fbb16184a5933e9f78a34c6ab
Solidity
NFTokenEnumerableMetadata
abstract contract NFTokenEnumerableMetadata is NFToken, ERC721Metadata, ERC721Enumerable { /** * @dev A descriptive name for a collection of NFTs. */ string internal nftName; /** * @dev An abbreviated name for NFTokens. */ string internal nftSymbol; /** * @dev An uri to represent the metadata for this contract. */ string internal nftContractMetadataUri; /** * @dev Mapping from NFT ID to metadata uri. */ mapping (uint256 => string) internal idToUri; /** * @dev Mapping from NFT ID to encrypted value. */ mapping (uint256 => string) internal idToPayload; /** * @dev Contract constructor. * @notice When implementing this contract don't forget to set nftName and nftSymbol. */ constructor() public { supportedInterfaces[0x5b5e139f] = true; // ERC721Metadata supportedInterfaces[0x780e9d63] = true; // ERC721Enumerable } /** * @dev Returns a descriptive name for a collection of NFTokens. * @return _name Representing name. */ function name() external override view returns (string memory _name) { _name = nftName; } /** * @dev Returns an abbreviated name for NFTokens. * @return _symbol Representing symbol. */ function symbol() external override view returns (string memory _symbol) { _symbol = nftSymbol; } /** * @dev A distinct URI (RFC 3986) for a given NFT. * @param _tokenId Id for which we want uri. * @return URI of _tokenId. */ function tokenURI( uint256 _tokenId ) external override view validNFToken(_tokenId) returns (string memory) { return idToUri[_tokenId]; } /** * @dev A distinct URI (RFC 3986) for a given NFT. * @param _tokenId Id for which we want uri. * @return URI of _tokenId. */ function tokenPayload( uint256 _tokenId ) external view validNFToken(_tokenId) returns (string memory) { return idToPayload[_tokenId]; } /** * @dev Set a distinct URI (RFC 3986) for a given NFT ID. * @notice This is an internal function which should be called from user-implemented external * function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _tokenId Id for which we want URI. * @param _uri String representing RFC 3986 URI. */ function _setTokenUri( uint256 _tokenId, string memory _uri ) internal validNFToken(_tokenId) { idToUri[_tokenId] = _uri; } function _setTokenPayload( uint256 _tokenId, string memory _uri ) internal validNFToken(_tokenId) { idToPayload[_tokenId] = _uri; } /** * List of revert message codes. Implementing dApp should handle showing the correct message. * Based on 0xcert framework error codes. */ string constant INVALID_INDEX = "005007"; /** * @dev Array of all NFT IDs. */ uint256[] internal tokens; /** * @dev Mapping from token ID to its index in global tokens array. */ mapping(uint256 => uint256) internal idToIndex; /** * @dev Mapping from owner to list of owned NFT IDs. */ mapping(address => uint256[]) internal ownerToIds; /** * @dev Mapping from NFT ID to its index in the owner tokens list. */ mapping(uint256 => uint256) internal idToOwnerIndex; /** * @dev Returns the count of all existing NFTokens. * @return Total supply of NFTs. */ function totalSupply() external override view returns (uint256) { return tokens.length; } /** * @dev Returns NFT ID by its index. * @param _index A counter less than `totalSupply()`. * @return Token id. */ function tokenByIndex( uint256 _index ) external override view returns (uint256) { require(_index < tokens.length, INVALID_INDEX); return tokens[_index]; } /** * @dev returns the n-th NFT ID from a list of owner's tokens. * @param _owner Token owner's address. * @param _index Index number representing n-th token in owner's list of tokens. * @return Token id. */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) external override view returns (uint256) { require(_index < ownerToIds[_owner].length, INVALID_INDEX); return ownerToIds[_owner][_index]; } /** * @dev Mints a new NFT. * @notice This is an internal function which should be called from user-implemented external * mint function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _to The address that will own the minted NFT. * @param _tokenId of the NFT to be minted by the msg.sender. */ function _mint( address _to, uint256 _tokenId ) internal override virtual { super._mint(_to, _tokenId); tokens.push(_tokenId); idToIndex[_tokenId] = tokens.length - 1; } /** * @dev Burns a NFT. * @notice This is an internal function which should be called from user-implemented external * burn function. Its purpose is to show and properly initialize data structures when using this * implementation. Also, note that this burn implementation allows the minter to re-mint a burned * NFT. * @param _tokenId ID of the NFT to be burned. */ function _burn( uint256 _tokenId ) internal override virtual { super._burn(_tokenId); if (bytes(idToUri[_tokenId]).length != 0) { delete idToUri[_tokenId]; } if (bytes(idToPayload[_tokenId]).length != 0) { delete idToPayload[_tokenId]; } uint256 tokenIndex = idToIndex[_tokenId]; uint256 lastTokenIndex = tokens.length - 1; uint256 lastToken = tokens[lastTokenIndex]; tokens[tokenIndex] = lastToken; tokens.pop(); // This wastes gas if you are burning the last token but saves a little gas if you are not. idToIndex[lastToken] = tokenIndex; idToIndex[_tokenId] = 0; } /** * @dev Removes a NFT from an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _from Address from wich we want to remove the NFT. * @param _tokenId Which NFT we want to remove. */ function _removeNFToken( address _from, uint256 _tokenId ) internal override virtual { require(idToOwner[_tokenId] == _from, NOT_OWNER); delete idToOwner[_tokenId]; uint256 tokenToRemoveIndex = idToOwnerIndex[_tokenId]; uint256 lastTokenIndex = ownerToIds[_from].length - 1; if (lastTokenIndex != tokenToRemoveIndex) { uint256 lastToken = ownerToIds[_from][lastTokenIndex]; ownerToIds[_from][tokenToRemoveIndex] = lastToken; idToOwnerIndex[lastToken] = tokenToRemoveIndex; } ownerToIds[_from].pop(); } /** * @dev Assignes a new NFT to an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _to Address to wich we want to add the NFT. * @param _tokenId Which NFT we want to add. */ function _addNFToken( address _to, uint256 _tokenId ) internal override virtual { require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS); idToOwner[_tokenId] = _to; ownerToIds[_to].push(_tokenId); idToOwnerIndex[_tokenId] = ownerToIds[_to].length - 1; } /** * @dev Helper function that gets NFT count of owner. This is needed for overriding in enumerable * extension to remove double storage(gas optimization) of owner nft count. * @param _owner Address for whom to query the count. * @return Number of _owner NFTs. */ function _getOwnerNFTCount( address _owner ) internal override virtual view returns (uint256) { return ownerToIds[_owner].length; } }
/** * @dev Optional metadata implementation for ERC-721 non-fungible token standard. */
NatSpecMultiLine
symbol
function symbol() external override view returns (string memory _symbol) { _symbol = nftSymbol; }
/** * @dev Returns an abbreviated name for NFTokens. * @return _symbol Representing symbol. */
NatSpecMultiLine
v0.6.2+commit.bacdbe57
MIT
ipfs://6626fd920334c84d658057cbe16dd3b47b41fc7475707238fefa241a53c0a511
{ "func_code_index": [ 1324, 1455 ] }
874
EmblemVault
browser/github/0xcert/ethereum-erc721/src/contracts/tokens/nf-token-enumerable-metadata.sol
0x82c7a8f707110f5fbb16184a5933e9f78a34c6ab
Solidity
NFTokenEnumerableMetadata
abstract contract NFTokenEnumerableMetadata is NFToken, ERC721Metadata, ERC721Enumerable { /** * @dev A descriptive name for a collection of NFTs. */ string internal nftName; /** * @dev An abbreviated name for NFTokens. */ string internal nftSymbol; /** * @dev An uri to represent the metadata for this contract. */ string internal nftContractMetadataUri; /** * @dev Mapping from NFT ID to metadata uri. */ mapping (uint256 => string) internal idToUri; /** * @dev Mapping from NFT ID to encrypted value. */ mapping (uint256 => string) internal idToPayload; /** * @dev Contract constructor. * @notice When implementing this contract don't forget to set nftName and nftSymbol. */ constructor() public { supportedInterfaces[0x5b5e139f] = true; // ERC721Metadata supportedInterfaces[0x780e9d63] = true; // ERC721Enumerable } /** * @dev Returns a descriptive name for a collection of NFTokens. * @return _name Representing name. */ function name() external override view returns (string memory _name) { _name = nftName; } /** * @dev Returns an abbreviated name for NFTokens. * @return _symbol Representing symbol. */ function symbol() external override view returns (string memory _symbol) { _symbol = nftSymbol; } /** * @dev A distinct URI (RFC 3986) for a given NFT. * @param _tokenId Id for which we want uri. * @return URI of _tokenId. */ function tokenURI( uint256 _tokenId ) external override view validNFToken(_tokenId) returns (string memory) { return idToUri[_tokenId]; } /** * @dev A distinct URI (RFC 3986) for a given NFT. * @param _tokenId Id for which we want uri. * @return URI of _tokenId. */ function tokenPayload( uint256 _tokenId ) external view validNFToken(_tokenId) returns (string memory) { return idToPayload[_tokenId]; } /** * @dev Set a distinct URI (RFC 3986) for a given NFT ID. * @notice This is an internal function which should be called from user-implemented external * function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _tokenId Id for which we want URI. * @param _uri String representing RFC 3986 URI. */ function _setTokenUri( uint256 _tokenId, string memory _uri ) internal validNFToken(_tokenId) { idToUri[_tokenId] = _uri; } function _setTokenPayload( uint256 _tokenId, string memory _uri ) internal validNFToken(_tokenId) { idToPayload[_tokenId] = _uri; } /** * List of revert message codes. Implementing dApp should handle showing the correct message. * Based on 0xcert framework error codes. */ string constant INVALID_INDEX = "005007"; /** * @dev Array of all NFT IDs. */ uint256[] internal tokens; /** * @dev Mapping from token ID to its index in global tokens array. */ mapping(uint256 => uint256) internal idToIndex; /** * @dev Mapping from owner to list of owned NFT IDs. */ mapping(address => uint256[]) internal ownerToIds; /** * @dev Mapping from NFT ID to its index in the owner tokens list. */ mapping(uint256 => uint256) internal idToOwnerIndex; /** * @dev Returns the count of all existing NFTokens. * @return Total supply of NFTs. */ function totalSupply() external override view returns (uint256) { return tokens.length; } /** * @dev Returns NFT ID by its index. * @param _index A counter less than `totalSupply()`. * @return Token id. */ function tokenByIndex( uint256 _index ) external override view returns (uint256) { require(_index < tokens.length, INVALID_INDEX); return tokens[_index]; } /** * @dev returns the n-th NFT ID from a list of owner's tokens. * @param _owner Token owner's address. * @param _index Index number representing n-th token in owner's list of tokens. * @return Token id. */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) external override view returns (uint256) { require(_index < ownerToIds[_owner].length, INVALID_INDEX); return ownerToIds[_owner][_index]; } /** * @dev Mints a new NFT. * @notice This is an internal function which should be called from user-implemented external * mint function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _to The address that will own the minted NFT. * @param _tokenId of the NFT to be minted by the msg.sender. */ function _mint( address _to, uint256 _tokenId ) internal override virtual { super._mint(_to, _tokenId); tokens.push(_tokenId); idToIndex[_tokenId] = tokens.length - 1; } /** * @dev Burns a NFT. * @notice This is an internal function which should be called from user-implemented external * burn function. Its purpose is to show and properly initialize data structures when using this * implementation. Also, note that this burn implementation allows the minter to re-mint a burned * NFT. * @param _tokenId ID of the NFT to be burned. */ function _burn( uint256 _tokenId ) internal override virtual { super._burn(_tokenId); if (bytes(idToUri[_tokenId]).length != 0) { delete idToUri[_tokenId]; } if (bytes(idToPayload[_tokenId]).length != 0) { delete idToPayload[_tokenId]; } uint256 tokenIndex = idToIndex[_tokenId]; uint256 lastTokenIndex = tokens.length - 1; uint256 lastToken = tokens[lastTokenIndex]; tokens[tokenIndex] = lastToken; tokens.pop(); // This wastes gas if you are burning the last token but saves a little gas if you are not. idToIndex[lastToken] = tokenIndex; idToIndex[_tokenId] = 0; } /** * @dev Removes a NFT from an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _from Address from wich we want to remove the NFT. * @param _tokenId Which NFT we want to remove. */ function _removeNFToken( address _from, uint256 _tokenId ) internal override virtual { require(idToOwner[_tokenId] == _from, NOT_OWNER); delete idToOwner[_tokenId]; uint256 tokenToRemoveIndex = idToOwnerIndex[_tokenId]; uint256 lastTokenIndex = ownerToIds[_from].length - 1; if (lastTokenIndex != tokenToRemoveIndex) { uint256 lastToken = ownerToIds[_from][lastTokenIndex]; ownerToIds[_from][tokenToRemoveIndex] = lastToken; idToOwnerIndex[lastToken] = tokenToRemoveIndex; } ownerToIds[_from].pop(); } /** * @dev Assignes a new NFT to an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _to Address to wich we want to add the NFT. * @param _tokenId Which NFT we want to add. */ function _addNFToken( address _to, uint256 _tokenId ) internal override virtual { require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS); idToOwner[_tokenId] = _to; ownerToIds[_to].push(_tokenId); idToOwnerIndex[_tokenId] = ownerToIds[_to].length - 1; } /** * @dev Helper function that gets NFT count of owner. This is needed for overriding in enumerable * extension to remove double storage(gas optimization) of owner nft count. * @param _owner Address for whom to query the count. * @return Number of _owner NFTs. */ function _getOwnerNFTCount( address _owner ) internal override virtual view returns (uint256) { return ownerToIds[_owner].length; } }
/** * @dev Optional metadata implementation for ERC-721 non-fungible token standard. */
NatSpecMultiLine
tokenURI
function tokenURI( uint256 _tokenId ) external override view validNFToken(_tokenId) returns (string memory) { return idToUri[_tokenId]; }
/** * @dev A distinct URI (RFC 3986) for a given NFT. * @param _tokenId Id for which we want uri. * @return URI of _tokenId. */
NatSpecMultiLine
v0.6.2+commit.bacdbe57
MIT
ipfs://6626fd920334c84d658057cbe16dd3b47b41fc7475707238fefa241a53c0a511
{ "func_code_index": [ 1605, 1789 ] }
875
EmblemVault
browser/github/0xcert/ethereum-erc721/src/contracts/tokens/nf-token-enumerable-metadata.sol
0x82c7a8f707110f5fbb16184a5933e9f78a34c6ab
Solidity
NFTokenEnumerableMetadata
abstract contract NFTokenEnumerableMetadata is NFToken, ERC721Metadata, ERC721Enumerable { /** * @dev A descriptive name for a collection of NFTs. */ string internal nftName; /** * @dev An abbreviated name for NFTokens. */ string internal nftSymbol; /** * @dev An uri to represent the metadata for this contract. */ string internal nftContractMetadataUri; /** * @dev Mapping from NFT ID to metadata uri. */ mapping (uint256 => string) internal idToUri; /** * @dev Mapping from NFT ID to encrypted value. */ mapping (uint256 => string) internal idToPayload; /** * @dev Contract constructor. * @notice When implementing this contract don't forget to set nftName and nftSymbol. */ constructor() public { supportedInterfaces[0x5b5e139f] = true; // ERC721Metadata supportedInterfaces[0x780e9d63] = true; // ERC721Enumerable } /** * @dev Returns a descriptive name for a collection of NFTokens. * @return _name Representing name. */ function name() external override view returns (string memory _name) { _name = nftName; } /** * @dev Returns an abbreviated name for NFTokens. * @return _symbol Representing symbol. */ function symbol() external override view returns (string memory _symbol) { _symbol = nftSymbol; } /** * @dev A distinct URI (RFC 3986) for a given NFT. * @param _tokenId Id for which we want uri. * @return URI of _tokenId. */ function tokenURI( uint256 _tokenId ) external override view validNFToken(_tokenId) returns (string memory) { return idToUri[_tokenId]; } /** * @dev A distinct URI (RFC 3986) for a given NFT. * @param _tokenId Id for which we want uri. * @return URI of _tokenId. */ function tokenPayload( uint256 _tokenId ) external view validNFToken(_tokenId) returns (string memory) { return idToPayload[_tokenId]; } /** * @dev Set a distinct URI (RFC 3986) for a given NFT ID. * @notice This is an internal function which should be called from user-implemented external * function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _tokenId Id for which we want URI. * @param _uri String representing RFC 3986 URI. */ function _setTokenUri( uint256 _tokenId, string memory _uri ) internal validNFToken(_tokenId) { idToUri[_tokenId] = _uri; } function _setTokenPayload( uint256 _tokenId, string memory _uri ) internal validNFToken(_tokenId) { idToPayload[_tokenId] = _uri; } /** * List of revert message codes. Implementing dApp should handle showing the correct message. * Based on 0xcert framework error codes. */ string constant INVALID_INDEX = "005007"; /** * @dev Array of all NFT IDs. */ uint256[] internal tokens; /** * @dev Mapping from token ID to its index in global tokens array. */ mapping(uint256 => uint256) internal idToIndex; /** * @dev Mapping from owner to list of owned NFT IDs. */ mapping(address => uint256[]) internal ownerToIds; /** * @dev Mapping from NFT ID to its index in the owner tokens list. */ mapping(uint256 => uint256) internal idToOwnerIndex; /** * @dev Returns the count of all existing NFTokens. * @return Total supply of NFTs. */ function totalSupply() external override view returns (uint256) { return tokens.length; } /** * @dev Returns NFT ID by its index. * @param _index A counter less than `totalSupply()`. * @return Token id. */ function tokenByIndex( uint256 _index ) external override view returns (uint256) { require(_index < tokens.length, INVALID_INDEX); return tokens[_index]; } /** * @dev returns the n-th NFT ID from a list of owner's tokens. * @param _owner Token owner's address. * @param _index Index number representing n-th token in owner's list of tokens. * @return Token id. */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) external override view returns (uint256) { require(_index < ownerToIds[_owner].length, INVALID_INDEX); return ownerToIds[_owner][_index]; } /** * @dev Mints a new NFT. * @notice This is an internal function which should be called from user-implemented external * mint function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _to The address that will own the minted NFT. * @param _tokenId of the NFT to be minted by the msg.sender. */ function _mint( address _to, uint256 _tokenId ) internal override virtual { super._mint(_to, _tokenId); tokens.push(_tokenId); idToIndex[_tokenId] = tokens.length - 1; } /** * @dev Burns a NFT. * @notice This is an internal function which should be called from user-implemented external * burn function. Its purpose is to show and properly initialize data structures when using this * implementation. Also, note that this burn implementation allows the minter to re-mint a burned * NFT. * @param _tokenId ID of the NFT to be burned. */ function _burn( uint256 _tokenId ) internal override virtual { super._burn(_tokenId); if (bytes(idToUri[_tokenId]).length != 0) { delete idToUri[_tokenId]; } if (bytes(idToPayload[_tokenId]).length != 0) { delete idToPayload[_tokenId]; } uint256 tokenIndex = idToIndex[_tokenId]; uint256 lastTokenIndex = tokens.length - 1; uint256 lastToken = tokens[lastTokenIndex]; tokens[tokenIndex] = lastToken; tokens.pop(); // This wastes gas if you are burning the last token but saves a little gas if you are not. idToIndex[lastToken] = tokenIndex; idToIndex[_tokenId] = 0; } /** * @dev Removes a NFT from an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _from Address from wich we want to remove the NFT. * @param _tokenId Which NFT we want to remove. */ function _removeNFToken( address _from, uint256 _tokenId ) internal override virtual { require(idToOwner[_tokenId] == _from, NOT_OWNER); delete idToOwner[_tokenId]; uint256 tokenToRemoveIndex = idToOwnerIndex[_tokenId]; uint256 lastTokenIndex = ownerToIds[_from].length - 1; if (lastTokenIndex != tokenToRemoveIndex) { uint256 lastToken = ownerToIds[_from][lastTokenIndex]; ownerToIds[_from][tokenToRemoveIndex] = lastToken; idToOwnerIndex[lastToken] = tokenToRemoveIndex; } ownerToIds[_from].pop(); } /** * @dev Assignes a new NFT to an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _to Address to wich we want to add the NFT. * @param _tokenId Which NFT we want to add. */ function _addNFToken( address _to, uint256 _tokenId ) internal override virtual { require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS); idToOwner[_tokenId] = _to; ownerToIds[_to].push(_tokenId); idToOwnerIndex[_tokenId] = ownerToIds[_to].length - 1; } /** * @dev Helper function that gets NFT count of owner. This is needed for overriding in enumerable * extension to remove double storage(gas optimization) of owner nft count. * @param _owner Address for whom to query the count. * @return Number of _owner NFTs. */ function _getOwnerNFTCount( address _owner ) internal override virtual view returns (uint256) { return ownerToIds[_owner].length; } }
/** * @dev Optional metadata implementation for ERC-721 non-fungible token standard. */
NatSpecMultiLine
tokenPayload
function tokenPayload( uint256 _tokenId ) external view validNFToken(_tokenId) returns (string memory) { return idToPayload[_tokenId]; }
/** * @dev A distinct URI (RFC 3986) for a given NFT. * @param _tokenId Id for which we want uri. * @return URI of _tokenId. */
NatSpecMultiLine
v0.6.2+commit.bacdbe57
MIT
ipfs://6626fd920334c84d658057cbe16dd3b47b41fc7475707238fefa241a53c0a511
{ "func_code_index": [ 1943, 2121 ] }
876
EmblemVault
browser/github/0xcert/ethereum-erc721/src/contracts/tokens/nf-token-enumerable-metadata.sol
0x82c7a8f707110f5fbb16184a5933e9f78a34c6ab
Solidity
NFTokenEnumerableMetadata
abstract contract NFTokenEnumerableMetadata is NFToken, ERC721Metadata, ERC721Enumerable { /** * @dev A descriptive name for a collection of NFTs. */ string internal nftName; /** * @dev An abbreviated name for NFTokens. */ string internal nftSymbol; /** * @dev An uri to represent the metadata for this contract. */ string internal nftContractMetadataUri; /** * @dev Mapping from NFT ID to metadata uri. */ mapping (uint256 => string) internal idToUri; /** * @dev Mapping from NFT ID to encrypted value. */ mapping (uint256 => string) internal idToPayload; /** * @dev Contract constructor. * @notice When implementing this contract don't forget to set nftName and nftSymbol. */ constructor() public { supportedInterfaces[0x5b5e139f] = true; // ERC721Metadata supportedInterfaces[0x780e9d63] = true; // ERC721Enumerable } /** * @dev Returns a descriptive name for a collection of NFTokens. * @return _name Representing name. */ function name() external override view returns (string memory _name) { _name = nftName; } /** * @dev Returns an abbreviated name for NFTokens. * @return _symbol Representing symbol. */ function symbol() external override view returns (string memory _symbol) { _symbol = nftSymbol; } /** * @dev A distinct URI (RFC 3986) for a given NFT. * @param _tokenId Id for which we want uri. * @return URI of _tokenId. */ function tokenURI( uint256 _tokenId ) external override view validNFToken(_tokenId) returns (string memory) { return idToUri[_tokenId]; } /** * @dev A distinct URI (RFC 3986) for a given NFT. * @param _tokenId Id for which we want uri. * @return URI of _tokenId. */ function tokenPayload( uint256 _tokenId ) external view validNFToken(_tokenId) returns (string memory) { return idToPayload[_tokenId]; } /** * @dev Set a distinct URI (RFC 3986) for a given NFT ID. * @notice This is an internal function which should be called from user-implemented external * function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _tokenId Id for which we want URI. * @param _uri String representing RFC 3986 URI. */ function _setTokenUri( uint256 _tokenId, string memory _uri ) internal validNFToken(_tokenId) { idToUri[_tokenId] = _uri; } function _setTokenPayload( uint256 _tokenId, string memory _uri ) internal validNFToken(_tokenId) { idToPayload[_tokenId] = _uri; } /** * List of revert message codes. Implementing dApp should handle showing the correct message. * Based on 0xcert framework error codes. */ string constant INVALID_INDEX = "005007"; /** * @dev Array of all NFT IDs. */ uint256[] internal tokens; /** * @dev Mapping from token ID to its index in global tokens array. */ mapping(uint256 => uint256) internal idToIndex; /** * @dev Mapping from owner to list of owned NFT IDs. */ mapping(address => uint256[]) internal ownerToIds; /** * @dev Mapping from NFT ID to its index in the owner tokens list. */ mapping(uint256 => uint256) internal idToOwnerIndex; /** * @dev Returns the count of all existing NFTokens. * @return Total supply of NFTs. */ function totalSupply() external override view returns (uint256) { return tokens.length; } /** * @dev Returns NFT ID by its index. * @param _index A counter less than `totalSupply()`. * @return Token id. */ function tokenByIndex( uint256 _index ) external override view returns (uint256) { require(_index < tokens.length, INVALID_INDEX); return tokens[_index]; } /** * @dev returns the n-th NFT ID from a list of owner's tokens. * @param _owner Token owner's address. * @param _index Index number representing n-th token in owner's list of tokens. * @return Token id. */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) external override view returns (uint256) { require(_index < ownerToIds[_owner].length, INVALID_INDEX); return ownerToIds[_owner][_index]; } /** * @dev Mints a new NFT. * @notice This is an internal function which should be called from user-implemented external * mint function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _to The address that will own the minted NFT. * @param _tokenId of the NFT to be minted by the msg.sender. */ function _mint( address _to, uint256 _tokenId ) internal override virtual { super._mint(_to, _tokenId); tokens.push(_tokenId); idToIndex[_tokenId] = tokens.length - 1; } /** * @dev Burns a NFT. * @notice This is an internal function which should be called from user-implemented external * burn function. Its purpose is to show and properly initialize data structures when using this * implementation. Also, note that this burn implementation allows the minter to re-mint a burned * NFT. * @param _tokenId ID of the NFT to be burned. */ function _burn( uint256 _tokenId ) internal override virtual { super._burn(_tokenId); if (bytes(idToUri[_tokenId]).length != 0) { delete idToUri[_tokenId]; } if (bytes(idToPayload[_tokenId]).length != 0) { delete idToPayload[_tokenId]; } uint256 tokenIndex = idToIndex[_tokenId]; uint256 lastTokenIndex = tokens.length - 1; uint256 lastToken = tokens[lastTokenIndex]; tokens[tokenIndex] = lastToken; tokens.pop(); // This wastes gas if you are burning the last token but saves a little gas if you are not. idToIndex[lastToken] = tokenIndex; idToIndex[_tokenId] = 0; } /** * @dev Removes a NFT from an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _from Address from wich we want to remove the NFT. * @param _tokenId Which NFT we want to remove. */ function _removeNFToken( address _from, uint256 _tokenId ) internal override virtual { require(idToOwner[_tokenId] == _from, NOT_OWNER); delete idToOwner[_tokenId]; uint256 tokenToRemoveIndex = idToOwnerIndex[_tokenId]; uint256 lastTokenIndex = ownerToIds[_from].length - 1; if (lastTokenIndex != tokenToRemoveIndex) { uint256 lastToken = ownerToIds[_from][lastTokenIndex]; ownerToIds[_from][tokenToRemoveIndex] = lastToken; idToOwnerIndex[lastToken] = tokenToRemoveIndex; } ownerToIds[_from].pop(); } /** * @dev Assignes a new NFT to an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _to Address to wich we want to add the NFT. * @param _tokenId Which NFT we want to add. */ function _addNFToken( address _to, uint256 _tokenId ) internal override virtual { require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS); idToOwner[_tokenId] = _to; ownerToIds[_to].push(_tokenId); idToOwnerIndex[_tokenId] = ownerToIds[_to].length - 1; } /** * @dev Helper function that gets NFT count of owner. This is needed for overriding in enumerable * extension to remove double storage(gas optimization) of owner nft count. * @param _owner Address for whom to query the count. * @return Number of _owner NFTs. */ function _getOwnerNFTCount( address _owner ) internal override virtual view returns (uint256) { return ownerToIds[_owner].length; } }
/** * @dev Optional metadata implementation for ERC-721 non-fungible token standard. */
NatSpecMultiLine
_setTokenUri
function _setTokenUri( uint256 _tokenId, string memory _uri ) internal validNFToken(_tokenId) { idToUri[_tokenId] = _uri; }
/** * @dev Set a distinct URI (RFC 3986) for a given NFT ID. * @notice This is an internal function which should be called from user-implemented external * function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _tokenId Id for which we want URI. * @param _uri String representing RFC 3986 URI. */
NatSpecMultiLine
v0.6.2+commit.bacdbe57
MIT
ipfs://6626fd920334c84d658057cbe16dd3b47b41fc7475707238fefa241a53c0a511
{ "func_code_index": [ 2513, 2673 ] }
877
EmblemVault
browser/github/0xcert/ethereum-erc721/src/contracts/tokens/nf-token-enumerable-metadata.sol
0x82c7a8f707110f5fbb16184a5933e9f78a34c6ab
Solidity
NFTokenEnumerableMetadata
abstract contract NFTokenEnumerableMetadata is NFToken, ERC721Metadata, ERC721Enumerable { /** * @dev A descriptive name for a collection of NFTs. */ string internal nftName; /** * @dev An abbreviated name for NFTokens. */ string internal nftSymbol; /** * @dev An uri to represent the metadata for this contract. */ string internal nftContractMetadataUri; /** * @dev Mapping from NFT ID to metadata uri. */ mapping (uint256 => string) internal idToUri; /** * @dev Mapping from NFT ID to encrypted value. */ mapping (uint256 => string) internal idToPayload; /** * @dev Contract constructor. * @notice When implementing this contract don't forget to set nftName and nftSymbol. */ constructor() public { supportedInterfaces[0x5b5e139f] = true; // ERC721Metadata supportedInterfaces[0x780e9d63] = true; // ERC721Enumerable } /** * @dev Returns a descriptive name for a collection of NFTokens. * @return _name Representing name. */ function name() external override view returns (string memory _name) { _name = nftName; } /** * @dev Returns an abbreviated name for NFTokens. * @return _symbol Representing symbol. */ function symbol() external override view returns (string memory _symbol) { _symbol = nftSymbol; } /** * @dev A distinct URI (RFC 3986) for a given NFT. * @param _tokenId Id for which we want uri. * @return URI of _tokenId. */ function tokenURI( uint256 _tokenId ) external override view validNFToken(_tokenId) returns (string memory) { return idToUri[_tokenId]; } /** * @dev A distinct URI (RFC 3986) for a given NFT. * @param _tokenId Id for which we want uri. * @return URI of _tokenId. */ function tokenPayload( uint256 _tokenId ) external view validNFToken(_tokenId) returns (string memory) { return idToPayload[_tokenId]; } /** * @dev Set a distinct URI (RFC 3986) for a given NFT ID. * @notice This is an internal function which should be called from user-implemented external * function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _tokenId Id for which we want URI. * @param _uri String representing RFC 3986 URI. */ function _setTokenUri( uint256 _tokenId, string memory _uri ) internal validNFToken(_tokenId) { idToUri[_tokenId] = _uri; } function _setTokenPayload( uint256 _tokenId, string memory _uri ) internal validNFToken(_tokenId) { idToPayload[_tokenId] = _uri; } /** * List of revert message codes. Implementing dApp should handle showing the correct message. * Based on 0xcert framework error codes. */ string constant INVALID_INDEX = "005007"; /** * @dev Array of all NFT IDs. */ uint256[] internal tokens; /** * @dev Mapping from token ID to its index in global tokens array. */ mapping(uint256 => uint256) internal idToIndex; /** * @dev Mapping from owner to list of owned NFT IDs. */ mapping(address => uint256[]) internal ownerToIds; /** * @dev Mapping from NFT ID to its index in the owner tokens list. */ mapping(uint256 => uint256) internal idToOwnerIndex; /** * @dev Returns the count of all existing NFTokens. * @return Total supply of NFTs. */ function totalSupply() external override view returns (uint256) { return tokens.length; } /** * @dev Returns NFT ID by its index. * @param _index A counter less than `totalSupply()`. * @return Token id. */ function tokenByIndex( uint256 _index ) external override view returns (uint256) { require(_index < tokens.length, INVALID_INDEX); return tokens[_index]; } /** * @dev returns the n-th NFT ID from a list of owner's tokens. * @param _owner Token owner's address. * @param _index Index number representing n-th token in owner's list of tokens. * @return Token id. */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) external override view returns (uint256) { require(_index < ownerToIds[_owner].length, INVALID_INDEX); return ownerToIds[_owner][_index]; } /** * @dev Mints a new NFT. * @notice This is an internal function which should be called from user-implemented external * mint function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _to The address that will own the minted NFT. * @param _tokenId of the NFT to be minted by the msg.sender. */ function _mint( address _to, uint256 _tokenId ) internal override virtual { super._mint(_to, _tokenId); tokens.push(_tokenId); idToIndex[_tokenId] = tokens.length - 1; } /** * @dev Burns a NFT. * @notice This is an internal function which should be called from user-implemented external * burn function. Its purpose is to show and properly initialize data structures when using this * implementation. Also, note that this burn implementation allows the minter to re-mint a burned * NFT. * @param _tokenId ID of the NFT to be burned. */ function _burn( uint256 _tokenId ) internal override virtual { super._burn(_tokenId); if (bytes(idToUri[_tokenId]).length != 0) { delete idToUri[_tokenId]; } if (bytes(idToPayload[_tokenId]).length != 0) { delete idToPayload[_tokenId]; } uint256 tokenIndex = idToIndex[_tokenId]; uint256 lastTokenIndex = tokens.length - 1; uint256 lastToken = tokens[lastTokenIndex]; tokens[tokenIndex] = lastToken; tokens.pop(); // This wastes gas if you are burning the last token but saves a little gas if you are not. idToIndex[lastToken] = tokenIndex; idToIndex[_tokenId] = 0; } /** * @dev Removes a NFT from an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _from Address from wich we want to remove the NFT. * @param _tokenId Which NFT we want to remove. */ function _removeNFToken( address _from, uint256 _tokenId ) internal override virtual { require(idToOwner[_tokenId] == _from, NOT_OWNER); delete idToOwner[_tokenId]; uint256 tokenToRemoveIndex = idToOwnerIndex[_tokenId]; uint256 lastTokenIndex = ownerToIds[_from].length - 1; if (lastTokenIndex != tokenToRemoveIndex) { uint256 lastToken = ownerToIds[_from][lastTokenIndex]; ownerToIds[_from][tokenToRemoveIndex] = lastToken; idToOwnerIndex[lastToken] = tokenToRemoveIndex; } ownerToIds[_from].pop(); } /** * @dev Assignes a new NFT to an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _to Address to wich we want to add the NFT. * @param _tokenId Which NFT we want to add. */ function _addNFToken( address _to, uint256 _tokenId ) internal override virtual { require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS); idToOwner[_tokenId] = _to; ownerToIds[_to].push(_tokenId); idToOwnerIndex[_tokenId] = ownerToIds[_to].length - 1; } /** * @dev Helper function that gets NFT count of owner. This is needed for overriding in enumerable * extension to remove double storage(gas optimization) of owner nft count. * @param _owner Address for whom to query the count. * @return Number of _owner NFTs. */ function _getOwnerNFTCount( address _owner ) internal override virtual view returns (uint256) { return ownerToIds[_owner].length; } }
/** * @dev Optional metadata implementation for ERC-721 non-fungible token standard. */
NatSpecMultiLine
totalSupply
function totalSupply() external override view returns (uint256) { return tokens.length; }
/** * @dev Returns the count of all existing NFTokens. * @return Total supply of NFTs. */
NatSpecMultiLine
v0.6.2+commit.bacdbe57
MIT
ipfs://6626fd920334c84d658057cbe16dd3b47b41fc7475707238fefa241a53c0a511
{ "func_code_index": [ 3643, 3766 ] }
878
EmblemVault
browser/github/0xcert/ethereum-erc721/src/contracts/tokens/nf-token-enumerable-metadata.sol
0x82c7a8f707110f5fbb16184a5933e9f78a34c6ab
Solidity
NFTokenEnumerableMetadata
abstract contract NFTokenEnumerableMetadata is NFToken, ERC721Metadata, ERC721Enumerable { /** * @dev A descriptive name for a collection of NFTs. */ string internal nftName; /** * @dev An abbreviated name for NFTokens. */ string internal nftSymbol; /** * @dev An uri to represent the metadata for this contract. */ string internal nftContractMetadataUri; /** * @dev Mapping from NFT ID to metadata uri. */ mapping (uint256 => string) internal idToUri; /** * @dev Mapping from NFT ID to encrypted value. */ mapping (uint256 => string) internal idToPayload; /** * @dev Contract constructor. * @notice When implementing this contract don't forget to set nftName and nftSymbol. */ constructor() public { supportedInterfaces[0x5b5e139f] = true; // ERC721Metadata supportedInterfaces[0x780e9d63] = true; // ERC721Enumerable } /** * @dev Returns a descriptive name for a collection of NFTokens. * @return _name Representing name. */ function name() external override view returns (string memory _name) { _name = nftName; } /** * @dev Returns an abbreviated name for NFTokens. * @return _symbol Representing symbol. */ function symbol() external override view returns (string memory _symbol) { _symbol = nftSymbol; } /** * @dev A distinct URI (RFC 3986) for a given NFT. * @param _tokenId Id for which we want uri. * @return URI of _tokenId. */ function tokenURI( uint256 _tokenId ) external override view validNFToken(_tokenId) returns (string memory) { return idToUri[_tokenId]; } /** * @dev A distinct URI (RFC 3986) for a given NFT. * @param _tokenId Id for which we want uri. * @return URI of _tokenId. */ function tokenPayload( uint256 _tokenId ) external view validNFToken(_tokenId) returns (string memory) { return idToPayload[_tokenId]; } /** * @dev Set a distinct URI (RFC 3986) for a given NFT ID. * @notice This is an internal function which should be called from user-implemented external * function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _tokenId Id for which we want URI. * @param _uri String representing RFC 3986 URI. */ function _setTokenUri( uint256 _tokenId, string memory _uri ) internal validNFToken(_tokenId) { idToUri[_tokenId] = _uri; } function _setTokenPayload( uint256 _tokenId, string memory _uri ) internal validNFToken(_tokenId) { idToPayload[_tokenId] = _uri; } /** * List of revert message codes. Implementing dApp should handle showing the correct message. * Based on 0xcert framework error codes. */ string constant INVALID_INDEX = "005007"; /** * @dev Array of all NFT IDs. */ uint256[] internal tokens; /** * @dev Mapping from token ID to its index in global tokens array. */ mapping(uint256 => uint256) internal idToIndex; /** * @dev Mapping from owner to list of owned NFT IDs. */ mapping(address => uint256[]) internal ownerToIds; /** * @dev Mapping from NFT ID to its index in the owner tokens list. */ mapping(uint256 => uint256) internal idToOwnerIndex; /** * @dev Returns the count of all existing NFTokens. * @return Total supply of NFTs. */ function totalSupply() external override view returns (uint256) { return tokens.length; } /** * @dev Returns NFT ID by its index. * @param _index A counter less than `totalSupply()`. * @return Token id. */ function tokenByIndex( uint256 _index ) external override view returns (uint256) { require(_index < tokens.length, INVALID_INDEX); return tokens[_index]; } /** * @dev returns the n-th NFT ID from a list of owner's tokens. * @param _owner Token owner's address. * @param _index Index number representing n-th token in owner's list of tokens. * @return Token id. */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) external override view returns (uint256) { require(_index < ownerToIds[_owner].length, INVALID_INDEX); return ownerToIds[_owner][_index]; } /** * @dev Mints a new NFT. * @notice This is an internal function which should be called from user-implemented external * mint function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _to The address that will own the minted NFT. * @param _tokenId of the NFT to be minted by the msg.sender. */ function _mint( address _to, uint256 _tokenId ) internal override virtual { super._mint(_to, _tokenId); tokens.push(_tokenId); idToIndex[_tokenId] = tokens.length - 1; } /** * @dev Burns a NFT. * @notice This is an internal function which should be called from user-implemented external * burn function. Its purpose is to show and properly initialize data structures when using this * implementation. Also, note that this burn implementation allows the minter to re-mint a burned * NFT. * @param _tokenId ID of the NFT to be burned. */ function _burn( uint256 _tokenId ) internal override virtual { super._burn(_tokenId); if (bytes(idToUri[_tokenId]).length != 0) { delete idToUri[_tokenId]; } if (bytes(idToPayload[_tokenId]).length != 0) { delete idToPayload[_tokenId]; } uint256 tokenIndex = idToIndex[_tokenId]; uint256 lastTokenIndex = tokens.length - 1; uint256 lastToken = tokens[lastTokenIndex]; tokens[tokenIndex] = lastToken; tokens.pop(); // This wastes gas if you are burning the last token but saves a little gas if you are not. idToIndex[lastToken] = tokenIndex; idToIndex[_tokenId] = 0; } /** * @dev Removes a NFT from an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _from Address from wich we want to remove the NFT. * @param _tokenId Which NFT we want to remove. */ function _removeNFToken( address _from, uint256 _tokenId ) internal override virtual { require(idToOwner[_tokenId] == _from, NOT_OWNER); delete idToOwner[_tokenId]; uint256 tokenToRemoveIndex = idToOwnerIndex[_tokenId]; uint256 lastTokenIndex = ownerToIds[_from].length - 1; if (lastTokenIndex != tokenToRemoveIndex) { uint256 lastToken = ownerToIds[_from][lastTokenIndex]; ownerToIds[_from][tokenToRemoveIndex] = lastToken; idToOwnerIndex[lastToken] = tokenToRemoveIndex; } ownerToIds[_from].pop(); } /** * @dev Assignes a new NFT to an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _to Address to wich we want to add the NFT. * @param _tokenId Which NFT we want to add. */ function _addNFToken( address _to, uint256 _tokenId ) internal override virtual { require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS); idToOwner[_tokenId] = _to; ownerToIds[_to].push(_tokenId); idToOwnerIndex[_tokenId] = ownerToIds[_to].length - 1; } /** * @dev Helper function that gets NFT count of owner. This is needed for overriding in enumerable * extension to remove double storage(gas optimization) of owner nft count. * @param _owner Address for whom to query the count. * @return Number of _owner NFTs. */ function _getOwnerNFTCount( address _owner ) internal override virtual view returns (uint256) { return ownerToIds[_owner].length; } }
/** * @dev Optional metadata implementation for ERC-721 non-fungible token standard. */
NatSpecMultiLine
tokenByIndex
function tokenByIndex( uint256 _index ) external override view returns (uint256) { require(_index < tokens.length, INVALID_INDEX); return tokens[_index]; }
/** * @dev Returns NFT ID by its index. * @param _index A counter less than `totalSupply()`. * @return Token id. */
NatSpecMultiLine
v0.6.2+commit.bacdbe57
MIT
ipfs://6626fd920334c84d658057cbe16dd3b47b41fc7475707238fefa241a53c0a511
{ "func_code_index": [ 3904, 4106 ] }
879
EmblemVault
browser/github/0xcert/ethereum-erc721/src/contracts/tokens/nf-token-enumerable-metadata.sol
0x82c7a8f707110f5fbb16184a5933e9f78a34c6ab
Solidity
NFTokenEnumerableMetadata
abstract contract NFTokenEnumerableMetadata is NFToken, ERC721Metadata, ERC721Enumerable { /** * @dev A descriptive name for a collection of NFTs. */ string internal nftName; /** * @dev An abbreviated name for NFTokens. */ string internal nftSymbol; /** * @dev An uri to represent the metadata for this contract. */ string internal nftContractMetadataUri; /** * @dev Mapping from NFT ID to metadata uri. */ mapping (uint256 => string) internal idToUri; /** * @dev Mapping from NFT ID to encrypted value. */ mapping (uint256 => string) internal idToPayload; /** * @dev Contract constructor. * @notice When implementing this contract don't forget to set nftName and nftSymbol. */ constructor() public { supportedInterfaces[0x5b5e139f] = true; // ERC721Metadata supportedInterfaces[0x780e9d63] = true; // ERC721Enumerable } /** * @dev Returns a descriptive name for a collection of NFTokens. * @return _name Representing name. */ function name() external override view returns (string memory _name) { _name = nftName; } /** * @dev Returns an abbreviated name for NFTokens. * @return _symbol Representing symbol. */ function symbol() external override view returns (string memory _symbol) { _symbol = nftSymbol; } /** * @dev A distinct URI (RFC 3986) for a given NFT. * @param _tokenId Id for which we want uri. * @return URI of _tokenId. */ function tokenURI( uint256 _tokenId ) external override view validNFToken(_tokenId) returns (string memory) { return idToUri[_tokenId]; } /** * @dev A distinct URI (RFC 3986) for a given NFT. * @param _tokenId Id for which we want uri. * @return URI of _tokenId. */ function tokenPayload( uint256 _tokenId ) external view validNFToken(_tokenId) returns (string memory) { return idToPayload[_tokenId]; } /** * @dev Set a distinct URI (RFC 3986) for a given NFT ID. * @notice This is an internal function which should be called from user-implemented external * function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _tokenId Id for which we want URI. * @param _uri String representing RFC 3986 URI. */ function _setTokenUri( uint256 _tokenId, string memory _uri ) internal validNFToken(_tokenId) { idToUri[_tokenId] = _uri; } function _setTokenPayload( uint256 _tokenId, string memory _uri ) internal validNFToken(_tokenId) { idToPayload[_tokenId] = _uri; } /** * List of revert message codes. Implementing dApp should handle showing the correct message. * Based on 0xcert framework error codes. */ string constant INVALID_INDEX = "005007"; /** * @dev Array of all NFT IDs. */ uint256[] internal tokens; /** * @dev Mapping from token ID to its index in global tokens array. */ mapping(uint256 => uint256) internal idToIndex; /** * @dev Mapping from owner to list of owned NFT IDs. */ mapping(address => uint256[]) internal ownerToIds; /** * @dev Mapping from NFT ID to its index in the owner tokens list. */ mapping(uint256 => uint256) internal idToOwnerIndex; /** * @dev Returns the count of all existing NFTokens. * @return Total supply of NFTs. */ function totalSupply() external override view returns (uint256) { return tokens.length; } /** * @dev Returns NFT ID by its index. * @param _index A counter less than `totalSupply()`. * @return Token id. */ function tokenByIndex( uint256 _index ) external override view returns (uint256) { require(_index < tokens.length, INVALID_INDEX); return tokens[_index]; } /** * @dev returns the n-th NFT ID from a list of owner's tokens. * @param _owner Token owner's address. * @param _index Index number representing n-th token in owner's list of tokens. * @return Token id. */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) external override view returns (uint256) { require(_index < ownerToIds[_owner].length, INVALID_INDEX); return ownerToIds[_owner][_index]; } /** * @dev Mints a new NFT. * @notice This is an internal function which should be called from user-implemented external * mint function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _to The address that will own the minted NFT. * @param _tokenId of the NFT to be minted by the msg.sender. */ function _mint( address _to, uint256 _tokenId ) internal override virtual { super._mint(_to, _tokenId); tokens.push(_tokenId); idToIndex[_tokenId] = tokens.length - 1; } /** * @dev Burns a NFT. * @notice This is an internal function which should be called from user-implemented external * burn function. Its purpose is to show and properly initialize data structures when using this * implementation. Also, note that this burn implementation allows the minter to re-mint a burned * NFT. * @param _tokenId ID of the NFT to be burned. */ function _burn( uint256 _tokenId ) internal override virtual { super._burn(_tokenId); if (bytes(idToUri[_tokenId]).length != 0) { delete idToUri[_tokenId]; } if (bytes(idToPayload[_tokenId]).length != 0) { delete idToPayload[_tokenId]; } uint256 tokenIndex = idToIndex[_tokenId]; uint256 lastTokenIndex = tokens.length - 1; uint256 lastToken = tokens[lastTokenIndex]; tokens[tokenIndex] = lastToken; tokens.pop(); // This wastes gas if you are burning the last token but saves a little gas if you are not. idToIndex[lastToken] = tokenIndex; idToIndex[_tokenId] = 0; } /** * @dev Removes a NFT from an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _from Address from wich we want to remove the NFT. * @param _tokenId Which NFT we want to remove. */ function _removeNFToken( address _from, uint256 _tokenId ) internal override virtual { require(idToOwner[_tokenId] == _from, NOT_OWNER); delete idToOwner[_tokenId]; uint256 tokenToRemoveIndex = idToOwnerIndex[_tokenId]; uint256 lastTokenIndex = ownerToIds[_from].length - 1; if (lastTokenIndex != tokenToRemoveIndex) { uint256 lastToken = ownerToIds[_from][lastTokenIndex]; ownerToIds[_from][tokenToRemoveIndex] = lastToken; idToOwnerIndex[lastToken] = tokenToRemoveIndex; } ownerToIds[_from].pop(); } /** * @dev Assignes a new NFT to an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _to Address to wich we want to add the NFT. * @param _tokenId Which NFT we want to add. */ function _addNFToken( address _to, uint256 _tokenId ) internal override virtual { require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS); idToOwner[_tokenId] = _to; ownerToIds[_to].push(_tokenId); idToOwnerIndex[_tokenId] = ownerToIds[_to].length - 1; } /** * @dev Helper function that gets NFT count of owner. This is needed for overriding in enumerable * extension to remove double storage(gas optimization) of owner nft count. * @param _owner Address for whom to query the count. * @return Number of _owner NFTs. */ function _getOwnerNFTCount( address _owner ) internal override virtual view returns (uint256) { return ownerToIds[_owner].length; } }
/** * @dev Optional metadata implementation for ERC-721 non-fungible token standard. */
NatSpecMultiLine
tokenOfOwnerByIndex
function tokenOfOwnerByIndex( address _owner, uint256 _index ) external override view returns (uint256) { require(_index < ownerToIds[_owner].length, INVALID_INDEX); return ownerToIds[_owner][_index]; }
/** * @dev returns the n-th NFT ID from a list of owner's tokens. * @param _owner Token owner's address. * @param _index Index number representing n-th token in owner's list of tokens. * @return Token id. */
NatSpecMultiLine
v0.6.2+commit.bacdbe57
MIT
ipfs://6626fd920334c84d658057cbe16dd3b47b41fc7475707238fefa241a53c0a511
{ "func_code_index": [ 4340, 4594 ] }
880
EmblemVault
browser/github/0xcert/ethereum-erc721/src/contracts/tokens/nf-token-enumerable-metadata.sol
0x82c7a8f707110f5fbb16184a5933e9f78a34c6ab
Solidity
NFTokenEnumerableMetadata
abstract contract NFTokenEnumerableMetadata is NFToken, ERC721Metadata, ERC721Enumerable { /** * @dev A descriptive name for a collection of NFTs. */ string internal nftName; /** * @dev An abbreviated name for NFTokens. */ string internal nftSymbol; /** * @dev An uri to represent the metadata for this contract. */ string internal nftContractMetadataUri; /** * @dev Mapping from NFT ID to metadata uri. */ mapping (uint256 => string) internal idToUri; /** * @dev Mapping from NFT ID to encrypted value. */ mapping (uint256 => string) internal idToPayload; /** * @dev Contract constructor. * @notice When implementing this contract don't forget to set nftName and nftSymbol. */ constructor() public { supportedInterfaces[0x5b5e139f] = true; // ERC721Metadata supportedInterfaces[0x780e9d63] = true; // ERC721Enumerable } /** * @dev Returns a descriptive name for a collection of NFTokens. * @return _name Representing name. */ function name() external override view returns (string memory _name) { _name = nftName; } /** * @dev Returns an abbreviated name for NFTokens. * @return _symbol Representing symbol. */ function symbol() external override view returns (string memory _symbol) { _symbol = nftSymbol; } /** * @dev A distinct URI (RFC 3986) for a given NFT. * @param _tokenId Id for which we want uri. * @return URI of _tokenId. */ function tokenURI( uint256 _tokenId ) external override view validNFToken(_tokenId) returns (string memory) { return idToUri[_tokenId]; } /** * @dev A distinct URI (RFC 3986) for a given NFT. * @param _tokenId Id for which we want uri. * @return URI of _tokenId. */ function tokenPayload( uint256 _tokenId ) external view validNFToken(_tokenId) returns (string memory) { return idToPayload[_tokenId]; } /** * @dev Set a distinct URI (RFC 3986) for a given NFT ID. * @notice This is an internal function which should be called from user-implemented external * function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _tokenId Id for which we want URI. * @param _uri String representing RFC 3986 URI. */ function _setTokenUri( uint256 _tokenId, string memory _uri ) internal validNFToken(_tokenId) { idToUri[_tokenId] = _uri; } function _setTokenPayload( uint256 _tokenId, string memory _uri ) internal validNFToken(_tokenId) { idToPayload[_tokenId] = _uri; } /** * List of revert message codes. Implementing dApp should handle showing the correct message. * Based on 0xcert framework error codes. */ string constant INVALID_INDEX = "005007"; /** * @dev Array of all NFT IDs. */ uint256[] internal tokens; /** * @dev Mapping from token ID to its index in global tokens array. */ mapping(uint256 => uint256) internal idToIndex; /** * @dev Mapping from owner to list of owned NFT IDs. */ mapping(address => uint256[]) internal ownerToIds; /** * @dev Mapping from NFT ID to its index in the owner tokens list. */ mapping(uint256 => uint256) internal idToOwnerIndex; /** * @dev Returns the count of all existing NFTokens. * @return Total supply of NFTs. */ function totalSupply() external override view returns (uint256) { return tokens.length; } /** * @dev Returns NFT ID by its index. * @param _index A counter less than `totalSupply()`. * @return Token id. */ function tokenByIndex( uint256 _index ) external override view returns (uint256) { require(_index < tokens.length, INVALID_INDEX); return tokens[_index]; } /** * @dev returns the n-th NFT ID from a list of owner's tokens. * @param _owner Token owner's address. * @param _index Index number representing n-th token in owner's list of tokens. * @return Token id. */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) external override view returns (uint256) { require(_index < ownerToIds[_owner].length, INVALID_INDEX); return ownerToIds[_owner][_index]; } /** * @dev Mints a new NFT. * @notice This is an internal function which should be called from user-implemented external * mint function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _to The address that will own the minted NFT. * @param _tokenId of the NFT to be minted by the msg.sender. */ function _mint( address _to, uint256 _tokenId ) internal override virtual { super._mint(_to, _tokenId); tokens.push(_tokenId); idToIndex[_tokenId] = tokens.length - 1; } /** * @dev Burns a NFT. * @notice This is an internal function which should be called from user-implemented external * burn function. Its purpose is to show and properly initialize data structures when using this * implementation. Also, note that this burn implementation allows the minter to re-mint a burned * NFT. * @param _tokenId ID of the NFT to be burned. */ function _burn( uint256 _tokenId ) internal override virtual { super._burn(_tokenId); if (bytes(idToUri[_tokenId]).length != 0) { delete idToUri[_tokenId]; } if (bytes(idToPayload[_tokenId]).length != 0) { delete idToPayload[_tokenId]; } uint256 tokenIndex = idToIndex[_tokenId]; uint256 lastTokenIndex = tokens.length - 1; uint256 lastToken = tokens[lastTokenIndex]; tokens[tokenIndex] = lastToken; tokens.pop(); // This wastes gas if you are burning the last token but saves a little gas if you are not. idToIndex[lastToken] = tokenIndex; idToIndex[_tokenId] = 0; } /** * @dev Removes a NFT from an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _from Address from wich we want to remove the NFT. * @param _tokenId Which NFT we want to remove. */ function _removeNFToken( address _from, uint256 _tokenId ) internal override virtual { require(idToOwner[_tokenId] == _from, NOT_OWNER); delete idToOwner[_tokenId]; uint256 tokenToRemoveIndex = idToOwnerIndex[_tokenId]; uint256 lastTokenIndex = ownerToIds[_from].length - 1; if (lastTokenIndex != tokenToRemoveIndex) { uint256 lastToken = ownerToIds[_from][lastTokenIndex]; ownerToIds[_from][tokenToRemoveIndex] = lastToken; idToOwnerIndex[lastToken] = tokenToRemoveIndex; } ownerToIds[_from].pop(); } /** * @dev Assignes a new NFT to an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _to Address to wich we want to add the NFT. * @param _tokenId Which NFT we want to add. */ function _addNFToken( address _to, uint256 _tokenId ) internal override virtual { require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS); idToOwner[_tokenId] = _to; ownerToIds[_to].push(_tokenId); idToOwnerIndex[_tokenId] = ownerToIds[_to].length - 1; } /** * @dev Helper function that gets NFT count of owner. This is needed for overriding in enumerable * extension to remove double storage(gas optimization) of owner nft count. * @param _owner Address for whom to query the count. * @return Number of _owner NFTs. */ function _getOwnerNFTCount( address _owner ) internal override virtual view returns (uint256) { return ownerToIds[_owner].length; } }
/** * @dev Optional metadata implementation for ERC-721 non-fungible token standard. */
NatSpecMultiLine
_mint
function _mint( address _to, uint256 _tokenId ) internal override virtual { super._mint(_to, _tokenId); tokens.push(_tokenId); idToIndex[_tokenId] = tokens.length - 1; }
/** * @dev Mints a new NFT. * @notice This is an internal function which should be called from user-implemented external * mint function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _to The address that will own the minted NFT. * @param _tokenId of the NFT to be minted by the msg.sender. */
NatSpecMultiLine
v0.6.2+commit.bacdbe57
MIT
ipfs://6626fd920334c84d658057cbe16dd3b47b41fc7475707238fefa241a53c0a511
{ "func_code_index": [ 4982, 5203 ] }
881
EmblemVault
browser/github/0xcert/ethereum-erc721/src/contracts/tokens/nf-token-enumerable-metadata.sol
0x82c7a8f707110f5fbb16184a5933e9f78a34c6ab
Solidity
NFTokenEnumerableMetadata
abstract contract NFTokenEnumerableMetadata is NFToken, ERC721Metadata, ERC721Enumerable { /** * @dev A descriptive name for a collection of NFTs. */ string internal nftName; /** * @dev An abbreviated name for NFTokens. */ string internal nftSymbol; /** * @dev An uri to represent the metadata for this contract. */ string internal nftContractMetadataUri; /** * @dev Mapping from NFT ID to metadata uri. */ mapping (uint256 => string) internal idToUri; /** * @dev Mapping from NFT ID to encrypted value. */ mapping (uint256 => string) internal idToPayload; /** * @dev Contract constructor. * @notice When implementing this contract don't forget to set nftName and nftSymbol. */ constructor() public { supportedInterfaces[0x5b5e139f] = true; // ERC721Metadata supportedInterfaces[0x780e9d63] = true; // ERC721Enumerable } /** * @dev Returns a descriptive name for a collection of NFTokens. * @return _name Representing name. */ function name() external override view returns (string memory _name) { _name = nftName; } /** * @dev Returns an abbreviated name for NFTokens. * @return _symbol Representing symbol. */ function symbol() external override view returns (string memory _symbol) { _symbol = nftSymbol; } /** * @dev A distinct URI (RFC 3986) for a given NFT. * @param _tokenId Id for which we want uri. * @return URI of _tokenId. */ function tokenURI( uint256 _tokenId ) external override view validNFToken(_tokenId) returns (string memory) { return idToUri[_tokenId]; } /** * @dev A distinct URI (RFC 3986) for a given NFT. * @param _tokenId Id for which we want uri. * @return URI of _tokenId. */ function tokenPayload( uint256 _tokenId ) external view validNFToken(_tokenId) returns (string memory) { return idToPayload[_tokenId]; } /** * @dev Set a distinct URI (RFC 3986) for a given NFT ID. * @notice This is an internal function which should be called from user-implemented external * function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _tokenId Id for which we want URI. * @param _uri String representing RFC 3986 URI. */ function _setTokenUri( uint256 _tokenId, string memory _uri ) internal validNFToken(_tokenId) { idToUri[_tokenId] = _uri; } function _setTokenPayload( uint256 _tokenId, string memory _uri ) internal validNFToken(_tokenId) { idToPayload[_tokenId] = _uri; } /** * List of revert message codes. Implementing dApp should handle showing the correct message. * Based on 0xcert framework error codes. */ string constant INVALID_INDEX = "005007"; /** * @dev Array of all NFT IDs. */ uint256[] internal tokens; /** * @dev Mapping from token ID to its index in global tokens array. */ mapping(uint256 => uint256) internal idToIndex; /** * @dev Mapping from owner to list of owned NFT IDs. */ mapping(address => uint256[]) internal ownerToIds; /** * @dev Mapping from NFT ID to its index in the owner tokens list. */ mapping(uint256 => uint256) internal idToOwnerIndex; /** * @dev Returns the count of all existing NFTokens. * @return Total supply of NFTs. */ function totalSupply() external override view returns (uint256) { return tokens.length; } /** * @dev Returns NFT ID by its index. * @param _index A counter less than `totalSupply()`. * @return Token id. */ function tokenByIndex( uint256 _index ) external override view returns (uint256) { require(_index < tokens.length, INVALID_INDEX); return tokens[_index]; } /** * @dev returns the n-th NFT ID from a list of owner's tokens. * @param _owner Token owner's address. * @param _index Index number representing n-th token in owner's list of tokens. * @return Token id. */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) external override view returns (uint256) { require(_index < ownerToIds[_owner].length, INVALID_INDEX); return ownerToIds[_owner][_index]; } /** * @dev Mints a new NFT. * @notice This is an internal function which should be called from user-implemented external * mint function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _to The address that will own the minted NFT. * @param _tokenId of the NFT to be minted by the msg.sender. */ function _mint( address _to, uint256 _tokenId ) internal override virtual { super._mint(_to, _tokenId); tokens.push(_tokenId); idToIndex[_tokenId] = tokens.length - 1; } /** * @dev Burns a NFT. * @notice This is an internal function which should be called from user-implemented external * burn function. Its purpose is to show and properly initialize data structures when using this * implementation. Also, note that this burn implementation allows the minter to re-mint a burned * NFT. * @param _tokenId ID of the NFT to be burned. */ function _burn( uint256 _tokenId ) internal override virtual { super._burn(_tokenId); if (bytes(idToUri[_tokenId]).length != 0) { delete idToUri[_tokenId]; } if (bytes(idToPayload[_tokenId]).length != 0) { delete idToPayload[_tokenId]; } uint256 tokenIndex = idToIndex[_tokenId]; uint256 lastTokenIndex = tokens.length - 1; uint256 lastToken = tokens[lastTokenIndex]; tokens[tokenIndex] = lastToken; tokens.pop(); // This wastes gas if you are burning the last token but saves a little gas if you are not. idToIndex[lastToken] = tokenIndex; idToIndex[_tokenId] = 0; } /** * @dev Removes a NFT from an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _from Address from wich we want to remove the NFT. * @param _tokenId Which NFT we want to remove. */ function _removeNFToken( address _from, uint256 _tokenId ) internal override virtual { require(idToOwner[_tokenId] == _from, NOT_OWNER); delete idToOwner[_tokenId]; uint256 tokenToRemoveIndex = idToOwnerIndex[_tokenId]; uint256 lastTokenIndex = ownerToIds[_from].length - 1; if (lastTokenIndex != tokenToRemoveIndex) { uint256 lastToken = ownerToIds[_from][lastTokenIndex]; ownerToIds[_from][tokenToRemoveIndex] = lastToken; idToOwnerIndex[lastToken] = tokenToRemoveIndex; } ownerToIds[_from].pop(); } /** * @dev Assignes a new NFT to an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _to Address to wich we want to add the NFT. * @param _tokenId Which NFT we want to add. */ function _addNFToken( address _to, uint256 _tokenId ) internal override virtual { require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS); idToOwner[_tokenId] = _to; ownerToIds[_to].push(_tokenId); idToOwnerIndex[_tokenId] = ownerToIds[_to].length - 1; } /** * @dev Helper function that gets NFT count of owner. This is needed for overriding in enumerable * extension to remove double storage(gas optimization) of owner nft count. * @param _owner Address for whom to query the count. * @return Number of _owner NFTs. */ function _getOwnerNFTCount( address _owner ) internal override virtual view returns (uint256) { return ownerToIds[_owner].length; } }
/** * @dev Optional metadata implementation for ERC-721 non-fungible token standard. */
NatSpecMultiLine
_burn
function _burn( uint256 _tokenId ) internal override virtual { super._burn(_tokenId); if (bytes(idToUri[_tokenId]).length != 0) { delete idToUri[_tokenId]; } if (bytes(idToPayload[_tokenId]).length != 0) { delete idToPayload[_tokenId]; } uint256 tokenIndex = idToIndex[_tokenId]; uint256 lastTokenIndex = tokens.length - 1; uint256 lastToken = tokens[lastTokenIndex]; tokens[tokenIndex] = lastToken; tokens.pop(); // This wastes gas if you are burning the last token but saves a little gas if you are not. idToIndex[lastToken] = tokenIndex; idToIndex[_tokenId] = 0; }
/** * @dev Burns a NFT. * @notice This is an internal function which should be called from user-implemented external * burn function. Its purpose is to show and properly initialize data structures when using this * implementation. Also, note that this burn implementation allows the minter to re-mint a burned * NFT. * @param _tokenId ID of the NFT to be burned. */
NatSpecMultiLine
v0.6.2+commit.bacdbe57
MIT
ipfs://6626fd920334c84d658057cbe16dd3b47b41fc7475707238fefa241a53c0a511
{ "func_code_index": [ 5603, 6313 ] }
882
EmblemVault
browser/github/0xcert/ethereum-erc721/src/contracts/tokens/nf-token-enumerable-metadata.sol
0x82c7a8f707110f5fbb16184a5933e9f78a34c6ab
Solidity
NFTokenEnumerableMetadata
abstract contract NFTokenEnumerableMetadata is NFToken, ERC721Metadata, ERC721Enumerable { /** * @dev A descriptive name for a collection of NFTs. */ string internal nftName; /** * @dev An abbreviated name for NFTokens. */ string internal nftSymbol; /** * @dev An uri to represent the metadata for this contract. */ string internal nftContractMetadataUri; /** * @dev Mapping from NFT ID to metadata uri. */ mapping (uint256 => string) internal idToUri; /** * @dev Mapping from NFT ID to encrypted value. */ mapping (uint256 => string) internal idToPayload; /** * @dev Contract constructor. * @notice When implementing this contract don't forget to set nftName and nftSymbol. */ constructor() public { supportedInterfaces[0x5b5e139f] = true; // ERC721Metadata supportedInterfaces[0x780e9d63] = true; // ERC721Enumerable } /** * @dev Returns a descriptive name for a collection of NFTokens. * @return _name Representing name. */ function name() external override view returns (string memory _name) { _name = nftName; } /** * @dev Returns an abbreviated name for NFTokens. * @return _symbol Representing symbol. */ function symbol() external override view returns (string memory _symbol) { _symbol = nftSymbol; } /** * @dev A distinct URI (RFC 3986) for a given NFT. * @param _tokenId Id for which we want uri. * @return URI of _tokenId. */ function tokenURI( uint256 _tokenId ) external override view validNFToken(_tokenId) returns (string memory) { return idToUri[_tokenId]; } /** * @dev A distinct URI (RFC 3986) for a given NFT. * @param _tokenId Id for which we want uri. * @return URI of _tokenId. */ function tokenPayload( uint256 _tokenId ) external view validNFToken(_tokenId) returns (string memory) { return idToPayload[_tokenId]; } /** * @dev Set a distinct URI (RFC 3986) for a given NFT ID. * @notice This is an internal function which should be called from user-implemented external * function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _tokenId Id for which we want URI. * @param _uri String representing RFC 3986 URI. */ function _setTokenUri( uint256 _tokenId, string memory _uri ) internal validNFToken(_tokenId) { idToUri[_tokenId] = _uri; } function _setTokenPayload( uint256 _tokenId, string memory _uri ) internal validNFToken(_tokenId) { idToPayload[_tokenId] = _uri; } /** * List of revert message codes. Implementing dApp should handle showing the correct message. * Based on 0xcert framework error codes. */ string constant INVALID_INDEX = "005007"; /** * @dev Array of all NFT IDs. */ uint256[] internal tokens; /** * @dev Mapping from token ID to its index in global tokens array. */ mapping(uint256 => uint256) internal idToIndex; /** * @dev Mapping from owner to list of owned NFT IDs. */ mapping(address => uint256[]) internal ownerToIds; /** * @dev Mapping from NFT ID to its index in the owner tokens list. */ mapping(uint256 => uint256) internal idToOwnerIndex; /** * @dev Returns the count of all existing NFTokens. * @return Total supply of NFTs. */ function totalSupply() external override view returns (uint256) { return tokens.length; } /** * @dev Returns NFT ID by its index. * @param _index A counter less than `totalSupply()`. * @return Token id. */ function tokenByIndex( uint256 _index ) external override view returns (uint256) { require(_index < tokens.length, INVALID_INDEX); return tokens[_index]; } /** * @dev returns the n-th NFT ID from a list of owner's tokens. * @param _owner Token owner's address. * @param _index Index number representing n-th token in owner's list of tokens. * @return Token id. */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) external override view returns (uint256) { require(_index < ownerToIds[_owner].length, INVALID_INDEX); return ownerToIds[_owner][_index]; } /** * @dev Mints a new NFT. * @notice This is an internal function which should be called from user-implemented external * mint function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _to The address that will own the minted NFT. * @param _tokenId of the NFT to be minted by the msg.sender. */ function _mint( address _to, uint256 _tokenId ) internal override virtual { super._mint(_to, _tokenId); tokens.push(_tokenId); idToIndex[_tokenId] = tokens.length - 1; } /** * @dev Burns a NFT. * @notice This is an internal function which should be called from user-implemented external * burn function. Its purpose is to show and properly initialize data structures when using this * implementation. Also, note that this burn implementation allows the minter to re-mint a burned * NFT. * @param _tokenId ID of the NFT to be burned. */ function _burn( uint256 _tokenId ) internal override virtual { super._burn(_tokenId); if (bytes(idToUri[_tokenId]).length != 0) { delete idToUri[_tokenId]; } if (bytes(idToPayload[_tokenId]).length != 0) { delete idToPayload[_tokenId]; } uint256 tokenIndex = idToIndex[_tokenId]; uint256 lastTokenIndex = tokens.length - 1; uint256 lastToken = tokens[lastTokenIndex]; tokens[tokenIndex] = lastToken; tokens.pop(); // This wastes gas if you are burning the last token but saves a little gas if you are not. idToIndex[lastToken] = tokenIndex; idToIndex[_tokenId] = 0; } /** * @dev Removes a NFT from an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _from Address from wich we want to remove the NFT. * @param _tokenId Which NFT we want to remove. */ function _removeNFToken( address _from, uint256 _tokenId ) internal override virtual { require(idToOwner[_tokenId] == _from, NOT_OWNER); delete idToOwner[_tokenId]; uint256 tokenToRemoveIndex = idToOwnerIndex[_tokenId]; uint256 lastTokenIndex = ownerToIds[_from].length - 1; if (lastTokenIndex != tokenToRemoveIndex) { uint256 lastToken = ownerToIds[_from][lastTokenIndex]; ownerToIds[_from][tokenToRemoveIndex] = lastToken; idToOwnerIndex[lastToken] = tokenToRemoveIndex; } ownerToIds[_from].pop(); } /** * @dev Assignes a new NFT to an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _to Address to wich we want to add the NFT. * @param _tokenId Which NFT we want to add. */ function _addNFToken( address _to, uint256 _tokenId ) internal override virtual { require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS); idToOwner[_tokenId] = _to; ownerToIds[_to].push(_tokenId); idToOwnerIndex[_tokenId] = ownerToIds[_to].length - 1; } /** * @dev Helper function that gets NFT count of owner. This is needed for overriding in enumerable * extension to remove double storage(gas optimization) of owner nft count. * @param _owner Address for whom to query the count. * @return Number of _owner NFTs. */ function _getOwnerNFTCount( address _owner ) internal override virtual view returns (uint256) { return ownerToIds[_owner].length; } }
/** * @dev Optional metadata implementation for ERC-721 non-fungible token standard. */
NatSpecMultiLine
_removeNFToken
function _removeNFToken( address _from, uint256 _tokenId ) internal override virtual { require(idToOwner[_tokenId] == _from, NOT_OWNER); delete idToOwner[_tokenId]; uint256 tokenToRemoveIndex = idToOwnerIndex[_tokenId]; uint256 lastTokenIndex = ownerToIds[_from].length - 1; if (lastTokenIndex != tokenToRemoveIndex) { uint256 lastToken = ownerToIds[_from][lastTokenIndex]; ownerToIds[_from][tokenToRemoveIndex] = lastToken; idToOwnerIndex[lastToken] = tokenToRemoveIndex; } ownerToIds[_from].pop(); }
/** * @dev Removes a NFT from an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _from Address from wich we want to remove the NFT. * @param _tokenId Which NFT we want to remove. */
NatSpecMultiLine
v0.6.2+commit.bacdbe57
MIT
ipfs://6626fd920334c84d658057cbe16dd3b47b41fc7475707238fefa241a53c0a511
{ "func_code_index": [ 6589, 7194 ] }
883
EmblemVault
browser/github/0xcert/ethereum-erc721/src/contracts/tokens/nf-token-enumerable-metadata.sol
0x82c7a8f707110f5fbb16184a5933e9f78a34c6ab
Solidity
NFTokenEnumerableMetadata
abstract contract NFTokenEnumerableMetadata is NFToken, ERC721Metadata, ERC721Enumerable { /** * @dev A descriptive name for a collection of NFTs. */ string internal nftName; /** * @dev An abbreviated name for NFTokens. */ string internal nftSymbol; /** * @dev An uri to represent the metadata for this contract. */ string internal nftContractMetadataUri; /** * @dev Mapping from NFT ID to metadata uri. */ mapping (uint256 => string) internal idToUri; /** * @dev Mapping from NFT ID to encrypted value. */ mapping (uint256 => string) internal idToPayload; /** * @dev Contract constructor. * @notice When implementing this contract don't forget to set nftName and nftSymbol. */ constructor() public { supportedInterfaces[0x5b5e139f] = true; // ERC721Metadata supportedInterfaces[0x780e9d63] = true; // ERC721Enumerable } /** * @dev Returns a descriptive name for a collection of NFTokens. * @return _name Representing name. */ function name() external override view returns (string memory _name) { _name = nftName; } /** * @dev Returns an abbreviated name for NFTokens. * @return _symbol Representing symbol. */ function symbol() external override view returns (string memory _symbol) { _symbol = nftSymbol; } /** * @dev A distinct URI (RFC 3986) for a given NFT. * @param _tokenId Id for which we want uri. * @return URI of _tokenId. */ function tokenURI( uint256 _tokenId ) external override view validNFToken(_tokenId) returns (string memory) { return idToUri[_tokenId]; } /** * @dev A distinct URI (RFC 3986) for a given NFT. * @param _tokenId Id for which we want uri. * @return URI of _tokenId. */ function tokenPayload( uint256 _tokenId ) external view validNFToken(_tokenId) returns (string memory) { return idToPayload[_tokenId]; } /** * @dev Set a distinct URI (RFC 3986) for a given NFT ID. * @notice This is an internal function which should be called from user-implemented external * function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _tokenId Id for which we want URI. * @param _uri String representing RFC 3986 URI. */ function _setTokenUri( uint256 _tokenId, string memory _uri ) internal validNFToken(_tokenId) { idToUri[_tokenId] = _uri; } function _setTokenPayload( uint256 _tokenId, string memory _uri ) internal validNFToken(_tokenId) { idToPayload[_tokenId] = _uri; } /** * List of revert message codes. Implementing dApp should handle showing the correct message. * Based on 0xcert framework error codes. */ string constant INVALID_INDEX = "005007"; /** * @dev Array of all NFT IDs. */ uint256[] internal tokens; /** * @dev Mapping from token ID to its index in global tokens array. */ mapping(uint256 => uint256) internal idToIndex; /** * @dev Mapping from owner to list of owned NFT IDs. */ mapping(address => uint256[]) internal ownerToIds; /** * @dev Mapping from NFT ID to its index in the owner tokens list. */ mapping(uint256 => uint256) internal idToOwnerIndex; /** * @dev Returns the count of all existing NFTokens. * @return Total supply of NFTs. */ function totalSupply() external override view returns (uint256) { return tokens.length; } /** * @dev Returns NFT ID by its index. * @param _index A counter less than `totalSupply()`. * @return Token id. */ function tokenByIndex( uint256 _index ) external override view returns (uint256) { require(_index < tokens.length, INVALID_INDEX); return tokens[_index]; } /** * @dev returns the n-th NFT ID from a list of owner's tokens. * @param _owner Token owner's address. * @param _index Index number representing n-th token in owner's list of tokens. * @return Token id. */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) external override view returns (uint256) { require(_index < ownerToIds[_owner].length, INVALID_INDEX); return ownerToIds[_owner][_index]; } /** * @dev Mints a new NFT. * @notice This is an internal function which should be called from user-implemented external * mint function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _to The address that will own the minted NFT. * @param _tokenId of the NFT to be minted by the msg.sender. */ function _mint( address _to, uint256 _tokenId ) internal override virtual { super._mint(_to, _tokenId); tokens.push(_tokenId); idToIndex[_tokenId] = tokens.length - 1; } /** * @dev Burns a NFT. * @notice This is an internal function which should be called from user-implemented external * burn function. Its purpose is to show and properly initialize data structures when using this * implementation. Also, note that this burn implementation allows the minter to re-mint a burned * NFT. * @param _tokenId ID of the NFT to be burned. */ function _burn( uint256 _tokenId ) internal override virtual { super._burn(_tokenId); if (bytes(idToUri[_tokenId]).length != 0) { delete idToUri[_tokenId]; } if (bytes(idToPayload[_tokenId]).length != 0) { delete idToPayload[_tokenId]; } uint256 tokenIndex = idToIndex[_tokenId]; uint256 lastTokenIndex = tokens.length - 1; uint256 lastToken = tokens[lastTokenIndex]; tokens[tokenIndex] = lastToken; tokens.pop(); // This wastes gas if you are burning the last token but saves a little gas if you are not. idToIndex[lastToken] = tokenIndex; idToIndex[_tokenId] = 0; } /** * @dev Removes a NFT from an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _from Address from wich we want to remove the NFT. * @param _tokenId Which NFT we want to remove. */ function _removeNFToken( address _from, uint256 _tokenId ) internal override virtual { require(idToOwner[_tokenId] == _from, NOT_OWNER); delete idToOwner[_tokenId]; uint256 tokenToRemoveIndex = idToOwnerIndex[_tokenId]; uint256 lastTokenIndex = ownerToIds[_from].length - 1; if (lastTokenIndex != tokenToRemoveIndex) { uint256 lastToken = ownerToIds[_from][lastTokenIndex]; ownerToIds[_from][tokenToRemoveIndex] = lastToken; idToOwnerIndex[lastToken] = tokenToRemoveIndex; } ownerToIds[_from].pop(); } /** * @dev Assignes a new NFT to an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _to Address to wich we want to add the NFT. * @param _tokenId Which NFT we want to add. */ function _addNFToken( address _to, uint256 _tokenId ) internal override virtual { require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS); idToOwner[_tokenId] = _to; ownerToIds[_to].push(_tokenId); idToOwnerIndex[_tokenId] = ownerToIds[_to].length - 1; } /** * @dev Helper function that gets NFT count of owner. This is needed for overriding in enumerable * extension to remove double storage(gas optimization) of owner nft count. * @param _owner Address for whom to query the count. * @return Number of _owner NFTs. */ function _getOwnerNFTCount( address _owner ) internal override virtual view returns (uint256) { return ownerToIds[_owner].length; } }
/** * @dev Optional metadata implementation for ERC-721 non-fungible token standard. */
NatSpecMultiLine
_addNFToken
function _addNFToken( address _to, uint256 _tokenId ) internal override virtual { require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS); idToOwner[_tokenId] = _to; ownerToIds[_to].push(_tokenId); idToOwnerIndex[_tokenId] = ownerToIds[_to].length - 1; }
/** * @dev Assignes a new NFT to an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _to Address to wich we want to add the NFT. * @param _tokenId Which NFT we want to add. */
NatSpecMultiLine
v0.6.2+commit.bacdbe57
MIT
ipfs://6626fd920334c84d658057cbe16dd3b47b41fc7475707238fefa241a53c0a511
{ "func_code_index": [ 7463, 7783 ] }
884
EmblemVault
browser/github/0xcert/ethereum-erc721/src/contracts/tokens/nf-token-enumerable-metadata.sol
0x82c7a8f707110f5fbb16184a5933e9f78a34c6ab
Solidity
NFTokenEnumerableMetadata
abstract contract NFTokenEnumerableMetadata is NFToken, ERC721Metadata, ERC721Enumerable { /** * @dev A descriptive name for a collection of NFTs. */ string internal nftName; /** * @dev An abbreviated name for NFTokens. */ string internal nftSymbol; /** * @dev An uri to represent the metadata for this contract. */ string internal nftContractMetadataUri; /** * @dev Mapping from NFT ID to metadata uri. */ mapping (uint256 => string) internal idToUri; /** * @dev Mapping from NFT ID to encrypted value. */ mapping (uint256 => string) internal idToPayload; /** * @dev Contract constructor. * @notice When implementing this contract don't forget to set nftName and nftSymbol. */ constructor() public { supportedInterfaces[0x5b5e139f] = true; // ERC721Metadata supportedInterfaces[0x780e9d63] = true; // ERC721Enumerable } /** * @dev Returns a descriptive name for a collection of NFTokens. * @return _name Representing name. */ function name() external override view returns (string memory _name) { _name = nftName; } /** * @dev Returns an abbreviated name for NFTokens. * @return _symbol Representing symbol. */ function symbol() external override view returns (string memory _symbol) { _symbol = nftSymbol; } /** * @dev A distinct URI (RFC 3986) for a given NFT. * @param _tokenId Id for which we want uri. * @return URI of _tokenId. */ function tokenURI( uint256 _tokenId ) external override view validNFToken(_tokenId) returns (string memory) { return idToUri[_tokenId]; } /** * @dev A distinct URI (RFC 3986) for a given NFT. * @param _tokenId Id for which we want uri. * @return URI of _tokenId. */ function tokenPayload( uint256 _tokenId ) external view validNFToken(_tokenId) returns (string memory) { return idToPayload[_tokenId]; } /** * @dev Set a distinct URI (RFC 3986) for a given NFT ID. * @notice This is an internal function which should be called from user-implemented external * function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _tokenId Id for which we want URI. * @param _uri String representing RFC 3986 URI. */ function _setTokenUri( uint256 _tokenId, string memory _uri ) internal validNFToken(_tokenId) { idToUri[_tokenId] = _uri; } function _setTokenPayload( uint256 _tokenId, string memory _uri ) internal validNFToken(_tokenId) { idToPayload[_tokenId] = _uri; } /** * List of revert message codes. Implementing dApp should handle showing the correct message. * Based on 0xcert framework error codes. */ string constant INVALID_INDEX = "005007"; /** * @dev Array of all NFT IDs. */ uint256[] internal tokens; /** * @dev Mapping from token ID to its index in global tokens array. */ mapping(uint256 => uint256) internal idToIndex; /** * @dev Mapping from owner to list of owned NFT IDs. */ mapping(address => uint256[]) internal ownerToIds; /** * @dev Mapping from NFT ID to its index in the owner tokens list. */ mapping(uint256 => uint256) internal idToOwnerIndex; /** * @dev Returns the count of all existing NFTokens. * @return Total supply of NFTs. */ function totalSupply() external override view returns (uint256) { return tokens.length; } /** * @dev Returns NFT ID by its index. * @param _index A counter less than `totalSupply()`. * @return Token id. */ function tokenByIndex( uint256 _index ) external override view returns (uint256) { require(_index < tokens.length, INVALID_INDEX); return tokens[_index]; } /** * @dev returns the n-th NFT ID from a list of owner's tokens. * @param _owner Token owner's address. * @param _index Index number representing n-th token in owner's list of tokens. * @return Token id. */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) external override view returns (uint256) { require(_index < ownerToIds[_owner].length, INVALID_INDEX); return ownerToIds[_owner][_index]; } /** * @dev Mints a new NFT. * @notice This is an internal function which should be called from user-implemented external * mint function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _to The address that will own the minted NFT. * @param _tokenId of the NFT to be minted by the msg.sender. */ function _mint( address _to, uint256 _tokenId ) internal override virtual { super._mint(_to, _tokenId); tokens.push(_tokenId); idToIndex[_tokenId] = tokens.length - 1; } /** * @dev Burns a NFT. * @notice This is an internal function which should be called from user-implemented external * burn function. Its purpose is to show and properly initialize data structures when using this * implementation. Also, note that this burn implementation allows the minter to re-mint a burned * NFT. * @param _tokenId ID of the NFT to be burned. */ function _burn( uint256 _tokenId ) internal override virtual { super._burn(_tokenId); if (bytes(idToUri[_tokenId]).length != 0) { delete idToUri[_tokenId]; } if (bytes(idToPayload[_tokenId]).length != 0) { delete idToPayload[_tokenId]; } uint256 tokenIndex = idToIndex[_tokenId]; uint256 lastTokenIndex = tokens.length - 1; uint256 lastToken = tokens[lastTokenIndex]; tokens[tokenIndex] = lastToken; tokens.pop(); // This wastes gas if you are burning the last token but saves a little gas if you are not. idToIndex[lastToken] = tokenIndex; idToIndex[_tokenId] = 0; } /** * @dev Removes a NFT from an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _from Address from wich we want to remove the NFT. * @param _tokenId Which NFT we want to remove. */ function _removeNFToken( address _from, uint256 _tokenId ) internal override virtual { require(idToOwner[_tokenId] == _from, NOT_OWNER); delete idToOwner[_tokenId]; uint256 tokenToRemoveIndex = idToOwnerIndex[_tokenId]; uint256 lastTokenIndex = ownerToIds[_from].length - 1; if (lastTokenIndex != tokenToRemoveIndex) { uint256 lastToken = ownerToIds[_from][lastTokenIndex]; ownerToIds[_from][tokenToRemoveIndex] = lastToken; idToOwnerIndex[lastToken] = tokenToRemoveIndex; } ownerToIds[_from].pop(); } /** * @dev Assignes a new NFT to an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _to Address to wich we want to add the NFT. * @param _tokenId Which NFT we want to add. */ function _addNFToken( address _to, uint256 _tokenId ) internal override virtual { require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS); idToOwner[_tokenId] = _to; ownerToIds[_to].push(_tokenId); idToOwnerIndex[_tokenId] = ownerToIds[_to].length - 1; } /** * @dev Helper function that gets NFT count of owner. This is needed for overriding in enumerable * extension to remove double storage(gas optimization) of owner nft count. * @param _owner Address for whom to query the count. * @return Number of _owner NFTs. */ function _getOwnerNFTCount( address _owner ) internal override virtual view returns (uint256) { return ownerToIds[_owner].length; } }
/** * @dev Optional metadata implementation for ERC-721 non-fungible token standard. */
NatSpecMultiLine
_getOwnerNFTCount
function _getOwnerNFTCount( address _owner ) internal override virtual view returns (uint256) { return ownerToIds[_owner].length; }
/** * @dev Helper function that gets NFT count of owner. This is needed for overriding in enumerable * extension to remove double storage(gas optimization) of owner nft count. * @param _owner Address for whom to query the count. * @return Number of _owner NFTs. */
NatSpecMultiLine
v0.6.2+commit.bacdbe57
MIT
ipfs://6626fd920334c84d658057cbe16dd3b47b41fc7475707238fefa241a53c0a511
{ "func_code_index": [ 8074, 8252 ] }
885
YeFiMpool1
YeFiMpool1.sol
0x2bf30d058230ec127735c6bf444c49039aa7c243
Solidity
EnumerableSet
library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } }
/** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */
NatSpecMultiLine
_add
function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } }
/** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */
NatSpecMultiLine
v0.6.12+commit.27d51765
BSD-3-Clause
ipfs://202a02b2d591eacb8a21c8ff0334701d4451d0e29051d04d29532fe3bf0bdecd
{ "func_code_index": [ 908, 1327 ] }
886
YeFiMpool1
YeFiMpool1.sol
0x2bf30d058230ec127735c6bf444c49039aa7c243
Solidity
EnumerableSet
library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } }
/** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */
NatSpecMultiLine
_remove
function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } }
/** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */
NatSpecMultiLine
v0.6.12+commit.27d51765
BSD-3-Clause
ipfs://202a02b2d591eacb8a21c8ff0334701d4451d0e29051d04d29532fe3bf0bdecd
{ "func_code_index": [ 1498, 3047 ] }
887
YeFiMpool1
YeFiMpool1.sol
0x2bf30d058230ec127735c6bf444c49039aa7c243
Solidity
EnumerableSet
library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } }
/** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */
NatSpecMultiLine
_contains
function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; }
/** * @dev Returns true if the value is in the set. O(1). */
NatSpecMultiLine
v0.6.12+commit.27d51765
BSD-3-Clause
ipfs://202a02b2d591eacb8a21c8ff0334701d4451d0e29051d04d29532fe3bf0bdecd
{ "func_code_index": [ 3128, 3262 ] }
888
YeFiMpool1
YeFiMpool1.sol
0x2bf30d058230ec127735c6bf444c49039aa7c243
Solidity
EnumerableSet
library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } }
/** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */
NatSpecMultiLine
_length
function _length(Set storage set) private view returns (uint256) { return set._values.length; }
/** * @dev Returns the number of values on the set. O(1). */
NatSpecMultiLine
v0.6.12+commit.27d51765
BSD-3-Clause
ipfs://202a02b2d591eacb8a21c8ff0334701d4451d0e29051d04d29532fe3bf0bdecd
{ "func_code_index": [ 3343, 3457 ] }
889
YeFiMpool1
YeFiMpool1.sol
0x2bf30d058230ec127735c6bf444c49039aa7c243
Solidity
EnumerableSet
library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } }
/** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */
NatSpecMultiLine
_at
function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; }
/** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */
NatSpecMultiLine
v0.6.12+commit.27d51765
BSD-3-Clause
ipfs://202a02b2d591eacb8a21c8ff0334701d4451d0e29051d04d29532fe3bf0bdecd
{ "func_code_index": [ 3796, 4005 ] }
890
YeFiMpool1
YeFiMpool1.sol
0x2bf30d058230ec127735c6bf444c49039aa7c243
Solidity
EnumerableSet
library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } }
/** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */
NatSpecMultiLine
add
function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); }
/** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */
NatSpecMultiLine
v0.6.12+commit.27d51765
BSD-3-Clause
ipfs://202a02b2d591eacb8a21c8ff0334701d4451d0e29051d04d29532fe3bf0bdecd
{ "func_code_index": [ 4254, 4402 ] }
891
YeFiMpool1
YeFiMpool1.sol
0x2bf30d058230ec127735c6bf444c49039aa7c243
Solidity
EnumerableSet
library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } }
/** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */
NatSpecMultiLine
remove
function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); }
/** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */
NatSpecMultiLine
v0.6.12+commit.27d51765
BSD-3-Clause
ipfs://202a02b2d591eacb8a21c8ff0334701d4451d0e29051d04d29532fe3bf0bdecd
{ "func_code_index": [ 4573, 4727 ] }
892
YeFiMpool1
YeFiMpool1.sol
0x2bf30d058230ec127735c6bf444c49039aa7c243
Solidity
EnumerableSet
library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } }
/** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */
NatSpecMultiLine
contains
function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); }
/** * @dev Returns true if the value is in the set. O(1). */
NatSpecMultiLine
v0.6.12+commit.27d51765
BSD-3-Clause
ipfs://202a02b2d591eacb8a21c8ff0334701d4451d0e29051d04d29532fe3bf0bdecd
{ "func_code_index": [ 4808, 4971 ] }
893
YeFiMpool1
YeFiMpool1.sol
0x2bf30d058230ec127735c6bf444c49039aa7c243
Solidity
EnumerableSet
library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } }
/** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */
NatSpecMultiLine
length
function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); }
/** * @dev Returns the number of values in the set. O(1). */
NatSpecMultiLine
v0.6.12+commit.27d51765
BSD-3-Clause
ipfs://202a02b2d591eacb8a21c8ff0334701d4451d0e29051d04d29532fe3bf0bdecd
{ "func_code_index": [ 5052, 5174 ] }
894
YeFiMpool1
YeFiMpool1.sol
0x2bf30d058230ec127735c6bf444c49039aa7c243
Solidity
EnumerableSet
library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } }
/** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */
NatSpecMultiLine
at
function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); }
/** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */
NatSpecMultiLine
v0.6.12+commit.27d51765
BSD-3-Clause
ipfs://202a02b2d591eacb8a21c8ff0334701d4451d0e29051d04d29532fe3bf0bdecd
{ "func_code_index": [ 5513, 5667 ] }
895
YeFiMpool1
YeFiMpool1.sol
0x2bf30d058230ec127735c6bf444c49039aa7c243
Solidity
EnumerableSet
library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } }
/** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */
NatSpecMultiLine
add
function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); }
/** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */
NatSpecMultiLine
v0.6.12+commit.27d51765
BSD-3-Clause
ipfs://202a02b2d591eacb8a21c8ff0334701d4451d0e29051d04d29532fe3bf0bdecd
{ "func_code_index": [ 5912, 6048 ] }
896
YeFiMpool1
YeFiMpool1.sol
0x2bf30d058230ec127735c6bf444c49039aa7c243
Solidity
EnumerableSet
library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } }
/** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */
NatSpecMultiLine
remove
function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); }
/** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */
NatSpecMultiLine
v0.6.12+commit.27d51765
BSD-3-Clause
ipfs://202a02b2d591eacb8a21c8ff0334701d4451d0e29051d04d29532fe3bf0bdecd
{ "func_code_index": [ 6219, 6361 ] }
897
YeFiMpool1
YeFiMpool1.sol
0x2bf30d058230ec127735c6bf444c49039aa7c243
Solidity
EnumerableSet
library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } }
/** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */
NatSpecMultiLine
contains
function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); }
/** * @dev Returns true if the value is in the set. O(1). */
NatSpecMultiLine
v0.6.12+commit.27d51765
BSD-3-Clause
ipfs://202a02b2d591eacb8a21c8ff0334701d4451d0e29051d04d29532fe3bf0bdecd
{ "func_code_index": [ 6442, 6593 ] }
898
YeFiMpool1
YeFiMpool1.sol
0x2bf30d058230ec127735c6bf444c49039aa7c243
Solidity
EnumerableSet
library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } }
/** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */
NatSpecMultiLine
length
function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); }
/** * @dev Returns the number of values on the set. O(1). */
NatSpecMultiLine
v0.6.12+commit.27d51765
BSD-3-Clause
ipfs://202a02b2d591eacb8a21c8ff0334701d4451d0e29051d04d29532fe3bf0bdecd
{ "func_code_index": [ 6674, 6793 ] }
899