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
42
// Returns the most significant bit of a given uint256
function mostSignificantBit(uint256 x) internal pure returns (uint256) { uint8 o = 0; uint8 h = 255; while (h > o) { uint8 m = uint8 ((uint16 (o) + uint16 (h)) >> 1); uint256 t = x >> m; if (t == 0) h = m - 1; else if (t > 1) o = m + 1; else return m; } return h; }
function mostSignificantBit(uint256 x) internal pure returns (uint256) { uint8 o = 0; uint8 h = 255; while (h > o) { uint8 m = uint8 ((uint16 (o) + uint16 (h)) >> 1); uint256 t = x >> m; if (t == 0) h = m - 1; else if (t > 1) o = m + 1; else return m; } return h; }
17,386
175
// Returns collection's premint list capacity and current count collectionId_ collection ID /
function collectionPremintListDetails(uint256 collectionId_) public view returns (uint16, uint16)
function collectionPremintListDetails(uint256 collectionId_) public view returns (uint16, uint16)
34,462
18
// Derive expected offset as start of recipients + len64.
add( BasicOrder_signature_ptr, mul(
add( BasicOrder_signature_ptr, mul(
14,745
39
// Composite plus token. A composite plus token is backed by a basket of plus token. The composite plus token,along with its underlying tokens in the basket, should have the same peg. /
contract CompositePlus is ICompositePlus, Plus, ReentrancyGuardUpgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; using SafeMathUpgradeable for uint256; event Minted(address indexed user, address[] tokens, uint256[] amounts, uint256 mintShare, uint256 mintAmount); event Redeemed(address indexed user, address[] tokens, uint256[] amounts, uint256 redeemShare, uint256 redeemAmount, uint256 fee); event RebalancerUpdated(address indexed rebalancer, bool enabled); event MinLiquidityRatioUpdated(uint256 oldRatio, uint256 newRatio); event TokenAdded(address indexed token); event TokenRemoved(address indexed token); event Rebalanced(uint256 underlyingBefore, uint256 underlyingAfter, uint256 supply); // The underlying plus tokens that constitutes the composite plus token. address[] public override tokens; // Mapping: Token address => Whether the token is an underlying token. mapping(address => bool) public override tokenSupported; // Mapping: Token address => Whether minting with token is paused mapping(address => bool) public mintPaused; // Mapping: Address => Whether this is a rebalancer contract. mapping(address => bool) public rebalancers; // Liquidity ratio = Total supply / Total underlying // Liquidity ratio should larger than 1 in most cases except a short period after rebalance. // Minimum liquidity ratio sets the upper bound of impermanent loss caused by rebalance. uint256 public minLiquidityRatio; /** * @dev Initlaizes the composite plus token. */ function initialize(string memory _name, string memory _symbol) public initializer { __PlusToken__init(_name, _symbol); __ReentrancyGuard_init(); } /** * @dev Returns the total value of the plus token in terms of the peg value. * All underlying token amounts have been scaled to 18 decimals and expressed in WAD. */ function _totalUnderlyingInWad() internal view virtual override returns (uint256) { uint256 _amount = 0; for (uint256 i = 0; i < tokens.length; i++) { // Since all underlying tokens in the baskets are plus tokens with the same value peg, the amount // minted is the amount of all plus tokens in the basket added. // Note: All plus tokens, single or composite, have 18 decimals. _amount = _amount.add(IERC20Upgradeable(tokens[i]).balanceOf(address(this))); } // Plus tokens are in 18 decimals, need to return in WAD. return _amount.mul(WAD); } /** * @dev Returns the amount of composite plus tokens minted with the tokens provided. * @dev _tokens The tokens used to mint the composite plus token. * @dev _amounts Amount of tokens used to mint the composite plus token. */ function getMintAmount(address[] calldata _tokens, uint256[] calldata _amounts) external view override returns(uint256) { require(_tokens.length == _amounts.length, "invalid input"); uint256 _amount = 0; for (uint256 i = 0; i < _tokens.length; i++) { require(!mintPaused[_tokens[i]], "token paused"); require(tokenSupported[_tokens[i]], "token not supported"); if (_amounts[i] == 0) continue; // Since all underlying tokens in the baskets are plus tokens with the same value peg, the amount // minted is the amount of all tokens to mint added. // Note: All plus tokens, single or composite, have 18 decimals. _amount = _amount.add(_amounts[i]); } return _amount; } /** * @dev Mints composite plus tokens with underlying tokens provided. * @dev _tokens The tokens used to mint the composite plus token. The composite plus token must have sufficient allownance on the token. * @dev _amounts Amount of tokens used to mint the composite plus token. */ function mint(address[] calldata _tokens, uint256[] calldata _amounts) external override nonReentrant { require(_tokens.length == _amounts.length, "invalid input"); // Rebase first to make index up-to-date rebase(); uint256 _amount = 0; for (uint256 i = 0; i < _tokens.length; i++) { require(tokenSupported[_tokens[i]], "token not supported"); require(!mintPaused[_tokens[i]], "token paused"); if (_amounts[i] == 0) continue; _amount = _amount.add(_amounts[i]); // Transfers the token into pool. IERC20Upgradeable(_tokens[i]).safeTransferFrom(msg.sender, address(this), _amounts[i]); } uint256 _share = _amount.mul(WAD).div(index); uint256 _oldShare = userShare[msg.sender]; uint256 _newShare = _oldShare.add(_share); uint256 _totalShares = totalShares.add(_share); totalShares = _totalShares; userShare[msg.sender] = _newShare; emit UserShareUpdated(msg.sender, _oldShare, _newShare, _totalShares); emit Minted(msg.sender, _tokens, _amounts, _share, _amount); emit Transfer(address(0x0), msg.sender, _amount); } /** * @dev Returns the amount of tokens received in redeeming the composite plus token. * @param _amount Amounf of composite plus to redeem. * @return Addresses and amounts of tokens returned as well as fee collected. */ function getRedeemAmount(uint256 _amount) external view override returns (address[] memory, uint256[] memory, uint256, uint256) { require(_amount > 0, "zero amount"); // Special handling of -1 is required here in order to fully redeem all shares, since interest // will be accrued between the redeem transaction is signed and mined. uint256 _share; if (_amount == uint256(int256(-1))) { _share = userShare[msg.sender]; _amount = _share.mul(index).div(WAD); } else { _share = _amount.mul(WAD).div(index); } // Withdraw ratio = min(liquidity ratio, 1 - redeem fee) // Liquidity ratio is in WAD and redeem fee is in 0.01% uint256 _withdrawAmount1 = _amount.mul(liquidityRatio()).div(WAD); uint256 _withdrawAmount2 = _amount.mul(MAX_PERCENT - redeemFee).div(MAX_PERCENT); uint256 _withdrawAmount = MathUpgradeable.min(_withdrawAmount1, _withdrawAmount2); uint256 _fee = _amount.sub(_withdrawAmount); address[] memory _redeemTokens = tokens; uint256[] memory _redeemAmounts = new uint256[](_redeemTokens.length); uint256 _totalSupply = totalSupply(); for (uint256 i = 0; i < _redeemTokens.length; i++) { uint256 _balance = IERC20Upgradeable(_redeemTokens[i]).balanceOf(address(this)); if (_balance == 0) continue; _redeemAmounts[i] = _balance.mul(_withdrawAmount).div(_totalSupply); } return (_redeemTokens, _redeemAmounts, _share, _fee); } /** * @dev Redeems the composite plus token. In the current implementation only proportional redeem is supported. * @param _amount Amount of composite plus token to redeem. -1 means redeeming all shares. */ function redeem(uint256 _amount) external override nonReentrant { require(_amount > 0, "zero amount"); // Rebase first to make index up-to-date rebase(); // Special handling of -1 is required here in order to fully redeem all shares, since interest // will be accrued between the redeem transaction is signed and mined. uint256 _share; if (_amount == uint256(int256(-1))) { _share = userShare[msg.sender]; _amount = _share.mul(index).div(WAD); } else { _share = _amount.mul(WAD).div(index); } // Withdraw ratio = min(liquidity ratio, 1 - redeem fee) uint256 _withdrawAmount1 = _amount.mul(liquidityRatio()).div(WAD); uint256 _withdrawAmount2 = _amount.mul(MAX_PERCENT - redeemFee).div(MAX_PERCENT); uint256 _withdrawAmount = MathUpgradeable.min(_withdrawAmount1, _withdrawAmount2); uint256 _fee = _amount.sub(_withdrawAmount); address[] memory _redeemTokens = tokens; uint256[] memory _redeemAmounts = new uint256[](_redeemTokens.length); uint256 _totalSupply = totalSupply(); for (uint256 i = 0; i < _redeemTokens.length; i++) { uint256 _balance = IERC20Upgradeable(_redeemTokens[i]).balanceOf(address(this)); if (_balance == 0) continue; _redeemAmounts[i] = _balance.mul(_withdrawAmount).div(_totalSupply); IERC20Upgradeable(_redeemTokens[i]).safeTransfer(msg.sender, _redeemAmounts[i]); } // Updates the balance uint256 _oldShare = userShare[msg.sender]; uint256 _newShare = _oldShare.sub(_share); totalShares = totalShares.sub(_share); userShare[msg.sender] = _newShare; emit UserShareUpdated(msg.sender, _oldShare, _newShare, totalShares); emit Redeemed(msg.sender, _redeemTokens, _redeemAmounts, _share, _amount, _fee); emit Transfer(msg.sender, address(0x0), _amount); } /** * @dev Updates the mint paused state of a token. * @param _token Token to update mint paused. * @param _paused Whether minting with that token is paused. */ function setMintPaused(address _token, bool _paused) external onlyStrategist { require(tokenSupported[_token], "not supported"); require(mintPaused[_token] != _paused, "no change"); mintPaused[_token] = _paused; emit MintPausedUpdated(_token, _paused); } /** * @dev Adds a new rebalancer. Only governance can add new rebalancers. */ function addRebalancer(address _rebalancer) external onlyGovernance { require(_rebalancer != address(0x0), "rebalancer not set"); require(!rebalancers[_rebalancer], "rebalancer exist"); rebalancers[_rebalancer] = true; emit RebalancerUpdated(_rebalancer, true); } /** * @dev Remove an existing rebalancer. Only strategist can remove existing rebalancers. */ function removeRebalancer(address _rebalancer) external onlyStrategist { require(rebalancers[_rebalancer], "rebalancer exist"); rebalancers[_rebalancer] = false; emit RebalancerUpdated(_rebalancer, false); } /** * @dev Udpates the minimum liquidity ratio. Only governance can update minimum liquidity ratio. */ function setMinLiquidityRatio(uint256 _minLiquidityRatio) external onlyGovernance { require(_minLiquidityRatio <= WAD, "overflow"); require(_minLiquidityRatio <= liquidityRatio(), "ratio too big"); uint256 _oldRatio = minLiquidityRatio; minLiquidityRatio = _minLiquidityRatio; emit MinLiquidityRatioUpdated(_oldRatio, _minLiquidityRatio); } /** * @dev Adds a new plus token to the basket. Only governance can add new plus token. * @param _token The new plus token to add. */ function addToken(address _token) external onlyGovernance { require(_token != address(0x0), "token not set"); require(!tokenSupported[_token], "token exists"); tokenSupported[_token] = true; tokens.push(_token); emit TokenAdded(_token); } /** * @dev Removes a plus token from the basket. Only governance can remove a plus token. * Note: A token cannot be removed if it's balance is not zero! * @param _token The plus token to remove from the basket. */ function removeToken(address _token) external onlyGovernance { require(tokenSupported[_token], "token not exists"); require(IERC20Upgradeable(_token).balanceOf(address(this)) == 0, "nonzero balance"); uint256 _tokenSize = tokens.length; uint256 _tokenIndex = _tokenSize; for (uint256 i = 0; i < _tokenSize; i++) { if (tokens[i] == _token) { _tokenIndex = i; break; } } // We must have found the token! assert(_tokenIndex < _tokenSize); tokens[_tokenIndex] = tokens[_tokenSize - 1]; tokens.pop(); delete tokenSupported[_token]; // Delete the mint paused state as well delete mintPaused[_token]; emit TokenRemoved(_token); } /** * @dev Return the total number of tokens. */ function tokenSize() external view returns (uint256) { return tokens.length; } /** * @dev Returns the list of plus tokens. */ function tokenList() external view override returns (address[] memory) { return tokens; } /** * @dev Rebalances the basket, e.g. for a better yield. Only strategist can perform rebalance. * @param _tokens Address of the tokens to withdraw from the basket. * @param _amounts Amounts of the tokens to withdraw from the basket. * @param _rebalancer Address of the rebalancer contract to invoke. * @param _data Data to invoke on rebalancer contract. */ function rebalance(address[] memory _tokens, uint256[] memory _amounts, address _rebalancer, bytes calldata _data) external onlyStrategist { require(rebalancers[_rebalancer], "invalid rebalancer"); require(_tokens.length == _amounts.length, "invalid input"); // Rebase first to make index up-to-date rebase(); uint256 _underlyingBefore = _totalUnderlyingInWad(); for (uint256 i = 0; i < _tokens.length; i++) { require(tokenSupported[_tokens[i]], "token not supported"); if (_amounts[i] == 0) continue; IERC20Upgradeable(_tokens[i]).safeTransfer(_rebalancer, _amounts[i]); } // Invokes rebalancer contract. IRebalancer(_rebalancer).rebalance(_tokens, _amounts, _data); // Check post-rebalance conditions. uint256 _underlyingAfter = _totalUnderlyingInWad(); uint256 _supply = totalSupply(); // _underlyingAfter / _supply > minLiquidityRatio require(_underlyingAfter > _supply.mul(minLiquidityRatio), "too much loss"); emit Rebalanced(_underlyingBefore, _underlyingAfter, _supply); } /** * @dev Checks whether a token can be salvaged via salvageToken(). * @param _token Token to check salvageability. */ function _salvageable(address _token) internal view override returns (bool) { // For composite plus, all tokens in the basekt cannot be salvaged! return !tokenSupported[_token]; } uint256[50] private __gap; }
contract CompositePlus is ICompositePlus, Plus, ReentrancyGuardUpgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; using SafeMathUpgradeable for uint256; event Minted(address indexed user, address[] tokens, uint256[] amounts, uint256 mintShare, uint256 mintAmount); event Redeemed(address indexed user, address[] tokens, uint256[] amounts, uint256 redeemShare, uint256 redeemAmount, uint256 fee); event RebalancerUpdated(address indexed rebalancer, bool enabled); event MinLiquidityRatioUpdated(uint256 oldRatio, uint256 newRatio); event TokenAdded(address indexed token); event TokenRemoved(address indexed token); event Rebalanced(uint256 underlyingBefore, uint256 underlyingAfter, uint256 supply); // The underlying plus tokens that constitutes the composite plus token. address[] public override tokens; // Mapping: Token address => Whether the token is an underlying token. mapping(address => bool) public override tokenSupported; // Mapping: Token address => Whether minting with token is paused mapping(address => bool) public mintPaused; // Mapping: Address => Whether this is a rebalancer contract. mapping(address => bool) public rebalancers; // Liquidity ratio = Total supply / Total underlying // Liquidity ratio should larger than 1 in most cases except a short period after rebalance. // Minimum liquidity ratio sets the upper bound of impermanent loss caused by rebalance. uint256 public minLiquidityRatio; /** * @dev Initlaizes the composite plus token. */ function initialize(string memory _name, string memory _symbol) public initializer { __PlusToken__init(_name, _symbol); __ReentrancyGuard_init(); } /** * @dev Returns the total value of the plus token in terms of the peg value. * All underlying token amounts have been scaled to 18 decimals and expressed in WAD. */ function _totalUnderlyingInWad() internal view virtual override returns (uint256) { uint256 _amount = 0; for (uint256 i = 0; i < tokens.length; i++) { // Since all underlying tokens in the baskets are plus tokens with the same value peg, the amount // minted is the amount of all plus tokens in the basket added. // Note: All plus tokens, single or composite, have 18 decimals. _amount = _amount.add(IERC20Upgradeable(tokens[i]).balanceOf(address(this))); } // Plus tokens are in 18 decimals, need to return in WAD. return _amount.mul(WAD); } /** * @dev Returns the amount of composite plus tokens minted with the tokens provided. * @dev _tokens The tokens used to mint the composite plus token. * @dev _amounts Amount of tokens used to mint the composite plus token. */ function getMintAmount(address[] calldata _tokens, uint256[] calldata _amounts) external view override returns(uint256) { require(_tokens.length == _amounts.length, "invalid input"); uint256 _amount = 0; for (uint256 i = 0; i < _tokens.length; i++) { require(!mintPaused[_tokens[i]], "token paused"); require(tokenSupported[_tokens[i]], "token not supported"); if (_amounts[i] == 0) continue; // Since all underlying tokens in the baskets are plus tokens with the same value peg, the amount // minted is the amount of all tokens to mint added. // Note: All plus tokens, single or composite, have 18 decimals. _amount = _amount.add(_amounts[i]); } return _amount; } /** * @dev Mints composite plus tokens with underlying tokens provided. * @dev _tokens The tokens used to mint the composite plus token. The composite plus token must have sufficient allownance on the token. * @dev _amounts Amount of tokens used to mint the composite plus token. */ function mint(address[] calldata _tokens, uint256[] calldata _amounts) external override nonReentrant { require(_tokens.length == _amounts.length, "invalid input"); // Rebase first to make index up-to-date rebase(); uint256 _amount = 0; for (uint256 i = 0; i < _tokens.length; i++) { require(tokenSupported[_tokens[i]], "token not supported"); require(!mintPaused[_tokens[i]], "token paused"); if (_amounts[i] == 0) continue; _amount = _amount.add(_amounts[i]); // Transfers the token into pool. IERC20Upgradeable(_tokens[i]).safeTransferFrom(msg.sender, address(this), _amounts[i]); } uint256 _share = _amount.mul(WAD).div(index); uint256 _oldShare = userShare[msg.sender]; uint256 _newShare = _oldShare.add(_share); uint256 _totalShares = totalShares.add(_share); totalShares = _totalShares; userShare[msg.sender] = _newShare; emit UserShareUpdated(msg.sender, _oldShare, _newShare, _totalShares); emit Minted(msg.sender, _tokens, _amounts, _share, _amount); emit Transfer(address(0x0), msg.sender, _amount); } /** * @dev Returns the amount of tokens received in redeeming the composite plus token. * @param _amount Amounf of composite plus to redeem. * @return Addresses and amounts of tokens returned as well as fee collected. */ function getRedeemAmount(uint256 _amount) external view override returns (address[] memory, uint256[] memory, uint256, uint256) { require(_amount > 0, "zero amount"); // Special handling of -1 is required here in order to fully redeem all shares, since interest // will be accrued between the redeem transaction is signed and mined. uint256 _share; if (_amount == uint256(int256(-1))) { _share = userShare[msg.sender]; _amount = _share.mul(index).div(WAD); } else { _share = _amount.mul(WAD).div(index); } // Withdraw ratio = min(liquidity ratio, 1 - redeem fee) // Liquidity ratio is in WAD and redeem fee is in 0.01% uint256 _withdrawAmount1 = _amount.mul(liquidityRatio()).div(WAD); uint256 _withdrawAmount2 = _amount.mul(MAX_PERCENT - redeemFee).div(MAX_PERCENT); uint256 _withdrawAmount = MathUpgradeable.min(_withdrawAmount1, _withdrawAmount2); uint256 _fee = _amount.sub(_withdrawAmount); address[] memory _redeemTokens = tokens; uint256[] memory _redeemAmounts = new uint256[](_redeemTokens.length); uint256 _totalSupply = totalSupply(); for (uint256 i = 0; i < _redeemTokens.length; i++) { uint256 _balance = IERC20Upgradeable(_redeemTokens[i]).balanceOf(address(this)); if (_balance == 0) continue; _redeemAmounts[i] = _balance.mul(_withdrawAmount).div(_totalSupply); } return (_redeemTokens, _redeemAmounts, _share, _fee); } /** * @dev Redeems the composite plus token. In the current implementation only proportional redeem is supported. * @param _amount Amount of composite plus token to redeem. -1 means redeeming all shares. */ function redeem(uint256 _amount) external override nonReentrant { require(_amount > 0, "zero amount"); // Rebase first to make index up-to-date rebase(); // Special handling of -1 is required here in order to fully redeem all shares, since interest // will be accrued between the redeem transaction is signed and mined. uint256 _share; if (_amount == uint256(int256(-1))) { _share = userShare[msg.sender]; _amount = _share.mul(index).div(WAD); } else { _share = _amount.mul(WAD).div(index); } // Withdraw ratio = min(liquidity ratio, 1 - redeem fee) uint256 _withdrawAmount1 = _amount.mul(liquidityRatio()).div(WAD); uint256 _withdrawAmount2 = _amount.mul(MAX_PERCENT - redeemFee).div(MAX_PERCENT); uint256 _withdrawAmount = MathUpgradeable.min(_withdrawAmount1, _withdrawAmount2); uint256 _fee = _amount.sub(_withdrawAmount); address[] memory _redeemTokens = tokens; uint256[] memory _redeemAmounts = new uint256[](_redeemTokens.length); uint256 _totalSupply = totalSupply(); for (uint256 i = 0; i < _redeemTokens.length; i++) { uint256 _balance = IERC20Upgradeable(_redeemTokens[i]).balanceOf(address(this)); if (_balance == 0) continue; _redeemAmounts[i] = _balance.mul(_withdrawAmount).div(_totalSupply); IERC20Upgradeable(_redeemTokens[i]).safeTransfer(msg.sender, _redeemAmounts[i]); } // Updates the balance uint256 _oldShare = userShare[msg.sender]; uint256 _newShare = _oldShare.sub(_share); totalShares = totalShares.sub(_share); userShare[msg.sender] = _newShare; emit UserShareUpdated(msg.sender, _oldShare, _newShare, totalShares); emit Redeemed(msg.sender, _redeemTokens, _redeemAmounts, _share, _amount, _fee); emit Transfer(msg.sender, address(0x0), _amount); } /** * @dev Updates the mint paused state of a token. * @param _token Token to update mint paused. * @param _paused Whether minting with that token is paused. */ function setMintPaused(address _token, bool _paused) external onlyStrategist { require(tokenSupported[_token], "not supported"); require(mintPaused[_token] != _paused, "no change"); mintPaused[_token] = _paused; emit MintPausedUpdated(_token, _paused); } /** * @dev Adds a new rebalancer. Only governance can add new rebalancers. */ function addRebalancer(address _rebalancer) external onlyGovernance { require(_rebalancer != address(0x0), "rebalancer not set"); require(!rebalancers[_rebalancer], "rebalancer exist"); rebalancers[_rebalancer] = true; emit RebalancerUpdated(_rebalancer, true); } /** * @dev Remove an existing rebalancer. Only strategist can remove existing rebalancers. */ function removeRebalancer(address _rebalancer) external onlyStrategist { require(rebalancers[_rebalancer], "rebalancer exist"); rebalancers[_rebalancer] = false; emit RebalancerUpdated(_rebalancer, false); } /** * @dev Udpates the minimum liquidity ratio. Only governance can update minimum liquidity ratio. */ function setMinLiquidityRatio(uint256 _minLiquidityRatio) external onlyGovernance { require(_minLiquidityRatio <= WAD, "overflow"); require(_minLiquidityRatio <= liquidityRatio(), "ratio too big"); uint256 _oldRatio = minLiquidityRatio; minLiquidityRatio = _minLiquidityRatio; emit MinLiquidityRatioUpdated(_oldRatio, _minLiquidityRatio); } /** * @dev Adds a new plus token to the basket. Only governance can add new plus token. * @param _token The new plus token to add. */ function addToken(address _token) external onlyGovernance { require(_token != address(0x0), "token not set"); require(!tokenSupported[_token], "token exists"); tokenSupported[_token] = true; tokens.push(_token); emit TokenAdded(_token); } /** * @dev Removes a plus token from the basket. Only governance can remove a plus token. * Note: A token cannot be removed if it's balance is not zero! * @param _token The plus token to remove from the basket. */ function removeToken(address _token) external onlyGovernance { require(tokenSupported[_token], "token not exists"); require(IERC20Upgradeable(_token).balanceOf(address(this)) == 0, "nonzero balance"); uint256 _tokenSize = tokens.length; uint256 _tokenIndex = _tokenSize; for (uint256 i = 0; i < _tokenSize; i++) { if (tokens[i] == _token) { _tokenIndex = i; break; } } // We must have found the token! assert(_tokenIndex < _tokenSize); tokens[_tokenIndex] = tokens[_tokenSize - 1]; tokens.pop(); delete tokenSupported[_token]; // Delete the mint paused state as well delete mintPaused[_token]; emit TokenRemoved(_token); } /** * @dev Return the total number of tokens. */ function tokenSize() external view returns (uint256) { return tokens.length; } /** * @dev Returns the list of plus tokens. */ function tokenList() external view override returns (address[] memory) { return tokens; } /** * @dev Rebalances the basket, e.g. for a better yield. Only strategist can perform rebalance. * @param _tokens Address of the tokens to withdraw from the basket. * @param _amounts Amounts of the tokens to withdraw from the basket. * @param _rebalancer Address of the rebalancer contract to invoke. * @param _data Data to invoke on rebalancer contract. */ function rebalance(address[] memory _tokens, uint256[] memory _amounts, address _rebalancer, bytes calldata _data) external onlyStrategist { require(rebalancers[_rebalancer], "invalid rebalancer"); require(_tokens.length == _amounts.length, "invalid input"); // Rebase first to make index up-to-date rebase(); uint256 _underlyingBefore = _totalUnderlyingInWad(); for (uint256 i = 0; i < _tokens.length; i++) { require(tokenSupported[_tokens[i]], "token not supported"); if (_amounts[i] == 0) continue; IERC20Upgradeable(_tokens[i]).safeTransfer(_rebalancer, _amounts[i]); } // Invokes rebalancer contract. IRebalancer(_rebalancer).rebalance(_tokens, _amounts, _data); // Check post-rebalance conditions. uint256 _underlyingAfter = _totalUnderlyingInWad(); uint256 _supply = totalSupply(); // _underlyingAfter / _supply > minLiquidityRatio require(_underlyingAfter > _supply.mul(minLiquidityRatio), "too much loss"); emit Rebalanced(_underlyingBefore, _underlyingAfter, _supply); } /** * @dev Checks whether a token can be salvaged via salvageToken(). * @param _token Token to check salvageability. */ function _salvageable(address _token) internal view override returns (bool) { // For composite plus, all tokens in the basekt cannot be salvaged! return !tokenSupported[_token]; } uint256[50] private __gap; }
76,767
127
// Queries the approval status of an operator for a given owner./owner The owner of the Tokens/operatorAddress of authorized operator/ return True if the operator is approved, false if not
function isApprovedForAll(address owner, address operator) public override view returns (bool) { bool approved = operatorApproval[owner][operator]; if (!approved && exchangesRegistry != address(0)) { return WhitelistExchangesProxy(exchangesRegistry).isAddressWhitelisted(operator) == true; } return approved; }
function isApprovedForAll(address owner, address operator) public override view returns (bool) { bool approved = operatorApproval[owner][operator]; if (!approved && exchangesRegistry != address(0)) { return WhitelistExchangesProxy(exchangesRegistry).isAddressWhitelisted(operator) == true; } return approved; }
16,444
16
// ----- EVENTS
event Transfer(address indexed fromAddr, address indexed toAddr, uint256 amount); event Approval(address indexed _owner, address indexed _spender, uint256 amount);
event Transfer(address indexed fromAddr, address indexed toAddr, uint256 amount); event Approval(address indexed _owner, address indexed _spender, uint256 amount);
29,213
2
// count to track number of games own by user
mapping(address=>uint) public ownerGameCount;
mapping(address=>uint) public ownerGameCount;
36,309
19
// ------------------------------------------------------------------------ Account can add itself as an App account ------------------------------------------------------------------------
function addApp(string appName, address _feeAccount, uint _fee) public { App storage e = apps[msg.sender]; require(e.appAccount == address(0)); apps[msg.sender] = App({ appAccount: msg.sender, appName: appName, feeAccount: _feeAccount, fee: _fee, active: true }); appAccounts.push(msg.sender); AppAdded(msg.sender, appName, _feeAccount, _fee, true); }
function addApp(string appName, address _feeAccount, uint _fee) public { App storage e = apps[msg.sender]; require(e.appAccount == address(0)); apps[msg.sender] = App({ appAccount: msg.sender, appName: appName, feeAccount: _feeAccount, fee: _fee, active: true }); appAccounts.push(msg.sender); AppAdded(msg.sender, appName, _feeAccount, _fee, true); }
2,810
10
// checks if the input skill is alredy stored in DatabaseSkills contract/_skill The sought skill
function checkSkillExistence(bytes32 _skill) public view returns (bool) { return dbSkills.checkSkillExistence(_skill); }
function checkSkillExistence(bytes32 _skill) public view returns (bool) { return dbSkills.checkSkillExistence(_skill); }
13,302
50
// Metadata defining a token's icon.
struct Token { uint8 designIcon0; uint8 designIcon1; uint8 randIcon; uint8 combMethod; }
struct Token { uint8 designIcon0; uint8 designIcon1; uint8 randIcon; uint8 combMethod; }
63,743
21
// Pay for an airline in the registration queue/
function payAirlineFee (address newAirline) external payable requireIsOperational
function payAirlineFee (address newAirline) external payable requireIsOperational
5,414
154
// GET - The address of the Smart Contract whose code will serve as a model for all the Native EthItems.Every EthItem will have its own address, but the code will be cloned from this one. /
function nativeModel() external view returns (address nativeModelAddress, uint256 nativeModelVersion);
function nativeModel() external view returns (address nativeModelAddress, uint256 nativeModelVersion);
32,720
9
// 质押 ERC20 Token
function depositToken(address token, uint256 amount) external { require(token != address(0), "Address(0) is not allowed"); require(amount > 0, "Amount must be greater than 0"); bool success = IERC20(token).transferFrom(msg.sender, address(this), amount); require(success, "ERC20 Token transferFrom failed"); erc20Balances[msg.sender][token] += amount; emit DepositToken(msg.sender, token, amount, IERC20Metadata(token).symbol()); }
function depositToken(address token, uint256 amount) external { require(token != address(0), "Address(0) is not allowed"); require(amount > 0, "Amount must be greater than 0"); bool success = IERC20(token).transferFrom(msg.sender, address(this), amount); require(success, "ERC20 Token transferFrom failed"); erc20Balances[msg.sender][token] += amount; emit DepositToken(msg.sender, token, amount, IERC20Metadata(token).symbol()); }
22,199
108
// Returns the hash of internal node, calculated from child nodes.
function merkleInnerHash(bytes32 left, bytes32 right) internal pure returns (bytes32)
function merkleInnerHash(bytes32 left, bytes32 right) internal pure returns (bytes32)
28,361
1
// the fee in basis points for buying the asset for VOLT
uint256 public override redeemFeeBasisPoints;
uint256 public override redeemFeeBasisPoints;
48,164
42
// encodedPartialPath has elements that are each two hex characters (1 byte), but partialPath and slicedPath have elements that are each one hex character (1 nibble)
bytes memory partialPath = _getNibbleArray(encodedPartialPath); bytes memory slicedPath = new bytes(partialPath.length);
bytes memory partialPath = _getNibbleArray(encodedPartialPath); bytes memory slicedPath = new bytes(partialPath.length);
68,805
55
// Access Control Cliff Hall Role-based access control and contract upgrade functionality. /
contract AccessControl { using SafeMath for uint256; using SafeMath for uint16; using Roles for Roles.Role; Roles.Role private admins; Roles.Role private minters; Roles.Role private owners; /** * @notice Sets `msg.sender` as system admin by default. * Starts paused. System admin must unpause, and add other roles after deployment. */ constructor() public { admins.add(msg.sender); } /** * @notice Emitted when contract is paused by system administrator. */ event ContractPaused(); /** * @notice Emitted when contract is unpaused by system administrator. */ event ContractUnpaused(); /** * @notice Emitted when contract is upgraded by system administrator. * @param newContract address of the new version of the contract. */ event ContractUpgrade(address newContract); bool public paused = true; bool public upgraded = false; address public newContractAddress; /** * @notice Modifier to scope access to minters */ modifier onlyMinter() { require(minters.has(msg.sender)); _; } /** * @notice Modifier to scope access to owners */ modifier onlyOwner() { require(owners.has(msg.sender)); _; } /** * @notice Modifier to scope access to system administrators */ modifier onlySysAdmin() { require(admins.has(msg.sender)); _; } /** * @notice Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @notice Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @notice Modifier to make a function callable only when the contract not upgraded. */ modifier whenNotUpgraded() { require(!upgraded); _; } /** * @notice Called by a system administrator to mark the smart contract as upgraded, * in case there is a serious breaking bug. This method stores the new contract * address and emits an event to that effect. Clients of the contract should * update to the new contract address upon receiving this event. This contract will * remain paused indefinitely after such an upgrade. * @param _newAddress address of new contract */ function upgradeContract(address _newAddress) external onlySysAdmin whenPaused whenNotUpgraded { require(_newAddress != address(0)); upgraded = true; newContractAddress = _newAddress; emit ContractUpgrade(_newAddress); } /** * @notice Called by a system administrator to add a minter. * Reverts if `_minterAddress` already has minter role * @param _minterAddress approved minter */ function addMinter(address _minterAddress) external onlySysAdmin { minters.add(_minterAddress); require(minters.has(_minterAddress)); } /** * @notice Called by a system administrator to add an owner. * Reverts if `_ownerAddress` already has owner role * @param _ownerAddress approved owner * @return added boolean indicating whether the role was granted */ function addOwner(address _ownerAddress) external onlySysAdmin { owners.add(_ownerAddress); require(owners.has(_ownerAddress)); } /** * @notice Called by a system administrator to add another system admin. * Reverts if `_sysAdminAddress` already has sysAdmin role * @param _sysAdminAddress approved owner */ function addSysAdmin(address _sysAdminAddress) external onlySysAdmin { admins.add(_sysAdminAddress); require(admins.has(_sysAdminAddress)); } /** * @notice Called by an owner to remove all roles from an address. * Reverts if address had no roles to be removed. * @param _address address having its roles stripped */ function stripRoles(address _address) external onlyOwner { require(msg.sender != _address); bool stripped = false; if (admins.has(_address)) { admins.remove(_address); stripped = true; } if (minters.has(_address)) { minters.remove(_address); stripped = true; } if (owners.has(_address)) { owners.remove(_address); stripped = true; } require(stripped == true); } /** * @notice Called by a system administrator to pause, triggers stopped state */ function pause() external onlySysAdmin whenNotPaused { paused = true; emit ContractPaused(); } /** * @notice Called by a system administrator to un-pause, returns to normal state */ function unpause() external onlySysAdmin whenPaused whenNotUpgraded { paused = false; emit ContractUnpaused(); } }
contract AccessControl { using SafeMath for uint256; using SafeMath for uint16; using Roles for Roles.Role; Roles.Role private admins; Roles.Role private minters; Roles.Role private owners; /** * @notice Sets `msg.sender` as system admin by default. * Starts paused. System admin must unpause, and add other roles after deployment. */ constructor() public { admins.add(msg.sender); } /** * @notice Emitted when contract is paused by system administrator. */ event ContractPaused(); /** * @notice Emitted when contract is unpaused by system administrator. */ event ContractUnpaused(); /** * @notice Emitted when contract is upgraded by system administrator. * @param newContract address of the new version of the contract. */ event ContractUpgrade(address newContract); bool public paused = true; bool public upgraded = false; address public newContractAddress; /** * @notice Modifier to scope access to minters */ modifier onlyMinter() { require(minters.has(msg.sender)); _; } /** * @notice Modifier to scope access to owners */ modifier onlyOwner() { require(owners.has(msg.sender)); _; } /** * @notice Modifier to scope access to system administrators */ modifier onlySysAdmin() { require(admins.has(msg.sender)); _; } /** * @notice Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @notice Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @notice Modifier to make a function callable only when the contract not upgraded. */ modifier whenNotUpgraded() { require(!upgraded); _; } /** * @notice Called by a system administrator to mark the smart contract as upgraded, * in case there is a serious breaking bug. This method stores the new contract * address and emits an event to that effect. Clients of the contract should * update to the new contract address upon receiving this event. This contract will * remain paused indefinitely after such an upgrade. * @param _newAddress address of new contract */ function upgradeContract(address _newAddress) external onlySysAdmin whenPaused whenNotUpgraded { require(_newAddress != address(0)); upgraded = true; newContractAddress = _newAddress; emit ContractUpgrade(_newAddress); } /** * @notice Called by a system administrator to add a minter. * Reverts if `_minterAddress` already has minter role * @param _minterAddress approved minter */ function addMinter(address _minterAddress) external onlySysAdmin { minters.add(_minterAddress); require(minters.has(_minterAddress)); } /** * @notice Called by a system administrator to add an owner. * Reverts if `_ownerAddress` already has owner role * @param _ownerAddress approved owner * @return added boolean indicating whether the role was granted */ function addOwner(address _ownerAddress) external onlySysAdmin { owners.add(_ownerAddress); require(owners.has(_ownerAddress)); } /** * @notice Called by a system administrator to add another system admin. * Reverts if `_sysAdminAddress` already has sysAdmin role * @param _sysAdminAddress approved owner */ function addSysAdmin(address _sysAdminAddress) external onlySysAdmin { admins.add(_sysAdminAddress); require(admins.has(_sysAdminAddress)); } /** * @notice Called by an owner to remove all roles from an address. * Reverts if address had no roles to be removed. * @param _address address having its roles stripped */ function stripRoles(address _address) external onlyOwner { require(msg.sender != _address); bool stripped = false; if (admins.has(_address)) { admins.remove(_address); stripped = true; } if (minters.has(_address)) { minters.remove(_address); stripped = true; } if (owners.has(_address)) { owners.remove(_address); stripped = true; } require(stripped == true); } /** * @notice Called by a system administrator to pause, triggers stopped state */ function pause() external onlySysAdmin whenNotPaused { paused = true; emit ContractPaused(); } /** * @notice Called by a system administrator to un-pause, returns to normal state */ function unpause() external onlySysAdmin whenPaused whenNotUpgraded { paused = false; emit ContractUnpaused(); } }
53,294
45
// Custom Ownable/ Custom ownable contract.
contract CustomOwnable is Ownable { ///The trustee wallet. address private _trustee; event TrusteeAssigned(address indexed account); ///@notice Validates if the sender is actually the trustee. modifier onlyTrustee() { require(msg.sender == _trustee, "Access is denied."); _; } ///@notice Assigns or changes the trustee wallet. ///@param _account A wallet address which will become the new trustee. ///@return Returns true if the operation was successful. function assignTrustee(address _account) external onlyOwner returns(bool) { require(_account != address(0), "Please provide a valid address for trustee."); _trustee = _account; emit TrusteeAssigned(_account); return true; } ///@notice Changes the owner of this contract. ///@param _newOwner Specify a wallet address which will become the new owner. ///@return Returns true if the operation was successful. function reassignOwner(address _newOwner) external onlyTrustee returns(bool) { super._transferOwnership(_newOwner); return true; } ///@notice The trustee wallet has the power to change the owner in case of unforeseen or unavoidable situation. ///@return Wallet address of the trustee account. function getTrustee() external view returns(address) { return _trustee; } }
contract CustomOwnable is Ownable { ///The trustee wallet. address private _trustee; event TrusteeAssigned(address indexed account); ///@notice Validates if the sender is actually the trustee. modifier onlyTrustee() { require(msg.sender == _trustee, "Access is denied."); _; } ///@notice Assigns or changes the trustee wallet. ///@param _account A wallet address which will become the new trustee. ///@return Returns true if the operation was successful. function assignTrustee(address _account) external onlyOwner returns(bool) { require(_account != address(0), "Please provide a valid address for trustee."); _trustee = _account; emit TrusteeAssigned(_account); return true; } ///@notice Changes the owner of this contract. ///@param _newOwner Specify a wallet address which will become the new owner. ///@return Returns true if the operation was successful. function reassignOwner(address _newOwner) external onlyTrustee returns(bool) { super._transferOwnership(_newOwner); return true; } ///@notice The trustee wallet has the power to change the owner in case of unforeseen or unavoidable situation. ///@return Wallet address of the trustee account. function getTrustee() external view returns(address) { return _trustee; } }
49,580
231
// ============ Internal Functions ============ //Calculate notional rebalance quantity, whether to chunk rebalance based on max trade size and max borrow and invoke lever on CompoundLeverageModule/
function _lever( LeverageInfo memory _leverageInfo, uint256 _chunkRebalanceNotional ) internal { uint256 collateralRebalanceUnits = _chunkRebalanceNotional.preciseDiv(_leverageInfo.action.setTotalSupply); uint256 borrowUnits = _calculateBorrowUnits(collateralRebalanceUnits, _leverageInfo.action);
function _lever( LeverageInfo memory _leverageInfo, uint256 _chunkRebalanceNotional ) internal { uint256 collateralRebalanceUnits = _chunkRebalanceNotional.preciseDiv(_leverageInfo.action.setTotalSupply); uint256 borrowUnits = _calculateBorrowUnits(collateralRebalanceUnits, _leverageInfo.action);
53,998
102
// Roles are often managed via {grantRole} and {revokeRole}: this function'spurpose is to provide a mechanism for accounts to lose their privilegesif they are compromised (such as when a trusted device is misplaced). If the calling account had been granted `role`, emits a {RoleRevoked}event. Requirements: - the caller must be `account`. /
function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); }
function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); }
1,747
259
// We want to maintain a buffer on the Vault so calculate a percentage modifier to multiply each amount being allocated by to enforce the vault buffer
uint256 vaultBufferModifier; if (strategiesValue == 0) {
uint256 vaultBufferModifier; if (strategiesValue == 0) {
24,373
22
// value must be less than allowed value
require(_value <= _allowance);
require(_value <= _allowance);
37,611
0
// delivery security deposit is sent
balance = balance + msg.value;
balance = balance + msg.value;
40,807
14
// True if the creator revenue has already been withdrawn.
bool creatorRevenueHasBeenWithdrawn;
bool creatorRevenueHasBeenWithdrawn;
10,000
80
// Transfers the ownership of a given token ID to another address.
* Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * Requires the _msgSender() to be the owner, approved, or operator. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the _msgSender() to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the _msgSender() to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata _data ) external; /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address tokenHolderAdress); /** * @dev Returns 170 if the specified token exists, otherwise zero * */ function tokenExists(uint256 tokenId) external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external returns (uint256); /** * @dev Returns the name of the token. */ function name() external view returns (string memory tokenName); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory tokenSymbol); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory URI); /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); }
* Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * Requires the _msgSender() to be the owner, approved, or operator. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the _msgSender() to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the _msgSender() to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata _data ) external; /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address tokenHolderAdress); /** * @dev Returns 170 if the specified token exists, otherwise zero * */ function tokenExists(uint256 tokenId) external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external returns (uint256); /** * @dev Returns the name of the token. */ function name() external view returns (string memory tokenName); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory tokenSymbol); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory URI); /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); }
34,176
42
// The currently in range liquidity available to the pool/This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
function liquidity() external view returns (uint128);
4,371
57
// {UoA} = {sellTok}{UoA/sellTok}
uint192 delta = bal.minus(needed).mul(lotLow, FLOOR);
uint192 delta = bal.minus(needed).mul(lotLow, FLOOR);
40,246
70
// Return uniswap v3 Swap Router Address /
function getUniswapRouterAddr() internal pure returns (address) { return 0xE592427A0AEce92De3Edee1F18E0157C05861564; }
function getUniswapRouterAddr() internal pure returns (address) { return 0xE592427A0AEce92De3Edee1F18E0157C05861564; }
45,193
17
// No need to check for rounding error, previewWithdraw rounds up.
shares = previewWithdraw(assets); _withdrawAndSend(assets, shares, receiver, owner);
shares = previewWithdraw(assets); _withdrawAndSend(assets, shares, receiver, owner);
21,949
9
// remove from bidder set
bidderSet[tulipNumber].remove(msg.sender);
bidderSet[tulipNumber].remove(msg.sender);
59,395
13
// Total sETH threshold need to be met in order to rage quit. User must have more or same sETH than this at the house level
function sETHRedemptionThreshold(address _stakeHouse) external view returns (uint256);
function sETHRedemptionThreshold(address _stakeHouse) external view returns (uint256);
16,970
0
// You can add parameters to this function in order to pass indata to set your own state variables
function init() external {
function init() external {
19,766
18
// Transfer MockUSDC tokens to corresponding Circle account
mockUSDC.transfer(_account, _amount);
mockUSDC.transfer(_account, _amount);
50,329
119
// The SHOW TOKEN!
ISHOWIERC20 public show;
ISHOWIERC20 public show;
16,322
1
// Initialize LinkedList by setting limit on amount of nodes and inital value of node 0 _selfLinkedList to operate on _dataSizeLimit Max amount of nodes allowed in LinkedList_initialValueInitial value of node 0 in LinkedList /
function initialize( LinkedList storage _self, uint256 _dataSizeLimit, uint256 _initialValue ) internal
function initialize( LinkedList storage _self, uint256 _dataSizeLimit, uint256 _initialValue ) internal
13,949
23
// replace
require(oldFacetAddress != _newFacetAddress, "LibDiamondCut: Can't replace function with same function"); removeSelector(oldFacetAddress, selector); addSelector(_newFacetAddress, selector);
require(oldFacetAddress != _newFacetAddress, "LibDiamondCut: Can't replace function with same function"); removeSelector(oldFacetAddress, selector); addSelector(_newFacetAddress, selector);
34,248
41
// Update last_price
last_A_volume = _last_A_volume;
last_A_volume = _last_A_volume;
29,132
328
// TODO document SM functions
function blocksWithRewardsPassed(address _policyBook) external view returns (uint256); function rewardPerToken(address _policyBook) external view returns (uint256); function earned( address _policyBook, address _userLeveragePool, address _account ) external view returns (uint256);
function blocksWithRewardsPassed(address _policyBook) external view returns (uint256); function rewardPerToken(address _policyBook) external view returns (uint256); function earned( address _policyBook, address _userLeveragePool, address _account ) external view returns (uint256);
15,041
225
// get price and updated time for a currency
function getPriceAndUpdatedTime(bytes32 currencyName) external view returns (uint price, uint time);
function getPriceAndUpdatedTime(bytes32 currencyName) external view returns (uint price, uint time);
10,446
12
// TODO WRAP totalDeposited to WETHTODO SEND WETH TO AAVE V2
emit Deposit(msg.sender, msg.value, depositTime);
emit Deposit(msg.sender, msg.value, depositTime);
5,030
1
// Stores high level basket info /
struct Basket { /** @dev Array of Bassets currently active */ Basset[] bassets; /** @dev Max number of bAssets that can be present in any Basket */ uint8 maxBassets; /** @dev Some bAsset is undergoing re-collateralisation */ bool undergoingRecol; /** * @dev In the event that we do not raise enough funds from the auctioning of a failed Basset, * The Basket is deemed as failed, and is undercollateralised to a certain degree. * The collateralisation ratio is used to calc Masset burn rate. */ bool failed; uint256 collateralisationRatio; }
struct Basket { /** @dev Array of Bassets currently active */ Basset[] bassets; /** @dev Max number of bAssets that can be present in any Basket */ uint8 maxBassets; /** @dev Some bAsset is undergoing re-collateralisation */ bool undergoingRecol; /** * @dev In the event that we do not raise enough funds from the auctioning of a failed Basset, * The Basket is deemed as failed, and is undercollateralised to a certain degree. * The collateralisation ratio is used to calc Masset burn rate. */ bool failed; uint256 collateralisationRatio; }
25,906
138
// Domain-separation tag for the hash used as the final VOR output.
uint256 constant VOR_RANDOM_OUTPUT_HASH_PREFIX = 3;
uint256 constant VOR_RANDOM_OUTPUT_HASH_PREFIX = 3;
26,401
24
// Set ownership of the contract to a new account (`newOwner`).Can only be called by the current owner. /
function setOwner(address newOwner) public onlyOwner { require(newOwner != address(0), "PerpFiOwnableUpgrade: zero address"); require(newOwner != _owner, "PerpFiOwnableUpgrade: same as original"); require(newOwner != _candidate, "PerpFiOwnableUpgrade: same as candidate"); _candidate = newOwner; }
function setOwner(address newOwner) public onlyOwner { require(newOwner != address(0), "PerpFiOwnableUpgrade: zero address"); require(newOwner != _owner, "PerpFiOwnableUpgrade: same as original"); require(newOwner != _candidate, "PerpFiOwnableUpgrade: same as candidate"); _candidate = newOwner; }
67,042
42
// Check if voted
require(!hasVotedMap[_ballotId][_voter], "already voted"); require(ballotBasicMap[_ballotId].state == uint256(BallotStates.InProgress), "Not InProgress State"); voteMap[_voteId] = Vote(_voteId, _ballotId, _voter, _decision, _power, getTime()); _updateBallotForVote(_ballotId, _voter, _decision, _power); emit Voted(_voteId, _ballotId, _voter, _decision);
require(!hasVotedMap[_ballotId][_voter], "already voted"); require(ballotBasicMap[_ballotId].state == uint256(BallotStates.InProgress), "Not InProgress State"); voteMap[_voteId] = Vote(_voteId, _ballotId, _voter, _decision, _power, getTime()); _updateBallotForVote(_ballotId, _voter, _decision, _power); emit Voted(_voteId, _ballotId, _voter, _decision);
23,523
484
// Reads the uint248 at `cdPtr` in calldata.
function readUint248( CalldataPointer cdPtr
function readUint248( CalldataPointer cdPtr
23,579
0
// Private mapping of valid upgrade paths
mapping(address => mapping(address => bool)) private _validUpgradePaths;
mapping(address => mapping(address => bool)) private _validUpgradePaths;
18,175
14
// Will revert if _buyERC1155 reverts.
_buyERC1155(sellOrders[i], signatures[i], erc1155FillAmounts[i]); successes[i] = true;
_buyERC1155(sellOrders[i], signatures[i], erc1155FillAmounts[i]); successes[i] = true;
2,448
36
// Modifier to check if the pool is open to trade. /
modifier open() { bool indexed isPoolSelling, address indexed account, address indexed acoToken, uint256 tokenAmount, uint256 price, uint256 protocolFee, uint256 underlyingPrice ); require(isStarted() && notFinished(), "ACOPool:: Pool is not open"); _; }
modifier open() { bool indexed isPoolSelling, address indexed account, address indexed acoToken, uint256 tokenAmount, uint256 price, uint256 protocolFee, uint256 underlyingPrice ); require(isStarted() && notFinished(), "ACOPool:: Pool is not open"); _; }
16,595
138
// Ability to vote for or against asset sale /_vote for or against
function vote(uint _vote) external
function vote(uint _vote) external
16,009
115
// Contract instances
IMiniMeToken internal cToken; IMiniMeToken internal sToken; BetokenProxyInterface internal proxy;
IMiniMeToken internal cToken; IMiniMeToken internal sToken; BetokenProxyInterface internal proxy;
2,549
4
// Modifier that only allows invited member execution./
modifier onlyInvited() { require(isInvited[msg.sender], "Sender is not invited!"); _; }
modifier onlyInvited() { require(isInvited[msg.sender], "Sender is not invited!"); _; }
15,057
717
// Gets the `DERIVATIVE_PRICE_FEED` variable value/ return derivativePriceFeed_ The `DERIVATIVE_PRICE_FEED` variable value
function getDerivativePriceFeed() external view returns (address derivativePriceFeed_) { return DERIVATIVE_PRICE_FEED; } /// @notice Gets the `FACTORY` variable value /// @return factory_ The `FACTORY` variable value function getFactory() external view returns (address factory_) { return FACTORY; } /// @notice Gets the `PoolTokenInfo` for a given pool token /// @param _poolToken The pool token for which to get the `PoolTokenInfo` /// @return poolTokenInfo_ The `PoolTokenInfo` value function getPoolTokenInfo(address _poolToken) external view returns (PoolTokenInfo memory poolTokenInfo_) { return poolTokenToInfo[_poolToken]; } /// @notice Gets the underlyings for a given pool token /// @param _poolToken The pool token for which to get its underlyings /// @return token0_ The UniswapV2Pair.token0 value /// @return token1_ The UniswapV2Pair.token1 value function getPoolTokenUnderlyings(address _poolToken) external view returns (address token0_, address token1_) { return (poolTokenToInfo[_poolToken].token0, poolTokenToInfo[_poolToken].token1); } /// @notice Gets the `PRIMITIVE_PRICE_FEED` variable value /// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) { return PRIMITIVE_PRICE_FEED; } /// @notice Gets the `VALUE_INTERPRETER` variable value /// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value function getValueInterpreter() external view returns (address valueInterpreter_) { return VALUE_INTERPRETER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IUniswapV2Pair Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for our interactions with the Uniswap V2's Pair contract interface IUniswapV2Pair { function getReserves() external view returns ( uint112, uint112, uint32 ); function kLast() external view returns (uint256); function token0() external view returns (address); function token1() external view returns (address); function totalSupply() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../interfaces/IUniswapV2Factory.sol"; import "../../../interfaces/IUniswapV2Pair.sol"; /// @title UniswapV2PoolTokenValueCalculator Contract /// @author Enzyme Council <[email protected]> /// @notice Abstract contract for computing the value of Uniswap liquidity pool tokens /// @dev Unless otherwise noted, these functions are adapted to our needs and style guide from /// an un-merged Uniswap branch: /// https://github.com/Uniswap/uniswap-v2-periphery/blob/267ba44471f3357071a2fe2573fe4da42d5ad969/contracts/libraries/UniswapV2LiquidityMathLibrary.sol abstract contract UniswapV2PoolTokenValueCalculator { using SafeMath for uint256; uint256 private constant POOL_TOKEN_UNIT = 10**18; // INTERNAL FUNCTIONS /// @dev Given a Uniswap pool with token0 and token1 and their trusted rate, /// returns the value of one pool token unit in terms of token0 and token1. /// This is the only function used outside of this contract. function __calcTrustedPoolTokenValue( address _factory, address _pair, uint256 _token0TrustedRateAmount, uint256 _token1TrustedRateAmount ) internal view returns (uint256 token0Amount_, uint256 token1Amount_) { (uint256 reserve0, uint256 reserve1) = __calcReservesAfterArbitrage( _pair, _token0TrustedRateAmount, _token1TrustedRateAmount ); return __calcPoolTokenValue(_factory, _pair, reserve0, reserve1); } // PRIVATE FUNCTIONS /// @dev Computes liquidity value given all the parameters of the pair function __calcPoolTokenValue( address _factory, address _pair, uint256 _reserve0, uint256 _reserve1 ) private view returns (uint256 token0Amount_, uint256 token1Amount_) { IUniswapV2Pair pairContract = IUniswapV2Pair(_pair); uint256 totalSupply = pairContract.totalSupply(); if (IUniswapV2Factory(_factory).feeTo() != address(0)) { uint256 kLast = pairContract.kLast(); if (kLast > 0) { uint256 rootK = __uniswapSqrt(_reserve0.mul(_reserve1)); uint256 rootKLast = __uniswapSqrt(kLast); if (rootK > rootKLast) { uint256 numerator = totalSupply.mul(rootK.sub(rootKLast)); uint256 denominator = rootK.mul(5).add(rootKLast); uint256 feeLiquidity = numerator.div(denominator); totalSupply = totalSupply.add(feeLiquidity); } }
function getDerivativePriceFeed() external view returns (address derivativePriceFeed_) { return DERIVATIVE_PRICE_FEED; } /// @notice Gets the `FACTORY` variable value /// @return factory_ The `FACTORY` variable value function getFactory() external view returns (address factory_) { return FACTORY; } /// @notice Gets the `PoolTokenInfo` for a given pool token /// @param _poolToken The pool token for which to get the `PoolTokenInfo` /// @return poolTokenInfo_ The `PoolTokenInfo` value function getPoolTokenInfo(address _poolToken) external view returns (PoolTokenInfo memory poolTokenInfo_) { return poolTokenToInfo[_poolToken]; } /// @notice Gets the underlyings for a given pool token /// @param _poolToken The pool token for which to get its underlyings /// @return token0_ The UniswapV2Pair.token0 value /// @return token1_ The UniswapV2Pair.token1 value function getPoolTokenUnderlyings(address _poolToken) external view returns (address token0_, address token1_) { return (poolTokenToInfo[_poolToken].token0, poolTokenToInfo[_poolToken].token1); } /// @notice Gets the `PRIMITIVE_PRICE_FEED` variable value /// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) { return PRIMITIVE_PRICE_FEED; } /// @notice Gets the `VALUE_INTERPRETER` variable value /// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value function getValueInterpreter() external view returns (address valueInterpreter_) { return VALUE_INTERPRETER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IUniswapV2Pair Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for our interactions with the Uniswap V2's Pair contract interface IUniswapV2Pair { function getReserves() external view returns ( uint112, uint112, uint32 ); function kLast() external view returns (uint256); function token0() external view returns (address); function token1() external view returns (address); function totalSupply() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../interfaces/IUniswapV2Factory.sol"; import "../../../interfaces/IUniswapV2Pair.sol"; /// @title UniswapV2PoolTokenValueCalculator Contract /// @author Enzyme Council <[email protected]> /// @notice Abstract contract for computing the value of Uniswap liquidity pool tokens /// @dev Unless otherwise noted, these functions are adapted to our needs and style guide from /// an un-merged Uniswap branch: /// https://github.com/Uniswap/uniswap-v2-periphery/blob/267ba44471f3357071a2fe2573fe4da42d5ad969/contracts/libraries/UniswapV2LiquidityMathLibrary.sol abstract contract UniswapV2PoolTokenValueCalculator { using SafeMath for uint256; uint256 private constant POOL_TOKEN_UNIT = 10**18; // INTERNAL FUNCTIONS /// @dev Given a Uniswap pool with token0 and token1 and their trusted rate, /// returns the value of one pool token unit in terms of token0 and token1. /// This is the only function used outside of this contract. function __calcTrustedPoolTokenValue( address _factory, address _pair, uint256 _token0TrustedRateAmount, uint256 _token1TrustedRateAmount ) internal view returns (uint256 token0Amount_, uint256 token1Amount_) { (uint256 reserve0, uint256 reserve1) = __calcReservesAfterArbitrage( _pair, _token0TrustedRateAmount, _token1TrustedRateAmount ); return __calcPoolTokenValue(_factory, _pair, reserve0, reserve1); } // PRIVATE FUNCTIONS /// @dev Computes liquidity value given all the parameters of the pair function __calcPoolTokenValue( address _factory, address _pair, uint256 _reserve0, uint256 _reserve1 ) private view returns (uint256 token0Amount_, uint256 token1Amount_) { IUniswapV2Pair pairContract = IUniswapV2Pair(_pair); uint256 totalSupply = pairContract.totalSupply(); if (IUniswapV2Factory(_factory).feeTo() != address(0)) { uint256 kLast = pairContract.kLast(); if (kLast > 0) { uint256 rootK = __uniswapSqrt(_reserve0.mul(_reserve1)); uint256 rootKLast = __uniswapSqrt(kLast); if (rootK > rootKLast) { uint256 numerator = totalSupply.mul(rootK.sub(rootKLast)); uint256 denominator = rootK.mul(5).add(rootKLast); uint256 feeLiquidity = numerator.div(denominator); totalSupply = totalSupply.add(feeLiquidity); } }
82,931
574
// Get Token Amounts of Claimindex - Claim Index /
function tokenAmounts(uint256 index) external view returns (uint256[] memory)
function tokenAmounts(uint256 index) external view returns (uint256[] memory)
39,610
89
// This notifies buy token status./
event BuyTokenAllowedEvent(bool isAllowed);
event BuyTokenAllowedEvent(bool isAllowed);
39,152
6
// The address of the Uniswap governance token
UniInterface public uni;
UniInterface public uni;
6,791
200
// Indicates that the strategy update will happen in the future/
function announceStrategyUpdate(address _strategy) public onlyControllerOrGovernance { // records a new timestamp uint256 when = block.timestamp.add(strategyTimeLock()); _setStrategyUpdateTime(when); _setFutureStrategy(_strategy); emit StrategyAnnounced(_strategy, when); }
function announceStrategyUpdate(address _strategy) public onlyControllerOrGovernance { // records a new timestamp uint256 when = block.timestamp.add(strategyTimeLock()); _setStrategyUpdateTime(when); _setFutureStrategy(_strategy); emit StrategyAnnounced(_strategy, when); }
10,243
28
// Decrease the amount of tokens that an owner allowed to a spender._spender The address which will spend the funds. _subtractedValue The amount of tokens to decrease the allowance by. /
function decreaseApproval(address _spender, uint _subtractedValue) isRunning public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
function decreaseApproval(address _spender, uint _subtractedValue) isRunning public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
48,040
112
// string memory error = string(abi.encodePacked("Module: requested module not found - ", module)); require(moduleAddress != ZERO_ADDRESS, error);
require(moduleAddress != ZERO_ADDRESS, "Module: requested module not found"); return moduleAddress;
require(moduleAddress != ZERO_ADDRESS, "Module: requested module not found"); return moduleAddress;
18,034
20
// ICO is terminated by owner, ICO cannot be resumed.
Terminated,
Terminated,
27,305
77
// Initializes the contract by setting a `name` and a `symbol` to the token collection. /
constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; }
constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; }
18,588
4
// Returns the current initializing flag.return Boolean value of the initializing flag /
function _initializing() internal view returns (bool initializing) { bytes32 slot = INITIALIZING_SLOT; assembly { initializing := sload(slot) } }
function _initializing() internal view returns (bool initializing) { bytes32 slot = INITIALIZING_SLOT; assembly { initializing := sload(slot) } }
44,536
110
// If any account belongs to _isExcludedFromFee account then remove the fee
if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; }
if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; }
23,519
7
// p5js url
string p5jsUrl; string p5jsIntegrity; string imageUrl; string animationUrl;
string p5jsUrl; string p5jsIntegrity; string imageUrl; string animationUrl;
18,883
44
// Withdraw DAI from DSR. amt DAI amount to withdraw./
function withdrawDai(uint amt) external payable { address daiJoin = getMcdDaiJoin(); DaiJoinInterface daiJoinContract = DaiJoinInterface(daiJoin); VatLike vat = daiJoinContract.vat(); PotLike potContract = PotLike(getMcdPot()); uint chi = potContract.drip(); uint pie; uint _amt; if (amt == uint(-1)) { pie = potContract.pie(address(this)); _amt = mul(chi, pie) / RAY; } else { pie = mul(amt, RAY) / chi; } potContract.exit(pie); uint bal = vat.dai(address(this)); if (vat.can(address(this), address(daiJoin)) == 0) { vat.hope(daiJoin); } daiJoinContract.exit( address(this), bal >= mul(_amt, RAY) ? _amt : bal / RAY ); emit LogWithdrawDai(_amt); bytes32 _eventCode = keccak256("LogWithdrawDai(uint256)"); bytes memory _eventParam = abi.encode(_amt); (uint _type, uint _id) = connectorID(); EventInterface(getEventAddr()).emitEvent(_type, _id, _eventCode, _eventParam); }
function withdrawDai(uint amt) external payable { address daiJoin = getMcdDaiJoin(); DaiJoinInterface daiJoinContract = DaiJoinInterface(daiJoin); VatLike vat = daiJoinContract.vat(); PotLike potContract = PotLike(getMcdPot()); uint chi = potContract.drip(); uint pie; uint _amt; if (amt == uint(-1)) { pie = potContract.pie(address(this)); _amt = mul(chi, pie) / RAY; } else { pie = mul(amt, RAY) / chi; } potContract.exit(pie); uint bal = vat.dai(address(this)); if (vat.can(address(this), address(daiJoin)) == 0) { vat.hope(daiJoin); } daiJoinContract.exit( address(this), bal >= mul(_amt, RAY) ? _amt : bal / RAY ); emit LogWithdrawDai(_amt); bytes32 _eventCode = keccak256("LogWithdrawDai(uint256)"); bytes memory _eventParam = abi.encode(_amt); (uint _type, uint _id) = connectorID(); EventInterface(getEventAddr()).emitEvent(_type, _id, _eventCode, _eventParam); }
50,586
126
// A distinct URI (RFC 3986) for a given NFT. _tokenId Id for which we want uri.return URI of _tokenId. /
function tokenURI( uint256 _tokenId ) external override view validNFToken(_tokenId) returns (string memory)
function tokenURI( uint256 _tokenId ) external override view validNFToken(_tokenId) returns (string memory)
3,743
12
// Returns the value of the assets in the rigoblock network given a mock input/mockInput Random number, must be 1 for querying data/ return networkValue Value of the rigoblock network in wei/ return numberOfPools Number of active funds
function calcNetworkValueDuneAnalytics(uint256 mockInput) external view returns ( uint256 networkValue, uint256 numberOfPools )
function calcNetworkValueDuneAnalytics(uint256 mockInput) external view returns ( uint256 networkValue, uint256 numberOfPools )
15,747
61
// See {IERC20-totalSupply}. /
event swapTokensForExactTokens(
event swapTokensForExactTokens(
10,607
151
// Contract for SportZchain token An ERC20 implementation of the SportZchain ecosystem token. All tokens are initially pre-assigned tothe creator, and can later be distributed freely using transfer transferFrom and other ERC20 functions. /
contract SportZchainToken is Ownable, ERC20Pausable, ERC20Burnable, AccessControl { bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); /** * @dev Throws if called by any account other than the burner. */ modifier onlyBurner() { require(hasRole(BURNER_ROLE, msg.sender), "Caller is not a burner"); _; } /** * @dev Throws if called by any account other than the pauser. */ modifier onlyPauser() { require(hasRole(PAUSER_ROLE, msg.sender), "Caller is not a pauser"); _; } /** * @dev Constructor that gives msg.sender all of existing tokens. * * @param _name = token name * @param _symbol = token symbol * @param _decimals = token decimals * @param _totalSupply = token supply of the token */ constructor ( string memory _name, string memory _symbol, uint8 _decimals, uint256 _totalSupply ) ERC20(_name, _symbol) { // This is the only place where we ever mint tokens for initial supply _mint(_msgSender(), _totalSupply * (10 ** uint256(_decimals))); // set the owner as the admin _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); } /** * @dev Allow only users with burner role to burn tokens from the wallet, * There is no reason for a token holder to EVER call this method directly. It will be * used by the future SportZchain ecosystem. * * @param _amount = token amount to burn */ function burn( uint256 _amount ) public onlyBurner override (ERC20Burnable) { super.burn(_amount); } /** * @dev Allow only users with burner role to burn tokens from the a given address, * There is no reason for a token holder to EVER call this method directly. It will be * used by the future SportZchain ecosystem. * * @param account = burn from account * @param _amount = token amount to burn */ function burnFrom( address account, uint256 _amount ) public onlyBurner override (ERC20Burnable) { super.burnFrom(account, _amount); } /** * @dev Overrides _beforeTokenTransfer - See ERC20 and ERC20Pausable * * @param from = address from which the tokens needs to be transferred * @param to = address to which the tokens needs to be transferred * @param amount = token amount to be transferred */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override (ERC20,ERC20Pausable){ super._beforeTokenTransfer(from, to, amount); } /** * @dev Triggers stopped state. Can be paused only by the pauser */ function pause() external onlyPauser { _pause(); } /** * @dev Returns to normal state. Can be unpaused only by the pauser */ function unpause() external onlyPauser { _unpause(); } }
contract SportZchainToken is Ownable, ERC20Pausable, ERC20Burnable, AccessControl { bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); /** * @dev Throws if called by any account other than the burner. */ modifier onlyBurner() { require(hasRole(BURNER_ROLE, msg.sender), "Caller is not a burner"); _; } /** * @dev Throws if called by any account other than the pauser. */ modifier onlyPauser() { require(hasRole(PAUSER_ROLE, msg.sender), "Caller is not a pauser"); _; } /** * @dev Constructor that gives msg.sender all of existing tokens. * * @param _name = token name * @param _symbol = token symbol * @param _decimals = token decimals * @param _totalSupply = token supply of the token */ constructor ( string memory _name, string memory _symbol, uint8 _decimals, uint256 _totalSupply ) ERC20(_name, _symbol) { // This is the only place where we ever mint tokens for initial supply _mint(_msgSender(), _totalSupply * (10 ** uint256(_decimals))); // set the owner as the admin _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); } /** * @dev Allow only users with burner role to burn tokens from the wallet, * There is no reason for a token holder to EVER call this method directly. It will be * used by the future SportZchain ecosystem. * * @param _amount = token amount to burn */ function burn( uint256 _amount ) public onlyBurner override (ERC20Burnable) { super.burn(_amount); } /** * @dev Allow only users with burner role to burn tokens from the a given address, * There is no reason for a token holder to EVER call this method directly. It will be * used by the future SportZchain ecosystem. * * @param account = burn from account * @param _amount = token amount to burn */ function burnFrom( address account, uint256 _amount ) public onlyBurner override (ERC20Burnable) { super.burnFrom(account, _amount); } /** * @dev Overrides _beforeTokenTransfer - See ERC20 and ERC20Pausable * * @param from = address from which the tokens needs to be transferred * @param to = address to which the tokens needs to be transferred * @param amount = token amount to be transferred */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override (ERC20,ERC20Pausable){ super._beforeTokenTransfer(from, to, amount); } /** * @dev Triggers stopped state. Can be paused only by the pauser */ function pause() external onlyPauser { _pause(); } /** * @dev Returns to normal state. Can be unpaused only by the pauser */ function unpause() external onlyPauser { _unpause(); } }
50,853
26
// '_selectorSlot >> 3' is a gas efficient division by 8 '_selectorSlot / 8'
ds.selectorSlots[_selectorCount >> 3] = _selectorSlot; _selectorSlot = 0;
ds.selectorSlots[_selectorCount >> 3] = _selectorSlot; _selectorSlot = 0;
39,958
22
// Returns an array of token IDs owned by `owner`,in the range [`start`, `stop`)(i.e. `start <= tokenId < stop`). This function allows for tokens to be queried if the collection
* grows too big for a single call of {ERC721AQueryable-tokensOfOwner}. * * Requirements: * * - `start` < `stop` */ function tokensOfOwnerIn( address owner, uint256 start, uint256 stop ) public view returns (uint256[] memory t) { unchecked { if (start >= stop) return t; uint256 tokenIdsIdx; uint256 stopLimit = tokenIds.current(); // Set `start = max(start, _startTokenId())`. if (start < _startTokenId()) { start = _startTokenId(); } // Set `stop = min(stop, _currentIndex)`. if (stop > stopLimit) { stop = stopLimit; } uint256 tokenIdsMaxLength = balanceOf(owner); // Set `tokenIdsMaxLength = min(balanceOf(owner), stop - start)`, // to cater for cases where `balanceOf(owner)` is too big. if (start < stop) { uint256 rangeLength = stop - start; if (rangeLength < tokenIdsMaxLength) { tokenIdsMaxLength = rangeLength; } } else { tokenIdsMaxLength = 0; } uint256[] memory tokenIdsArr = new uint256[](tokenIdsMaxLength); if (tokenIdsMaxLength == 0) { return tokenIdsArr; } // We need to call `explicitOwnershipOf(start)`, // because the slot at `start` may not be initialized. address ownership = ownerOf(start); address currOwnershipAddr; // If the starting slot exists (i.e. not burned), initialize `currOwnershipAddr`. // `ownership.address` will not be zero, as `start` is clamped to the valid token ID range. if (ownership != address(0x0)) { currOwnershipAddr = ownership; } for (uint256 i = start; i != stop && tokenIdsIdx != tokenIdsMaxLength; ++i) { ownership = ownerOf(i); if (ownership == address(0x0)) { continue; } if (ownership != address(0)) { currOwnershipAddr = ownership; } if (currOwnershipAddr == owner) { tokenIdsArr[tokenIdsIdx++] = i; } } // Downsize the array to fit. assembly { mstore(tokenIdsArr, tokenIdsIdx) } return tokenIdsArr; } }
* grows too big for a single call of {ERC721AQueryable-tokensOfOwner}. * * Requirements: * * - `start` < `stop` */ function tokensOfOwnerIn( address owner, uint256 start, uint256 stop ) public view returns (uint256[] memory t) { unchecked { if (start >= stop) return t; uint256 tokenIdsIdx; uint256 stopLimit = tokenIds.current(); // Set `start = max(start, _startTokenId())`. if (start < _startTokenId()) { start = _startTokenId(); } // Set `stop = min(stop, _currentIndex)`. if (stop > stopLimit) { stop = stopLimit; } uint256 tokenIdsMaxLength = balanceOf(owner); // Set `tokenIdsMaxLength = min(balanceOf(owner), stop - start)`, // to cater for cases where `balanceOf(owner)` is too big. if (start < stop) { uint256 rangeLength = stop - start; if (rangeLength < tokenIdsMaxLength) { tokenIdsMaxLength = rangeLength; } } else { tokenIdsMaxLength = 0; } uint256[] memory tokenIdsArr = new uint256[](tokenIdsMaxLength); if (tokenIdsMaxLength == 0) { return tokenIdsArr; } // We need to call `explicitOwnershipOf(start)`, // because the slot at `start` may not be initialized. address ownership = ownerOf(start); address currOwnershipAddr; // If the starting slot exists (i.e. not burned), initialize `currOwnershipAddr`. // `ownership.address` will not be zero, as `start` is clamped to the valid token ID range. if (ownership != address(0x0)) { currOwnershipAddr = ownership; } for (uint256 i = start; i != stop && tokenIdsIdx != tokenIdsMaxLength; ++i) { ownership = ownerOf(i); if (ownership == address(0x0)) { continue; } if (ownership != address(0)) { currOwnershipAddr = ownership; } if (currOwnershipAddr == owner) { tokenIdsArr[tokenIdsIdx++] = i; } } // Downsize the array to fit. assembly { mstore(tokenIdsArr, tokenIdsIdx) } return tokenIdsArr; } }
36,351
15
// ONLY FOR TESTING
function mockRound1StartTime(uint256 _time) external isOwner { startTimeRound1 = _time; }
function mockRound1StartTime(uint256 _time) external isOwner { startTimeRound1 = _time; }
56,144
14
// Sets `_authority` address authority new authority address to set Requirements: - `saleOn` must be false,- the caller must be `owner`. /
function setAuthority( address authority) external isSaleOn(false) onlyOwner { _authority = authority; }
function setAuthority( address authority) external isSaleOn(false) onlyOwner { _authority = authority; }
36,701
489
// Amount of LUSD to be locked in gas pool on opening troves
uint constant public LUSD_GAS_COMPENSATION = 200e18;
uint constant public LUSD_GAS_COMPENSATION = 200e18;
8,866
424
// expmods_and_points.points[59] = -(g^4081z).
mstore(add(expmodsAndPoints, 0x9c0), point)
mstore(add(expmodsAndPoints, 0x9c0), point)
3,354
77
// Increase collaterallization of Lp position Only a sender with LP role can call this function self Data type the library is attached to lpPosition Position of the LP (see LPPosition struct) feeStatus Actual status of fee gained (see FeeStatus struct) collateralToTransfer Collateral to be transferred before increase collateral in the position collateralToIncrease Collateral to be added to the position sender Sender of the increaseCollateral transactionreturn newTotalCollateral New total collateral amount /
function increaseCollateral( ISynthereumLiquidityPoolStorage.Storage storage self, ISynthereumLiquidityPoolStorage.LPPosition storage lpPosition, ISynthereumLiquidityPoolStorage.FeeStatus storage feeStatus, FixedPoint.Unsigned calldata collateralToTransfer, FixedPoint.Unsigned calldata collateralToIncrease, address sender
function increaseCollateral( ISynthereumLiquidityPoolStorage.Storage storage self, ISynthereumLiquidityPoolStorage.LPPosition storage lpPosition, ISynthereumLiquidityPoolStorage.FeeStatus storage feeStatus, FixedPoint.Unsigned calldata collateralToTransfer, FixedPoint.Unsigned calldata collateralToIncrease, address sender
7,867
13
// check if node is slashed (node does not have minimum token amount) _node node addressreturn true if banned /
function isNodeSlashed(address _node) external view returns (bool) { return ((nodes[_node] == 3) && (slot[uint8(uint256(_node) >> 152)] == address(0))); }
function isNodeSlashed(address _node) external view returns (bool) { return ((nodes[_node] == 3) && (slot[uint8(uint256(_node) >> 152)] == address(0))); }
28,245
89
// function returns the hash of the fully encoded EIP712 message for this domain. /
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32)
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32)
47,100
162
// Deposit LP tokens to FarmMaster for XDEX allocation.
function deposit( uint256 _pid, IERC20 _lpToken, uint256 _amount
function deposit( uint256 _pid, IERC20 _lpToken, uint256 _amount
36,762
18
// View total circulationreturn Total circulation/
function allValue(address token) public view returns (uint256) { if (token == address(_nestContract)) { uint256 all = 10000000000 ether; uint256 leftNum = all.sub(_nestContract.balanceOf(address(_voteFactory.checkAddress("nest.v3.miningSave")))).sub(_nestContract.balanceOf(address(_destructionAddress))); return leftNum; } else { return ERC20(token).totalSupply(); } }
function allValue(address token) public view returns (uint256) { if (token == address(_nestContract)) { uint256 all = 10000000000 ether; uint256 leftNum = all.sub(_nestContract.balanceOf(address(_voteFactory.checkAddress("nest.v3.miningSave")))).sub(_nestContract.balanceOf(address(_destructionAddress))); return leftNum; } else { return ERC20(token).totalSupply(); } }
26,026
332
// Address of the bank contract/This contract is used to handle the token transactions
MarbleBankInterface public erc20Bank;
MarbleBankInterface public erc20Bank;
26,627
248
// using this part of code will result in losses but it is necessary to unlock full collateral in case of wind down we calculate how much want we need to fulfill the want request
uint256 remainingAmountWant = _amountNeeded.sub(balance);
uint256 remainingAmountWant = _amountNeeded.sub(balance);
54,444
113
// settles and pays borrowers based on the fees generated by their interest payments
function _SETTLEFEEREWARDFORINTERESTEXPENSE273( //inject NONSTANDARD NAMING LoanInterest storage loanInterestLocal, bytes32 loanId, address feeToken, address user, uint256 interestTime) internal
function _SETTLEFEEREWARDFORINTERESTEXPENSE273( //inject NONSTANDARD NAMING LoanInterest storage loanInterestLocal, bytes32 loanId, address feeToken, address user, uint256 interestTime) internal
43,490
68
// done for readability sake
bytes32 _whatProposal = whatProposal(_whatFunction); address _whichAdmin;
bytes32 _whatProposal = whatProposal(_whatFunction); address _whichAdmin;
41,903
28
// Allows the current owner to transfer control of the contract to a newOwner newOwner the address to transfer ownership to/
function transferOwnership(address payable newOwner) public onlyOwner { _transferOwnership(newOwner); }
function transferOwnership(address payable newOwner) public onlyOwner { _transferOwnership(newOwner); }
7,434
58
// @inheritdoc ISummaSwapV3PoolOwnerActions
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external override lock onlyFactoryOwner
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external override lock onlyFactoryOwner
32,331
187
// how much BNB did we just swap into?
uint256 swapBalanceBNB = address(this).balance.sub(initialBalance); uint256 amountBNBToSPG = swapBalanceBNB.div(100).mul(66); // 66% uint256 amountBNBToLiq = swapBalanceBNB.div(100).mul(33); // 33% uint256 amountBNBReward = swapBalanceBNB.div(1000);
uint256 swapBalanceBNB = address(this).balance.sub(initialBalance); uint256 amountBNBToSPG = swapBalanceBNB.div(100).mul(66); // 66% uint256 amountBNBToLiq = swapBalanceBNB.div(100).mul(33); // 33% uint256 amountBNBReward = swapBalanceBNB.div(1000);
11,783
78
// Computes the vanishing polynoimal and lagrange evaluations L1 and Ln.return Returns fractions as numerators and denominators. We combine with the public input fraction and compute inverses as a batch /
function compute_lagrange_and_vanishing_fractions(Types.VerificationKey memory vk, uint256 zeta
function compute_lagrange_and_vanishing_fractions(Types.VerificationKey memory vk, uint256 zeta
48,336
469
// Open future user's CDP in MCD
cdp = cdpManager.open(wethJoin.ilk(), address(this));
cdp = cdpManager.open(wethJoin.ilk(), address(this));
55,362
11
// template matching params
uint8 constant _OP_PUBKEYHASH = 253; uint8 constant _OP_PUBKEY = 254; uint8 constant _OP_INVALIDOPCODE = 255;
uint8 constant _OP_PUBKEYHASH = 253; uint8 constant _OP_PUBKEY = 254; uint8 constant _OP_INVALIDOPCODE = 255;
27,438
154
// Get max fee value. /
function getMaxFee() external pure override returns (uint256) { return MAX_FEE; }
function getMaxFee() external pure override returns (uint256) { return MAX_FEE; }
57,594
10
// A cheaper version of keccak256(toRlpBytes(item)) that avoids copying memory.return keccak256 hash of RLP encoded bytes. /
function rlpBytesKeccak256(RLPItem memory item) internal pure returns (bytes32) { uint256 ptr = item.memPtr; uint256 len = item.len; bytes32 result; assembly { result := keccak256(ptr, len) } return result; }
function rlpBytesKeccak256(RLPItem memory item) internal pure returns (bytes32) { uint256 ptr = item.memPtr; uint256 len = item.len; bytes32 result; assembly { result := keccak256(ptr, len) } return result; }
27,266
9
// Allows owner to modify an existing token's symbol./_token Address of existing token./_symbol New symbol.
function setTokenSymbol(address _token, string _symbol) public onlyOwner tokenExists(_token)
function setTokenSymbol(address _token, string _symbol) public onlyOwner tokenExists(_token)
55
1
// If true tokens can be minted in the public sale
bool publicSaleActive;
bool publicSaleActive;
28,949
30
// ---------------------------------- Define STD_TOKEN
contract STD_TOKEN is TRC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function plus_Approval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function minus_Approval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
contract STD_TOKEN is TRC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function plus_Approval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function minus_Approval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
3,200
41
// To store decimal version for token
string public version = 'v1.0';
string public version = 'v1.0';
3,540
65
// Returns the downcasted int56 from int256, reverting onoverflow (when the input is less than smallest int56 orgreater than largest int56). Counterpart to Solidity's `int56` operator. Requirements: - input must fit into 56 bits _Available since v4.7._ /
function toInt56(int256 value) internal pure returns (int56 downcasted) { downcasted = int56(value); require(downcasted == value, "SafeCast: value doesn't fit in 56 bits"); }
function toInt56(int256 value) internal pure returns (int56 downcasted) { downcasted = int56(value); require(downcasted == value, "SafeCast: value doesn't fit in 56 bits"); }
16,255
0
// Bounty ID --> Bounty
mapping(uint256 => Bounty) private _bounties;
mapping(uint256 => Bounty) private _bounties;
27,980
77
// 如果已经取款过,就返回0
if(pending_record.receive_state_14_21_arr[index] == true) { return 0; }
if(pending_record.receive_state_14_21_arr[index] == true) { return 0; }
32,604
35
// Update sensor data
function UpdateSensor(uint _id, string memory _mac, string memory _patientName,address _idDoctor, bool _active ) public { uint index = FindSensor(_id); sensorsDoctor[index].MAC=_mac; sensorsDoctor[index].patientName=_patientName; sensorsDoctor[index].idDoctor=_idDoctor; sensorsDoctor[index].active=_active; emit RefreshSensor(sensorsDoctor[index].idSensor, sensorsDoctor[index].MAC, sensorsDoctor[index].patientName, sensorsDoctor[index].idDoctor, sensorsDoctor[index].active); }
function UpdateSensor(uint _id, string memory _mac, string memory _patientName,address _idDoctor, bool _active ) public { uint index = FindSensor(_id); sensorsDoctor[index].MAC=_mac; sensorsDoctor[index].patientName=_patientName; sensorsDoctor[index].idDoctor=_idDoctor; sensorsDoctor[index].active=_active; emit RefreshSensor(sensorsDoctor[index].idSensor, sensorsDoctor[index].MAC, sensorsDoctor[index].patientName, sensorsDoctor[index].idDoctor, sensorsDoctor[index].active); }
30,453
3
// metadatas
string public baseURI; mapping(uint256 => uint256) private prices; constructor(address _pbwsAddress) ERC721("Paris NFT Day Speaker Cards", "PND SC")
string public baseURI; mapping(uint256 => uint256) private prices; constructor(address _pbwsAddress) ERC721("Paris NFT Day Speaker Cards", "PND SC")
26,661