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
51
// 10% goes to dev.
IERC20(_token).transfer(dev, amount / 10);
IERC20(_token).transfer(dev, amount / 10);
51,977
105
// Emits a {Transfer} event with `to` set to the zero address. Requirements: - `account` cannot be the zero address.- `account` must have at least `amount` tokens. / Present in ERC777
function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub( amount, "ERC20: burn amount exceeds balance" ); _totalSupply = _totalSupply.sub(amount);
function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub( amount, "ERC20: burn amount exceeds balance" ); _totalSupply = _totalSupply.sub(amount);
28,768
62
// Get batch of token balances.return Batch of token balances. /
function batchBalanceOf(address[] memory tokens, address[] memory tokenHolders) public view returns (uint256[] memory) { uint256[] memory batchBalanceOfResponse = new uint256[](tokenHolders.length * tokens.length); for (uint256 i = 0; i < tokenHolders.length; i++) { for (uint256 j = 0; j < tokens.length; j++) { batchBalanceOfResponse[i*tokens.length + j] = IERC20(tokens[j]).balanceOf(tokenHolders[i]); } } return batchBalanceOfResponse; }
function batchBalanceOf(address[] memory tokens, address[] memory tokenHolders) public view returns (uint256[] memory) { uint256[] memory batchBalanceOfResponse = new uint256[](tokenHolders.length * tokens.length); for (uint256 i = 0; i < tokenHolders.length; i++) { for (uint256 j = 0; j < tokens.length; j++) { batchBalanceOfResponse[i*tokens.length + j] = IERC20(tokens[j]).balanceOf(tokenHolders[i]); } } return batchBalanceOfResponse; }
40,829
58
// Record the accumulated distributed balance.
self.lastDistributedMarketBalanceD18 += actuallyDistributedD18.to128(); exhausted = iters == maxIter;
self.lastDistributedMarketBalanceD18 += actuallyDistributedD18.to128(); exhausted = iters == maxIter;
25,845
238
// Lender Functions ///
function fundLoan(address mintTo, uint256 amt) whenNotPaused external { _whenProtocolNotPaused(); _isValidState(State.Ready); _isValidPool(); _isWithinFundingPeriod(); liquidityAsset.safeTransferFrom(msg.sender, fundingLocker, amt); uint256 wad = _toWad(amt); // Convert to WAD precision. _mint(mintTo, wad); // Mint LoanFDTs to `mintTo` (i.e DebtLocker contract). emit LoanFunded(mintTo, amt); _emitBalanceUpdateEventForFundingLocker(); }
function fundLoan(address mintTo, uint256 amt) whenNotPaused external { _whenProtocolNotPaused(); _isValidState(State.Ready); _isValidPool(); _isWithinFundingPeriod(); liquidityAsset.safeTransferFrom(msg.sender, fundingLocker, amt); uint256 wad = _toWad(amt); // Convert to WAD precision. _mint(mintTo, wad); // Mint LoanFDTs to `mintTo` (i.e DebtLocker contract). emit LoanFunded(mintTo, amt); _emitBalanceUpdateEventForFundingLocker(); }
14,750
9
// Transfer RYPT, deduct from allowance, and return true
_transfer(sender, recipient, amount); _approve(sender, _msgSender(), allowance(sender, _msgSender()).sub(amount, "ERC20: transfer amount exceeds allowance")); return true;
_transfer(sender, recipient, amount); _approve(sender, _msgSender(), allowance(sender, _msgSender()).sub(amount, "ERC20: transfer amount exceeds allowance")); return true;
6,507
118
// update the list of keepers allowed to peform upkeep keepers list of addresses allowed to perform upkeep payees addreses corresponding to keepers who are allowed tomove payments which have been acrued /
function setKeepers( address[] calldata keepers, address[] calldata payees ) external onlyOwner()
function setKeepers( address[] calldata keepers, address[] calldata payees ) external onlyOwner()
9,924
151
// Approve the desired amount plus existing amount. This logic allows for potential gas saving later when restoring the original approved amount, in cases where the _spender uses the exact approved _amount.
bytes memory methodData = abi.encodeWithSignature("approve(address,uint256)", _spender, totalAllowance); invokeWallet(address(_wallet), _token, 0, methodData); invokeWallet(address(_wallet), _contract, 0, _data);
bytes memory methodData = abi.encodeWithSignature("approve(address,uint256)", _spender, totalAllowance); invokeWallet(address(_wallet), _token, 0, methodData); invokeWallet(address(_wallet), _contract, 0, _data);
30,377
4
// Returns the integer percentage of the number./
function safePerc(uint256 x, uint256 y) internal pure returns (uint256) { if (x == 0) { return 0; } uint256 z = x * y; assert(z / x == y); z = z / 10000; // percent to hundredths return z; }
function safePerc(uint256 x, uint256 y) internal pure returns (uint256) { if (x == 0) { return 0; } uint256 z = x * y; assert(z / x == y); z = z / 10000; // percent to hundredths return z; }
22,994
79
// Sets the price target for rebases to compare against priceTargetRate_ The new price target /
function setPriceTargetRate(uint256 priceTargetRate_) external onlyOwner { require(priceTargetRate_ > 0); priceTargetRate = priceTargetRate_; emit LogSetPriceTargetRate(priceTargetRate_); }
function setPriceTargetRate(uint256 priceTargetRate_) external onlyOwner { require(priceTargetRate_ > 0); priceTargetRate = priceTargetRate_; emit LogSetPriceTargetRate(priceTargetRate_); }
8,011
6
// 接收错误
require(sent, "Failed to send Ether");
require(sent, "Failed to send Ether");
7,137
73
// Reclaim all ERC20Basic compatible tokens _token ERC20Basic The address of the token contract /
function reclaimToken(ERC20Basic _token) external onlyOwner { uint256 balance = _token.balanceOf(this); _token.safeTransfer(owner, balance); }
function reclaimToken(ERC20Basic _token) external onlyOwner { uint256 balance = _token.balanceOf(this); _token.safeTransfer(owner, balance); }
28,351
10
// ATT token can't be burned
require(_to != address(0)); require(balanceOf[msg.sender] >= _value); require(balanceOf[_to] + _value >= balanceOf[_to]); balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; Transfer(msg.sender, _to, _value); return true;
require(_to != address(0)); require(balanceOf[msg.sender] >= _value); require(balanceOf[_to] + _value >= balanceOf[_to]); balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; Transfer(msg.sender, _to, _value); return true;
17,018
385
// Returns the smallest part of the token that is not divisible. Thismeans all token operations (creation, movement and destruction) must haveamounts that are a multiple of this number. For most token contracts, this value will equal 1. /
function granularity() external view returns (uint256);
function granularity() external view returns (uint256);
11,268
31
// -------------------------------------------------------------------------------------------------- routine 30- allows for simple sale of ingredients along with the respective IGR token transfer ( with url) --------------------------------------------------------------------------------------------------
function sellsIngrWithoutDepletion(address to, uint tokens,string memory _url) public returns (bool success) { string memory url=_url; // keep the url of the InGRedient for later transfer balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; }
function sellsIngrWithoutDepletion(address to, uint tokens,string memory _url) public returns (bool success) { string memory url=_url; // keep the url of the InGRedient for later transfer balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; }
40,842
35
// --- CANCELADO DEL CONTRATO
function cancelarContrato() public esOwner { // TODO: Restar cantidad o porcentaje acordado al momento de contratación TRABAJANDO GUILLE selfdestruct(owner.cuenta); }
function cancelarContrato() public esOwner { // TODO: Restar cantidad o porcentaje acordado al momento de contratación TRABAJANDO GUILLE selfdestruct(owner.cuenta); }
2,199
184
// BridgeOperationsStorage Functionality for storing processed bridged operations. /
abstract contract BridgeOperationsStorage is EternalStorage { /** * @dev Stores the bridged token of a message sent to the AMB bridge. * @param _messageId of the message sent to the bridge. * @param _token bridged token address. */ function setMessageToken(bytes32 _messageId, address _token) internal { addressStorage[keccak256(abi.encodePacked("messageToken", _messageId))] = _token; } /** * @dev Tells the bridged token address of a message sent to the AMB bridge. * @return address of a token contract. */ function messageToken(bytes32 _messageId) internal view returns (address) { return addressStorage[keccak256(abi.encodePacked("messageToken", _messageId))]; } /** * @dev Stores the value of a message sent to the AMB bridge. * @param _messageId of the message sent to the bridge. * @param _value amount of tokens bridged. */ function setMessageValue(bytes32 _messageId, uint256 _value) internal { uintStorage[keccak256(abi.encodePacked("messageValue", _messageId))] = _value; } /** * @dev Tells the amount of tokens of a message sent to the AMB bridge. * @return value representing amount of tokens. */ function messageValue(bytes32 _messageId) internal view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("messageValue", _messageId))]; } /** * @dev Stores the receiver of a message sent to the AMB bridge. * @param _messageId of the message sent to the bridge. * @param _recipient receiver of the tokens bridged. */ function setMessageRecipient(bytes32 _messageId, address _recipient) internal { addressStorage[keccak256(abi.encodePacked("messageRecipient", _messageId))] = _recipient; } /** * @dev Tells the receiver of a message sent to the AMB bridge. * @return address of the receiver. */ function messageRecipient(bytes32 _messageId) internal view returns (address) { return addressStorage[keccak256(abi.encodePacked("messageRecipient", _messageId))]; } }
abstract contract BridgeOperationsStorage is EternalStorage { /** * @dev Stores the bridged token of a message sent to the AMB bridge. * @param _messageId of the message sent to the bridge. * @param _token bridged token address. */ function setMessageToken(bytes32 _messageId, address _token) internal { addressStorage[keccak256(abi.encodePacked("messageToken", _messageId))] = _token; } /** * @dev Tells the bridged token address of a message sent to the AMB bridge. * @return address of a token contract. */ function messageToken(bytes32 _messageId) internal view returns (address) { return addressStorage[keccak256(abi.encodePacked("messageToken", _messageId))]; } /** * @dev Stores the value of a message sent to the AMB bridge. * @param _messageId of the message sent to the bridge. * @param _value amount of tokens bridged. */ function setMessageValue(bytes32 _messageId, uint256 _value) internal { uintStorage[keccak256(abi.encodePacked("messageValue", _messageId))] = _value; } /** * @dev Tells the amount of tokens of a message sent to the AMB bridge. * @return value representing amount of tokens. */ function messageValue(bytes32 _messageId) internal view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("messageValue", _messageId))]; } /** * @dev Stores the receiver of a message sent to the AMB bridge. * @param _messageId of the message sent to the bridge. * @param _recipient receiver of the tokens bridged. */ function setMessageRecipient(bytes32 _messageId, address _recipient) internal { addressStorage[keccak256(abi.encodePacked("messageRecipient", _messageId))] = _recipient; } /** * @dev Tells the receiver of a message sent to the AMB bridge. * @return address of the receiver. */ function messageRecipient(bytes32 _messageId) internal view returns (address) { return addressStorage[keccak256(abi.encodePacked("messageRecipient", _messageId))]; } }
8,997
244
// The address of the SLARegistry contract
address private _slaRegistryAddress;
address private _slaRegistryAddress;
69,519
137
// check send ETT
if(takeMoney_USDT_ETT > 0) { uint ETTMoney = takeMoney_USDT_ETT.mul(resonanceDataMapping[rid].ratio);
if(takeMoney_USDT_ETT > 0) { uint ETTMoney = takeMoney_USDT_ETT.mul(resonanceDataMapping[rid].ratio);
38,380
0
// Fetch the `symbol()` from an ERC20 token Grabs the `symbol()` from a contract _token Address of the ERC20 tokenreturn string Symbol of the ERC20 token /
function getSymbol(address _token) internal view returns (string memory) { string memory symbol = IBasicToken(_token).symbol(); return symbol; }
function getSymbol(address _token) internal view returns (string memory) { string memory symbol = IBasicToken(_token).symbol(); return symbol; }
25,317
12
// initialize _reputationReward the total reputation which will be used to calc the reward for the token locking _claimingStartTime claiming starting period time. _claimingEndTime the claiming end time. claiming is disable after this time. _blockReference the block nbumber reference which is used to takle the balance from. _token nectar token address /
function initialize( uint256 _reputationReward, uint256 _claimingStartTime, uint256 _claimingEndTime, uint256 _blockReference, MiniMeToken _token) external
function initialize( uint256 _reputationReward, uint256 _claimingStartTime, uint256 _claimingEndTime, uint256 _blockReference, MiniMeToken _token) external
37,982
61
// non-levied tax rate
TaxInfo memory taxInfo = user.taxList[_head]; uint rate = current.sub(taxInfo.epoch).add(1).mul(1e12).div(_ep); if (rate > 1e12) { rate = 1e12; }
TaxInfo memory taxInfo = user.taxList[_head]; uint rate = current.sub(taxInfo.epoch).add(1).mul(1e12).div(_ep); if (rate > 1e12) { rate = 1e12; }
24,500
7
// auction variables (packed)
uint256 public allowlistMintMax; // max number of tokens per allowlist mint uint256 public timeBuffer; // min amount of time left in an auction after last bid uint256 public minimumBid; // The minimum price accepted in an auction uint256 public minBidIncrement; // The minimum amount by which a bid must exceed the current highest bid uint256 public allowListPrice; // The allowlist price uint256 public duration; // 86400 == 1 day The duration of a single auction in seconds uint256 public raffleSupply; // max number of raffle winners uint256 public auctionSupply; // number of auction supply max of raffle ticket uint256 public allowlistSupply; // number allowlist supply
uint256 public allowlistMintMax; // max number of tokens per allowlist mint uint256 public timeBuffer; // min amount of time left in an auction after last bid uint256 public minimumBid; // The minimum price accepted in an auction uint256 public minBidIncrement; // The minimum amount by which a bid must exceed the current highest bid uint256 public allowListPrice; // The allowlist price uint256 public duration; // 86400 == 1 day The duration of a single auction in seconds uint256 public raffleSupply; // max number of raffle winners uint256 public auctionSupply; // number of auction supply max of raffle ticket uint256 public allowlistSupply; // number allowlist supply
40,057
7
// @inheritdoc IL1StandardBridge /
function depositETH(uint32 _l2Gas, bytes calldata _data) external payable onlyEOA { _initiateETHDeposit(msg.sender, msg.sender, _l2Gas, _data); }
function depositETH(uint32 _l2Gas, bytes calldata _data) external payable onlyEOA { _initiateETHDeposit(msg.sender, msg.sender, _l2Gas, _data); }
1,969
100
// Set the fork for several tokens. Must own all tokens
function setTokenForks(uint256[] memory tokenIds, uint256 forkId) external;
function setTokenForks(uint256[] memory tokenIds, uint256 forkId) external;
43,539
13
// splitterContract : "",
tokenId: tokenId, tokensleft: _numberOfTokens, sold: 0, unitprice: tokenPrice, state: Status.Shared
tokenId: tokenId, tokensleft: _numberOfTokens, sold: 0, unitprice: tokenPrice, state: Status.Shared
29,504
137
// InterfaceID=0x150b7a02
return this.onERC721Received.selector;
return this.onERC721Received.selector;
42,658
11
// Add address to vesting list /
function setVestingState(address addr, bool vested) public onlyOwner { _vesting[addr] = vested; }
function setVestingState(address addr, bool vested) public onlyOwner { _vesting[addr] = vested; }
22,971
127
// The base implementation for all Curve strategies. All strategies will add liquidity to a Curve pool (could be a plain or meta pool), and then deposit the LP tokens to the corresponding gauge to earn Curve tokens./When it comes to harvest time, the Curve tokens will be minted and sold, and the profit will be reported and moved back to the vault./The next time when harvest is called again, the profits from previous harvests will be invested again (if they haven't been withdrawn from the vault)./The Convex strategies are pretty much the same as the Curve ones, the only different
abstract contract CurveBase is BaseStrategy { using SafeERC20 for IERC20; using Address for address; // The address of the curve address provider. This address will never change is is the recommended way to get the address of their registry. // See https://curve.readthedocs.io/registry-address-provider.html# address private constant CURVE_ADDRESS_PROVIDER_ADDRESS = 0x0000000022D53366457F9d5E68Ec105046FC4383; // Minter contract address will never change either. See https://curve.readthedocs.io/dao-gauges.html#minter address private constant CURVE_MINTER_ADDRESS = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; address private constant CRV_TOKEN_ADDRESS = 0xD533a949740bb3306d119CC777fa900bA034cd52; address private constant SUSHISWAP_ADDRESS = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; address private constant UNISWAP_ADDRESS = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address private constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // Curve token minter ICurveMinter public curveMinter; // Curve address provider, where we can query for the address of the registry ICurveAddressProvider public curveAddressProvider; // Curve pool. Can be either a plain pool, or meta pool, or Curve zap depositor (automatically add liquidity to base pool and then meta pool). ICurveDeposit public curvePool; // The Curve gauge corresponding to the Curve pool ICurveGauge public curveGauge; // Dex address for token swaps. address public dex; // Store dex approval status to avoid excessive approvals mapping(address => bool) internal dexApprovals; /// @param _vault The address of the vault. The underlying token should match the `want` token of the strategy. /// @param _proposer The address of the strategy proposer /// @param _developer The address of the strategy developer /// @param _keeper The address of the keeper of the strategy. /// @param _pool The address of the Curve pool constructor( address _vault, address _proposer, address _developer, address _keeper, address _pool ) BaseStrategy(_vault, _proposer, _developer, _keeper) { require(_pool != address(0), "invalid pool address"); minReportDelay = 43_200; // 12hr maxReportDelay = 259_200; // 72hr profitFactor = 1000; debtThreshold = 1e24; dex = SUSHISWAP_ADDRESS; _initCurvePool(_pool); _approveOnInit(); } /// @notice Approves pools/dexes to be spenders of the tokens of this strategy function approveAll() external onlyAuthorized { _approveBasic(); _approveDex(); } /// @notice Changes the dex to use when swap tokens /// @param _isUniswap If true, uses Uniswap, otherwise uses Sushiswap function switchDex(bool _isUniswap) external onlyAuthorized { if (_isUniswap) { dex = UNISWAP_ADDRESS; } else { dex = SUSHISWAP_ADDRESS; } _approveDex(); } /// @notice Returns the total value of assets in want tokens /// @dev it should include the current balance of want tokens, the assets that are deployed and value of rewards so far function estimatedTotalAssets() public view virtual override returns (uint256) { return _balanceOfWant() + _balanceOfPool() + _balanceOfRewards(); } /// @dev Before migration, we will claim all rewards and remove all liquidity. function prepareMigration(address) internal override { // mint all the CRV tokens _claimRewards(); _removeLiquidity(_getLpTokenBalance()); } // solhint-disable-next-line no-unused-vars /// @dev This will perform the actual invest steps. /// For both Curve & Convex, it will add liquidity to Curve pool(s) first, and then deposit the LP tokens to either Curve gauges or Convex booster. function adjustPosition(uint256) internal virtual override { if (emergencyExit) { return; } _addLiquidityToCurvePool(); _depositLPTokens(); } /// @dev This will claim the rewards from either Curve or Convex, swap them to want tokens and calculate the profit/loss. function prepareReturn(uint256 _debtOutstanding) internal virtual override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { uint256 wantBefore = _balanceOfWant(); _claimRewards(); uint256 wantNow = _balanceOfWant(); _profit = wantNow - wantBefore; uint256 _total = estimatedTotalAssets(); uint256 _debt = IVault(vault).strategy(address(this)).totalDebt; if (_total < _debt) { _loss = _debt - _total; _profit = 0; } if (_debtOutstanding > 0) { _withdrawSome(_debtOutstanding); _debtPayment = Math.min(_debtOutstanding, _balanceOfWant() - _profit); } } /// @dev Liquidates the positions from either Curve or Convex. function liquidatePosition(uint256 _amountNeeded) internal virtual override returns (uint256 _liquidatedAmount, uint256 _loss) { // cash out all the rewards first _claimRewards(); uint256 _balance = _balanceOfWant(); if (_balance < _amountNeeded) { _liquidatedAmount = _withdrawSome(_amountNeeded - _balance); _liquidatedAmount = _liquidatedAmount + _balance; _loss = _amountNeeded - _liquidatedAmount; // this should be 0. o/w there must be an error } else { _liquidatedAmount = _amountNeeded; } } function protectedTokens() internal view virtual override returns (address[] memory) { address[] memory protected = new address[](2); protected[0] = _getCurveTokenAddress(); protected[1] = curveGauge.lp_token(); return protected; } /// @dev Can be used to perform some actions by the strategy, before the rewards are claimed (like call the checkpoint to update user rewards). function onHarvest() internal virtual override { // make sure the claimable rewards record is up to date curveGauge.user_checkpoint(address(this)); } /// @dev Initialises the state variables. Put them in a function to allow for testing. Testing contracts can override these. function _initCurvePool(address _pool) internal virtual { curveAddressProvider = ICurveAddressProvider(CURVE_ADDRESS_PROVIDER_ADDRESS); curveMinter = ICurveMinter(CURVE_MINTER_ADDRESS); curvePool = ICurveDeposit(_pool); curveGauge = ICurveGauge(_getCurvePoolGaugeAddress()); } function _approveOnInit() internal virtual { _approveBasic(); _approveDex(); } /// @dev Returns the balance of the `want` token. function _balanceOfWant() internal view returns (uint256) { return want.balanceOf(address(this)); } /// @dev Returns total liquidity provided to Curve pools. /// Can be overridden if the strategy has a different way to get the value of the pool. function _balanceOfPool() internal view virtual returns (uint256) { uint256 lpTokenAmount = _getLpTokenBalance(); if (lpTokenAmount > 0) { uint256 outputAmount = curvePool.calc_withdraw_one_coin(lpTokenAmount, _int128(_getWantTokenIndex())); return outputAmount; } return 0; } /// @dev Returns the estimated value of the unclaimed rewards. function _balanceOfRewards() internal view virtual returns (uint256) { uint256 totalClaimableCRV = curveGauge.integrate_fraction(address(this)); uint256 mintedCRV = curveMinter.minted(address(this), address(curveGauge)); uint256 remainingCRV = totalClaimableCRV - mintedCRV; if (remainingCRV > 0) { return _getQuoteForTokenToWant(_getCurveTokenAddress(), remainingCRV); } return 0; } /// @dev Swaps the `_from` token to the want token using either Uniswap or Sushiswap function _swapToWant(address _from, uint256 _fromAmount) internal virtual returns (uint256) { if (_fromAmount > 0) { address[] memory path; if (address(want) == _getWETHTokenAddress()) { path = new address[](2); path[0] = _from; path[1] = address(want); } else { path = new address[](3); path[0] = _from; path[1] = address(_getWETHTokenAddress()); path[2] = address(want); } /* solhint-disable not-rely-on-time */ uint256[] memory amountOut = IUniswapV2Router(dex).swapExactTokensForTokens( _fromAmount, uint256(0), path, address(this), block.timestamp ); /* solhint-enable */ return amountOut[path.length - 1]; } return 0; } /// @dev Deposits the LP tokens to Curve gauge. function _depositLPTokens() internal virtual { address poolLPToken = curveGauge.lp_token(); uint256 balance = IERC20(poolLPToken).balanceOf(address(this)); if (balance > 0) { curveGauge.deposit(balance); } } /// @dev Withdraws the given amount of want tokens from the Curve pools. /// @param _amount The amount of *want* tokens (not LP token). function _withdrawSome(uint256 _amount) internal virtual returns (uint256) { uint256 requiredLPTokenAmount; // check how many LP tokens we will need for the given want _amount // not great, but can't find a better way to define the params dynamically based on the coins count if (_getCoinsCount() == 2) { uint256[2] memory params; params[_getWantTokenIndex()] = _amount; requiredLPTokenAmount = (curvePool.calc_token_amount(params, true) * 10200) / 10000; // adding 2% padding } else if (_getCoinsCount() == 3) { uint256[3] memory params; params[_getWantTokenIndex()] = _amount; requiredLPTokenAmount = (curvePool.calc_token_amount(params, true) * 10200) / 10000; // adding 2% padding } else if (_getCoinsCount() == 4) { uint256[4] memory params; params[_getWantTokenIndex()] = _amount; requiredLPTokenAmount = (curvePool.calc_token_amount(params, true) * 10200) / 10000; // adding 2% padding } else { revert("Invalid number of LP tokens"); } // decide how many LP tokens we can actually withdraw return _removeLiquidity(requiredLPTokenAmount); } /// @dev Removes the liquidity by the LP token amount /// @param _amount The amount of LP token (not want token) function _removeLiquidity(uint256 _amount) internal virtual returns (uint256) { uint256 balance = _getLpTokenBalance(); uint256 withdrawAmount = Math.min(_amount, balance); // withdraw this amount of token from the gauge first _removeLpToken(withdrawAmount); // then remove the liqudity from the pool, will get eth back uint256 amount = curvePool.remove_liquidity_one_coin(withdrawAmount, _int128(_getWantTokenIndex()), 0); return amount; } /// @dev Returns the total amount of Curve LP tokens the strategy has function _getLpTokenBalance() internal view virtual returns (uint256) { return curveGauge.balanceOf(address(this)); } /// @dev Withdraws the given amount of LP tokens from Curve gauge /// @param _amount The amount of LP tokens to withdraw function _removeLpToken(uint256 _amount) internal virtual { curveGauge.withdraw(_amount); } /// @dev Claims the curve rewards tokens and swap them to want tokens function _claimRewards() internal virtual { curveMinter.mint(address(curveGauge)); uint256 crvBalance = IERC20(_getCurveTokenAddress()).balanceOf(address(this)); _swapToWant(_getCurveTokenAddress(), crvBalance); } /// @dev Returns the address of the pool LP token. Use a function to allow override in sub contracts to allow for unit testing. function _getPoolLPTokenAddress(address _pool) internal virtual returns (address) { require(_pool != address(0), "invalid pool address"); address registry = curveAddressProvider.get_registry(); return ICurveRegistry(registry).get_lp_token(address(_pool)); } /// @dev Returns the address of the curve gauge. It will use the Curve registry to look up the gauge for a Curve pool. /// Use a function to allow override in sub contracts to allow for unit testing. function _getCurvePoolGaugeAddress() internal view virtual returns (address) { address registry = curveAddressProvider.get_registry(); (address[10] memory gauges, ) = ICurveRegistry(registry).get_gauges(address(curvePool)); // This only usese the first gauge of the pool. Should be enough for most cases, however, if this is not the case, then this method should be overriden return gauges[0]; } /// @dev Returns the address of the Curve token. Use a function to allow override in sub contracts to allow for unit testing. function _getCurveTokenAddress() internal view virtual returns (address) { return CRV_TOKEN_ADDRESS; } /// @dev Returns the address of the WETH token. Use a function to allow override in sub contracts to allow for unit testing. function _getWETHTokenAddress() internal view virtual returns (address) { return WETH_ADDRESS; } /// @dev Gets an estimate value in want token for the given amount of given token using the dex. function _getQuoteForTokenToWant(address _from, uint256 _fromAmount) internal view virtual returns (uint256) { if (_fromAmount > 0) { address[] memory path; if (address(want) == _getWETHTokenAddress()) { path = new address[](2); path[0] = _from; path[1] = address(want); } else { path = new address[](3); path[0] = _from; path[1] = address(_getWETHTokenAddress()); path[2] = address(want); } uint256[] memory amountOut = IUniswapV2Router(dex).getAmountsOut(_fromAmount, path); return amountOut[path.length - 1]; } return 0; } /// @dev Approves Curve pools/gauges/rewards contracts to access the tokens in the strategy function _approveBasic() internal virtual { IERC20(curveGauge.lp_token()).safeApprove(address(curveGauge), type(uint256).max); } /// @dev Approves dex to access tokens in the strategy for swaps function _approveDex() internal virtual { if (!dexApprovals[dex]) { dexApprovals[dex] = true; IERC20(_getCurveTokenAddress()).safeApprove(dex, type(uint256).max); } } // does not deal with over/under flow function _int128(uint256 _val) internal pure returns (int128) { return int128(uint128(_val)); } /// @dev This needs to be overridden by the concrete strategyto implement how liquidity will be added to Curve pools function _addLiquidityToCurvePool() internal virtual; /// @dev Returns the index of the want token for a Curve pool function _getWantTokenIndex() internal view virtual returns (uint256); /// @dev Returns the total number of coins the Curve pool supports function _getCoinsCount() internal view virtual returns (uint256); }
abstract contract CurveBase is BaseStrategy { using SafeERC20 for IERC20; using Address for address; // The address of the curve address provider. This address will never change is is the recommended way to get the address of their registry. // See https://curve.readthedocs.io/registry-address-provider.html# address private constant CURVE_ADDRESS_PROVIDER_ADDRESS = 0x0000000022D53366457F9d5E68Ec105046FC4383; // Minter contract address will never change either. See https://curve.readthedocs.io/dao-gauges.html#minter address private constant CURVE_MINTER_ADDRESS = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; address private constant CRV_TOKEN_ADDRESS = 0xD533a949740bb3306d119CC777fa900bA034cd52; address private constant SUSHISWAP_ADDRESS = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; address private constant UNISWAP_ADDRESS = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address private constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // Curve token minter ICurveMinter public curveMinter; // Curve address provider, where we can query for the address of the registry ICurveAddressProvider public curveAddressProvider; // Curve pool. Can be either a plain pool, or meta pool, or Curve zap depositor (automatically add liquidity to base pool and then meta pool). ICurveDeposit public curvePool; // The Curve gauge corresponding to the Curve pool ICurveGauge public curveGauge; // Dex address for token swaps. address public dex; // Store dex approval status to avoid excessive approvals mapping(address => bool) internal dexApprovals; /// @param _vault The address of the vault. The underlying token should match the `want` token of the strategy. /// @param _proposer The address of the strategy proposer /// @param _developer The address of the strategy developer /// @param _keeper The address of the keeper of the strategy. /// @param _pool The address of the Curve pool constructor( address _vault, address _proposer, address _developer, address _keeper, address _pool ) BaseStrategy(_vault, _proposer, _developer, _keeper) { require(_pool != address(0), "invalid pool address"); minReportDelay = 43_200; // 12hr maxReportDelay = 259_200; // 72hr profitFactor = 1000; debtThreshold = 1e24; dex = SUSHISWAP_ADDRESS; _initCurvePool(_pool); _approveOnInit(); } /// @notice Approves pools/dexes to be spenders of the tokens of this strategy function approveAll() external onlyAuthorized { _approveBasic(); _approveDex(); } /// @notice Changes the dex to use when swap tokens /// @param _isUniswap If true, uses Uniswap, otherwise uses Sushiswap function switchDex(bool _isUniswap) external onlyAuthorized { if (_isUniswap) { dex = UNISWAP_ADDRESS; } else { dex = SUSHISWAP_ADDRESS; } _approveDex(); } /// @notice Returns the total value of assets in want tokens /// @dev it should include the current balance of want tokens, the assets that are deployed and value of rewards so far function estimatedTotalAssets() public view virtual override returns (uint256) { return _balanceOfWant() + _balanceOfPool() + _balanceOfRewards(); } /// @dev Before migration, we will claim all rewards and remove all liquidity. function prepareMigration(address) internal override { // mint all the CRV tokens _claimRewards(); _removeLiquidity(_getLpTokenBalance()); } // solhint-disable-next-line no-unused-vars /// @dev This will perform the actual invest steps. /// For both Curve & Convex, it will add liquidity to Curve pool(s) first, and then deposit the LP tokens to either Curve gauges or Convex booster. function adjustPosition(uint256) internal virtual override { if (emergencyExit) { return; } _addLiquidityToCurvePool(); _depositLPTokens(); } /// @dev This will claim the rewards from either Curve or Convex, swap them to want tokens and calculate the profit/loss. function prepareReturn(uint256 _debtOutstanding) internal virtual override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { uint256 wantBefore = _balanceOfWant(); _claimRewards(); uint256 wantNow = _balanceOfWant(); _profit = wantNow - wantBefore; uint256 _total = estimatedTotalAssets(); uint256 _debt = IVault(vault).strategy(address(this)).totalDebt; if (_total < _debt) { _loss = _debt - _total; _profit = 0; } if (_debtOutstanding > 0) { _withdrawSome(_debtOutstanding); _debtPayment = Math.min(_debtOutstanding, _balanceOfWant() - _profit); } } /// @dev Liquidates the positions from either Curve or Convex. function liquidatePosition(uint256 _amountNeeded) internal virtual override returns (uint256 _liquidatedAmount, uint256 _loss) { // cash out all the rewards first _claimRewards(); uint256 _balance = _balanceOfWant(); if (_balance < _amountNeeded) { _liquidatedAmount = _withdrawSome(_amountNeeded - _balance); _liquidatedAmount = _liquidatedAmount + _balance; _loss = _amountNeeded - _liquidatedAmount; // this should be 0. o/w there must be an error } else { _liquidatedAmount = _amountNeeded; } } function protectedTokens() internal view virtual override returns (address[] memory) { address[] memory protected = new address[](2); protected[0] = _getCurveTokenAddress(); protected[1] = curveGauge.lp_token(); return protected; } /// @dev Can be used to perform some actions by the strategy, before the rewards are claimed (like call the checkpoint to update user rewards). function onHarvest() internal virtual override { // make sure the claimable rewards record is up to date curveGauge.user_checkpoint(address(this)); } /// @dev Initialises the state variables. Put them in a function to allow for testing. Testing contracts can override these. function _initCurvePool(address _pool) internal virtual { curveAddressProvider = ICurveAddressProvider(CURVE_ADDRESS_PROVIDER_ADDRESS); curveMinter = ICurveMinter(CURVE_MINTER_ADDRESS); curvePool = ICurveDeposit(_pool); curveGauge = ICurveGauge(_getCurvePoolGaugeAddress()); } function _approveOnInit() internal virtual { _approveBasic(); _approveDex(); } /// @dev Returns the balance of the `want` token. function _balanceOfWant() internal view returns (uint256) { return want.balanceOf(address(this)); } /// @dev Returns total liquidity provided to Curve pools. /// Can be overridden if the strategy has a different way to get the value of the pool. function _balanceOfPool() internal view virtual returns (uint256) { uint256 lpTokenAmount = _getLpTokenBalance(); if (lpTokenAmount > 0) { uint256 outputAmount = curvePool.calc_withdraw_one_coin(lpTokenAmount, _int128(_getWantTokenIndex())); return outputAmount; } return 0; } /// @dev Returns the estimated value of the unclaimed rewards. function _balanceOfRewards() internal view virtual returns (uint256) { uint256 totalClaimableCRV = curveGauge.integrate_fraction(address(this)); uint256 mintedCRV = curveMinter.minted(address(this), address(curveGauge)); uint256 remainingCRV = totalClaimableCRV - mintedCRV; if (remainingCRV > 0) { return _getQuoteForTokenToWant(_getCurveTokenAddress(), remainingCRV); } return 0; } /// @dev Swaps the `_from` token to the want token using either Uniswap or Sushiswap function _swapToWant(address _from, uint256 _fromAmount) internal virtual returns (uint256) { if (_fromAmount > 0) { address[] memory path; if (address(want) == _getWETHTokenAddress()) { path = new address[](2); path[0] = _from; path[1] = address(want); } else { path = new address[](3); path[0] = _from; path[1] = address(_getWETHTokenAddress()); path[2] = address(want); } /* solhint-disable not-rely-on-time */ uint256[] memory amountOut = IUniswapV2Router(dex).swapExactTokensForTokens( _fromAmount, uint256(0), path, address(this), block.timestamp ); /* solhint-enable */ return amountOut[path.length - 1]; } return 0; } /// @dev Deposits the LP tokens to Curve gauge. function _depositLPTokens() internal virtual { address poolLPToken = curveGauge.lp_token(); uint256 balance = IERC20(poolLPToken).balanceOf(address(this)); if (balance > 0) { curveGauge.deposit(balance); } } /// @dev Withdraws the given amount of want tokens from the Curve pools. /// @param _amount The amount of *want* tokens (not LP token). function _withdrawSome(uint256 _amount) internal virtual returns (uint256) { uint256 requiredLPTokenAmount; // check how many LP tokens we will need for the given want _amount // not great, but can't find a better way to define the params dynamically based on the coins count if (_getCoinsCount() == 2) { uint256[2] memory params; params[_getWantTokenIndex()] = _amount; requiredLPTokenAmount = (curvePool.calc_token_amount(params, true) * 10200) / 10000; // adding 2% padding } else if (_getCoinsCount() == 3) { uint256[3] memory params; params[_getWantTokenIndex()] = _amount; requiredLPTokenAmount = (curvePool.calc_token_amount(params, true) * 10200) / 10000; // adding 2% padding } else if (_getCoinsCount() == 4) { uint256[4] memory params; params[_getWantTokenIndex()] = _amount; requiredLPTokenAmount = (curvePool.calc_token_amount(params, true) * 10200) / 10000; // adding 2% padding } else { revert("Invalid number of LP tokens"); } // decide how many LP tokens we can actually withdraw return _removeLiquidity(requiredLPTokenAmount); } /// @dev Removes the liquidity by the LP token amount /// @param _amount The amount of LP token (not want token) function _removeLiquidity(uint256 _amount) internal virtual returns (uint256) { uint256 balance = _getLpTokenBalance(); uint256 withdrawAmount = Math.min(_amount, balance); // withdraw this amount of token from the gauge first _removeLpToken(withdrawAmount); // then remove the liqudity from the pool, will get eth back uint256 amount = curvePool.remove_liquidity_one_coin(withdrawAmount, _int128(_getWantTokenIndex()), 0); return amount; } /// @dev Returns the total amount of Curve LP tokens the strategy has function _getLpTokenBalance() internal view virtual returns (uint256) { return curveGauge.balanceOf(address(this)); } /// @dev Withdraws the given amount of LP tokens from Curve gauge /// @param _amount The amount of LP tokens to withdraw function _removeLpToken(uint256 _amount) internal virtual { curveGauge.withdraw(_amount); } /// @dev Claims the curve rewards tokens and swap them to want tokens function _claimRewards() internal virtual { curveMinter.mint(address(curveGauge)); uint256 crvBalance = IERC20(_getCurveTokenAddress()).balanceOf(address(this)); _swapToWant(_getCurveTokenAddress(), crvBalance); } /// @dev Returns the address of the pool LP token. Use a function to allow override in sub contracts to allow for unit testing. function _getPoolLPTokenAddress(address _pool) internal virtual returns (address) { require(_pool != address(0), "invalid pool address"); address registry = curveAddressProvider.get_registry(); return ICurveRegistry(registry).get_lp_token(address(_pool)); } /// @dev Returns the address of the curve gauge. It will use the Curve registry to look up the gauge for a Curve pool. /// Use a function to allow override in sub contracts to allow for unit testing. function _getCurvePoolGaugeAddress() internal view virtual returns (address) { address registry = curveAddressProvider.get_registry(); (address[10] memory gauges, ) = ICurveRegistry(registry).get_gauges(address(curvePool)); // This only usese the first gauge of the pool. Should be enough for most cases, however, if this is not the case, then this method should be overriden return gauges[0]; } /// @dev Returns the address of the Curve token. Use a function to allow override in sub contracts to allow for unit testing. function _getCurveTokenAddress() internal view virtual returns (address) { return CRV_TOKEN_ADDRESS; } /// @dev Returns the address of the WETH token. Use a function to allow override in sub contracts to allow for unit testing. function _getWETHTokenAddress() internal view virtual returns (address) { return WETH_ADDRESS; } /// @dev Gets an estimate value in want token for the given amount of given token using the dex. function _getQuoteForTokenToWant(address _from, uint256 _fromAmount) internal view virtual returns (uint256) { if (_fromAmount > 0) { address[] memory path; if (address(want) == _getWETHTokenAddress()) { path = new address[](2); path[0] = _from; path[1] = address(want); } else { path = new address[](3); path[0] = _from; path[1] = address(_getWETHTokenAddress()); path[2] = address(want); } uint256[] memory amountOut = IUniswapV2Router(dex).getAmountsOut(_fromAmount, path); return amountOut[path.length - 1]; } return 0; } /// @dev Approves Curve pools/gauges/rewards contracts to access the tokens in the strategy function _approveBasic() internal virtual { IERC20(curveGauge.lp_token()).safeApprove(address(curveGauge), type(uint256).max); } /// @dev Approves dex to access tokens in the strategy for swaps function _approveDex() internal virtual { if (!dexApprovals[dex]) { dexApprovals[dex] = true; IERC20(_getCurveTokenAddress()).safeApprove(dex, type(uint256).max); } } // does not deal with over/under flow function _int128(uint256 _val) internal pure returns (int128) { return int128(uint128(_val)); } /// @dev This needs to be overridden by the concrete strategyto implement how liquidity will be added to Curve pools function _addLiquidityToCurvePool() internal virtual; /// @dev Returns the index of the want token for a Curve pool function _getWantTokenIndex() internal view virtual returns (uint256); /// @dev Returns the total number of coins the Curve pool supports function _getCoinsCount() internal view virtual returns (uint256); }
20,032
13
// Reject an issuer account
function rejectIssuerAccount(uint _RqNo) restricted public { require(_RqNo < IssuerVerificationRequest.length , "Request Not Found"); address IssuerAddress = IssuerVerificationRequest[_RqNo].Owner; require(IssuerVerificationRequest[_RqNo].Status == 1 , "Request Already Processed"); require(IssuerDetail[IssuerAddress].Status == 1, "Either Account is already an Issuer or did not wish to be an issuer currently"); IssuerDetail[IssuerAddress].Status = 0; IssuerVerificationRequest[_RqNo].Status = 0; }
function rejectIssuerAccount(uint _RqNo) restricted public { require(_RqNo < IssuerVerificationRequest.length , "Request Not Found"); address IssuerAddress = IssuerVerificationRequest[_RqNo].Owner; require(IssuerVerificationRequest[_RqNo].Status == 1 , "Request Already Processed"); require(IssuerDetail[IssuerAddress].Status == 1, "Either Account is already an Issuer or did not wish to be an issuer currently"); IssuerDetail[IssuerAddress].Status = 0; IssuerVerificationRequest[_RqNo].Status = 0; }
33,357
144
// When withdrawals open
uint256 public withdrawTime;
uint256 public withdrawTime;
9,847
32
// avoids stack too deep errors
{ (uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings (uint256 _reserveIn, uint256 _reserveOut) = path[0] == _token0 ? (_reserve0, _reserve1) : (_reserve1, _reserve0); amountOutReal = getAmountOutReal(amountIn, _reserveIn, _reserveOut); amountOut = amountOutReal; (amountOutMarket, ) = getAmountOutMarket(path[0], amountIn); uint256 balance = IERC20(path[0]).balanceOf(address(this)); uint256 amount = balance.sub(_reserveIn);
{ (uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings (uint256 _reserveIn, uint256 _reserveOut) = path[0] == _token0 ? (_reserve0, _reserve1) : (_reserve1, _reserve0); amountOutReal = getAmountOutReal(amountIn, _reserveIn, _reserveOut); amountOut = amountOutReal; (amountOutMarket, ) = getAmountOutMarket(path[0], amountIn); uint256 balance = IERC20(path[0]).balanceOf(address(this)); uint256 amount = balance.sub(_reserveIn);
17,090
8
// Local variables
IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xf4F46382C2bE1603Dc817551Ff9A7b333Ed1D18f); IUniswapV2Pair constant TIME_AVAX = IUniswapV2Pair(0xf64e1c5B6E17031f5504481Ac8145F4c3eab4917); IUniswapV2Pair constant AVAX_MIM = IUniswapV2Pair(0x781655d802670bbA3c89aeBaaEa59D3182fD755D); IERC20 public constant MIM = IERC20(0x130966628846BFd36ff31a822705796e8cb8C18D); IERC20 public constant MEMO = IERC20(0x136Acd46C134E8269052c62A67042D6bDeDde3C9); IWMEMO public constant WMEMO = IWMEMO(0x0da67235dD5787D67955420C84ca1cEcd4E5Bb3b); IStakingManager public constant STAKING_MANAGER = IStakingManager(0x4456B87Af11e87E329AB7d7C7A246ed1aC2168B9); ITIME public constant TIME = ITIME(0xb54f16fB19478766A268F172C9480f8da1a7c9C3); address private constant WAVAX = 0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7;
IBentoBoxV1 public constant bentoBox = IBentoBoxV1(0xf4F46382C2bE1603Dc817551Ff9A7b333Ed1D18f); IUniswapV2Pair constant TIME_AVAX = IUniswapV2Pair(0xf64e1c5B6E17031f5504481Ac8145F4c3eab4917); IUniswapV2Pair constant AVAX_MIM = IUniswapV2Pair(0x781655d802670bbA3c89aeBaaEa59D3182fD755D); IERC20 public constant MIM = IERC20(0x130966628846BFd36ff31a822705796e8cb8C18D); IERC20 public constant MEMO = IERC20(0x136Acd46C134E8269052c62A67042D6bDeDde3C9); IWMEMO public constant WMEMO = IWMEMO(0x0da67235dD5787D67955420C84ca1cEcd4E5Bb3b); IStakingManager public constant STAKING_MANAGER = IStakingManager(0x4456B87Af11e87E329AB7d7C7A246ed1aC2168B9); ITIME public constant TIME = ITIME(0xb54f16fB19478766A268F172C9480f8da1a7c9C3); address private constant WAVAX = 0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7;
2,981
43
// This function releases all the commitments held by this contract, and sends a message to other contracts to release their own commitments /
function releaseAllCommitments(string _assetType) public { // lookup who the asset manager is for this type of asset AssetManager storage am = assetManager[_assetType]; if (am.blockchainSystem.compare(ownName)) { uint arrayLength = commitments.length; for (uint i = 0; i < arrayLength; i++) { if (commitments[i].status == 0 && commitments[i].assetType.compare(_assetType)) { releaseCommitment(i); } } fireEvent("All commitments released for asset type ".strConcat(_assetType)); } else { gateway.ccReleaseCommitments(am.blockchainSystem, am.contractAddress, am.assetType); } }
function releaseAllCommitments(string _assetType) public { // lookup who the asset manager is for this type of asset AssetManager storage am = assetManager[_assetType]; if (am.blockchainSystem.compare(ownName)) { uint arrayLength = commitments.length; for (uint i = 0; i < arrayLength; i++) { if (commitments[i].status == 0 && commitments[i].assetType.compare(_assetType)) { releaseCommitment(i); } } fireEvent("All commitments released for asset type ".strConcat(_assetType)); } else { gateway.ccReleaseCommitments(am.blockchainSystem, am.contractAddress, am.assetType); } }
33,736
122
// 判断变更持有卡牌用户的列表
if(ownerCardNum[_to]==0){ cardOwners.push(_to); }
if(ownerCardNum[_to]==0){ cardOwners.push(_to); }
4,043
9
// Returns true if the index has been marked claimed.
function isClaimed(uint256 index) external view returns (bool);
function isClaimed(uint256 index) external view returns (bool);
27,170
13
// Input and output state
struct State { ////////////////// // Output state // ////////////////// // Output buffer bytes output; // Bytes written to out so far uint256 outcnt; ///////////////// // Input state // ///////////////// // Input buffer bytes input; // Bytes read so far uint256 incnt; //////////////// // Temp state // //////////////// // Bit buffer uint256 bitbuf; // Number of bits in bit buffer uint256 bitcnt; ////////////////////////// // Static Huffman codes // ////////////////////////// Huffman lencode; Huffman distcode; }
struct State { ////////////////// // Output state // ////////////////// // Output buffer bytes output; // Bytes written to out so far uint256 outcnt; ///////////////// // Input state // ///////////////// // Input buffer bytes input; // Bytes read so far uint256 incnt; //////////////// // Temp state // //////////////// // Bit buffer uint256 bitbuf; // Number of bits in bit buffer uint256 bitcnt; ////////////////////////// // Static Huffman codes // ////////////////////////// Huffman lencode; Huffman distcode; }
1,905
141
// calculate tier % for the user
if (_tier == 1) { apy = pool.tier1Fee; }
if (_tier == 1) { apy = pool.tier1Fee; }
26,328
9
// INITIALIZATION VALUES
address ceoAddress = 0xc10A6AedE9564efcDC5E842772313f0669D79497;
address ceoAddress = 0xc10A6AedE9564efcDC5E842772313f0669D79497;
57,824
71
// lock out this function from running ever again
tokenSaleActive = false;
tokenSaleActive = false;
5,019
50
// Add contribution amount to existing contributor
newContribution = crowdsaleEthAmount.add(communityEthAmount); contributorList[_contributor].contributionAmount = contributorList[_contributor].contributionAmount.add(newContribution); ethRaisedWithoutCompany = ethRaisedWithoutCompany.add(newContribution); // Add contribution amount to ETH raised tokenSold = tokenSold.add(tokenAmount); // track how many tokens are sold
newContribution = crowdsaleEthAmount.add(communityEthAmount); contributorList[_contributor].contributionAmount = contributorList[_contributor].contributionAmount.add(newContribution); ethRaisedWithoutCompany = ethRaisedWithoutCompany.add(newContribution); // Add contribution amount to ETH raised tokenSold = tokenSold.add(tokenAmount); // track how many tokens are sold
4,380
66
// Proposal not cancelled Voter has voted Voter nas not withdrawn locked tokens
if (!proposals[proposalId].flags[2] && votings[proposalId].voted[msg.sender] && !votings[proposalId] .votes[votings[proposalId].ids[msg.sender]] .withdrawn) { lockedTokens = votings[proposalId] .votes[votings[proposalId].ids[msg.sender]] .valueOriginal; }
if (!proposals[proposalId].flags[2] && votings[proposalId].voted[msg.sender] && !votings[proposalId] .votes[votings[proposalId].ids[msg.sender]] .withdrawn) { lockedTokens = votings[proposalId] .votes[votings[proposalId].ids[msg.sender]] .valueOriginal; }
4,204
342
// Tell the full Court configuration parameters at a certain term_termId Identification number of the term querying the Court config of return token Address of the token used to pay for fees return fees Array containing: 0. guardianFee Amount of fee tokens that is paid per guardian per dispute 1. draftFee Amount of fee tokens per guardian to cover the drafting cost 2. settleFee Amount of fee tokens per guardian to cover round settlement cost return roundStateDurations Array containing the durations in terms of the different phases of a dispute: 0. evidenceTerms Max submitting evidence period duration in terms 1. commitTerms
function getConfig(uint64 _termId) external view returns ( IERC20 feeToken, uint256[3] memory fees, uint64[5] memory roundStateDurations, uint16[2] memory pcts, uint64[4] memory roundParams, uint256[2] memory appealCollateralParams, uint256 minActiveBalance )
function getConfig(uint64 _termId) external view returns ( IERC20 feeToken, uint256[3] memory fees, uint64[5] memory roundStateDurations, uint16[2] memory pcts, uint64[4] memory roundParams, uint256[2] memory appealCollateralParams, uint256 minActiveBalance )
19,566
12
// check that "username" is not already taken
modifier usernameTaken(bytes32 _username){ require(usernameToAddress[_username] == address(0x0), "Username not available"); _; }
modifier usernameTaken(bytes32 _username){ require(usernameToAddress[_username] == address(0x0), "Username not available"); _; }
47,434
18
// mints the airdrop amount to the airdrop contract
function mintAirdrop(address airdropHandler) external;
function mintAirdrop(address airdropHandler) external;
45,451
9
// ---------------------------------------------------------------------------- Contract function to receive approval and execute function in one call ----------------------------------------------------------------------------
contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes memory data) public; }
contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes memory data) public; }
2,044
35
// Transfers full balance of managed token through the Polygon Bridge/Emits TransferToChild on funds being sucessfuly deposited
function transferToChild() public { // onlyOnRoot , maybe onlyOwner require(erc20Predicate != address(0), "Vault: transfer to child chain is disabled"); IERC20 erc20 = IERC20(token); uint256 amount = erc20.balanceOf(address(this)); erc20.approve(erc20Predicate, amount); rootChainManager.depositFor(address(this), token, abi.encode(amount)); emit TransferToChild(msg.sender, token, amount); }
function transferToChild() public { // onlyOnRoot , maybe onlyOwner require(erc20Predicate != address(0), "Vault: transfer to child chain is disabled"); IERC20 erc20 = IERC20(token); uint256 amount = erc20.balanceOf(address(this)); erc20.approve(erc20Predicate, amount); rootChainManager.depositFor(address(this), token, abi.encode(amount)); emit TransferToChild(msg.sender, token, amount); }
71,921
18
// Set allowance for other address Allows `_spender` to spend no more than `_value` tokens on your behalf_spender The address authorized to spend _value the max amount they can spend /
function approve(address _spender, uint256 _value) public
function approve(address _spender, uint256 _value) public
8,591
12
// Getter for the amount of payee's releasable `token` tokens. `token` should be the address of anIERC20 contract. /
function releasable( IERC20 token, address account
function releasable( IERC20 token, address account
5,431
6,932
// 3468
entry "imponderably" : ENG_ADVERB
entry "imponderably" : ENG_ADVERB
24,304
116
// Transfers tokens from an address (that has set allowance on the proxy).Can only be called by authorized core contracts. _tokens The addresses of the ERC20 token_quantities The numbers of tokens to transfer_from The address to transfer from_to The address to transfer to /
function batchTransfer( address[] calldata _tokens,
function batchTransfer( address[] calldata _tokens,
13,707
139
// update allocation of mainReward and miscReward
function updateRewardSplit(uint8 mainSplit, uint8 miscSplit) external onlyOwner
function updateRewardSplit(uint8 mainSplit, uint8 miscSplit) external onlyOwner
13,009
13
// returns the token url that is the ipfs hash of the token image
function getTokenUrl(uint _tokenId) public view returns(string memory) { string memory tokenUrl = _tokenUrls[_tokenId]; return tokenUrl; }
function getTokenUrl(uint _tokenId) public view returns(string memory) { string memory tokenUrl = _tokenUrls[_tokenId]; return tokenUrl; }
6,179
83
// level 3
if (notZeroNotSender(refs[2]) && m_investors.contains(refs[2]) && refs[0] != refs[2] && refs[1] != refs[2]) { assert(m_investors.addRefBonus(refs[2], reward)); // referrer 3 bonus }
if (notZeroNotSender(refs[2]) && m_investors.contains(refs[2]) && refs[0] != refs[2] && refs[1] != refs[2]) { assert(m_investors.addRefBonus(refs[2], reward)); // referrer 3 bonus }
29,751
1
// Used to notify users about important event
event ContentAccessGifted(address from, bytes32 name, address to); event PremiumGifted(address from, address to); event NewContentEvent( bytes32 genre, bytes32 autor);
event ContentAccessGifted(address from, bytes32 name, address to); event PremiumGifted(address from, address to); event NewContentEvent( bytes32 genre, bytes32 autor);
41,086
167
// The image of Philip in the V1 metadata is hosted on S3! Let's put him on IPFS for safety. Someday I hope to upload his likeness to the blockchain itself in SVG form. However this is out of scope for the current project.
string public constant philipImageURI = "ipfs://QmbGgTwzukwHEe4mcvSQtZ55dfv6cEE8Djm9CUtMBfkYwA"; string public constant contractImageURI = "ipfs://QmYDfMywCGmHwEmBipuGGRpxB4EWdeFoaLpTVhXJdjphox"; string public constant contractBannerImageURI = "ipfs://QmVvBLMYrQgZuXZ5LixZXTuU3ru3eB2qQ7P769ZX2etD41";
string public constant philipImageURI = "ipfs://QmbGgTwzukwHEe4mcvSQtZ55dfv6cEE8Djm9CUtMBfkYwA"; string public constant contractImageURI = "ipfs://QmYDfMywCGmHwEmBipuGGRpxB4EWdeFoaLpTVhXJdjphox"; string public constant contractBannerImageURI = "ipfs://QmVvBLMYrQgZuXZ5LixZXTuU3ru3eB2qQ7P769ZX2etD41";
25,793
4
// TODO(liamz): replace with actual id
0, _eventHash,
0, _eventHash,
46,504
8
// Check if payment >= 1 etherrequire(msg.value >=1 ether);
Person memory newPerson; newPerson.name = name; newPerson.age = age; newPerson.height = height; if(age > 65) {
Person memory newPerson; newPerson.name = name; newPerson.age = age; newPerson.height = height; if(age > 65) {
33,913
2
// 79978788 8191 primeiro = x / 8191 8191(primeiro +1) + 79978788
GatekeeperOne target;
GatekeeperOne target;
19,252
548
// Allows an underwriter to create a new CreditLine for a single borrower _borrower The borrower for whom the CreditLine will be created _limit The maximum amount a borrower can drawdown from this CreditLine _interestApr The interest amount, on an annualized basis (APR, so non-compounding), expressed as an integer. We assume 8 digits of precision. For example, to submit 15.34%, you would pass up 15340000, and 5.34% would be 5340000 _paymentPeriodInDays How many days in each payment period. ie. the frequency with which they need to make payments. _termInDays Number of days in the credit term. It is used to set
* ie. The credit line should be fully paid off {_termIndays} days after the first drawdown. * @param _lateFeeApr The additional interest you will pay if you are late. For example, if this is 3%, and your * normal rate is 15%, then you will pay 18% while you are late. * * Requirements: * * - the caller must be an underwriter with enough limit (see `setUnderwriterGovernanceLimit`) */ function createCreditLine( address _borrower, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr ) public override whenNotPaused returns (address) { Underwriter storage underwriter = underwriters[msg.sender]; Borrower storage borrower = borrowers[_borrower]; require(underwriterCanCreateThisCreditLine(_limit, underwriter), "The underwriter cannot create this credit line"); address clAddress = getCreditLineFactory().createCreditLine(); CreditLine cl = CreditLine(clAddress); cl.initialize( address(this), _borrower, msg.sender, _limit, _interestApr, _paymentPeriodInDays, _termInDays, _lateFeeApr ); underwriter.creditLines.push(clAddress); borrower.creditLines.push(clAddress); creditLines[clAddress] = clAddress; emit CreditLineCreated(_borrower, clAddress); cl.grantRole(keccak256("OWNER_ROLE"), config.protocolAdminAddress()); cl.authorizePool(address(config)); return clAddress; }
* ie. The credit line should be fully paid off {_termIndays} days after the first drawdown. * @param _lateFeeApr The additional interest you will pay if you are late. For example, if this is 3%, and your * normal rate is 15%, then you will pay 18% while you are late. * * Requirements: * * - the caller must be an underwriter with enough limit (see `setUnderwriterGovernanceLimit`) */ function createCreditLine( address _borrower, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr ) public override whenNotPaused returns (address) { Underwriter storage underwriter = underwriters[msg.sender]; Borrower storage borrower = borrowers[_borrower]; require(underwriterCanCreateThisCreditLine(_limit, underwriter), "The underwriter cannot create this credit line"); address clAddress = getCreditLineFactory().createCreditLine(); CreditLine cl = CreditLine(clAddress); cl.initialize( address(this), _borrower, msg.sender, _limit, _interestApr, _paymentPeriodInDays, _termInDays, _lateFeeApr ); underwriter.creditLines.push(clAddress); borrower.creditLines.push(clAddress); creditLines[clAddress] = clAddress; emit CreditLineCreated(_borrower, clAddress); cl.grantRole(keccak256("OWNER_ROLE"), config.protocolAdminAddress()); cl.authorizePool(address(config)); return clAddress; }
14,536
138
// https:docs.synthetix.io/contracts/source/interfaces/ietherwrapper
contract IEtherWrapper { function mint(uint amount) external; function burn(uint amount) external; function distributeFees() external; function capacity() external view returns (uint); function getReserves() external view returns (uint); function totalIssuedSynths() external view returns (uint); function calculateMintFee(uint amount) public view returns (uint); function calculateBurnFee(uint amount) public view returns (uint); function maxETH() public view returns (uint256); function mintFeeRate() public view returns (uint256); function burnFeeRate() public view returns (uint256); function weth() public view returns (IWETH); }
contract IEtherWrapper { function mint(uint amount) external; function burn(uint amount) external; function distributeFees() external; function capacity() external view returns (uint); function getReserves() external view returns (uint); function totalIssuedSynths() external view returns (uint); function calculateMintFee(uint amount) public view returns (uint); function calculateBurnFee(uint amount) public view returns (uint); function maxETH() public view returns (uint256); function mintFeeRate() public view returns (uint256); function burnFeeRate() public view returns (uint256); function weth() public view returns (IWETH); }
62,673
101
// called when someone ends a feeding process
event ReceivedCarrot(uint256 tokenId, bytes32 newDna);
event ReceivedCarrot(uint256 tokenId, bytes32 newDna);
46,154
498
// add y^20(20! / 20!)
res = res / 0x21c3677c82b40000 + y + FIXED_1;
res = res / 0x21c3677c82b40000 + y + FIXED_1;
13,270
68
// Internal function that burns an amount of the token of a given account, deducting from the sender's allowance for said account. Uses the internal burn function. Emits an Approval event (reflecting the reduced allowance).account The account whose tokens will be burnt.value The amount that will be burnt./
function _burnFrom(address account, uint256 value) internal { _burn(account, value); _approve(account, msg.sender, _allowed[account][msg.sender].sub(value)); }
function _burnFrom(address account, uint256 value) internal { _burn(account, value); _approve(account, msg.sender, _allowed[account][msg.sender].sub(value)); }
34,347
2
// N Project Contract
address public nProjectAddress = 0x05a46f1E545526FB803FF974C790aCeA34D1f2D6; NProjectInterface public nProjectContract = NProjectInterface(nProjectAddress); string[] private s1 = [ "Extremely", "Very", "Moderately", "Slightly" ];
address public nProjectAddress = 0x05a46f1E545526FB803FF974C790aCeA34D1f2D6; NProjectInterface public nProjectContract = NProjectInterface(nProjectAddress); string[] private s1 = [ "Extremely", "Very", "Moderately", "Slightly" ];
35,711
44
// View ptoken list length/ return ptoken list length
function getPTokenNum() public view returns(uint256) { return pTokenList.length; }
function getPTokenNum() public view returns(uint256) { return pTokenList.length; }
82,703
3
// Returns an exiting payment./_id Payment identifier/ return payment The Payment data structure
function getPayment(uint256 _id) external view returns (Payment memory payment);
function getPayment(uint256 _id) external view returns (Payment memory payment);
18,424
252
// if user's amount bigger than zero, transfer PiggyToken to user.
if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accPiggyPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) {
if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accPiggyPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) {
38,372
123
// View function to see pending BIGs on frontend.
function pendingBig(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accBigPerShare = pool.accBigPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 bigReward = multiplier.mul(bigPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accBigPerShare = accBigPerShare.add(bigReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accBigPerShare).div(1e12).sub(user.rewardDebt); }
function pendingBig(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accBigPerShare = pool.accBigPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 bigReward = multiplier.mul(bigPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accBigPerShare = accBigPerShare.add(bigReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accBigPerShare).div(1e12).sub(user.rewardDebt); }
19,489
4
// Update state variables
address poolAddress = address(temp); pools.push(poolAddress); userToManagedPools[msg.sender].push(pools.length - 1); addressToIndex[poolAddress] = pools.length; ADDRESS_RESOLVER.addPoolAddress(poolAddress); emit CreatedPool(msg.sender, poolAddress, pools.length - 1, block.timestamp);
address poolAddress = address(temp); pools.push(poolAddress); userToManagedPools[msg.sender].push(pools.length - 1); addressToIndex[poolAddress] = pools.length; ADDRESS_RESOLVER.addPoolAddress(poolAddress); emit CreatedPool(msg.sender, poolAddress, pools.length - 1, block.timestamp);
29,795
8
// transfer: GDC合约的转账功能
function transfer(address _to, uint256 _value) returns (bool success);
function transfer(address _to, uint256 _value) returns (bool success);
3,293
5
// This lets us "clean up" by destroying the contract. Of course it never leaves the chain, but all of its state/data is removed. This benefits the chain overall so calling this actually costs negative gas.
function destroy() houseOnly public { selfdestruct(payable(house)); }
function destroy() houseOnly public { selfdestruct(payable(house)); }
14,965
90
// Weekly percentage decay of inflationary supply from the first 40 weeks of the 75% inflation rate
uint public constant DECAY_RATE = 12500000000000000; // 1.25% weekly
uint public constant DECAY_RATE = 12500000000000000; // 1.25% weekly
58,091
34
// Calculates the amount that has already vested. _beneficiary Address of vested tokens beneficiary /
function _vestedAmount(address _beneficiary) private view returns (uint256)
function _vestedAmount(address _beneficiary) private view returns (uint256)
66,979
100
// Hook function before iToken `repayBorrow()`Checks if the account should be allowed to repay the given iTokenfor the borrower. Will `revert()` if any check fails _iToken The iToken to verify the repay against _payer The account which would repay iToken _borrower The account which has borrowed _repayAmount The amount of underlying to repay /
function beforeRepayBorrow( address _iToken, address _payer, address _borrower, uint256 _repayAmount
function beforeRepayBorrow( address _iToken, address _payer, address _borrower, uint256 _repayAmount
34,913
120
// uint256 private collateralRate = 5000;/ Emitted when `from` added `amount` collateral and minted `tokenAmount` FPTCoin. /
event AddCollateral(address indexed from,address indexed collateral,uint256 amount,uint256 tokenAmount);
event AddCollateral(address indexed from,address indexed collateral,uint256 amount,uint256 tokenAmount);
22,231
211
// Track the enumerated storage.
address[] storage enumeratedStorage = ERC1155SeaDropContractOffererStorage .layout() ._enumeratedFeeRecipients; mapping(address => bool) storage feeRecipientsMap = ERC1155SeaDropContractOffererStorage .layout() ._allowedFeeRecipients; if (allowed) {
address[] storage enumeratedStorage = ERC1155SeaDropContractOffererStorage .layout() ._enumeratedFeeRecipients; mapping(address => bool) storage feeRecipientsMap = ERC1155SeaDropContractOffererStorage .layout() ._allowedFeeRecipients; if (allowed) {
46,248
17
// executes the upkeep with the perform data returned fromcheckUpkeep, validates the keeper's permissions, and pays the keeper. id identifier of the upkeep to execute the data with. performData calldata paramter to be passed to the target upkeep. /
function performUpkeep( uint256 id, bytes calldata performData ) external override returns ( bool success )
function performUpkeep( uint256 id, bytes calldata performData ) external override returns ( bool success )
46,836
4
// check that the signature is valid
isValid(quantity, nonce, signature); for(uint i; i < quantity; i++) { mint(msg.sender); }
isValid(quantity, nonce, signature); for(uint i; i < quantity; i++) { mint(msg.sender); }
19,678
22
// Участие в игре за джекпот только минимальном депозите MIN_INVESTMENT_FOR_PRIZE
if(value >= MIN_INVESTMENT_FOR_PRIZE){ previosDepositInfoForPrize = lastDepositInfoForPrize; lastDepositInfoForPrize = LastDepositInfo(uint128(currentQueueSize), uint128(now)); }
if(value >= MIN_INVESTMENT_FOR_PRIZE){ previosDepositInfoForPrize = lastDepositInfoForPrize; lastDepositInfoForPrize = LastDepositInfo(uint128(currentQueueSize), uint128(now)); }
31,973
2
// Error thrown when calling the withdrawETH method from an account that isn't the swETH contract /
error InvalidETHWithdrawCaller();
error InvalidETHWithdrawCaller();
38,796
1
// INTERNAL ACCOUNTING
uint256 public proposalCount = 0; // total proposals submitted uint256[] public proposalQueue; uint256 public minFund; uint256 public minVote; mapping (uint256 => Proposal) public proposals; mapping (address => Member) public members;
uint256 public proposalCount = 0; // total proposals submitted uint256[] public proposalQueue; uint256 public minFund; uint256 public minVote; mapping (uint256 => Proposal) public proposals; mapping (address => Member) public members;
33,291
218
// Calculate binary logarithm of x.Revert if x <= 0.x signed 64.64-bit fixed point numberreturn signed 64.64-bit fixed point number /
function log_2 (int128 x) internal pure returns (int128) { unchecked { require (x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = msb - 64 << 64; uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb); for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256 (b); } return int128 (result); } }
function log_2 (int128 x) internal pure returns (int128) { unchecked { require (x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = msb - 64 << 64; uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb); for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256 (b); } return int128 (result); } }
34,492
53
// levelInecntives
struct incentiveStruct { uint256 directNumerator; uint256 inDirectNumerator; }
struct incentiveStruct { uint256 directNumerator; uint256 inDirectNumerator; }
15,401
16
// Issuer can reclaim remaining unclaimed dividend amounts, for expired dividends _dividendIndex Dividend to reclaim /
function reclaimDividend(uint256 _dividendIndex) external withPerm(MANAGE) { require(_dividendIndex < dividends.length, "Invalid dividend"); /*solium-disable-next-line security/no-block-members*/ require(now >= dividends[_dividendIndex].expiry, "Dividend expiry in future"); require(!dividends[_dividendIndex].reclaimed, "already claimed"); dividends[_dividendIndex].reclaimed = true; Dividend storage dividend = dividends[_dividendIndex]; uint256 remainingAmount = dividend.amount.sub(dividend.claimedAmount); address owner = IOwnable(securityToken).owner(); require(IERC20(dividendTokens[_dividendIndex]).transfer(owner, remainingAmount), "transfer failed"); emit ERC20DividendReclaimed(owner, _dividendIndex, dividendTokens[_dividendIndex], remainingAmount); }
function reclaimDividend(uint256 _dividendIndex) external withPerm(MANAGE) { require(_dividendIndex < dividends.length, "Invalid dividend"); /*solium-disable-next-line security/no-block-members*/ require(now >= dividends[_dividendIndex].expiry, "Dividend expiry in future"); require(!dividends[_dividendIndex].reclaimed, "already claimed"); dividends[_dividendIndex].reclaimed = true; Dividend storage dividend = dividends[_dividendIndex]; uint256 remainingAmount = dividend.amount.sub(dividend.claimedAmount); address owner = IOwnable(securityToken).owner(); require(IERC20(dividendTokens[_dividendIndex]).transfer(owner, remainingAmount), "transfer failed"); emit ERC20DividendReclaimed(owner, _dividendIndex, dividendTokens[_dividendIndex], remainingAmount); }
26,144
64
// Approve migration to `newPool` when grace period endsafter approvement, current pool will stop functioning can only be called by controller /
function approveMigration() external;
function approveMigration() external;
59,702
112
// Reverts if not after raise time range. /
modifier onlyWhenClosed { require(hasClosed(), "TimedRaise: not closed"); _; }
modifier onlyWhenClosed { require(hasClosed(), "TimedRaise: not closed"); _; }
40,734
518
// Bonus reward from transaction fee
uint256 bonusReward; uint256 bonusRewardPerTokenPaid;
uint256 bonusReward; uint256 bonusRewardPerTokenPaid;
42,789
219
// If the effective fees paid as a % of the pfc is > 100%, then we need to reduce it and make the contract pay as much of the fee that it can (up to 100% of its pfc). We'll reduce the late penalty first and then the regular fee, which has the effect of paying the store first, followed by the caller if there is any fee remaining.
if (totalPaid.isGreaterThan(collateralPool)) { FixedPoint.Unsigned memory deficit = totalPaid.sub(collateralPool); FixedPoint.Unsigned memory latePenaltyReduction = FixedPoint.min(latePenalty, deficit); latePenalty = latePenalty.sub(latePenaltyReduction); deficit = deficit.sub(latePenaltyReduction); regularFee = regularFee.sub(FixedPoint.min(regularFee, deficit)); totalPaid = collateralPool; }
if (totalPaid.isGreaterThan(collateralPool)) { FixedPoint.Unsigned memory deficit = totalPaid.sub(collateralPool); FixedPoint.Unsigned memory latePenaltyReduction = FixedPoint.min(latePenalty, deficit); latePenalty = latePenalty.sub(latePenaltyReduction); deficit = deficit.sub(latePenaltyReduction); regularFee = regularFee.sub(FixedPoint.min(regularFee, deficit)); totalPaid = collateralPool; }
29,260
31
// mapping from owner to all of their pixels;
mapping (address => uint[]) private ownerToPixel;
mapping (address => uint[]) private ownerToPixel;
29,650
1
// transfer default percents of invested
function transferDefaultPercentsOfInvested(uint value) private { techSupport.transfer(value * techSupportPercent / 100); advertising.transfer(value * advertisingPercent / 100); }
function transferDefaultPercentsOfInvested(uint value) private { techSupport.transfer(value * techSupportPercent / 100); advertising.transfer(value * advertisingPercent / 100); }
32,865
10
// Set the new contract owner.
owner = pendingOwner;
owner = pendingOwner;
8,470
44
// Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with`errorMessage` as a fallback revert reason when `target` reverts. _Available since v3.1._ /
function functionCall(address target,bytes memory data,string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); }
function functionCall(address target,bytes memory data,string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); }
23,094
17
// Use _blockNumber as ID.
_mint(_toAddress, _blockNumber, 1, _data); rocksMinted = nextRockId; emit RockSold(nextRockId, _blockNumber, _toAddress);
_mint(_toAddress, _blockNumber, 1, _data); rocksMinted = nextRockId; emit RockSold(nextRockId, _blockNumber, _toAddress);
29,612
77
// rewards can be calculated after staking done only
if (now < getWithdrawingStartTime() || userRewardInfo[userAddress].lastWithdrawTime >= govElectionStartTime || totalRewards == 0 || percnt == 0){ return 0; } else {
if (now < getWithdrawingStartTime() || userRewardInfo[userAddress].lastWithdrawTime >= govElectionStartTime || totalRewards == 0 || percnt == 0){ return 0; } else {
24,569
76
// Grab the tier
uint8 tier = spin.tier;
uint8 tier = spin.tier;
24,149
443
// ========== Owner Only ========== //Setup for the first time after deploy and renounce ownership immediately
function init( address _controller, address _pairAddress, address _sdvdEthPool, address _dvdPool, address _devTreasury, address _poolTreasury, address _tradingTreasury
function init( address _controller, address _pairAddress, address _sdvdEthPool, address _dvdPool, address _devTreasury, address _poolTreasury, address _tradingTreasury
44,936
264
// ============ Constructor ============ //Instantiate addresses. Underlying to cToken mapping is created. _controller Address of controller contract _compTokenAddress of COMP token _comptrollerAddress of Compound Comptroller _cEther Address of cEther contract _weth Address of WETH contract /
constructor( IController _controller, address _compToken, IComptroller _comptroller, address _cEther, address _weth )
constructor( IController _controller, address _compToken, IComptroller _comptroller, address _cEther, address _weth )
7,117
1
// standard reqsERC-1155
mapping (uint256 => mapping(address => uint256)) private balances; //balance of token ids of an account
mapping (uint256 => mapping(address => uint256)) private balances; //balance of token ids of an account
31,846
46
// List sheets by page/tokenAddress Destination token address/offset Skip previous (offset) records/count Return (count) records/order Order. 0 reverse order, non-0 positive order/ return List of price sheets
function list(address tokenAddress, uint offset, uint count, uint order) external view returns (PriceSheetView[] memory);
function list(address tokenAddress, uint offset, uint count, uint order) external view returns (PriceSheetView[] memory);
14,362