Unnamed: 0
int64
0
7.36k
comments
stringlengths
3
35.2k
code_string
stringlengths
1
527k
code
stringlengths
1
527k
__index_level_0__
int64
0
88.6k
214
// Makes an arbitrary call with the VaultProxy contract as the sender/_contract The contract to call/_selector The selector to call/_encodedArgs The encoded arguments for the call/ return returnData_ The data returned by the call
function vaultCallOnContract( address _contract, bytes4 _selector, bytes calldata _encodedArgs
function vaultCallOnContract( address _contract, bytes4 _selector, bytes calldata _encodedArgs
38,715
38
// ========== Internal Functions ========== // Open a new position. return The new position and the ID of the opened position /
function openPosition( uint256 collateralAmount, uint256 borrowAmount ) internal returns (MozartTypes.Position memory, uint256)
function openPosition( uint256 collateralAmount, uint256 borrowAmount ) internal returns (MozartTypes.Position memory, uint256)
49,871
65
// Returns an `Bytes32Slot` with member `value` located at `slot`. /
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } }
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } }
11,943
24
// multiply a UQ112x112 by a uint, returning a UQ144x112reverts on overflow
// function mul(uq112x112 memory self, uint256 y) internal pure returns (uq144x112 memory) { // uint256 z = 0; // require(y == 0 || (z = self._x * y) / y == self._x, 'FixedPoint::mul: overflow'); // return uq144x112(z); // }
// function mul(uq112x112 memory self, uint256 y) internal pure returns (uq144x112 memory) { // uint256 z = 0; // require(y == 0 || (z = self._x * y) / y == self._x, 'FixedPoint::mul: overflow'); // return uq144x112(z); // }
48,622
89
// private view methods/Get actual token price. return price One token price in wei. /
function calcTokenPriceInWei() private view returns(uint256 price)
function calcTokenPriceInWei() private view returns(uint256 price)
41,288
4
// Returns `randomProvider` address. /
function getRandomProvider() external view returns(address) { return _randomProvider; }
function getRandomProvider() external view returns(address) { return _randomProvider; }
19,169
198
// Deposit LP tokens to YFGFinancing for YFGEN allocation.
function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accYFGPerShare).div(1e12).sub(user.rewardDebt); safeYFGTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accYFGPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); }
function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accYFGPerShare).div(1e12).sub(user.rewardDebt); safeYFGTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accYFGPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); }
42,148
17
// This Token is Claimed We need to get you a new one.
id = uint256( nextTokenInOrder( _claimData[i].tokenId, _claimData[i].startRange, _claimData[i].endRange ) ); // Get the replacement token
id = uint256( nextTokenInOrder( _claimData[i].tokenId, _claimData[i].startRange, _claimData[i].endRange ) ); // Get the replacement token
12,074
15
// Raini rewards
_generalRewardVars.rainiRewardPerTokenStored = uint64(rainiRewardPerToken()); _generalRewardVars.lastUpdateTime = uint32(lastTimeRewardApplicable()); if (_owner != address(0)) { uint32 duration = uint32(block.timestamp) - _accountRewardVars.lastUpdated; uint128 reward = calculateReward(_owner, _accountVars.staked, duration); _accountVars.unicornBalance = _accountVars.unicornBalance + reward; _accountRewardVars.lastUpdated = uint32(block.timestamp); _accountRewardVars.lastBonus = uint40(Math.min(maxBonus, _accountRewardVars.lastBonus + bonusRate * duration));
_generalRewardVars.rainiRewardPerTokenStored = uint64(rainiRewardPerToken()); _generalRewardVars.lastUpdateTime = uint32(lastTimeRewardApplicable()); if (_owner != address(0)) { uint32 duration = uint32(block.timestamp) - _accountRewardVars.lastUpdated; uint128 reward = calculateReward(_owner, _accountVars.staked, duration); _accountVars.unicornBalance = _accountVars.unicornBalance + reward; _accountRewardVars.lastUpdated = uint32(block.timestamp); _accountRewardVars.lastBonus = uint40(Math.min(maxBonus, _accountRewardVars.lastBonus + bonusRate * duration));
11,725
111
// Prevents receiving Ether or calls to unsuported methods /
fallback () external { revert("NiftyswapExchange:UNSUPPORTED_METHOD"); }
fallback () external { revert("NiftyswapExchange:UNSUPPORTED_METHOD"); }
23,964
37
// 领取剩余 nest
nestDao.collectNestReward();
nestDao.collectNestReward();
157
12
// Check if we will need to add an extra node
if (nextLevelLength % 2 == 1 && nextLevelLength != 1) { nodes[nextLevelLength] = defaultHashes[currentLevel]; nextLevelLength += 1; }
if (nextLevelLength % 2 == 1 && nextLevelLength != 1) { nodes[nextLevelLength] = defaultHashes[currentLevel]; nextLevelLength += 1; }
6,793
2
// イベント:レジストリ登録
event Registered( address indexed contractAddress, string contractType, address contractOwner );
event Registered( address indexed contractAddress, string contractType, address contractOwner );
52,327
7
// Destination address of gram transfer.
address dest;
address dest;
41,679
29
// MetaSwap - A StableSwap implementation in solidity. This contract is responsible for custody of closely pegged assets (eg. group of stablecoins)and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokensin desired ratios for an exchange of the pool token that represents their share of the pool.Users can burn pool tokens and withdraw their share of token(s). Each time a swap between the pooled tokens happens, a set fee incurs which effectively getsdistributed to the LPs. In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - whichstops the ratio of the tokens
contract MetaSwap is Swap { using MetaSwapUtils for SwapUtils.Swap; MetaSwapUtils.MetaSwap public metaSwapStorage; uint256 constant MAX_UINT256 = 2**256 - 1; /*** EVENTS ***/ // events replicated from SwapUtils to make the ABI easier for dumb // clients event TokenSwapUnderlying( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION_DECIMALS */ function getVirtualPrice() external view virtual override returns (uint256) { return MetaSwapUtils.getVirtualPrice(swapStorage, metaSwapStorage); } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual override returns (uint256) { return MetaSwapUtils.calculateSwap( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx ); } /** * @notice Calculate amount of tokens you receive on swap. For this function, * the token indices are flattened out so that underlying tokens are represented. * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual returns (uint256) { return MetaSwapUtils.calculateSwapUnderlying( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx ); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view virtual override returns (uint256) { return MetaSwapUtils.calculateTokenAmount( swapStorage, metaSwapStorage, amounts, deposit ); } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view virtual override returns (uint256) { return MetaSwapUtils.calculateWithdrawOneToken( swapStorage, metaSwapStorage, tokenAmount, tokenIndex ); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice This overrides Swap's initialize function to prevent initializing * without the address of the base Swap contract. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) public virtual override initializer { revert("use initializeMetaSwap() instead"); } /** * @notice Initializes this MetaSwap contract with the given parameters. * MetaSwap uses an existing Swap pool to expand the available liquidity. * _pooledTokens array should contain the base Swap pool's LP token as * the last element. For example, if there is a Swap pool consisting of * [DAI, USDC, USDT]. Then a MetaSwap pool can be created with [zUSD, BaseSwapLPToken] * as _pooledTokens. * * This will also deploy the LPToken that represents users' * LP position. The owner of LPToken will be this contract - which means * only this contract is allowed to mint new tokens. * * @param _pooledTokens an array of ERC20s this pool will accept. The last * element must be an existing Swap pool's LP token's address. * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with */ function initializeMetaSwap( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress, ISwap baseSwap ) external virtual initializer { Swap.initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, lpTokenTargetAddress ); // MetaSwap initializer metaSwapStorage.baseSwap = baseSwap; metaSwapStorage.baseVirtualPrice = baseSwap.getVirtualPrice(); metaSwapStorage.baseCacheLastUpdated = block.timestamp; // Read all tokens that belong to baseSwap { uint8 i; for (; i < 32; i++) { try baseSwap.getToken(i) returns (IERC20 token) { metaSwapStorage.baseTokens.push(token); token.safeApprove(address(baseSwap), MAX_UINT256); } catch { break; } } require(i > 1, "baseSwap must pool at least 2 tokens"); } // Check the last element of _pooledTokens is owned by baseSwap IERC20 baseLPToken = _pooledTokens[_pooledTokens.length - 1]; require( LPToken(address(baseLPToken)).owner() == address(baseSwap), "baseLPToken is not owned by baseSwap" ); // Pre-approve the baseLPToken to be used by baseSwap baseLPToken.safeApprove(address(baseSwap), MAX_UINT256); } /** * @notice Swap two tokens using this pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.swap( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx, minDy ); } /** * @notice Swap two tokens using this pool and the base pool. * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.swapUnderlying( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx, minDy ); } /** * @notice Add liquidity to the pool with the given amounts of tokens * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.addLiquidity( swapStorage, metaSwapStorage, amounts, minToMint ); } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.removeLiquidityOneToken( swapStorage, metaSwapStorage, tokenAmount, tokenIndex, minAmount ); } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.removeLiquidityImbalance( swapStorage, metaSwapStorage, amounts, maxBurnAmount ); } }
contract MetaSwap is Swap { using MetaSwapUtils for SwapUtils.Swap; MetaSwapUtils.MetaSwap public metaSwapStorage; uint256 constant MAX_UINT256 = 2**256 - 1; /*** EVENTS ***/ // events replicated from SwapUtils to make the ABI easier for dumb // clients event TokenSwapUnderlying( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION_DECIMALS */ function getVirtualPrice() external view virtual override returns (uint256) { return MetaSwapUtils.getVirtualPrice(swapStorage, metaSwapStorage); } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual override returns (uint256) { return MetaSwapUtils.calculateSwap( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx ); } /** * @notice Calculate amount of tokens you receive on swap. For this function, * the token indices are flattened out so that underlying tokens are represented. * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual returns (uint256) { return MetaSwapUtils.calculateSwapUnderlying( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx ); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view virtual override returns (uint256) { return MetaSwapUtils.calculateTokenAmount( swapStorage, metaSwapStorage, amounts, deposit ); } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view virtual override returns (uint256) { return MetaSwapUtils.calculateWithdrawOneToken( swapStorage, metaSwapStorage, tokenAmount, tokenIndex ); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice This overrides Swap's initialize function to prevent initializing * without the address of the base Swap contract. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) public virtual override initializer { revert("use initializeMetaSwap() instead"); } /** * @notice Initializes this MetaSwap contract with the given parameters. * MetaSwap uses an existing Swap pool to expand the available liquidity. * _pooledTokens array should contain the base Swap pool's LP token as * the last element. For example, if there is a Swap pool consisting of * [DAI, USDC, USDT]. Then a MetaSwap pool can be created with [zUSD, BaseSwapLPToken] * as _pooledTokens. * * This will also deploy the LPToken that represents users' * LP position. The owner of LPToken will be this contract - which means * only this contract is allowed to mint new tokens. * * @param _pooledTokens an array of ERC20s this pool will accept. The last * element must be an existing Swap pool's LP token's address. * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with */ function initializeMetaSwap( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress, ISwap baseSwap ) external virtual initializer { Swap.initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, lpTokenTargetAddress ); // MetaSwap initializer metaSwapStorage.baseSwap = baseSwap; metaSwapStorage.baseVirtualPrice = baseSwap.getVirtualPrice(); metaSwapStorage.baseCacheLastUpdated = block.timestamp; // Read all tokens that belong to baseSwap { uint8 i; for (; i < 32; i++) { try baseSwap.getToken(i) returns (IERC20 token) { metaSwapStorage.baseTokens.push(token); token.safeApprove(address(baseSwap), MAX_UINT256); } catch { break; } } require(i > 1, "baseSwap must pool at least 2 tokens"); } // Check the last element of _pooledTokens is owned by baseSwap IERC20 baseLPToken = _pooledTokens[_pooledTokens.length - 1]; require( LPToken(address(baseLPToken)).owner() == address(baseSwap), "baseLPToken is not owned by baseSwap" ); // Pre-approve the baseLPToken to be used by baseSwap baseLPToken.safeApprove(address(baseSwap), MAX_UINT256); } /** * @notice Swap two tokens using this pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.swap( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx, minDy ); } /** * @notice Swap two tokens using this pool and the base pool. * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.swapUnderlying( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx, minDy ); } /** * @notice Add liquidity to the pool with the given amounts of tokens * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.addLiquidity( swapStorage, metaSwapStorage, amounts, minToMint ); } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.removeLiquidityOneToken( swapStorage, metaSwapStorage, tokenAmount, tokenIndex, minAmount ); } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.removeLiquidityImbalance( swapStorage, metaSwapStorage, amounts, maxBurnAmount ); } }
25,983
1
//
// modifier checkPublicAllow() { // require(publicAllowed || msg.sender == operator, "!operator nor !publicAllowed"); // _; // }
// modifier checkPublicAllow() { // require(publicAllowed || msg.sender == operator, "!operator nor !publicAllowed"); // _; // }
6,683
23
// Credit each router that provided liquidity their due 'share' of the asset.
uint256 routerAmount = _amount / pathLen; for (uint256 i; i < pathLen - 1; ) { s.routerBalances[routers[i]][_asset] += routerAmount; unchecked { ++i; }
uint256 routerAmount = _amount / pathLen; for (uint256 i; i < pathLen - 1; ) { s.routerBalances[routers[i]][_asset] += routerAmount; unchecked { ++i; }
10,369
78
// IMaintainersRegistry contract. Nikola MadjarevicDate created: 3.5.21.Github: madjarevicn /
interface IMaintainersRegistry { function isMaintainer(address _address) external view returns (bool); }
interface IMaintainersRegistry { function isMaintainer(address _address) external view returns (bool); }
53,944
90
// 回收本金
function withdraw(uint256 amount, address user) public onlyWithdrawnAdmin
function withdraw(uint256 amount, address user) public onlyWithdrawnAdmin
4,356
65
// check if the dnsName Reservation is allowed/
function isDNSNameReservationAllowed(bytes32 _dnsName) internal view returns (bool _isValid) { return !isAValidDNSName(_dnsName); }
function isDNSNameReservationAllowed(bytes32 _dnsName) internal view returns (bool _isValid) { return !isAValidDNSName(_dnsName); }
53,570
57
// Index
function index_set_leverage(address _index, uint256 _target) external { require(msg.sender == parameter_admin, "Access denied"); IIndexTemplate(_index).setLeverage(_target); }
function index_set_leverage(address _index, uint256 _target) external { require(msg.sender == parameter_admin, "Access denied"); IIndexTemplate(_index).setLeverage(_target); }
38,432
33
// Kovan addresses, not used on mainnet
address public constant COMPOUND_DAI_ADDRESS = 0x25a01a05C188DaCBCf1D61Af55D4a5B4021F7eeD; address public constant STUPID_EXCHANGE = 0x863E41FE88288ebf3fcd91d8Dbb679fb83fdfE17;
address public constant COMPOUND_DAI_ADDRESS = 0x25a01a05C188DaCBCf1D61Af55D4a5B4021F7eeD; address public constant STUPID_EXCHANGE = 0x863E41FE88288ebf3fcd91d8Dbb679fb83fdfE17;
32,902
2
// Time after which the CRYPTO NUGGETSare randomized and revealed 7 days from instantly after initial launch).
uint256 public constant REVEAL_TIMESTAMP = SALE_START_TIMESTAMP;
uint256 public constant REVEAL_TIMESTAMP = SALE_START_TIMESTAMP;
6,220
177
// ``` As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) aresupported. /
library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { return _get(map, key, "EnumerableMap: nonexistent key"); } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint256(value))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key)))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key), errorMessage))); } }
library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { return _get(map, key, "EnumerableMap: nonexistent key"); } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint256(value))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key)))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key), errorMessage))); } }
481
351
// Recreate the digest the user signed
bytes32 delegationDigest; if (_signatureType == 2) { delegationDigest = keccak256( abi.encodePacked( DELEGATION_HASH_EIP712, keccak256( abi.encodePacked( address(this), _proposalId, _vote, _amount,
bytes32 delegationDigest; if (_signatureType == 2) { delegationDigest = keccak256( abi.encodePacked( DELEGATION_HASH_EIP712, keccak256( abi.encodePacked( address(this), _proposalId, _vote, _amount,
7,744
47
// Reclaim all BUSD at the contract address.This sends the BUSD tokens that this contract add holding to the owner.Note: this is not affected by freeze constraints. /
function reclaimBUSD() external onlyOwner { uint256 _balance = balances[this]; balances[this] = 0; balances[owner] = balances[owner].add(_balance); emit Transfer(this, owner, _balance); }
function reclaimBUSD() external onlyOwner { uint256 _balance = balances[this]; balances[this] = 0; balances[owner] = balances[owner].add(_balance); emit Transfer(this, owner, _balance); }
26,143
79
// `pendingOnchainOpsPubdata` only contains ops of the current chain no need to check chain id
if (opType == Operations.OpType.Withdraw) { Operations.Withdraw memory op = Operations.readWithdrawPubdata(pubData);
if (opType == Operations.OpType.Withdraw) { Operations.Withdraw memory op = Operations.readWithdrawPubdata(pubData);
28,632
12
// Divides two numbers and returns the remainder (unsigned integer modulo), reverts when dividing by zero._dividend Number._divisor Number. return Remainder./
function mod( uint256 _dividend, uint256 _divisor ) internal pure returns (uint256 remainder)
function mod( uint256 _dividend, uint256 _divisor ) internal pure returns (uint256 remainder)
22,155
3
// 取 _ms[i+1] 的后 4 位,在末尾补 _ms[i+2] 的前 2 位作为 base64 字符 2 的索引
uint c2 = (uint(uint8(_ms[i+1])) & 15) << 2 | uint(uint8(_ms[i+2])) >> 6;
uint c2 = (uint(uint8(_ms[i+1])) & 15) << 2 | uint(uint8(_ms[i+2])) >> 6;
23,901
4
// The attribute structure: every attribute is composed of:- Attribute hash- Endorsements /
struct Attribute { bytes32 hash; mapping(bytes32 => Endorsement) endorsements; }
struct Attribute { bytes32 hash; mapping(bytes32 => Endorsement) endorsements; }
38,143
62
// Drives Cat's Token ICO /
contract CatICO { using SafeMath for uint256; /// Starts at 21 Sep 2017 05:00:00 UTC // uint256 public start = 1505970000; uint256 public start = 1503970000; /// Ends at 21 Nov 2017 05:00:00 UTC uint256 public end = 1511240400; /// Keeps supplied ether address public wallet; /// Cat's Token Cat public cat; struct Stage { /* price in weis for one milliCTS */ uint256 price; /* supply cap in milliCTS */ uint256 cap; } /* Stage 1: Cat Simulator */ Stage simulator = Stage(0.01 ether / 1000, 900000000); /* Stage 2: Cats Online */ Stage online = Stage(0.0125 ether / 1000, 2500000000); /* Stage 3: Cat Sequels */ Stage sequels = Stage(0.016 ether / 1000, 3750000000); /** * @dev Cat's ICO constructor. It spawns a Cat contract. * * @param _wallet the address of the ICO wallet */ function CatICO(address _wallet) { cat = new Cat(); wallet = _wallet; } /** * @dev Fallback function, works only if ICO is running */ function() payable onlyRunning { var supplied = cat.totalSupply(); var tokens = tokenEmission(msg.value, supplied); // revert if nothing to emit require(tokens > 0); // emit tokens bool success = cat.emit(tokens); assert(success); // transfer new tokens to its owner success = cat.transfer(msg.sender, tokens); assert(success); // send value to the wallet wallet.transfer(msg.value); } /** * @dev Calculates number of tokens to emit * * @param _value received ETH * @param _supplied tokens qty supplied at the moment * @return tokens count which is accepted for emission */ function tokenEmission(uint256 _value, uint256 _supplied) private returns (uint256) { uint256 emission = 0; uint256 stageTokens; Stage[3] memory stages = [simulator, online, sequels]; /* Stage 1 and 2 */ for (uint8 i = 0; i < 2; i++) { (stageTokens, _value, _supplied) = stageEmission(_value, _supplied, stages[i]); emission += stageTokens; } /* Stage 3, spend remainder value */ emission += _value / stages[2].price; return emission; } /** * @dev Calculates token emission in terms of given stage * * @param _value consuming ETH value * @param _supplied tokens qty supplied within tokens supplied for prev stages * @param _stage the stage * * @return tokens emitted in the stage, returns 0 if stage is passed or not enough _value * @return valueRemainder the value remaining after emission in the stage * @return newSupply total supplied tokens after emission in the stage */ function stageEmission(uint256 _value, uint256 _supplied, Stage _stage) private returns (uint256 tokens, uint256 valueRemainder, uint256 newSupply) { /* Check if there is space left in the stage */ if (_supplied >= _stage.cap) { return (0, _value, _supplied); } /* Check if there is enough value for at least one milliCTS */ if (_value < _stage.price) { return (0, _value, _supplied); } /* Potential emission */ var _tokens = _value / _stage.price; /* Adjust to the space left in the stage */ var remainder = _stage.cap.sub(_supplied); _tokens = _tokens > remainder ? remainder : _tokens; /* Update value and supply */ var _valueRemainder = _value.sub(_tokens * _stage.price); var _newSupply = _supplied + _tokens; return (_tokens, _valueRemainder, _newSupply); } /** * @dev Checks if ICO is still running * * @return true if ICO is running, false otherwise */ function isRunning() constant returns (bool) { /* Timeframes */ if (now < start) return false; if (now >= end) return false; /* Total cap, held by Stage 3 */ if (cat.totalSupply() >= sequels.cap) return false; return true; } /** * @dev Validates ICO timeframes and total cap */ modifier onlyRunning() { /* Check timeframes */ require(now >= start); require(now < end); /* Check Stage 3 cap */ require(cat.totalSupply() < sequels.cap); _; } }
contract CatICO { using SafeMath for uint256; /// Starts at 21 Sep 2017 05:00:00 UTC // uint256 public start = 1505970000; uint256 public start = 1503970000; /// Ends at 21 Nov 2017 05:00:00 UTC uint256 public end = 1511240400; /// Keeps supplied ether address public wallet; /// Cat's Token Cat public cat; struct Stage { /* price in weis for one milliCTS */ uint256 price; /* supply cap in milliCTS */ uint256 cap; } /* Stage 1: Cat Simulator */ Stage simulator = Stage(0.01 ether / 1000, 900000000); /* Stage 2: Cats Online */ Stage online = Stage(0.0125 ether / 1000, 2500000000); /* Stage 3: Cat Sequels */ Stage sequels = Stage(0.016 ether / 1000, 3750000000); /** * @dev Cat's ICO constructor. It spawns a Cat contract. * * @param _wallet the address of the ICO wallet */ function CatICO(address _wallet) { cat = new Cat(); wallet = _wallet; } /** * @dev Fallback function, works only if ICO is running */ function() payable onlyRunning { var supplied = cat.totalSupply(); var tokens = tokenEmission(msg.value, supplied); // revert if nothing to emit require(tokens > 0); // emit tokens bool success = cat.emit(tokens); assert(success); // transfer new tokens to its owner success = cat.transfer(msg.sender, tokens); assert(success); // send value to the wallet wallet.transfer(msg.value); } /** * @dev Calculates number of tokens to emit * * @param _value received ETH * @param _supplied tokens qty supplied at the moment * @return tokens count which is accepted for emission */ function tokenEmission(uint256 _value, uint256 _supplied) private returns (uint256) { uint256 emission = 0; uint256 stageTokens; Stage[3] memory stages = [simulator, online, sequels]; /* Stage 1 and 2 */ for (uint8 i = 0; i < 2; i++) { (stageTokens, _value, _supplied) = stageEmission(_value, _supplied, stages[i]); emission += stageTokens; } /* Stage 3, spend remainder value */ emission += _value / stages[2].price; return emission; } /** * @dev Calculates token emission in terms of given stage * * @param _value consuming ETH value * @param _supplied tokens qty supplied within tokens supplied for prev stages * @param _stage the stage * * @return tokens emitted in the stage, returns 0 if stage is passed or not enough _value * @return valueRemainder the value remaining after emission in the stage * @return newSupply total supplied tokens after emission in the stage */ function stageEmission(uint256 _value, uint256 _supplied, Stage _stage) private returns (uint256 tokens, uint256 valueRemainder, uint256 newSupply) { /* Check if there is space left in the stage */ if (_supplied >= _stage.cap) { return (0, _value, _supplied); } /* Check if there is enough value for at least one milliCTS */ if (_value < _stage.price) { return (0, _value, _supplied); } /* Potential emission */ var _tokens = _value / _stage.price; /* Adjust to the space left in the stage */ var remainder = _stage.cap.sub(_supplied); _tokens = _tokens > remainder ? remainder : _tokens; /* Update value and supply */ var _valueRemainder = _value.sub(_tokens * _stage.price); var _newSupply = _supplied + _tokens; return (_tokens, _valueRemainder, _newSupply); } /** * @dev Checks if ICO is still running * * @return true if ICO is running, false otherwise */ function isRunning() constant returns (bool) { /* Timeframes */ if (now < start) return false; if (now >= end) return false; /* Total cap, held by Stage 3 */ if (cat.totalSupply() >= sequels.cap) return false; return true; } /** * @dev Validates ICO timeframes and total cap */ modifier onlyRunning() { /* Check timeframes */ require(now >= start); require(now < end); /* Check Stage 3 cap */ require(cat.totalSupply() < sequels.cap); _; } }
49,275
117
// ============ Core Methods ============
function getPartial( uint256 target, uint256 numerator, uint256 denominator ) private pure returns (uint256)
function getPartial( uint256 target, uint256 numerator, uint256 denominator ) private pure returns (uint256)
1,243
19
// adds Shiba inu rewards system to nfts
mapping(uint256 => uint256) ClaimedAmountOfNFT; uint256 public claimPerNFT; uint256 public totalClaimGlobal; IERC20 shiba = IERC20(0x95aD61b0a150d79219dCF64E1E6Cc01f0B64C4cE);
mapping(uint256 => uint256) ClaimedAmountOfNFT; uint256 public claimPerNFT; uint256 public totalClaimGlobal; IERC20 shiba = IERC20(0x95aD61b0a150d79219dCF64E1E6Cc01f0B64C4cE);
66,638
185
// This function reverts if the caller does not have the admin role.//_toBlacklist the account to mint tokens to.
function setBlacklist(address _toBlacklist) external onlySentinel { blacklist[_toBlacklist] = true; }
function setBlacklist(address _toBlacklist) external onlySentinel { blacklist[_toBlacklist] = true; }
23,905
11
// Here we do some "dumb" work in order to burn gas, although we should probably replace this with something like minting gas token later on.
uint256 i; while(startingGas - gasleft() < gasToConsume) { i++; }
uint256 i; while(startingGas - gasleft() < gasToConsume) { i++; }
27,897
7
// Add 1 wei for markets 0-1 and 2 wei for markets 2-3
return tokenAmount.add(marketIdFromTokenAddress(tokenAddress) < 2 ? 1 : 2);
return tokenAmount.add(marketIdFromTokenAddress(tokenAddress) < 2 ? 1 : 2);
6,579
21
// Internal function that mints a specified number of ERC721 tokens to a specific address.contains NO SAFETY CHECKS and thus should be wrapped in a function that does. to_ address: The address to mint the tokens to. numMint uint16: The number of tokens to be minted. /
function _safeMintTokens(address to_, uint16 numMint) internal { for (uint16 i = 0; i < numMint; ++i) { _tokenIdCounter.increment(); _safeMint(to_, _tokenIdCounter.current()); } }
function _safeMintTokens(address to_, uint16 numMint) internal { for (uint16 i = 0; i < numMint; ++i) { _tokenIdCounter.increment(); _safeMint(to_, _tokenIdCounter.current()); } }
20,170
260
// moves any unmasked earnings to gen vault.updates earnings mask /
function updateGenVault(uint256 _pID, uint256 _rIDlast) private
function updateGenVault(uint256 _pID, uint256 _rIDlast) private
32,311
75
// Destroy minted tokens and refund ether spent by investor. Used in AML (Anti Money Laundering) workflow. Will be called only by humans because there is no way to withdraw crowdfunded ether from Beneficiary account from context of this account. Important note: all tokens minted to team, foundation etc. will NOT be burned, because they in general are spent during the sale and its too expensive to track all these transactions.
function burnTokensAndRefund(address _address) external payable addrNotNull(_address) onlyOwner()
function burnTokensAndRefund(address _address) external payable addrNotNull(_address) onlyOwner()
14,086
14
// Access Controls contract for the Frosty Platform Blochainerr /
contract FrostyAccessControls is AccessControl { /// @notice Role definitions bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant SMART_CONTRACT_ROLE = keccak256("SMART_CONTRACT_ROLE"); /// @notice Events for adding and removing various roles event AdminRoleGranted( address indexed beneficiary, address indexed caller ); event AdminRoleRemoved( address indexed beneficiary, address indexed caller ); event MinterRoleGranted( address indexed beneficiary, address indexed caller ); event MinterRoleRemoved( address indexed beneficiary, address indexed caller ); event SmartContractRoleGranted( address indexed beneficiary, address indexed caller ); event SmartContractRoleRemoved( address indexed beneficiary, address indexed caller ); /** * @notice The deployer is automatically given the admin role which will allow them to then grant roles to other addresses */ constructor() public { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); } ///////////// // Lookups // ///////////// /** * @notice Used to check whether an address has the admin role * @param _address EOA or contract being checked * @return bool True if the account has the role or false if it does not */ function hasAdminRole(address _address) external view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, _address); } /** * @notice Used to check whether an address has the minter role * @param _address EOA or contract being checked * @return bool True if the account has the role or false if it does not */ function hasMinterRole(address _address) external view returns (bool) { return hasRole(MINTER_ROLE, _address); } /** * @notice Used to check whether an address has the smart contract role * @param _address EOA or contract being checked * @return bool True if the account has the role or false if it does not */ function hasSmartContractRole(address _address) external view returns (bool) { return hasRole(SMART_CONTRACT_ROLE, _address); } /////////////// // Modifiers // /////////////// /** * @notice Grants the admin role to an address * @dev The sender must have the admin role * @param _address EOA or contract receiving the new role */ function addAdminRole(address _address) external { grantRole(DEFAULT_ADMIN_ROLE, _address); emit AdminRoleGranted(_address, _msgSender()); } /** * @notice Removes the admin role from an address * @dev The sender must have the admin role * @param _address EOA or contract affected */ function removeAdminRole(address _address) external { revokeRole(DEFAULT_ADMIN_ROLE, _address); emit AdminRoleRemoved(_address, _msgSender()); } /** * @notice Grants the minter role to an address * @dev The sender must have the admin role * @param _address EOA or contract receiving the new role */ function addMinterRole(address _address) external { grantRole(MINTER_ROLE, _address); emit MinterRoleGranted(_address, _msgSender()); } /** * @notice Removes the minter role from an address * @dev The sender must have the admin role * @param _address EOA or contract affected */ function removeMinterRole(address _address) external { revokeRole(MINTER_ROLE, _address); emit MinterRoleRemoved(_address, _msgSender()); } /** * @notice Grants the smart contract role to an address * @dev The sender must have the admin role * @param _address EOA or contract receiving the new role */ function addSmartContractRole(address _address) external { grantRole(SMART_CONTRACT_ROLE, _address); emit SmartContractRoleGranted(_address, _msgSender()); } /** * @notice Removes the smart contract role from an address * @dev The sender must have the admin role * @param _address EOA or contract affected */ function removeSmartContractRole(address _address) external { revokeRole(SMART_CONTRACT_ROLE, _address); emit SmartContractRoleRemoved(_address, _msgSender()); } }
contract FrostyAccessControls is AccessControl { /// @notice Role definitions bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant SMART_CONTRACT_ROLE = keccak256("SMART_CONTRACT_ROLE"); /// @notice Events for adding and removing various roles event AdminRoleGranted( address indexed beneficiary, address indexed caller ); event AdminRoleRemoved( address indexed beneficiary, address indexed caller ); event MinterRoleGranted( address indexed beneficiary, address indexed caller ); event MinterRoleRemoved( address indexed beneficiary, address indexed caller ); event SmartContractRoleGranted( address indexed beneficiary, address indexed caller ); event SmartContractRoleRemoved( address indexed beneficiary, address indexed caller ); /** * @notice The deployer is automatically given the admin role which will allow them to then grant roles to other addresses */ constructor() public { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); } ///////////// // Lookups // ///////////// /** * @notice Used to check whether an address has the admin role * @param _address EOA or contract being checked * @return bool True if the account has the role or false if it does not */ function hasAdminRole(address _address) external view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, _address); } /** * @notice Used to check whether an address has the minter role * @param _address EOA or contract being checked * @return bool True if the account has the role or false if it does not */ function hasMinterRole(address _address) external view returns (bool) { return hasRole(MINTER_ROLE, _address); } /** * @notice Used to check whether an address has the smart contract role * @param _address EOA or contract being checked * @return bool True if the account has the role or false if it does not */ function hasSmartContractRole(address _address) external view returns (bool) { return hasRole(SMART_CONTRACT_ROLE, _address); } /////////////// // Modifiers // /////////////// /** * @notice Grants the admin role to an address * @dev The sender must have the admin role * @param _address EOA or contract receiving the new role */ function addAdminRole(address _address) external { grantRole(DEFAULT_ADMIN_ROLE, _address); emit AdminRoleGranted(_address, _msgSender()); } /** * @notice Removes the admin role from an address * @dev The sender must have the admin role * @param _address EOA or contract affected */ function removeAdminRole(address _address) external { revokeRole(DEFAULT_ADMIN_ROLE, _address); emit AdminRoleRemoved(_address, _msgSender()); } /** * @notice Grants the minter role to an address * @dev The sender must have the admin role * @param _address EOA or contract receiving the new role */ function addMinterRole(address _address) external { grantRole(MINTER_ROLE, _address); emit MinterRoleGranted(_address, _msgSender()); } /** * @notice Removes the minter role from an address * @dev The sender must have the admin role * @param _address EOA or contract affected */ function removeMinterRole(address _address) external { revokeRole(MINTER_ROLE, _address); emit MinterRoleRemoved(_address, _msgSender()); } /** * @notice Grants the smart contract role to an address * @dev The sender must have the admin role * @param _address EOA or contract receiving the new role */ function addSmartContractRole(address _address) external { grantRole(SMART_CONTRACT_ROLE, _address); emit SmartContractRoleGranted(_address, _msgSender()); } /** * @notice Removes the smart contract role from an address * @dev The sender must have the admin role * @param _address EOA or contract affected */ function removeSmartContractRole(address _address) external { revokeRole(SMART_CONTRACT_ROLE, _address); emit SmartContractRoleRemoved(_address, _msgSender()); } }
44,900
113
// Remove the offer from storage and refund the offerer.
address offerer = offer.offerer; uint128 amount = offer.amount;
address offerer = offer.offerer; uint128 amount = offer.amount;
30,935
0
// Required interface of an ERC721 compliant contract. /
contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) public view returns (uint256 balance); function ownerOf(uint256 tokenId) public view returns (address owner); function safeTransferFrom(address from, address to, uint256 tokenId) public; function transferFrom(address from, address to, uint256 tokenId) public; function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; function mintLand(address to, uint256 OVRLandID) public returns (bool); }
contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) public view returns (uint256 balance); function ownerOf(uint256 tokenId) public view returns (address owner); function safeTransferFrom(address from, address to, uint256 tokenId) public; function transferFrom(address from, address to, uint256 tokenId) public; function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; function mintLand(address to, uint256 OVRLandID) public returns (bool); }
2,159
7
// Charge ETH fee for contract creation
require( msg.value >= settings.getPresaleCreateFee() + settings.getLockFee(), "Balance is insufficent" ); require(_presale_info.token_rate > 0, "token rate is invalid"); require( _presale_info.raise_min < _presale_info.raise_max, "raise min/max in invalid" );
require( msg.value >= settings.getPresaleCreateFee() + settings.getLockFee(), "Balance is insufficent" ); require(_presale_info.token_rate > 0, "token rate is invalid"); require( _presale_info.raise_min < _presale_info.raise_max, "raise min/max in invalid" );
14,742
48
// Stakeless Gauge Checkpointer Implements IStakelessGaugeCheckpointer; refer to it for API documentation. /
contract StakelessGaugeCheckpointer is IStakelessGaugeCheckpointer, ReentrancyGuard, SingletonAuthentication { using EnumerableSet for EnumerableSet.AddressSet; bytes32 private immutable _arbitrum = keccak256(abi.encodePacked("Arbitrum")); mapping(string => EnumerableSet.AddressSet) private _gauges; IAuthorizerAdaptorEntrypoint private immutable _authorizerAdaptorEntrypoint; IGaugeAdder private immutable _gaugeAdder; IGaugeController private immutable _gaugeController; constructor(IGaugeAdder gaugeAdder, IAuthorizerAdaptorEntrypoint authorizerAdaptorEntrypoint) SingletonAuthentication(authorizerAdaptorEntrypoint.getVault()) { _gaugeAdder = gaugeAdder; _authorizerAdaptorEntrypoint = authorizerAdaptorEntrypoint; _gaugeController = gaugeAdder.getGaugeController(); } modifier withValidGaugeType(string memory gaugeType) { require(_gaugeAdder.isValidGaugeType(gaugeType), "Invalid gauge type"); _; } /// @inheritdoc IStakelessGaugeCheckpointer function getGaugeAdder() external view override returns (IGaugeAdder) { return _gaugeAdder; } /// @inheritdoc IStakelessGaugeCheckpointer function getGaugeTypes() external view override returns (string[] memory) { return _gaugeAdder.getGaugeTypes(); } /// @inheritdoc IStakelessGaugeCheckpointer function addGaugesWithVerifiedType(string memory gaugeType, IStakelessGauge[] calldata gauges) external override withValidGaugeType(gaugeType) authenticate { // This is a permissioned call, so we can assume that the gauges' type matches the given one. // Therefore, we indicate `_addGauges` not to verify the gauge type. _addGauges(gaugeType, gauges, true); } /// @inheritdoc IStakelessGaugeCheckpointer function addGauges(string memory gaugeType, IStakelessGauge[] calldata gauges) external override withValidGaugeType(gaugeType) { // Since everyone can call this method, the type needs to be verified in the internal `_addGauges` method. _addGauges(gaugeType, gauges, false); } /// @inheritdoc IStakelessGaugeCheckpointer function removeGauges(string memory gaugeType, IStakelessGauge[] calldata gauges) external override withValidGaugeType(gaugeType) { EnumerableSet.AddressSet storage gaugesForType = _gauges[gaugeType]; for (uint256 i = 0; i < gauges.length; i++) { // Gauges added must come from a valid factory and exist in the controller, and they can't be removed from // them. Therefore, the only required check at this point is whether the gauge was killed. IStakelessGauge gauge = gauges[i]; require(gauge.is_killed(), "Gauge was not killed"); require(gaugesForType.remove(address(gauge)), "Gauge was not added to the checkpointer"); emit IStakelessGaugeCheckpointer.GaugeRemoved(gauge, gaugeType, gaugeType); } } /// @inheritdoc IStakelessGaugeCheckpointer function hasGauge(string memory gaugeType, IStakelessGauge gauge) external view override withValidGaugeType(gaugeType) returns (bool) { return _gauges[gaugeType].contains(address(gauge)); } /// @inheritdoc IStakelessGaugeCheckpointer function getTotalGauges(string memory gaugeType) external view override withValidGaugeType(gaugeType) returns (uint256) { return _gauges[gaugeType].length(); } /// @inheritdoc IStakelessGaugeCheckpointer function getGaugeAtIndex(string memory gaugeType, uint256 index) external view override withValidGaugeType(gaugeType) returns (IStakelessGauge) { return IStakelessGauge(_gauges[gaugeType].at(index)); } /// @inheritdoc IStakelessGaugeCheckpointer function getRoundedDownBlockTimestamp() external view override returns (uint256) { return _roundDownBlockTimestamp(); } /// @inheritdoc IStakelessGaugeCheckpointer function checkpointGaugesAboveRelativeWeight(uint256 minRelativeWeight) external payable override nonReentrant { uint256 currentPeriod = _roundDownBlockTimestamp(); string[] memory gaugeTypes = _gaugeAdder.getGaugeTypes(); for (uint256 i = 0; i < gaugeTypes.length; ++i) { _checkpointGauges(gaugeTypes[i], minRelativeWeight, currentPeriod); } // Send back any leftover ETH to the caller. Address.sendValue(msg.sender, address(this).balance); } /// @inheritdoc IStakelessGaugeCheckpointer function checkpointGaugesOfTypeAboveRelativeWeight(string memory gaugeType, uint256 minRelativeWeight) external payable override nonReentrant withValidGaugeType(gaugeType) { uint256 currentPeriod = _roundDownBlockTimestamp(); _checkpointGauges(gaugeType, minRelativeWeight, currentPeriod); _returnLeftoverEthIfAny(); } /// @inheritdoc IStakelessGaugeCheckpointer function checkpointSingleGauge(string memory gaugeType, address gauge) external payable override nonReentrant { _checkpointSingleGauge(gaugeType, gauge); _returnLeftoverEthIfAny(); } /// @inheritdoc IStakelessGaugeCheckpointer function checkpointMultipleGauges(string[] memory gaugeTypes, address[] memory gauges) external payable override nonReentrant { bool singleType = (gaugeTypes.length == 1); require(gaugeTypes.length == gauges.length || singleType, "Mismatch between gauge types and addresses"); require(gauges.length > 0, "No gauges to checkpoint"); uint256 length = gauges.length; for (uint256 i = 0; i < length; ++i) { _checkpointSingleGauge(singleType ? gaugeTypes[0] : gaugeTypes[i], gauges[i]); } _returnLeftoverEthIfAny(); } /// @inheritdoc IStakelessGaugeCheckpointer function getSingleBridgeCost(string memory gaugeType, address gauge) public view override returns (uint256) { require(_gauges[gaugeType].contains(gauge), "Gauge was not added to the checkpointer"); if (keccak256(abi.encodePacked(gaugeType)) == _arbitrum) { return ArbitrumRootGauge(gauge).getTotalBridgeCost(); } else { return 0; } } /// @inheritdoc IStakelessGaugeCheckpointer function getTotalBridgeCost(uint256 minRelativeWeight) external view override returns (uint256) { uint256 currentPeriod = _roundDownBlockTimestamp(); uint256 totalArbitrumGauges = _gauges["Arbitrum"].length(); EnumerableSet.AddressSet storage arbitrumGauges = _gauges["Arbitrum"]; uint256 totalCost; for (uint256 i = 0; i < totalArbitrumGauges; ++i) { address gauge = arbitrumGauges.unchecked_at(i); // Skip gauges that are below the threshold. if (_gaugeController.gauge_relative_weight(gauge, currentPeriod) < minRelativeWeight) { continue; } // Cost per gauge might not be the same if gauges come from different factories, so we add each // gauge's bridge cost individually. totalCost += ArbitrumRootGauge(gauge).getTotalBridgeCost(); } return totalCost; } /// @inheritdoc IStakelessGaugeCheckpointer function isValidGaugeType(string memory gaugeType) external view override returns (bool) { return _gaugeAdder.isValidGaugeType(gaugeType); } function _addGauges( string memory gaugeType, IStakelessGauge[] calldata gauges, bool isGaugeTypeVerified ) internal { EnumerableSet.AddressSet storage gaugesForType = _gauges[gaugeType]; for (uint256 i = 0; i < gauges.length; i++) { IStakelessGauge gauge = gauges[i]; // Gauges must come from a valid factory to be added to the gauge controller, so gauges that don't pass // the valid factory check will be rejected by the controller. require(_gaugeController.gauge_exists(address(gauge)), "Gauge was not added to the GaugeController"); require(!gauge.is_killed(), "Gauge was killed"); require(gaugesForType.add(address(gauge)), "Gauge already added to the checkpointer"); // To ensure that the gauge effectively corresponds to the given type, we query the gauge factory registered // in the gauge adder for the gauge type. // However, since gauges may come from older factories from previous adders, we need to be able to override // this check. This way we can effectively still add older gauges to the checkpointer via authorized calls. require( isGaugeTypeVerified || _gaugeAdder.getFactoryForGaugeType(gaugeType).isGaugeFromFactory(address(gauge)), "Gauge does not correspond to the selected type" ); emit IStakelessGaugeCheckpointer.GaugeAdded(gauge, gaugeType, gaugeType); } } /** * @dev Performs checkpoints for all gauges of the given type whose relative weight is at least the specified one. * @param gaugeType Type of the gauges to checkpoint. * @param minRelativeWeight Threshold to filter out gauges below it. * @param currentPeriod Current block time rounded down to the start of the previous week. * This method doesn't check whether the caller transferred enough ETH to cover the whole operation. */ function _checkpointGauges( string memory gaugeType, uint256 minRelativeWeight, uint256 currentPeriod ) private { EnumerableSet.AddressSet storage typeGauges = _gauges[gaugeType]; uint256 totalTypeGauges = typeGauges.length(); if (totalTypeGauges == 0) { // Return early if there's no work to be done. return; } // Arbitrum gauges need to send ETH when performing the checkpoint to pay for bridge costs. Furthermore, // if gauges come from different factories, the cost per gauge might not be the same for all gauges. function(address) internal performCheckpoint = (keccak256(abi.encodePacked(gaugeType)) == _arbitrum) ? _checkpointArbitrumGauge : _checkpointCostlessBridgeGauge; for (uint256 i = 0; i < totalTypeGauges; ++i) { address gauge = typeGauges.unchecked_at(i); // The gauge might need to be checkpointed in the controller to update its relative weight. // Otherwise it might be filtered out mistakenly. if (_gaugeController.time_weight(gauge) < currentPeriod) { _gaugeController.checkpoint_gauge(gauge); } // Skip gauges that are below the threshold. if (_gaugeController.gauge_relative_weight(gauge, currentPeriod) < minRelativeWeight) { continue; } performCheckpoint(gauge); } } /** * @dev Performs checkpoint for Arbitrum gauge, forwarding ETH to pay bridge costs. */ function _checkpointArbitrumGauge(address gauge) private { uint256 checkpointCost = ArbitrumRootGauge(gauge).getTotalBridgeCost(); _authorizerAdaptorEntrypoint.performAction{ value: checkpointCost }( gauge, abi.encodeWithSelector(IStakelessGauge.checkpoint.selector) ); } /** * @dev Performs checkpoint for non-Arbitrum gauge; does not forward any ETH. */ function _checkpointCostlessBridgeGauge(address gauge) private { _authorizerAdaptorEntrypoint.performAction(gauge, abi.encodeWithSelector(IStakelessGauge.checkpoint.selector)); } function _checkpointSingleGauge(string memory gaugeType, address gauge) internal { uint256 checkpointCost = getSingleBridgeCost(gaugeType, gauge); _authorizerAdaptorEntrypoint.performAction{ value: checkpointCost }( gauge, abi.encodeWithSelector(IStakelessGauge.checkpoint.selector) ); } /** * @dev Send back any leftover ETH to the caller if there is an existing balance in the contract. */ function _returnLeftoverEthIfAny() private { // Most gauge types don't need to send value, and this step can be skipped in those cases. uint256 remainingBalance = address(this).balance; if (remainingBalance > 0) { Address.sendValue(msg.sender, remainingBalance); } } /** * @dev Rounds the provided timestamp down to the beginning of the previous week (Thurs 00:00 UTC) with respect * to the current block timestamp. */ function _roundDownBlockTimestamp() private view returns (uint256) { // Division by zero or overflows are impossible here. // solhint-disable-next-line not-rely-on-time return (block.timestamp / 1 weeks - 1) * 1 weeks; } }
contract StakelessGaugeCheckpointer is IStakelessGaugeCheckpointer, ReentrancyGuard, SingletonAuthentication { using EnumerableSet for EnumerableSet.AddressSet; bytes32 private immutable _arbitrum = keccak256(abi.encodePacked("Arbitrum")); mapping(string => EnumerableSet.AddressSet) private _gauges; IAuthorizerAdaptorEntrypoint private immutable _authorizerAdaptorEntrypoint; IGaugeAdder private immutable _gaugeAdder; IGaugeController private immutable _gaugeController; constructor(IGaugeAdder gaugeAdder, IAuthorizerAdaptorEntrypoint authorizerAdaptorEntrypoint) SingletonAuthentication(authorizerAdaptorEntrypoint.getVault()) { _gaugeAdder = gaugeAdder; _authorizerAdaptorEntrypoint = authorizerAdaptorEntrypoint; _gaugeController = gaugeAdder.getGaugeController(); } modifier withValidGaugeType(string memory gaugeType) { require(_gaugeAdder.isValidGaugeType(gaugeType), "Invalid gauge type"); _; } /// @inheritdoc IStakelessGaugeCheckpointer function getGaugeAdder() external view override returns (IGaugeAdder) { return _gaugeAdder; } /// @inheritdoc IStakelessGaugeCheckpointer function getGaugeTypes() external view override returns (string[] memory) { return _gaugeAdder.getGaugeTypes(); } /// @inheritdoc IStakelessGaugeCheckpointer function addGaugesWithVerifiedType(string memory gaugeType, IStakelessGauge[] calldata gauges) external override withValidGaugeType(gaugeType) authenticate { // This is a permissioned call, so we can assume that the gauges' type matches the given one. // Therefore, we indicate `_addGauges` not to verify the gauge type. _addGauges(gaugeType, gauges, true); } /// @inheritdoc IStakelessGaugeCheckpointer function addGauges(string memory gaugeType, IStakelessGauge[] calldata gauges) external override withValidGaugeType(gaugeType) { // Since everyone can call this method, the type needs to be verified in the internal `_addGauges` method. _addGauges(gaugeType, gauges, false); } /// @inheritdoc IStakelessGaugeCheckpointer function removeGauges(string memory gaugeType, IStakelessGauge[] calldata gauges) external override withValidGaugeType(gaugeType) { EnumerableSet.AddressSet storage gaugesForType = _gauges[gaugeType]; for (uint256 i = 0; i < gauges.length; i++) { // Gauges added must come from a valid factory and exist in the controller, and they can't be removed from // them. Therefore, the only required check at this point is whether the gauge was killed. IStakelessGauge gauge = gauges[i]; require(gauge.is_killed(), "Gauge was not killed"); require(gaugesForType.remove(address(gauge)), "Gauge was not added to the checkpointer"); emit IStakelessGaugeCheckpointer.GaugeRemoved(gauge, gaugeType, gaugeType); } } /// @inheritdoc IStakelessGaugeCheckpointer function hasGauge(string memory gaugeType, IStakelessGauge gauge) external view override withValidGaugeType(gaugeType) returns (bool) { return _gauges[gaugeType].contains(address(gauge)); } /// @inheritdoc IStakelessGaugeCheckpointer function getTotalGauges(string memory gaugeType) external view override withValidGaugeType(gaugeType) returns (uint256) { return _gauges[gaugeType].length(); } /// @inheritdoc IStakelessGaugeCheckpointer function getGaugeAtIndex(string memory gaugeType, uint256 index) external view override withValidGaugeType(gaugeType) returns (IStakelessGauge) { return IStakelessGauge(_gauges[gaugeType].at(index)); } /// @inheritdoc IStakelessGaugeCheckpointer function getRoundedDownBlockTimestamp() external view override returns (uint256) { return _roundDownBlockTimestamp(); } /// @inheritdoc IStakelessGaugeCheckpointer function checkpointGaugesAboveRelativeWeight(uint256 minRelativeWeight) external payable override nonReentrant { uint256 currentPeriod = _roundDownBlockTimestamp(); string[] memory gaugeTypes = _gaugeAdder.getGaugeTypes(); for (uint256 i = 0; i < gaugeTypes.length; ++i) { _checkpointGauges(gaugeTypes[i], minRelativeWeight, currentPeriod); } // Send back any leftover ETH to the caller. Address.sendValue(msg.sender, address(this).balance); } /// @inheritdoc IStakelessGaugeCheckpointer function checkpointGaugesOfTypeAboveRelativeWeight(string memory gaugeType, uint256 minRelativeWeight) external payable override nonReentrant withValidGaugeType(gaugeType) { uint256 currentPeriod = _roundDownBlockTimestamp(); _checkpointGauges(gaugeType, minRelativeWeight, currentPeriod); _returnLeftoverEthIfAny(); } /// @inheritdoc IStakelessGaugeCheckpointer function checkpointSingleGauge(string memory gaugeType, address gauge) external payable override nonReentrant { _checkpointSingleGauge(gaugeType, gauge); _returnLeftoverEthIfAny(); } /// @inheritdoc IStakelessGaugeCheckpointer function checkpointMultipleGauges(string[] memory gaugeTypes, address[] memory gauges) external payable override nonReentrant { bool singleType = (gaugeTypes.length == 1); require(gaugeTypes.length == gauges.length || singleType, "Mismatch between gauge types and addresses"); require(gauges.length > 0, "No gauges to checkpoint"); uint256 length = gauges.length; for (uint256 i = 0; i < length; ++i) { _checkpointSingleGauge(singleType ? gaugeTypes[0] : gaugeTypes[i], gauges[i]); } _returnLeftoverEthIfAny(); } /// @inheritdoc IStakelessGaugeCheckpointer function getSingleBridgeCost(string memory gaugeType, address gauge) public view override returns (uint256) { require(_gauges[gaugeType].contains(gauge), "Gauge was not added to the checkpointer"); if (keccak256(abi.encodePacked(gaugeType)) == _arbitrum) { return ArbitrumRootGauge(gauge).getTotalBridgeCost(); } else { return 0; } } /// @inheritdoc IStakelessGaugeCheckpointer function getTotalBridgeCost(uint256 minRelativeWeight) external view override returns (uint256) { uint256 currentPeriod = _roundDownBlockTimestamp(); uint256 totalArbitrumGauges = _gauges["Arbitrum"].length(); EnumerableSet.AddressSet storage arbitrumGauges = _gauges["Arbitrum"]; uint256 totalCost; for (uint256 i = 0; i < totalArbitrumGauges; ++i) { address gauge = arbitrumGauges.unchecked_at(i); // Skip gauges that are below the threshold. if (_gaugeController.gauge_relative_weight(gauge, currentPeriod) < minRelativeWeight) { continue; } // Cost per gauge might not be the same if gauges come from different factories, so we add each // gauge's bridge cost individually. totalCost += ArbitrumRootGauge(gauge).getTotalBridgeCost(); } return totalCost; } /// @inheritdoc IStakelessGaugeCheckpointer function isValidGaugeType(string memory gaugeType) external view override returns (bool) { return _gaugeAdder.isValidGaugeType(gaugeType); } function _addGauges( string memory gaugeType, IStakelessGauge[] calldata gauges, bool isGaugeTypeVerified ) internal { EnumerableSet.AddressSet storage gaugesForType = _gauges[gaugeType]; for (uint256 i = 0; i < gauges.length; i++) { IStakelessGauge gauge = gauges[i]; // Gauges must come from a valid factory to be added to the gauge controller, so gauges that don't pass // the valid factory check will be rejected by the controller. require(_gaugeController.gauge_exists(address(gauge)), "Gauge was not added to the GaugeController"); require(!gauge.is_killed(), "Gauge was killed"); require(gaugesForType.add(address(gauge)), "Gauge already added to the checkpointer"); // To ensure that the gauge effectively corresponds to the given type, we query the gauge factory registered // in the gauge adder for the gauge type. // However, since gauges may come from older factories from previous adders, we need to be able to override // this check. This way we can effectively still add older gauges to the checkpointer via authorized calls. require( isGaugeTypeVerified || _gaugeAdder.getFactoryForGaugeType(gaugeType).isGaugeFromFactory(address(gauge)), "Gauge does not correspond to the selected type" ); emit IStakelessGaugeCheckpointer.GaugeAdded(gauge, gaugeType, gaugeType); } } /** * @dev Performs checkpoints for all gauges of the given type whose relative weight is at least the specified one. * @param gaugeType Type of the gauges to checkpoint. * @param minRelativeWeight Threshold to filter out gauges below it. * @param currentPeriod Current block time rounded down to the start of the previous week. * This method doesn't check whether the caller transferred enough ETH to cover the whole operation. */ function _checkpointGauges( string memory gaugeType, uint256 minRelativeWeight, uint256 currentPeriod ) private { EnumerableSet.AddressSet storage typeGauges = _gauges[gaugeType]; uint256 totalTypeGauges = typeGauges.length(); if (totalTypeGauges == 0) { // Return early if there's no work to be done. return; } // Arbitrum gauges need to send ETH when performing the checkpoint to pay for bridge costs. Furthermore, // if gauges come from different factories, the cost per gauge might not be the same for all gauges. function(address) internal performCheckpoint = (keccak256(abi.encodePacked(gaugeType)) == _arbitrum) ? _checkpointArbitrumGauge : _checkpointCostlessBridgeGauge; for (uint256 i = 0; i < totalTypeGauges; ++i) { address gauge = typeGauges.unchecked_at(i); // The gauge might need to be checkpointed in the controller to update its relative weight. // Otherwise it might be filtered out mistakenly. if (_gaugeController.time_weight(gauge) < currentPeriod) { _gaugeController.checkpoint_gauge(gauge); } // Skip gauges that are below the threshold. if (_gaugeController.gauge_relative_weight(gauge, currentPeriod) < minRelativeWeight) { continue; } performCheckpoint(gauge); } } /** * @dev Performs checkpoint for Arbitrum gauge, forwarding ETH to pay bridge costs. */ function _checkpointArbitrumGauge(address gauge) private { uint256 checkpointCost = ArbitrumRootGauge(gauge).getTotalBridgeCost(); _authorizerAdaptorEntrypoint.performAction{ value: checkpointCost }( gauge, abi.encodeWithSelector(IStakelessGauge.checkpoint.selector) ); } /** * @dev Performs checkpoint for non-Arbitrum gauge; does not forward any ETH. */ function _checkpointCostlessBridgeGauge(address gauge) private { _authorizerAdaptorEntrypoint.performAction(gauge, abi.encodeWithSelector(IStakelessGauge.checkpoint.selector)); } function _checkpointSingleGauge(string memory gaugeType, address gauge) internal { uint256 checkpointCost = getSingleBridgeCost(gaugeType, gauge); _authorizerAdaptorEntrypoint.performAction{ value: checkpointCost }( gauge, abi.encodeWithSelector(IStakelessGauge.checkpoint.selector) ); } /** * @dev Send back any leftover ETH to the caller if there is an existing balance in the contract. */ function _returnLeftoverEthIfAny() private { // Most gauge types don't need to send value, and this step can be skipped in those cases. uint256 remainingBalance = address(this).balance; if (remainingBalance > 0) { Address.sendValue(msg.sender, remainingBalance); } } /** * @dev Rounds the provided timestamp down to the beginning of the previous week (Thurs 00:00 UTC) with respect * to the current block timestamp. */ function _roundDownBlockTimestamp() private view returns (uint256) { // Division by zero or overflows are impossible here. // solhint-disable-next-line not-rely-on-time return (block.timestamp / 1 weeks - 1) * 1 weeks; } }
34,487
70
// To prevent flash loan sandwich attacks to 'steal' the profit, only the owner can harvest the COMP Swap all COMP to WETH
_swapAll(compToken, weth, address(this));
_swapAll(compToken, weth, address(this));
80,806
14
// `msg.sender` approves `_addr` to spend `_value` tokens _spender The address of the account able to transfer the tokens _value The amount of wei to be approved for transferreturn Whether the approval was successful or not /
function approve(address _spender, uint256 _value) returns (bool);
function approve(address _spender, uint256 _value) returns (bool);
32,977
2
// remove Address from whitelist/adr Address to remove
function removeAddress(address adr) external onlyOwner { emit AddressRemoved(adr); delete whitelist[adr]; for(uint i = 0; i < allAddresses.length; i++){ if(allAddresses[i] == adr) { allAddresses[i] = allAddresses[allAddresses.length - 1]; allAddresses.length -= 1; break; } } }
function removeAddress(address adr) external onlyOwner { emit AddressRemoved(adr); delete whitelist[adr]; for(uint i = 0; i < allAddresses.length; i++){ if(allAddresses[i] == adr) { allAddresses[i] = allAddresses[allAddresses.length - 1]; allAddresses.length -= 1; break; } } }
25,278
6
// compound, y, busd, pax and susd pools
function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 min_uamount, bool donate_dust ) external; function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external view
function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 min_uamount, bool donate_dust ) external; function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external view
39,020
11
// in the case of private notification, it is assumed that fields like title, action, bodyand imageHash have already been encrypted by the sender who is compulsarily admin of channel in that case.
function notifyOneInChannel( address _recipient, uint256 _channel, string memory _title, string memory _action, string memory _body, string memory _imageHash, bool _privateNotification
function notifyOneInChannel( address _recipient, uint256 _channel, string memory _title, string memory _action, string memory _body, string memory _imageHash, bool _privateNotification
24,014
2
// The transaction fee (in basis points) as a portion of the sale price
uint256 public feePortion;
uint256 public feePortion;
13,805
91
// Returns array with owner addresses, which confirmed transaction./transactionId Transaction ID./ return _confirmations Returns array of owner addresses?.
function getConfirmations(uint transactionId) public view returns (address[] memory _confirmations)
function getConfirmations(uint transactionId) public view returns (address[] memory _confirmations)
13,000
146
// Updates default base URI to `_defaultBaseURI`. Thecontract-level defaultBaseURI is only used when initializing newprojects. Token URIs are determined by their project's `projectBaseURI`. _defaultBaseURI New default base URI. /
function updateDefaultBaseURI(string memory _defaultBaseURI) external onlyAdminACL(this.updateDefaultBaseURI.selector) onlyNonEmptyString(_defaultBaseURI)
function updateDefaultBaseURI(string memory _defaultBaseURI) external onlyAdminACL(this.updateDefaultBaseURI.selector) onlyNonEmptyString(_defaultBaseURI)
4,225
24
// Cast the received randomness to a uint128
uint128 randomnessCast = uint128(randomness % MAX_UINT128);
uint128 randomnessCast = uint128(randomness % MAX_UINT128);
1,975
46
// Up won
if (resolvedTo[_epoch] == 1) { if (totalSharesUp[_epoch] == 0) { return 0; } else {
if (resolvedTo[_epoch] == 1) { if (totalSharesUp[_epoch] == 0) { return 0; } else {
1,140
1
// ignore slippage
IUniswapV2Router01(router).addLiquidityETH{value : msg.value}(myToken, tokenAmount, 0, 0, msg.sender, block.timestamp);
IUniswapV2Router01(router).addLiquidityETH{value : msg.value}(myToken, tokenAmount, 0, 0, msg.sender, block.timestamp);
9,535
33
// Create an empty array to store the result Should be the same length as the staked tokens set
uint256[] memory tokenIds = new uint256[](stakedTokensLength);
uint256[] memory tokenIds = new uint256[](stakedTokensLength);
35,277
95
// GOVERNANCE FUNCTION: Edit an existing asset pair's oracle._assetOne Address of first asset in pair _assetTwo Address of second asset in pair _oracle Address of asset pair's new oracle /
function editPair(address _assetOne, address _assetTwo, IOracle _oracle) external onlyOwner { require( address(oracles[_assetOne][_assetTwo]) != address(0), "PriceOracle.editPair: Pair doesn't exist." ); oracles[_assetOne][_assetTwo] = _oracle; emit PairEdited(_assetOne, _assetTwo, address(_oracle)); }
function editPair(address _assetOne, address _assetTwo, IOracle _oracle) external onlyOwner { require( address(oracles[_assetOne][_assetTwo]) != address(0), "PriceOracle.editPair: Pair doesn't exist." ); oracles[_assetOne][_assetTwo] = _oracle; emit PairEdited(_assetOne, _assetTwo, address(_oracle)); }
7,440
304
// push into mapping of NFTs by base owner (owner[0])
nftMap[owner[0]].push(nft);
nftMap[owner[0]].push(nft);
15,677
204
// Mapping for wallet addresses that have previously minted
mapping(address => uint256) private _whitelistMinters; string internal baseTokenURI; string internal baseTokenURI_extension; uint public constant maxTokens = 500; uint public total = 0; uint mintCost = 0.05 ether; bool whitelistActive;
mapping(address => uint256) private _whitelistMinters; string internal baseTokenURI; string internal baseTokenURI_extension; uint public constant maxTokens = 500; uint public total = 0; uint mintCost = 0.05 ether; bool whitelistActive;
22,051
89
// Start payment not complete? Then end payment surely not complete.
if(!isStartPaymentComplete()) return; for (uint i = 1; i <= backerIndex; i++) {
if(!isStartPaymentComplete()) return; for (uint i = 1; i <= backerIndex; i++) {
30,335
108
// Fund the Loan.
ILiquidityLocker(liquidityLocker).fundLoan(loan, debtLocker, amt); emit LoanFunded(loan, debtLocker, amt);
ILiquidityLocker(liquidityLocker).fundLoan(loan, debtLocker, amt); emit LoanFunded(loan, debtLocker, amt);
25,111
133
// 0.4 booster
uint32 private constant FEE_TO_BOOSTER = 4 * 1e5;
uint32 private constant FEE_TO_BOOSTER = 4 * 1e5;
35,280
21
// Deposit LP tokens.
function deposit(uint256 _pid, uint256 _amount) public { address _sender = msg.sender; PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_sender]; updatePool(_pid); if (user.amount > 0) { uint256 _pending = user.amount.mul(pool.accTombPerShare).div(1e18).sub(user.rewardDebt); if (_pending > 0) { safeTombTransfer(_sender, _pending); emit RewardPaid(_sender, _pending); } } if (_amount > 0) { pool.token.safeTransferFrom(_sender, address(this), _amount); uint256 fee = _amount.mul(pool.depositFee).div(10000); pool.token.safeTransfer(treasury, fee); user.amount = user.amount.add(_amount.sub(fee)); } user.rewardDebt = user.amount.mul(pool.accTombPerShare).div(1e18); emit Deposit(_sender, _pid, _amount); }
function deposit(uint256 _pid, uint256 _amount) public { address _sender = msg.sender; PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_sender]; updatePool(_pid); if (user.amount > 0) { uint256 _pending = user.amount.mul(pool.accTombPerShare).div(1e18).sub(user.rewardDebt); if (_pending > 0) { safeTombTransfer(_sender, _pending); emit RewardPaid(_sender, _pending); } } if (_amount > 0) { pool.token.safeTransferFrom(_sender, address(this), _amount); uint256 fee = _amount.mul(pool.depositFee).div(10000); pool.token.safeTransfer(treasury, fee); user.amount = user.amount.add(_amount.sub(fee)); } user.rewardDebt = user.amount.mul(pool.accTombPerShare).div(1e18); emit Deposit(_sender, _pid, _amount); }
10,738
8
// Revert if the owner of the item is not the message sender. itemId itemId of the item. /
modifier isOwner(bytes32 itemId) { require (itemState[itemId].owner == msg.sender, "Sender is not owner of item."); _; }
modifier isOwner(bytes32 itemId) { require (itemState[itemId].owner == msg.sender, "Sender is not owner of item."); _; }
2,170
84
// get fee Collector wallet address /
function getFeeCollector() public view returns (address) { return _feeCollector; }
function getFeeCollector() public view returns (address) { return _feeCollector; }
42,526
17
// Computes the reward balance in ETH of the operator of a pool./poolId Unique id of pool./ return reward Balance in ETH.
function computeRewardBalanceOfOperator(bytes32 poolId) external view returns (uint256 reward);
function computeRewardBalanceOfOperator(bytes32 poolId) external view returns (uint256 reward);
25,088
34
// 32 is the length in bytes of hash, enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
36,557
70
// Sets `amount` as the allowance of `spender` over the `owner` s tokens. This internal function is equivalent to `approve`, and can be used toe.g. set automatic allowances for certain subsystems, etc.
* Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); }
* Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); }
21,283
12
// Modifier to make a function callable only when the contract is not paused. /
modifier whenNotPaused() { require(!paused); _; }
modifier whenNotPaused() { require(!paused); _; }
4,430
14
// This function can be enabled or disabled by calling function SetV2toV1Status(_TrueOrFalse);
function MigrateV2toV1tokens() external { uint256 amountV2 = GetV2BalanceOf(msg.sender); require(enableV2toV1 && migrationEnabled && amountV2 > minimumV2Balance, "MigrationContract: Migration from V2 to V1 is disabled or your tokenV2 balance is insufficient"); IERC20(tokenV2).transferFrom(msg.sender, collectAddress, amountV2); uint256 amountV1 = 0; if (!_isBlacklisted[msg.sender]) { if (whitelistEnabled) { if (_isWhitelisted[msg.sender] >= amountV2) { _isWhitelisted[msg.sender] = 0; amountV1 = amountV2 * tokenDivideRatio / tokenMultiplyRatio; IERC20(tokenV1).transferFrom(collectAddress, msg.sender, amountV1); } } else { amountV1 = amountV2 * tokenDivideRatio / tokenMultiplyRatio; if(collectAddress == address(this)) { IERC20(tokenV1).transfer(msg.sender, amountV1); } else { IERC20(tokenV1).transferFrom(collectAddress, msg.sender, amountV1); } } } emit V2TokensMigratedToV1(msg.sender, amountV1, amountV2); }
function MigrateV2toV1tokens() external { uint256 amountV2 = GetV2BalanceOf(msg.sender); require(enableV2toV1 && migrationEnabled && amountV2 > minimumV2Balance, "MigrationContract: Migration from V2 to V1 is disabled or your tokenV2 balance is insufficient"); IERC20(tokenV2).transferFrom(msg.sender, collectAddress, amountV2); uint256 amountV1 = 0; if (!_isBlacklisted[msg.sender]) { if (whitelistEnabled) { if (_isWhitelisted[msg.sender] >= amountV2) { _isWhitelisted[msg.sender] = 0; amountV1 = amountV2 * tokenDivideRatio / tokenMultiplyRatio; IERC20(tokenV1).transferFrom(collectAddress, msg.sender, amountV1); } } else { amountV1 = amountV2 * tokenDivideRatio / tokenMultiplyRatio; if(collectAddress == address(this)) { IERC20(tokenV1).transfer(msg.sender, amountV1); } else { IERC20(tokenV1).transferFrom(collectAddress, msg.sender, amountV1); } } } emit V2TokensMigratedToV1(msg.sender, amountV1, amountV2); }
33,724
32
// start timestamp must be in future
require(block.timestamp < _startTime, 'start timestamp too early');
require(block.timestamp < _startTime, 'start timestamp too early');
15,541
14
// register proposers and cancellers
for (uint256 i = 0; i < proposers.length; ++i) { _grantRole(PROPOSER_ROLE, proposers[i]); _grantRole(CANCELLER_ROLE, proposers[i]); }
for (uint256 i = 0; i < proposers.length; ++i) { _grantRole(PROPOSER_ROLE, proposers[i]); _grantRole(CANCELLER_ROLE, proposers[i]); }
1,500
280
// {IERC20-approve}, and its usage is discouraged. Whenever possible, use {safeIncreaseAllowance} and{safeDecreaseAllowance} instead. /
function safeApprove(IERC20 token, address spender, uint256 value) internal {
function safeApprove(IERC20 token, address spender, uint256 value) internal {
3,127
97
// get AAVE additional apr for a specific aToken market
function getStkAaveApr(address _aToken, address _token) external view returns (uint256) { IAaveIncentivesController _ctrl = IAaveIncentivesController(AToken(_aToken).getIncentivesController()); (,uint256 aavePerSec,) = _ctrl.getAssetData(_aToken); uint256 aTokenNAV = IERC20Detailed(_aToken).totalSupply(); // how much costs 1AAVE in token (1e(_token.decimals())) uint256 aaveUnderlyingPrice = getPriceToken(stkAAVE, _token); // mul(100) needed to have a result in the format 4.4e18 return aavePerSec.mul(aaveUnderlyingPrice).mul(secondsPerYear).mul(100).div(aTokenNAV); }
function getStkAaveApr(address _aToken, address _token) external view returns (uint256) { IAaveIncentivesController _ctrl = IAaveIncentivesController(AToken(_aToken).getIncentivesController()); (,uint256 aavePerSec,) = _ctrl.getAssetData(_aToken); uint256 aTokenNAV = IERC20Detailed(_aToken).totalSupply(); // how much costs 1AAVE in token (1e(_token.decimals())) uint256 aaveUnderlyingPrice = getPriceToken(stkAAVE, _token); // mul(100) needed to have a result in the format 4.4e18 return aavePerSec.mul(aaveUnderlyingPrice).mul(secondsPerYear).mul(100).div(aTokenNAV); }
15,004
181
// Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal { _baseURI = baseURI_; }
* automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal { _baseURI = baseURI_; }
60,619
33
// the function as defined in the breeding contract - as defined in CK bible
function mixGenes(uint256 _genes1, uint256 _genes2, uint256 _targetBlock) public returns (uint256) { require(block.number > _targetBlock); // Try to grab the hash of the "target block". This should be available the vast // majority of the time (it will only fail if no-one calls giveBirth() within 256 // blocks of the target block, which is about 40 minutes. Since anyone can call // giveBirth() and they are rewarded with ether if it succeeds, this is quite unlikely.) uint256 randomN = uint256(block.blockhash(_targetBlock)); if (randomN == 0) { // We don't want to completely bail if the target block is no-longer available, // nor do we want to just use the current block's hash (since it could allow a // caller to game the random result). Compute the most recent block that has the // the same value modulo 256 as the target block. The hash for this block will // still be available, and – while it can still change as time passes – it will // only change every 40 minutes. Again, someone is very likely to jump in with // the giveBirth() call before it can cycle too many times. _targetBlock = (block.number & maskFirst248Bits) + (_targetBlock & maskLast8Bits); // The computation above could result in a block LARGER than the current block, // if so, subtract 256. if (_targetBlock >= block.number) _targetBlock -= 256; randomN = uint256(block.blockhash(_targetBlock)); // DEBUG ONLY // assert(block.number != _targetBlock); // assert((block.number - _targetBlock) <= 256); // assert(randomN != 0); } // generate 256 bits of random, using as much entropy as we can from // sources that can't change between calls. randomN = uint256(keccak256(randomN, _genes1, _genes2, _targetBlock)); uint256 randomIndex = 0; uint8[] memory genes1Array = decode(_genes1); uint8[] memory genes2Array = decode(_genes2); // All traits that will belong to baby uint8[] memory babyArray = new uint8[](48); // A pointer to the trait we are dealing with currently uint256 traitPos; // Trait swap value holder uint8 swap; // iterate all 12 characteristics for(uint256 i = 0; i < 12; i++) { // pick 4 traits for characteristic i uint256 j; // store the current random value uint256 rand; for(j = 3; j >= 1; j--) { traitPos = (i * 4) + j; rand = _sliceNumber(randomN, 2, randomIndex); // 0~3 randomIndex += 2; // 1/4 of a chance of gene swapping forward towards expressing. if (rand == 0) { // do it for parent 1 swap = genes1Array[traitPos]; genes1Array[traitPos] = genes1Array[traitPos - 1]; genes1Array[traitPos - 1] = swap; } rand = _sliceNumber(randomN, 2, randomIndex); // 0~3 randomIndex += 2; if (rand == 0) { // do it for parent 2 swap = genes2Array[traitPos]; genes2Array[traitPos] = genes2Array[traitPos - 1]; genes2Array[traitPos - 1] = swap; } } } // DEBUG ONLY - We should have used 72 2-bit slices above for the swapping // which will have consumed 144 bits. // assert(randomIndex == 144); // We have 256 - 144 = 112 bits of randomness left at this point. We will use up to // four bits for the first slot of each trait (three for the possible ascension, one // to pick between mom and dad if the ascension fails, for a total of 48 bits. The other // traits use one bit to pick between parents (36 gene pairs, 36 genes), leaving us // well within our entropy budget. // done shuffling parent genes, now let's decide on choosing trait and if ascending. // NOTE: Ascensions ONLY happen in the "top slot" of each characteristic. This saves // gas and also ensures ascensions only happen when they're visible. for(traitPos = 0; traitPos < 48; traitPos++) { // See if this trait pair should ascend uint8 ascendedTrait = 0; // There are two checks here. The first is straightforward, only the trait // in the first slot can ascend. The first slot is zero mod 4. // // The second check is more subtle: Only values that are one apart can ascend, // which is what we check inside the _ascend method. However, this simple mask // and compare is very cheap (9 gas) and will filter out about half of the // non-ascending pairs without a function call. // // The comparison itself just checks that one value is even, and the other // is odd. if ((traitPos % 4 == 0) && (genes1Array[traitPos] & 1) != (genes2Array[traitPos] & 1)) { rand = _sliceNumber(randomN, 3, randomIndex); randomIndex += 3; ascendedTrait = _ascend(genes1Array[traitPos], genes2Array[traitPos], rand); } if (ascendedTrait > 0) { babyArray[traitPos] = uint8(ascendedTrait); } else { // did not ascend, pick one of the parent's traits for the baby // We use the top bit of rand for this (the bottom three bits were used // to check for the ascension itself). rand = _sliceNumber(randomN, 1, randomIndex); randomIndex += 1; if (rand == 0) { babyArray[traitPos] = uint8(genes1Array[traitPos]); } else { babyArray[traitPos] = uint8(genes2Array[traitPos]); } } } return encode(babyArray); }
function mixGenes(uint256 _genes1, uint256 _genes2, uint256 _targetBlock) public returns (uint256) { require(block.number > _targetBlock); // Try to grab the hash of the "target block". This should be available the vast // majority of the time (it will only fail if no-one calls giveBirth() within 256 // blocks of the target block, which is about 40 minutes. Since anyone can call // giveBirth() and they are rewarded with ether if it succeeds, this is quite unlikely.) uint256 randomN = uint256(block.blockhash(_targetBlock)); if (randomN == 0) { // We don't want to completely bail if the target block is no-longer available, // nor do we want to just use the current block's hash (since it could allow a // caller to game the random result). Compute the most recent block that has the // the same value modulo 256 as the target block. The hash for this block will // still be available, and – while it can still change as time passes – it will // only change every 40 minutes. Again, someone is very likely to jump in with // the giveBirth() call before it can cycle too many times. _targetBlock = (block.number & maskFirst248Bits) + (_targetBlock & maskLast8Bits); // The computation above could result in a block LARGER than the current block, // if so, subtract 256. if (_targetBlock >= block.number) _targetBlock -= 256; randomN = uint256(block.blockhash(_targetBlock)); // DEBUG ONLY // assert(block.number != _targetBlock); // assert((block.number - _targetBlock) <= 256); // assert(randomN != 0); } // generate 256 bits of random, using as much entropy as we can from // sources that can't change between calls. randomN = uint256(keccak256(randomN, _genes1, _genes2, _targetBlock)); uint256 randomIndex = 0; uint8[] memory genes1Array = decode(_genes1); uint8[] memory genes2Array = decode(_genes2); // All traits that will belong to baby uint8[] memory babyArray = new uint8[](48); // A pointer to the trait we are dealing with currently uint256 traitPos; // Trait swap value holder uint8 swap; // iterate all 12 characteristics for(uint256 i = 0; i < 12; i++) { // pick 4 traits for characteristic i uint256 j; // store the current random value uint256 rand; for(j = 3; j >= 1; j--) { traitPos = (i * 4) + j; rand = _sliceNumber(randomN, 2, randomIndex); // 0~3 randomIndex += 2; // 1/4 of a chance of gene swapping forward towards expressing. if (rand == 0) { // do it for parent 1 swap = genes1Array[traitPos]; genes1Array[traitPos] = genes1Array[traitPos - 1]; genes1Array[traitPos - 1] = swap; } rand = _sliceNumber(randomN, 2, randomIndex); // 0~3 randomIndex += 2; if (rand == 0) { // do it for parent 2 swap = genes2Array[traitPos]; genes2Array[traitPos] = genes2Array[traitPos - 1]; genes2Array[traitPos - 1] = swap; } } } // DEBUG ONLY - We should have used 72 2-bit slices above for the swapping // which will have consumed 144 bits. // assert(randomIndex == 144); // We have 256 - 144 = 112 bits of randomness left at this point. We will use up to // four bits for the first slot of each trait (three for the possible ascension, one // to pick between mom and dad if the ascension fails, for a total of 48 bits. The other // traits use one bit to pick between parents (36 gene pairs, 36 genes), leaving us // well within our entropy budget. // done shuffling parent genes, now let's decide on choosing trait and if ascending. // NOTE: Ascensions ONLY happen in the "top slot" of each characteristic. This saves // gas and also ensures ascensions only happen when they're visible. for(traitPos = 0; traitPos < 48; traitPos++) { // See if this trait pair should ascend uint8 ascendedTrait = 0; // There are two checks here. The first is straightforward, only the trait // in the first slot can ascend. The first slot is zero mod 4. // // The second check is more subtle: Only values that are one apart can ascend, // which is what we check inside the _ascend method. However, this simple mask // and compare is very cheap (9 gas) and will filter out about half of the // non-ascending pairs without a function call. // // The comparison itself just checks that one value is even, and the other // is odd. if ((traitPos % 4 == 0) && (genes1Array[traitPos] & 1) != (genes2Array[traitPos] & 1)) { rand = _sliceNumber(randomN, 3, randomIndex); randomIndex += 3; ascendedTrait = _ascend(genes1Array[traitPos], genes2Array[traitPos], rand); } if (ascendedTrait > 0) { babyArray[traitPos] = uint8(ascendedTrait); } else { // did not ascend, pick one of the parent's traits for the baby // We use the top bit of rand for this (the bottom three bits were used // to check for the ascension itself). rand = _sliceNumber(randomN, 1, randomIndex); randomIndex += 1; if (rand == 0) { babyArray[traitPos] = uint8(genes1Array[traitPos]); } else { babyArray[traitPos] = uint8(genes2Array[traitPos]); } } } return encode(babyArray); }
46,635
173
// Allow refund to investors. Available to the owner of the contract.
function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; RefundsEnabled(); }
function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; RefundsEnabled(); }
27,824
16
// TODO: Check price
IUniswapV2Router02(_sushiswap).swapExactTokensForTokens( sushiBalance, uint256(0), paths, address(this), block.timestamp + 1800 );
IUniswapV2Router02(_sushiswap).swapExactTokensForTokens( sushiBalance, uint256(0), paths, address(this), block.timestamp + 1800 );
23,119
14
// Adds a token as approved. _token The address of the token to be approved.return A boolean indicating whether the operation was successful or not. /
function approveToken(address _token) external onlyAdmin returns (bool) { require(!approvedTokens[address(this)][_token], "Token is already approved"); approvedTokens[address(this)][_token] = true; emit TokenApproved(_token); return true; }
function approveToken(address _token) external onlyAdmin returns (bool) { require(!approvedTokens[address(this)][_token], "Token is already approved"); approvedTokens[address(this)][_token] = true; emit TokenApproved(_token); return true; }
17,368
31
// Get a project info _projectId Project Id to fetchreturn Project /
function getProject( uint256 _projectId ) public view returns (Project memory)
function getProject( uint256 _projectId ) public view returns (Project memory)
13,652
7
// 35% of entryFee_ (i.e. 7% dividends) is given to referrer
uint8 constant internal refferalFee_ = 35; uint256 constant internal tokenPriceInitial_ = 0.00180000 ether; uint256 constant internal tokenPriceIncremental_ = 0.000000001 ether; uint256 constant internal magnitude = 2 ** 64;
uint8 constant internal refferalFee_ = 35; uint256 constant internal tokenPriceInitial_ = 0.00180000 ether; uint256 constant internal tokenPriceIncremental_ = 0.000000001 ether; uint256 constant internal magnitude = 2 ** 64;
48,127
29
// Cast a vote._choiceIndex the vote choice index./
function castVote(uint256 _choiceIndex) internal onlyIfActive onlyIfUserVoteAbsent onlyIfValidChoiceIndex(_choiceIndex) onlyIfAuthorizedUser
function castVote(uint256 _choiceIndex) internal onlyIfActive onlyIfUserVoteAbsent onlyIfValidChoiceIndex(_choiceIndex) onlyIfAuthorizedUser
22,089
43
// If an address is holding X percent of the supply, then it can claim up to X percent of the reward pool
uint256 reward = bnbPool * balance / holdersAmount; if (reward > _maxClaimAllowed) { reward = _maxClaimAllowed; }
uint256 reward = bnbPool * balance / holdersAmount; if (reward > _maxClaimAllowed) { reward = _maxClaimAllowed; }
4,996
54
// Pull `tokenB` from msg.sender to add to Uniswap V2 Pair. Warning: calls into msg.sender using `safeTransferFrom`. Msg.sender is not trusted.
IERC20(tokenB).safeTransferFrom( msg.sender, address(this), amountBDesired );
IERC20(tokenB).safeTransferFrom( msg.sender, address(this), amountBDesired );
34,062
7
// bump the current data to the list of old adrs before adding new data
uint id = stateCount ++; state a = stateList[id]; a.ipfsAddr = currentAddr; a.date = dateUpdated;
uint id = stateCount ++; state a = stateList[id]; a.ipfsAddr = currentAddr; a.date = dateUpdated;
10,506
4
// A unique identifier of the AS.
bytes32 schema;
bytes32 schema;
33,512
200
// Changes the reward points for the provided tokens. Reward points are a weighting system that enables certaintokens to accrue DMG faster than others, allowing the protocol to prioritize certain deposits. At the start ofseason 1, mETH had points of 100 (equalling 1) and the stablecoins had 200, doubling their weight against mETH. /
function setRewardPointsByTokens(
function setRewardPointsByTokens(
40,370
12
// -----------------------------------------------------
function claim() whenNotPaused public { uint256 rewardClass = checkFind(msg.sender); require(!balances.checkClaimed(msg.sender)); require(rewardClass != 9000); balances.setClaimed(msg.sender); balances.addBalance(msg.sender, rewardClass, msg.sender); emit Mine(msg.sender, rewardClass, msg.sender); }
function claim() whenNotPaused public { uint256 rewardClass = checkFind(msg.sender); require(!balances.checkClaimed(msg.sender)); require(rewardClass != 9000); balances.setClaimed(msg.sender); balances.addBalance(msg.sender, rewardClass, msg.sender); emit Mine(msg.sender, rewardClass, msg.sender); }
45,914
52
// 重置时间
releaseTime += month30; success = true;
releaseTime += month30; success = true;
12,519
11
// public actions
function giftCode(address to) onlyOwner public returns (uint256)
function giftCode(address to) onlyOwner public returns (uint256)
56,897
127
// Public functions /
function transfer(address to, uint value) public returns (bool); function transferFrom(address from, address to, uint value) public returns (bool); function approve(address spender, uint value) public returns (bool); function balanceOf(address owner) public view returns (uint); function allowance(address owner, address spender) public view returns (uint); function totalSupply() public view returns (uint);
function transfer(address to, uint value) public returns (bool); function transferFrom(address from, address to, uint value) public returns (bool); function approve(address spender, uint value) public returns (bool); function balanceOf(address owner) public view returns (uint); function allowance(address owner, address spender) public view returns (uint); function totalSupply() public view returns (uint);
24,324
9
// In order to fetch and display all ARI
mapping(uint256 => bytes32[]) public houseArikeyMap;
mapping(uint256 => bytes32[]) public houseArikeyMap;
13,443
113
// add token to set
assert(_bonusTokenSet.add(bonusToken));
assert(_bonusTokenSet.add(bonusToken));
72,013
100
// Ensure that the escape hatch account is the caller.
if (msg.sender != escapeHatch) { revert(_revertReason(7)); }
if (msg.sender != escapeHatch) { revert(_revertReason(7)); }
32,032
8
// Transfer prize to the winner
payable(winner).transfer(address(this).balance); uint256 amountToBurn = depositors[winner].totalDeposited; burnedPRIZE = amountToBurn; // Update the burnedPRIZE variable prizeToken.transfer(0x000000000000000000000000000000000000dEaD, amountToBurn); emit WinnerSet(winner);
payable(winner).transfer(address(this).balance); uint256 amountToBurn = depositors[winner].totalDeposited; burnedPRIZE = amountToBurn; // Update the burnedPRIZE variable prizeToken.transfer(0x000000000000000000000000000000000000dEaD, amountToBurn); emit WinnerSet(winner);
29,782
28
// Single use contract for testing No hiding or revealing
contract HigherLower is Admin { // Current bets mapping (uint256 => mapping (address => uint)) public bets; mapping (uint256 => uint) public betTotals; address public currentWinner; uint public currentGame; // Timestamps for when to deal with bets uint public betLength = 60; uint public claimLength = 30; uint public endBets; uint public startNext; // Events event Bet(address player, uint amount); event Withdraw(address player, uint amount); event NewCurrentWinner(address winner); event PrizesClaimed(address winner); event NewGame(uint number); // Errors error TooLate(uint time); error TooEarly(uint time); // Modifiers modifier onlyBefore(uint _time) { if (block.timestamp >= _time) revert TooLate(_time); _; } modifier onlyAfter(uint _time) { if (block.timestamp <= _time) revert TooEarly(_time); _; } constructor() Admin() { currentWinner = owner(); currentGame = 1; // Bet time = betLength seconds endBets = block.timestamp + betLength; // Time to collect prizes = claimLength seconds startNext = endBets + claimLength; // Sets the winner's bets to 0 bets[currentGame][currentWinner] = 0; // Sets the current game's bet total to 0 betTotals[currentGame] = 0; } // Starts the next game function startNextGame() public onlyAfter(startNext) { // Winner starts as owner currentWinner = owner(); // Starts new game currentGame++; endBets = block.timestamp + betLength; startNext = endBets + claimLength; bets[currentGame][currentWinner] = 0; betTotals[currentGame] = 0; emit NewGame(currentGame); } // Adds bet to current game function bet() public payable onlyBefore(endBets) { bets[currentGame][msg.sender] += msg.value; betTotals[currentGame] += msg.value; if (bets[currentGame][msg.sender] > bets[currentGame][currentWinner]) { currentWinner = msg.sender; emit NewCurrentWinner(currentWinner); } emit Bet(msg.sender, msg.value); } // Current betters can withdraw their bets if they're not the current winner function withdraw(uint amount) public onlyBefore(endBets) { // The current winner cannot withdraw require(msg.sender != currentWinner); require(amount <= bets[currentGame][msg.sender]); require(amount <= address(this).balance); bets[currentGame][msg.sender] -= amount; betTotals[currentGame] -= amount; // Send the bets they made in the current game Address.sendValue(payable(msg.sender), bets[currentGame][msg.sender]); emit Withdraw(msg.sender, amount); } // Winner claims all bets made during the game they won in function claim() public onlyAfter(endBets) onlyBefore(startNext) { require(msg.sender == currentWinner); uint total = betTotals[currentGame]; // Sets the bet total to 0 betTotals[currentGame] = 0; // Lets new game start immediately after startNext = block.timestamp; // Sends all bets in the current game Address.sendValue(payable(msg.sender), total); emit PrizesClaimed(currentWinner); } // View methods: // Gets the current bet of an address function getCurrentBet() public view returns (uint) { return bets[currentGame][msg.sender]; } // Gets the current total bets of the game function getCurrentTotal() public view returns (uint) { return betTotals[currentGame]; } // Gets the time left before betting closes function getTimeLeft() public view returns (uint) { require(endBets > block.timestamp); return endBets - block.timestamp; } // Gets whether the prize is claimable or not function getClaimable() public view returns (bool) { return block.timestamp > endBets && block.timestamp < startNext; } // Gets whether a new game is possible function getNewGame() public view returns (bool) { return block.timestamp > startNext; } }
contract HigherLower is Admin { // Current bets mapping (uint256 => mapping (address => uint)) public bets; mapping (uint256 => uint) public betTotals; address public currentWinner; uint public currentGame; // Timestamps for when to deal with bets uint public betLength = 60; uint public claimLength = 30; uint public endBets; uint public startNext; // Events event Bet(address player, uint amount); event Withdraw(address player, uint amount); event NewCurrentWinner(address winner); event PrizesClaimed(address winner); event NewGame(uint number); // Errors error TooLate(uint time); error TooEarly(uint time); // Modifiers modifier onlyBefore(uint _time) { if (block.timestamp >= _time) revert TooLate(_time); _; } modifier onlyAfter(uint _time) { if (block.timestamp <= _time) revert TooEarly(_time); _; } constructor() Admin() { currentWinner = owner(); currentGame = 1; // Bet time = betLength seconds endBets = block.timestamp + betLength; // Time to collect prizes = claimLength seconds startNext = endBets + claimLength; // Sets the winner's bets to 0 bets[currentGame][currentWinner] = 0; // Sets the current game's bet total to 0 betTotals[currentGame] = 0; } // Starts the next game function startNextGame() public onlyAfter(startNext) { // Winner starts as owner currentWinner = owner(); // Starts new game currentGame++; endBets = block.timestamp + betLength; startNext = endBets + claimLength; bets[currentGame][currentWinner] = 0; betTotals[currentGame] = 0; emit NewGame(currentGame); } // Adds bet to current game function bet() public payable onlyBefore(endBets) { bets[currentGame][msg.sender] += msg.value; betTotals[currentGame] += msg.value; if (bets[currentGame][msg.sender] > bets[currentGame][currentWinner]) { currentWinner = msg.sender; emit NewCurrentWinner(currentWinner); } emit Bet(msg.sender, msg.value); } // Current betters can withdraw their bets if they're not the current winner function withdraw(uint amount) public onlyBefore(endBets) { // The current winner cannot withdraw require(msg.sender != currentWinner); require(amount <= bets[currentGame][msg.sender]); require(amount <= address(this).balance); bets[currentGame][msg.sender] -= amount; betTotals[currentGame] -= amount; // Send the bets they made in the current game Address.sendValue(payable(msg.sender), bets[currentGame][msg.sender]); emit Withdraw(msg.sender, amount); } // Winner claims all bets made during the game they won in function claim() public onlyAfter(endBets) onlyBefore(startNext) { require(msg.sender == currentWinner); uint total = betTotals[currentGame]; // Sets the bet total to 0 betTotals[currentGame] = 0; // Lets new game start immediately after startNext = block.timestamp; // Sends all bets in the current game Address.sendValue(payable(msg.sender), total); emit PrizesClaimed(currentWinner); } // View methods: // Gets the current bet of an address function getCurrentBet() public view returns (uint) { return bets[currentGame][msg.sender]; } // Gets the current total bets of the game function getCurrentTotal() public view returns (uint) { return betTotals[currentGame]; } // Gets the time left before betting closes function getTimeLeft() public view returns (uint) { require(endBets > block.timestamp); return endBets - block.timestamp; } // Gets whether the prize is claimable or not function getClaimable() public view returns (bool) { return block.timestamp > endBets && block.timestamp < startNext; } // Gets whether a new game is possible function getNewGame() public view returns (bool) { return block.timestamp > startNext; } }
34,617
51
// Modifies `self` to contain everything from the first occurrence of `needle` to the end of the slice. `self` is set to the empty slice if `needle` is not found. self The slice to search and modify. needle The text to search for.return `self`. /
function find(slice memory self, slice memory needle) internal pure returns (slice memory) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); self._len -= ptr - self._ptr; self._ptr = ptr; return self; }
function find(slice memory self, slice memory needle) internal pure returns (slice memory) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); self._len -= ptr - self._ptr; self._ptr = ptr; return self; }
289
60
// 1.判断是否首次投资,若是首次则只能投1~2级,否则可以任意投资级别
if(user.investDataIndex == 0) { require(money < paramsMapping[3003],"invalid first invest range"); } else {
if(user.investDataIndex == 0) { require(money < paramsMapping[3003],"invalid first invest range"); } else {
12,723
0
// STRUCTURE DEFINATIONS/
struct StoremanGroupConfig { uint deposit; uint[2] chain; uint[2] curve; bytes gpk1; bytes gpk2; uint startTime; uint endTime; uint8 status; bool isDebtClean; }
struct StoremanGroupConfig { uint deposit; uint[2] chain; uint[2] curve; bytes gpk1; bytes gpk2; uint startTime; uint endTime; uint8 status; bool isDebtClean; }
50,151
262
// These functions deal with verification of Merkle Tree proofs. The tree and the proofs can be generated using ourYou will find a quickstart guide in the readme. WARNING: You should avoid using leaf values that are 64 bytes long prior tohashing, or use a hash function other than keccak256 for hashing leaves.This is because the concatenation of a sorted pair of internal nodes inthe merkle tree could be reinterpreted as a leaf value.OpenZeppelin's JavaScript library generates merkle trees that are safeagainst this attack out of the box. /
library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Calldata version of {verify} * * _Available since v4.7._ */ function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { return processProofCalldata(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { computedHash = _hashPair(computedHash, proof[i]); } return computedHash; } /** * @dev Calldata version of {processProof} * * _Available since v4.7._ */ function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { computedHash = _hashPair(computedHash, proof[i]); } return computedHash; } /** * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a merkle tree defined by * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}. * * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details. * * _Available since v4.7._ */ function multiProofVerify( bytes32[] memory proof, bool[] memory proofFlags, bytes32 root, bytes32[] memory leaves ) internal pure returns (bool) { return processMultiProof(proof, proofFlags, leaves) == root; } /** * @dev Calldata version of {multiProofVerify} * * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details. * * _Available since v4.7._ */ function multiProofVerifyCalldata( bytes32[] calldata proof, bool[] calldata proofFlags, bytes32 root, bytes32[] memory leaves ) internal pure returns (bool) { return processMultiProofCalldata(proof, proofFlags, leaves) == root; } /** * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false * respectively. * * CAUTION: Not all merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer). * * _Available since v4.7._ */ function processMultiProof( bytes32[] memory proof, bool[] memory proofFlags, bytes32[] memory leaves ) internal pure returns (bytes32 merkleRoot) { // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of // the merkle tree. uint256 leavesLen = leaves.length; uint256 proofLen = proof.length; uint256 totalHashes = proofFlags.length; // Check proof validity. require(leavesLen + proofLen - 1 == totalHashes, "MerkleProof: invalid multiproof"); // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop". bytes32[] memory hashes = new bytes32[](totalHashes); uint256 leafPos = 0; uint256 hashPos = 0; uint256 proofPos = 0; // At each step, we compute the next hash using two values: // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we // get the next hash. // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the // `proof` array. for (uint256 i = 0; i < totalHashes; i++) { bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++]; bytes32 b = proofFlags[i] ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++]) : proof[proofPos++]; hashes[i] = _hashPair(a, b); } if (totalHashes > 0) { require(proofPos == proofLen, "MerkleProof: invalid multiproof"); unchecked { return hashes[totalHashes - 1]; } } else if (leavesLen > 0) { return leaves[0]; } else { return proof[0]; } } /** * @dev Calldata version of {processMultiProof}. * * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details. * * _Available since v4.7._ */ function processMultiProofCalldata( bytes32[] calldata proof, bool[] calldata proofFlags, bytes32[] memory leaves ) internal pure returns (bytes32 merkleRoot) { // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of // the merkle tree. uint256 leavesLen = leaves.length; uint256 proofLen = proof.length; uint256 totalHashes = proofFlags.length; // Check proof validity. require(leavesLen + proofLen - 1 == totalHashes, "MerkleProof: invalid multiproof"); // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop". bytes32[] memory hashes = new bytes32[](totalHashes); uint256 leafPos = 0; uint256 hashPos = 0; uint256 proofPos = 0; // At each step, we compute the next hash using two values: // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we // get the next hash. // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the // `proof` array. for (uint256 i = 0; i < totalHashes; i++) { bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++]; bytes32 b = proofFlags[i] ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++]) : proof[proofPos++]; hashes[i] = _hashPair(a, b); } if (totalHashes > 0) { require(proofPos == proofLen, "MerkleProof: invalid multiproof"); unchecked { return hashes[totalHashes - 1]; } } else if (leavesLen > 0) { return leaves[0]; } else { return proof[0]; } } function _hashPair(bytes32 a, bytes32 b) private pure returns (bytes32) { return a < b ? _efficientHash(a, b) : _efficientHash(b, a); } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { /// @solidity memory-safe-assembly assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } }
library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Calldata version of {verify} * * _Available since v4.7._ */ function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { return processProofCalldata(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { computedHash = _hashPair(computedHash, proof[i]); } return computedHash; } /** * @dev Calldata version of {processProof} * * _Available since v4.7._ */ function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { computedHash = _hashPair(computedHash, proof[i]); } return computedHash; } /** * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a merkle tree defined by * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}. * * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details. * * _Available since v4.7._ */ function multiProofVerify( bytes32[] memory proof, bool[] memory proofFlags, bytes32 root, bytes32[] memory leaves ) internal pure returns (bool) { return processMultiProof(proof, proofFlags, leaves) == root; } /** * @dev Calldata version of {multiProofVerify} * * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details. * * _Available since v4.7._ */ function multiProofVerifyCalldata( bytes32[] calldata proof, bool[] calldata proofFlags, bytes32 root, bytes32[] memory leaves ) internal pure returns (bool) { return processMultiProofCalldata(proof, proofFlags, leaves) == root; } /** * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false * respectively. * * CAUTION: Not all merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer). * * _Available since v4.7._ */ function processMultiProof( bytes32[] memory proof, bool[] memory proofFlags, bytes32[] memory leaves ) internal pure returns (bytes32 merkleRoot) { // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of // the merkle tree. uint256 leavesLen = leaves.length; uint256 proofLen = proof.length; uint256 totalHashes = proofFlags.length; // Check proof validity. require(leavesLen + proofLen - 1 == totalHashes, "MerkleProof: invalid multiproof"); // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop". bytes32[] memory hashes = new bytes32[](totalHashes); uint256 leafPos = 0; uint256 hashPos = 0; uint256 proofPos = 0; // At each step, we compute the next hash using two values: // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we // get the next hash. // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the // `proof` array. for (uint256 i = 0; i < totalHashes; i++) { bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++]; bytes32 b = proofFlags[i] ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++]) : proof[proofPos++]; hashes[i] = _hashPair(a, b); } if (totalHashes > 0) { require(proofPos == proofLen, "MerkleProof: invalid multiproof"); unchecked { return hashes[totalHashes - 1]; } } else if (leavesLen > 0) { return leaves[0]; } else { return proof[0]; } } /** * @dev Calldata version of {processMultiProof}. * * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details. * * _Available since v4.7._ */ function processMultiProofCalldata( bytes32[] calldata proof, bool[] calldata proofFlags, bytes32[] memory leaves ) internal pure returns (bytes32 merkleRoot) { // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of // the merkle tree. uint256 leavesLen = leaves.length; uint256 proofLen = proof.length; uint256 totalHashes = proofFlags.length; // Check proof validity. require(leavesLen + proofLen - 1 == totalHashes, "MerkleProof: invalid multiproof"); // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop". bytes32[] memory hashes = new bytes32[](totalHashes); uint256 leafPos = 0; uint256 hashPos = 0; uint256 proofPos = 0; // At each step, we compute the next hash using two values: // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we // get the next hash. // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the // `proof` array. for (uint256 i = 0; i < totalHashes; i++) { bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++]; bytes32 b = proofFlags[i] ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++]) : proof[proofPos++]; hashes[i] = _hashPair(a, b); } if (totalHashes > 0) { require(proofPos == proofLen, "MerkleProof: invalid multiproof"); unchecked { return hashes[totalHashes - 1]; } } else if (leavesLen > 0) { return leaves[0]; } else { return proof[0]; } } function _hashPair(bytes32 a, bytes32 b) private pure returns (bytes32) { return a < b ? _efficientHash(a, b) : _efficientHash(b, a); } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { /// @solidity memory-safe-assembly assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } }
7,045