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
44
// Returns the address of the token that the payments are made in/ return tokenAddress Token address
function getTokenAddress() external view returns (address tokenAddress)
function getTokenAddress() external view returns (address tokenAddress)
16,050
52
// Whether `a` is less than `b`. a a FixedPoint.Signed. b an int256.return True if `a < b`, or False. /
function isLessThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledInt(b).rawValue; }
function isLessThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledInt(b).rawValue; }
34,145
3
// Sets the current TGE from where the vesting period will be counted. Can be used only if TGE is zero. /
function setTGE(uint _date) public onlyOwner { require(TGE == 0, "TGE has already been set"); TGE = _date; }
function setTGE(uint _date) public onlyOwner { require(TGE == 0, "TGE has already been set"); TGE = _date; }
66,625
33
// user is whitelisted
mapping(address => bool) public whitelisted; mapping(address => InvestorInfo) public investorInfoMap; constructor( address _investToken, uint256 _startTime, uint256 _duration, uint256 _epochTime, uint256 _initialCap,
mapping(address => bool) public whitelisted; mapping(address => InvestorInfo) public investorInfoMap; constructor( address _investToken, uint256 _startTime, uint256 _duration, uint256 _epochTime, uint256 _initialCap,
36,488
108
// Emitted when a root's confirmation is modified by governance root The root for which confirmAt has been set previousConfirmAt The previous value of confirmAt newConfirmAt The new value of confirmAt /
event SetConfirmation(
event SetConfirmation(
83,440
109
// get first in line
cheatLine[nextInLine] = sender;
cheatLine[nextInLine] = sender;
16,486
110
// (uint256 sigmoidParamA,,) = getSigmoidParameters();if (sigmoidParamA == 0 && totalSupplyFactor() == 0) revert("emission stopped"); new deposit, calculate interests
(uint256 userShare, uint256 timePassed) = _calcRewards(_sender, _id, 0); uint256 newBalance = balances[_sender][_id].add(_amount); balances[_sender][_id] = newBalance; totalStaked = totalStaked.add(_amount); depositDates[_sender][_id] = _now(); emit Deposited(_sender, _id, _amount, newBalance, userShare, timePassed);
(uint256 userShare, uint256 timePassed) = _calcRewards(_sender, _id, 0); uint256 newBalance = balances[_sender][_id].add(_amount); balances[_sender][_id] = newBalance; totalStaked = totalStaked.add(_amount); depositDates[_sender][_id] = _now(); emit Deposited(_sender, _id, _amount, newBalance, userShare, timePassed);
80,043
49
// Pays out dividends to tokens holders of record, based on 500,000 token payment
function payOutDividend() onlyOwner returns (bool success) { createRecord(); uint256 volume = totalSupply; for (uint i = 0; i < (tokenHolders.length.sub(1)); i++) { address payee = getTokenHolder(i); uint256 stake = volume.div(dividendPayment.div(multiplier)); uint256 dividendPayout = balanceOf(payee).div(stake).mul(multiplier); balance[payee] = balance[payee].add(dividendPayout); totalSupply = totalSupply.add(dividendPayout); Transfer(0, payee, dividendPayout); } return true; }
function payOutDividend() onlyOwner returns (bool success) { createRecord(); uint256 volume = totalSupply; for (uint i = 0; i < (tokenHolders.length.sub(1)); i++) { address payee = getTokenHolder(i); uint256 stake = volume.div(dividendPayment.div(multiplier)); uint256 dividendPayout = balanceOf(payee).div(stake).mul(multiplier); balance[payee] = balance[payee].add(dividendPayout); totalSupply = totalSupply.add(dividendPayout); Transfer(0, payee, dividendPayout); } return true; }
9,119
23
// Withdraw/redeem common workflow. /
function _withdraw( address caller, address receiver, address owner, uint256 assets, uint256 shares
function _withdraw( address caller, address receiver, address owner, uint256 assets, uint256 shares
36,705
7
// ETH-PRICE / TOKEN-USD-PRICE
_wserate = _rate.mul(10**_multiplier); emit RateChanged(_wserate);
_wserate = _rate.mul(10**_multiplier); emit RateChanged(_wserate);
21,329
183
// if any account belongs to _isExcludedFromFee account then remove the fee don't take a fee unless it's a buy / sell
if ( (_isExcludedFromFees[from] || _isExcludedFromFees[to]) || (!automatedMarketMakerPairs[from] && !automatedMarketMakerPairs[to]) ) { takeFee = false; }
if ( (_isExcludedFromFees[from] || _isExcludedFromFees[to]) || (!automatedMarketMakerPairs[from] && !automatedMarketMakerPairs[to]) ) { takeFee = false; }
26,277
300
// calculates the balance of the user, which is the principal balance + interest generated by the principal balance + interest generated by the redirected balance_user the user for which the balance is being calculated return the total balance of the user/
function balanceOf(address _user) public view returns(uint256) { //current principal balance of the user uint256 currentPrincipalBalance = super.balanceOf(_user); //balance redirected by other users to _user for interest rate accrual uint256 redirectedBalance = redirectedBalances[_user]; if(currentPrincipalBalance == 0 && redirectedBalance == 0){ return 0; } //if the _user is not redirecting the interest to anybody, accrues //the interest for himself if(interestRedirectionAddresses[_user] == address(0)){ //accruing for himself means that both the principal balance and //the redirected balance partecipate in the interest return calculateCumulatedBalanceInternal( _user, currentPrincipalBalance.add(redirectedBalance) ) .sub(redirectedBalance); } else { //if the user redirected the interest, then only the redirected //balance generates interest. In that case, the interest generated //by the redirected balance is added to the current principal balance. return currentPrincipalBalance.add( calculateCumulatedBalanceInternal( _user, redirectedBalance ) .sub(redirectedBalance) ); } }
function balanceOf(address _user) public view returns(uint256) { //current principal balance of the user uint256 currentPrincipalBalance = super.balanceOf(_user); //balance redirected by other users to _user for interest rate accrual uint256 redirectedBalance = redirectedBalances[_user]; if(currentPrincipalBalance == 0 && redirectedBalance == 0){ return 0; } //if the _user is not redirecting the interest to anybody, accrues //the interest for himself if(interestRedirectionAddresses[_user] == address(0)){ //accruing for himself means that both the principal balance and //the redirected balance partecipate in the interest return calculateCumulatedBalanceInternal( _user, currentPrincipalBalance.add(redirectedBalance) ) .sub(redirectedBalance); } else { //if the user redirected the interest, then only the redirected //balance generates interest. In that case, the interest generated //by the redirected balance is added to the current principal balance. return currentPrincipalBalance.add( calculateCumulatedBalanceInternal( _user, redirectedBalance ) .sub(redirectedBalance) ); } }
81,037
55
// newBalTo = poolRatio^(1/weightTo)balTo;
uint tokenOutRatio = bpow(poolRatio, bdiv(BONE, normalizedWeight)); uint newTokenBalanceOut = bmul(tokenOutRatio, tokenBalanceOut); uint tokenAmountOutBeforeSwapFee = bsub(tokenBalanceOut, newTokenBalanceOut);
uint tokenOutRatio = bpow(poolRatio, bdiv(BONE, normalizedWeight)); uint newTokenBalanceOut = bmul(tokenOutRatio, tokenBalanceOut); uint tokenAmountOutBeforeSwapFee = bsub(tokenBalanceOut, newTokenBalanceOut);
7,529
20
// Else, if the last update was before the end of the duration.
} else if (self.lastUpdate < self.start + self.duration) {
} else if (self.lastUpdate < self.start + self.duration) {
25,724
19
// Adjust token (must be in correct state)Can only be called only from configured operator accountSwap needs to be done with max price difference from current pool price - otherwise reverts /
function execute(ExecuteParams memory params) external { if (!operators[msg.sender]) { revert Unauthorized(); } ExecuteState memory state; PositionConfig memory config = positionConfigs[params.tokenId]; if (config.lowerTickDelta == config.upperTickDelta) { revert NotConfigured(); } // get position info (,, state.token0, state.token1, state.fee, state.tickLower, state.tickUpper, state.liquidity, , , , ) = nonfungiblePositionManager.positions(params.tokenId); if (state.liquidity != params.liquidity) { revert LiquidityChanged(); } (state.amount0, state.amount1) = _decreaseFullLiquidityAndCollect(params.tokenId, state.liquidity, params.amountRemoveMin0, params.amountRemoveMin1, params.deadline); if (params.swap0To1 && params.amountIn > state.amount0 || !params.swap0To1 && params.amountIn > state.amount1) { revert SwapAmountTooLarge(); } // get pool info state.pool = _getPool(state.token0, state.token1, state.fee); // check oracle for swap (state.amountOutMin,state.currentTick,,) = _validateSwap(params.swap0To1, params.amountIn, state.pool, TWAPSeconds, maxTWAPTickDifference, params.swap0To1 ? config.token0SlippageX64 : config.token1SlippageX64); if (state.currentTick < state.tickLower - config.lowerTickLimit || state.currentTick >= state.tickUpper + config.upperTickLimit) { int24 tickSpacing = _getTickSpacing(state.fee); int24 baseTick = state.currentTick - (((state.currentTick % tickSpacing) + tickSpacing) % tickSpacing); // check if new range same as old range if (baseTick + config.lowerTickDelta == state.tickLower && baseTick + config.upperTickDelta == state.tickUpper) { revert SameRange(); } (state.amountInDelta, state.amountOutDelta) = _swap(params.swap0To1 ? IERC20(state.token0) : IERC20(state.token1), params.swap0To1 ? IERC20(state.token1) : IERC20(state.token0), params.amountIn, state.amountOutMin, params.swapData); state.amount0 = params.swap0To1 ? state.amount0 - state.amountInDelta : state.amount0 + state.amountOutDelta; state.amount1 = params.swap0To1 ? state.amount1 + state.amountOutDelta : state.amount1 - state.amountInDelta; // max amount to add - removing max potential fees state.maxAddAmount0 = state.amount0 * Q64 / (protocolRewardX64 + Q64); state.maxAddAmount1 = state.amount1 * Q64 / (protocolRewardX64 + Q64); INonfungiblePositionManager.MintParams memory mintParams = INonfungiblePositionManager.MintParams( address(state.token0), address(state.token1), state.fee, SafeCast.toInt24(baseTick + config.lowerTickDelta), // reverts if out of valid range SafeCast.toInt24(baseTick + config.upperTickDelta), // reverts if out of valid range state.maxAddAmount0, state.maxAddAmount1, 0, 0, address(this), // is sent to real recipient aftwards params.deadline ); // approve npm SafeERC20.safeApprove(IERC20(state.token0), address(nonfungiblePositionManager), state.maxAddAmount0); SafeERC20.safeApprove(IERC20(state.token1), address(nonfungiblePositionManager), state.maxAddAmount1); // mint is done to address(this) first - its not a safemint (state.newTokenId,,state.amountAdded0,state.amountAdded1) = nonfungiblePositionManager.mint(mintParams); // remove remaining approval SafeERC20.safeApprove(IERC20(state.token0), address(nonfungiblePositionManager), 0); SafeERC20.safeApprove(IERC20(state.token1), address(nonfungiblePositionManager), 0); state.owner = nonfungiblePositionManager.ownerOf(params.tokenId); // send it to current owner nonfungiblePositionManager.safeTransferFrom(address(this), state.owner, state.newTokenId); // protocol reward is calculated based on added amount (to incentivize optimal swap done by operator) state.protocolReward0 = state.amountAdded0 * protocolRewardX64 / Q64; state.protocolReward1 = state.amountAdded1 * protocolRewardX64 / Q64; // send leftover to owner if (state.amount0 - state.protocolReward0 - state.amountAdded0 > 0) { _transferToken(state.owner, IERC20(state.token0), state.amount0 - state.protocolReward0 - state.amountAdded0, true); } if (state.amount1 - state.protocolReward1 - state.amountAdded1 > 0) { _transferToken(state.owner, IERC20(state.token1), state.amount1 - state.protocolReward1 - state.amountAdded1, true); } // copy token config for new token positionConfigs[state.newTokenId] = config; emit PositionConfigured( state.newTokenId, config.lowerTickLimit, config.upperTickLimit, config.lowerTickDelta, config.upperTickDelta, config.token0SlippageX64, config.token1SlippageX64 ); // delete config for old position delete positionConfigs[params.tokenId]; emit PositionConfigured(params.tokenId, 0, 0, 0, 0, 0, 0); emit RangeChanged(params.tokenId, state.newTokenId); } else { revert NotReady(); } }
function execute(ExecuteParams memory params) external { if (!operators[msg.sender]) { revert Unauthorized(); } ExecuteState memory state; PositionConfig memory config = positionConfigs[params.tokenId]; if (config.lowerTickDelta == config.upperTickDelta) { revert NotConfigured(); } // get position info (,, state.token0, state.token1, state.fee, state.tickLower, state.tickUpper, state.liquidity, , , , ) = nonfungiblePositionManager.positions(params.tokenId); if (state.liquidity != params.liquidity) { revert LiquidityChanged(); } (state.amount0, state.amount1) = _decreaseFullLiquidityAndCollect(params.tokenId, state.liquidity, params.amountRemoveMin0, params.amountRemoveMin1, params.deadline); if (params.swap0To1 && params.amountIn > state.amount0 || !params.swap0To1 && params.amountIn > state.amount1) { revert SwapAmountTooLarge(); } // get pool info state.pool = _getPool(state.token0, state.token1, state.fee); // check oracle for swap (state.amountOutMin,state.currentTick,,) = _validateSwap(params.swap0To1, params.amountIn, state.pool, TWAPSeconds, maxTWAPTickDifference, params.swap0To1 ? config.token0SlippageX64 : config.token1SlippageX64); if (state.currentTick < state.tickLower - config.lowerTickLimit || state.currentTick >= state.tickUpper + config.upperTickLimit) { int24 tickSpacing = _getTickSpacing(state.fee); int24 baseTick = state.currentTick - (((state.currentTick % tickSpacing) + tickSpacing) % tickSpacing); // check if new range same as old range if (baseTick + config.lowerTickDelta == state.tickLower && baseTick + config.upperTickDelta == state.tickUpper) { revert SameRange(); } (state.amountInDelta, state.amountOutDelta) = _swap(params.swap0To1 ? IERC20(state.token0) : IERC20(state.token1), params.swap0To1 ? IERC20(state.token1) : IERC20(state.token0), params.amountIn, state.amountOutMin, params.swapData); state.amount0 = params.swap0To1 ? state.amount0 - state.amountInDelta : state.amount0 + state.amountOutDelta; state.amount1 = params.swap0To1 ? state.amount1 + state.amountOutDelta : state.amount1 - state.amountInDelta; // max amount to add - removing max potential fees state.maxAddAmount0 = state.amount0 * Q64 / (protocolRewardX64 + Q64); state.maxAddAmount1 = state.amount1 * Q64 / (protocolRewardX64 + Q64); INonfungiblePositionManager.MintParams memory mintParams = INonfungiblePositionManager.MintParams( address(state.token0), address(state.token1), state.fee, SafeCast.toInt24(baseTick + config.lowerTickDelta), // reverts if out of valid range SafeCast.toInt24(baseTick + config.upperTickDelta), // reverts if out of valid range state.maxAddAmount0, state.maxAddAmount1, 0, 0, address(this), // is sent to real recipient aftwards params.deadline ); // approve npm SafeERC20.safeApprove(IERC20(state.token0), address(nonfungiblePositionManager), state.maxAddAmount0); SafeERC20.safeApprove(IERC20(state.token1), address(nonfungiblePositionManager), state.maxAddAmount1); // mint is done to address(this) first - its not a safemint (state.newTokenId,,state.amountAdded0,state.amountAdded1) = nonfungiblePositionManager.mint(mintParams); // remove remaining approval SafeERC20.safeApprove(IERC20(state.token0), address(nonfungiblePositionManager), 0); SafeERC20.safeApprove(IERC20(state.token1), address(nonfungiblePositionManager), 0); state.owner = nonfungiblePositionManager.ownerOf(params.tokenId); // send it to current owner nonfungiblePositionManager.safeTransferFrom(address(this), state.owner, state.newTokenId); // protocol reward is calculated based on added amount (to incentivize optimal swap done by operator) state.protocolReward0 = state.amountAdded0 * protocolRewardX64 / Q64; state.protocolReward1 = state.amountAdded1 * protocolRewardX64 / Q64; // send leftover to owner if (state.amount0 - state.protocolReward0 - state.amountAdded0 > 0) { _transferToken(state.owner, IERC20(state.token0), state.amount0 - state.protocolReward0 - state.amountAdded0, true); } if (state.amount1 - state.protocolReward1 - state.amountAdded1 > 0) { _transferToken(state.owner, IERC20(state.token1), state.amount1 - state.protocolReward1 - state.amountAdded1, true); } // copy token config for new token positionConfigs[state.newTokenId] = config; emit PositionConfigured( state.newTokenId, config.lowerTickLimit, config.upperTickLimit, config.lowerTickDelta, config.upperTickDelta, config.token0SlippageX64, config.token1SlippageX64 ); // delete config for old position delete positionConfigs[params.tokenId]; emit PositionConfigured(params.tokenId, 0, 0, 0, 0, 0, 0); emit RangeChanged(params.tokenId, state.newTokenId); } else { revert NotReady(); } }
21,748
34
// must show immediate balance (not written / remaining) required by uniswap to mint
return _balances[account];
return _balances[account];
52,004
0
// Public variables of the token // This creates an array with all balances // This generates a public event on the blockchain that will notify clients /
function Token() { totalSupply = 5*(10**8)*(10**18); balanceOf[msg.sender] = 5*(10**8)*(10**18); // Give the creator all initial tokens name = "klcoin"; // Set the name for display purposes symbol = "KLC"; // Set the symbol for display purposes decimals = 18; // Amount of decimals for display purposes }
function Token() { totalSupply = 5*(10**8)*(10**18); balanceOf[msg.sender] = 5*(10**8)*(10**18); // Give the creator all initial tokens name = "klcoin"; // Set the name for display purposes symbol = "KLC"; // Set the symbol for display purposes decimals = 18; // Amount of decimals for display purposes }
27,785
183
// Do the book-keeping
bookDonation(addr, timestamp, chfCents, currency, memo);
bookDonation(addr, timestamp, chfCents, currency, memo);
37,434
173
// Check if accountCollateralTokens have been initialized. /
mapping (address => bool) public isCollateralTokenInit;
mapping (address => bool) public isCollateralTokenInit;
43,341
2
// Kepping the conditon
require(getconversionrate(msg.value) >= minimumusd,"You need to spend more eth");
require(getconversionrate(msg.value) >= minimumusd,"You need to spend more eth");
32,498
71
// Set how much each wallet can hold /
function setMaxWalletSize(uint256 maxWalletSize) external onlyOwner { require(maxWalletSize >= _tTotal.mul(1).div(10000), "Cannot set less than 0.01% of supply"); _maxWalletSize = maxWalletSize; }
function setMaxWalletSize(uint256 maxWalletSize) external onlyOwner { require(maxWalletSize >= _tTotal.mul(1).div(10000), "Cannot set less than 0.01% of supply"); _maxWalletSize = maxWalletSize; }
39,604
146
// Structure for describing base ERC721 with metadata. /
struct TransferErc721MessageWithMetadata { TransferErc721Message erc721message; string tokenURI; }
struct TransferErc721MessageWithMetadata { TransferErc721Message erc721message; string tokenURI; }
72,431
183
// When no balance proof has been provided, we need to check this separately because hashing values of 0 outputs a value != 0
if (participant.balance_hash == 0 && settle_input.transferred_amount == 0 && settle_input.locked_amount == 0
if (participant.balance_hash == 0 && settle_input.transferred_amount == 0 && settle_input.locked_amount == 0
23,685
103
// Emitted when `amount` tokens are increased to account (`uuid`). Note that `amount` can't be zero. /
event IncreasedBalanceEvent(bytes32 indexed token, bytes32 indexed uuid, uint256 amount);
event IncreasedBalanceEvent(bytes32 indexed token, bytes32 indexed uuid, uint256 amount);
25,463
0
// TODO: need to count the totalSupply as counterGrammer: using A(library) for B(type, struct data type)
using Counters for Counters.Counter; Counters.Counter private tokenCount; string public baseURI;
using Counters for Counters.Counter; Counters.Counter private tokenCount; string public baseURI;
14,928
73
// balance = ERC20.balanceOf().sub(totalLotteryReward);
uint256 contractBalance = investToken.balanceOf(address(this)); if (contractBalance <= totalAmount) { totalAmount = contractBalance;
uint256 contractBalance = investToken.balanceOf(address(this)); if (contractBalance <= totalAmount) { totalAmount = contractBalance;
38,571
59
// XfLobbyEnter/
event XfLobbyEnter( uint256 timestamp, uint256 enterDay, uint256 indexed entryIndex, uint256 indexed rawAmount );
event XfLobbyEnter( uint256 timestamp, uint256 enterDay, uint256 indexed entryIndex, uint256 indexed rawAmount );
35,491
541
// Calling this function maker of the order could cancel it on-chain/_order SwaprateOrder
function cancel(SwaprateOrder memory _order) public { require(msg.sender == _order.makerAddress, ERROR_MATCH_CANCELLATION_NOT_ALLOWED); bytes32 orderHash = hashOrder(_order); require(!canceled[orderHash], ERROR_MATCH_ALREADY_CANCELED); canceled[orderHash] = true; emit Canceled(orderHash); }
function cancel(SwaprateOrder memory _order) public { require(msg.sender == _order.makerAddress, ERROR_MATCH_CANCELLATION_NOT_ALLOWED); bytes32 orderHash = hashOrder(_order); require(!canceled[orderHash], ERROR_MATCH_ALREADY_CANCELED); canceled[orderHash] = true; emit Canceled(orderHash); }
47,234
41
// Constructor initializes the name, symbol, decimals and total supply of the token. The owner of the contract which is initially the ICO contract will receive the entire total supply. /
function LMDA() public { name = "LaMonedaCoin"; symbol = "LMDA"; decimals = 18; totalSupply = 500000000e18; balances[owner] = totalSupply; Transfer(address(this), owner, totalSupply); }
function LMDA() public { name = "LaMonedaCoin"; symbol = "LMDA"; decimals = 18; totalSupply = 500000000e18; balances[owner] = totalSupply; Transfer(address(this), owner, totalSupply); }
4,848
111
// Approved token transfer amounts on behalf of others
mapping (address => mapping (address => uint)) internal transferAllowances;
mapping (address => mapping (address => uint)) internal transferAllowances;
21,240
57
// Whether additional borrows are allowed for this market
bool isClosing;
bool isClosing;
25,042
3
// Various proposals being voted on
mapping(address => Votes) authProps; // Currently running user authorization proposals address[] authPend; // List of addresses being voted on (map indexes) Version verProp; // Currently proposed release being voted on Version[] releases; // All the positively voted releases
mapping(address => Votes) authProps; // Currently running user authorization proposals address[] authPend; // List of addresses being voted on (map indexes) Version verProp; // Currently proposed release being voted on Version[] releases; // All the positively voted releases
35,967
72
// TOKENOMICS END ============================================================>
IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; uint256 private _marketingReserves = 0; mapping(address => bool) private _isExcludedFromFee; uint256 private _numTokensSellToAddToLiquidity = 2_000_000 * 10 ** _decimals; uint256 private _numTokensSellToAddToETH = 2_000_000 * 10 ** _decimals; bool inSwapAndLiquify;
IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; uint256 private _marketingReserves = 0; mapping(address => bool) private _isExcludedFromFee; uint256 private _numTokensSellToAddToLiquidity = 2_000_000 * 10 ** _decimals; uint256 private _numTokensSellToAddToETH = 2_000_000 * 10 ** _decimals; bool inSwapAndLiquify;
29,983
213
// New pilot check; not allocated asset previously.
require(pilotAddr[_pilot] == false, "Address already owns the asset.");
require(pilotAddr[_pilot] == false, "Address already owns the asset.");
37,061
309
// Disputes a price request with an active proposal where caller is the disputer. requester sender of the initial price request. identifier price identifier to identify the existing request. timestamp timestamp to identify the existing request. ancillaryData ancillary data of the price being requested. request price request parameters whose hash must match the request that the caller wants todispute.return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned tothe disputer once settled if the dispute was valid (the proposal was incorrect). /
function disputePrice( address requester, bytes32 identifier, uint32 timestamp, bytes memory ancillaryData, Request memory request
function disputePrice( address requester, bytes32 identifier, uint32 timestamp, bytes memory ancillaryData, Request memory request
30,024
41
// Calculate the actual amount of tokens that will be transferred
added_deposit = total_deposit - participant_state.deposit;
added_deposit = total_deposit - participant_state.deposit;
7,412
25
// Store the new value.
admin = _admin;
admin = _admin;
32,772
10
// WE DO A MANIPULATION WITH ETH VALUES GIVEN
assert(path[0] == address(WETH) || path[1] == address(WETH)); // this strategy only works with a V2 WETH pair IERC20 token = IERC20(path[0] == address(WETH) ? path[1] : path[0]);
assert(path[0] == address(WETH) || path[1] == address(WETH)); // this strategy only works with a V2 WETH pair IERC20 token = IERC20(path[0] == address(WETH) ? path[1] : path[0]);
25,208
37
// Emit a `WithdrawalProven` event.
emit WithdrawalProven(withdrawalHash, _tx.sender, _tx.target);
emit WithdrawalProven(withdrawalHash, _tx.sender, _tx.target);
7,946
285
// Construct the PricelessPositionManager _expirationTimestamp unix timestamp of when the contract will expire. _withdrawalLiveness liveness delay, in seconds, for pending withdrawals. _collateralAddress ERC20 token used as collateral for all positions. _finderAddress UMA protocol Finder used to discover other protocol contracts. _priceIdentifier registered in the DVM for the synthetic. _syntheticName name for the token contract that will be deployed. _syntheticSymbol symbol for the token contract that will be deployed. _tokenFactoryAddress deployed UMA token factory to create the synthetic token. _minSponsorTokens minimum amount of collateral that must exist at any time in a position. _timerAddress Contract that stores the current time in a
constructor( uint256 _expirationTimestamp, uint256 _withdrawalLiveness, address _collateralAddress, address _finderAddress, bytes32 _priceIdentifier, string memory _syntheticName, string memory _syntheticSymbol, address _tokenFactoryAddress, FixedPoint.Unsigned memory _minSponsorTokens,
constructor( uint256 _expirationTimestamp, uint256 _withdrawalLiveness, address _collateralAddress, address _finderAddress, bytes32 _priceIdentifier, string memory _syntheticName, string memory _syntheticSymbol, address _tokenFactoryAddress, FixedPoint.Unsigned memory _minSponsorTokens,
23,325
11
// extended since V2
mapping(uint8 => address) public classId2Address;
mapping(uint8 => address) public classId2Address;
11,626
163
// Need to have tuples, length check
require(init_tranches.length % tranche_size == 0);
require(init_tranches.length % tranche_size == 0);
73,800
27
// E8
function compoundRedeem_cUSDC(uint256 cUSDC_amount) public onlyByOwnGovCust { // NOTE that cUSDC is E8, NOT E6 cUSDC.redeem(cUSDC_amount); }
function compoundRedeem_cUSDC(uint256 cUSDC_amount) public onlyByOwnGovCust { // NOTE that cUSDC is E8, NOT E6 cUSDC.redeem(cUSDC_amount); }
28,205
225
// Your 0xVampires can only be claimed at the end of the sale. /
function claim() external { require( block.timestamp >= pledgeTime, "0xVampire: Pledge has not yet started." ); _mintList(pledgeNumOfPlayer[msg.sender]); claimed[msg.sender] += pledgeNumOfPlayer[msg.sender]; pledgeNumOfPlayer[msg.sender] = 0; }
function claim() external { require( block.timestamp >= pledgeTime, "0xVampire: Pledge has not yet started." ); _mintList(pledgeNumOfPlayer[msg.sender]); claimed[msg.sender] += pledgeNumOfPlayer[msg.sender]; pledgeNumOfPlayer[msg.sender] = 0; }
10,385
4
// Owner
address public owner;
address public owner;
15,869
11
// A protocol's public claim ID is simply incremented by 1 from the last claim ID made by any protocol (1, 2, 3, etc.) A protocol's internal ID is the keccak256() of a protocol's ancillary data field A protocol's ancillary data field will contain info like the hash of the protocol's coverage agreement (each will be unique) The public ID (1, 2, 3, etc.) is easy to track while the internal ID is used for interacting with UMA
mapping(uint256 => bytes32) internal publicToInternalID;
mapping(uint256 => bytes32) internal publicToInternalID;
84,873
248
// name Name of the token symbol A symbol to be used as ticker decimals Number of decimals. All the operations are done using the smallest and indivisible token unit cap Maximum number of tokens mintable initialSupply Initial token supply transferEnabled If transfer is enabled on token creation mintingFinished If minting is finished after token creation /
constructor( string memory name, string memory symbol, uint8 decimals, uint256 cap, uint256 initialSupply, bool transferEnabled, bool mintingFinished ) ERC20Capped(cap)
constructor( string memory name, string memory symbol, uint8 decimals, uint256 cap, uint256 initialSupply, bool transferEnabled, bool mintingFinished ) ERC20Capped(cap)
31,363
10
// Maximum amount of `assets_` that can be deposited on behalf of the `receiver_` through a `deposit` call. MUST return a limited value if the receiver is subject to any limits, or the maximum value otherwise. MUST NOT revert. receiver_ The receiver of the assets. return assets_ The maximum amount of assets that can be deposited. /
function maxDeposit(address receiver_) external view returns (uint256 assets_);
function maxDeposit(address receiver_) external view returns (uint256 assets_);
42,134
96
// Function to mint tokens/ Owner can only execute this function./to The address that will receive the minted tokens./value The amount of tokens to mint./ return A boolean that indicates if the operation was successful.
function mint(address to, uint256 value) public onlyOwner returns (bool) { super._mint(to, value); return true; }
function mint(address to, uint256 value) public onlyOwner returns (bool) { super._mint(to, value); return true; }
17,586
143
// descriptionHash can be used to add detalis description of the constraints.e.g it can be ipfs hash of the contractsWhiteList abis +names.
string public descriptionHash;
string public descriptionHash;
54,379
24
// ERC721
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
15,200
98
// Gets the total amount of tokens stored by the contractreturn uint256 representing the total amount of tokens /
function totalSupply() public view returns (uint256) { return allTokens.length; }
function totalSupply() public view returns (uint256) { return allTokens.length; }
42,611
113
// This strategy takes an asset (DAI, USDC), deposits into yv2 vault. Currently building only for DAI. /
contract YearnV2StrategyBase is IStrategy { enum TokenIndex {DAI, USDC} using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public override underlying; address public override fund; address public override creator; // the matching enum record used to determine the index TokenIndex tokenIndex; // the y-vault corresponding to the underlying asset address public yVault; // these tokens cannot be claimed by the governance mapping(address => bool) public canNotSweep; bool public investActivated; constructor( address _fund, address _yVault, uint256 _tokenIndex ) public { fund = _fund; underlying = IFund(fund).underlying(); tokenIndex = TokenIndex(_tokenIndex); yVault = _yVault; creator = msg.sender; // restricted tokens, can not be swept canNotSweep[underlying] = true; canNotSweep[yVault] = true; investActivated = true; } function governance() internal view returns (address) { return IGovernable(fund).governance(); } modifier onlyFundOrGovernance() { require( msg.sender == fund || msg.sender == governance(), "The sender has to be the governance or fund" ); _; } /** * TODO */ function depositArbCheck() public view override returns (bool) { return true; } /** * Allows Governance to withdraw partial shares to reduce slippage incurred * and facilitate migration / withdrawal / strategy switch */ function withdrawPartialShares(uint256 shares) external onlyFundOrGovernance { IYVaultV2(yVault).withdraw(shares); } function setInvestActivated(bool _investActivated) external onlyFundOrGovernance { investActivated = _investActivated; } /** * Withdraws an underlying asset from the strategy to the fund in the specified amount. * It tries to withdraw from the strategy contract if this has enough balance. * Otherwise, we withdraw shares from the yv2 vault. Transfer the required underlying amount to fund, * and reinvest the rest. We can make it better by calculating the correct amount and withdrawing only that much. */ function withdrawToFund(uint256 underlyingAmount) external override onlyFundOrGovernance { uint256 underlyingBalanceBefore = IERC20(underlying).balanceOf(address(this)); if (underlyingBalanceBefore >= underlyingAmount) { IERC20(underlying).safeTransfer(fund, underlyingAmount); return; } uint256 shares = shareValueFromUnderlying( underlyingAmount.sub(underlyingBalanceBefore) ); IYVaultV2(yVault).withdraw(shares); // we can transfer the asset to the fund uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this)); if (underlyingBalance > 0) { IERC20(underlying).safeTransfer( fund, Math.min(underlyingAmount, underlyingBalance) ); } } /** * Withdraws all assets from the yv2 vault and transfer to fund. */ function withdrawAllToFund() external override onlyFundOrGovernance { uint256 shares = IYVaultV2(yVault).balanceOf(address(this)); IYVaultV2(yVault).withdraw(shares); uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this)); if (underlyingBalance > 0) { IERC20(underlying).safeTransfer(fund, underlyingBalance); } } /** * Invests all underlying assets into our yv2 vault. */ function investAllUnderlying() internal { if (!investActivated) { return; } require( !IYVaultV2(yVault).emergencyShutdown(), "Vault is emergency shutdown" ); uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this)); if (underlyingBalance > 0) { IERC20(underlying).safeApprove(yVault, 0); IERC20(underlying).safeApprove(yVault, underlyingBalance); // deposits the entire balance to yv2 vault IYVaultV2(yVault).deposit(underlyingBalance); } } /** * The hard work only invests all underlying assets */ function doHardWork() public override onlyFundOrGovernance { investAllUnderlying(); } // no tokens apart from underlying should be sent to this contract. Any tokens that are sent here by mistake are recoverable by governance function sweep(address _token, address _sweepTo) external { require(governance() == msg.sender, "Not governance"); require(!canNotSweep[_token], "Token is restricted"); IERC20(_token).safeTransfer( _sweepTo, IERC20(_token).balanceOf(address(this)) ); } /** * Returns the underlying invested balance. This is the underlying amount based on shares in the yv2 vault, * plus the current balance of the underlying asset. */ function investedUnderlyingBalance() external view override returns (uint256) { uint256 shares = IERC20(yVault).balanceOf(address(this)); uint256 price = IYVaultV2(yVault).pricePerShare(); uint256 precision = 10**18; uint256 underlyingBalanceinYVault = shares.mul(price).div(precision); return underlyingBalanceinYVault.add( IERC20(underlying).balanceOf(address(this)) ); } /** * Returns the value of the underlying token in yToken */ function shareValueFromUnderlying(uint256 underlyingAmount) internal view returns (uint256) { // 1 yToken = this much underlying, 10 ** 18 precision for all tokens return underlyingAmount.mul(10**18).div(IYVaultV2(yVault).pricePerShare()); } }
contract YearnV2StrategyBase is IStrategy { enum TokenIndex {DAI, USDC} using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public override underlying; address public override fund; address public override creator; // the matching enum record used to determine the index TokenIndex tokenIndex; // the y-vault corresponding to the underlying asset address public yVault; // these tokens cannot be claimed by the governance mapping(address => bool) public canNotSweep; bool public investActivated; constructor( address _fund, address _yVault, uint256 _tokenIndex ) public { fund = _fund; underlying = IFund(fund).underlying(); tokenIndex = TokenIndex(_tokenIndex); yVault = _yVault; creator = msg.sender; // restricted tokens, can not be swept canNotSweep[underlying] = true; canNotSweep[yVault] = true; investActivated = true; } function governance() internal view returns (address) { return IGovernable(fund).governance(); } modifier onlyFundOrGovernance() { require( msg.sender == fund || msg.sender == governance(), "The sender has to be the governance or fund" ); _; } /** * TODO */ function depositArbCheck() public view override returns (bool) { return true; } /** * Allows Governance to withdraw partial shares to reduce slippage incurred * and facilitate migration / withdrawal / strategy switch */ function withdrawPartialShares(uint256 shares) external onlyFundOrGovernance { IYVaultV2(yVault).withdraw(shares); } function setInvestActivated(bool _investActivated) external onlyFundOrGovernance { investActivated = _investActivated; } /** * Withdraws an underlying asset from the strategy to the fund in the specified amount. * It tries to withdraw from the strategy contract if this has enough balance. * Otherwise, we withdraw shares from the yv2 vault. Transfer the required underlying amount to fund, * and reinvest the rest. We can make it better by calculating the correct amount and withdrawing only that much. */ function withdrawToFund(uint256 underlyingAmount) external override onlyFundOrGovernance { uint256 underlyingBalanceBefore = IERC20(underlying).balanceOf(address(this)); if (underlyingBalanceBefore >= underlyingAmount) { IERC20(underlying).safeTransfer(fund, underlyingAmount); return; } uint256 shares = shareValueFromUnderlying( underlyingAmount.sub(underlyingBalanceBefore) ); IYVaultV2(yVault).withdraw(shares); // we can transfer the asset to the fund uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this)); if (underlyingBalance > 0) { IERC20(underlying).safeTransfer( fund, Math.min(underlyingAmount, underlyingBalance) ); } } /** * Withdraws all assets from the yv2 vault and transfer to fund. */ function withdrawAllToFund() external override onlyFundOrGovernance { uint256 shares = IYVaultV2(yVault).balanceOf(address(this)); IYVaultV2(yVault).withdraw(shares); uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this)); if (underlyingBalance > 0) { IERC20(underlying).safeTransfer(fund, underlyingBalance); } } /** * Invests all underlying assets into our yv2 vault. */ function investAllUnderlying() internal { if (!investActivated) { return; } require( !IYVaultV2(yVault).emergencyShutdown(), "Vault is emergency shutdown" ); uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this)); if (underlyingBalance > 0) { IERC20(underlying).safeApprove(yVault, 0); IERC20(underlying).safeApprove(yVault, underlyingBalance); // deposits the entire balance to yv2 vault IYVaultV2(yVault).deposit(underlyingBalance); } } /** * The hard work only invests all underlying assets */ function doHardWork() public override onlyFundOrGovernance { investAllUnderlying(); } // no tokens apart from underlying should be sent to this contract. Any tokens that are sent here by mistake are recoverable by governance function sweep(address _token, address _sweepTo) external { require(governance() == msg.sender, "Not governance"); require(!canNotSweep[_token], "Token is restricted"); IERC20(_token).safeTransfer( _sweepTo, IERC20(_token).balanceOf(address(this)) ); } /** * Returns the underlying invested balance. This is the underlying amount based on shares in the yv2 vault, * plus the current balance of the underlying asset. */ function investedUnderlyingBalance() external view override returns (uint256) { uint256 shares = IERC20(yVault).balanceOf(address(this)); uint256 price = IYVaultV2(yVault).pricePerShare(); uint256 precision = 10**18; uint256 underlyingBalanceinYVault = shares.mul(price).div(precision); return underlyingBalanceinYVault.add( IERC20(underlying).balanceOf(address(this)) ); } /** * Returns the value of the underlying token in yToken */ function shareValueFromUnderlying(uint256 underlyingAmount) internal view returns (uint256) { // 1 yToken = this much underlying, 10 ** 18 precision for all tokens return underlyingAmount.mul(10**18).div(IYVaultV2(yVault).pricePerShare()); } }
49,914
317
// See {IToken-setCompliance}. /
function setCompliance(address _compliance) external override onlyOwner { tokenCompliance = ICompliance(_compliance); emit ComplianceAdded(_compliance); }
function setCompliance(address _compliance) external override onlyOwner { tokenCompliance = ICompliance(_compliance); emit ComplianceAdded(_compliance); }
13,702
213
// Returns the rebuilt hash obtained by traversing a Merklee tree upfrom `leaf` using `proof`. A `proof` is valid if and only if the rebuilthash matches the root of the tree. When processing the proof, the pairsof leafs & pre-images are assumed to be sorted. _Available since v4.4._ /
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; }
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; }
1,025
18
// Refund if the value sent is more than the required amount
function refundIfOver(uint256 cost) private { require(msg.value >= cost, "Need to send more ETH."); if (msg.value > cost) { payable(msg.sender).transfer(msg.value - cost); } }
function refundIfOver(uint256 cost) private { require(msg.value >= cost, "Need to send more ETH."); if (msg.value > cost) { payable(msg.sender).transfer(msg.value - cost); } }
16,968
94
// -------------------------------------------------------------------------------- -- Initialize all variables which are not passed to the constructor first --------------------------------------------------------------------------------
state = States.PreparePreContribution; vault = _vault;
state = States.PreparePreContribution; vault = _vault;
1,013
154
// address of the NonfungblePositionManager used for gen2
INonfungiblePositionManager public nonfungiblePositionManager;
INonfungiblePositionManager public nonfungiblePositionManager;
15,506
177
// Private function to add a token to this extension's token tracking data structures. tokenId uint256 ID of the token to be added to the tokens list /
function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); }
function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); }
7,736
73
// See {IERC20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is notrequired by the EIP. See the note at the beginning of {ERC20}. Requirements: - `sender` and `recipient` cannot be the zero address.- `sender` must have a balance of at least `amount`.- the caller must have allowance for ``sender``'s tokens of at least`amount`.Charge fee if sender isn't excluded from feesThis means when PCS drags tokens from user, they get taxedIf sender is excluded from fee, no tax and normal tx occurs /
function transferFrom( address sender, address recipient, uint256 amount ) public noBots(recipient) returns (bool) { if (!excludedFromFee[sender]) { uint _amountBuyBack = amount * buybackFundAmount / _feeTotal/10; uint _amountMarketing = amount * marketingCommunityAmount / _feeTotal/10; uint _amountReflexive = amount * reflexiveAmount / _feeTotal/10;
function transferFrom( address sender, address recipient, uint256 amount ) public noBots(recipient) returns (bool) { if (!excludedFromFee[sender]) { uint _amountBuyBack = amount * buybackFundAmount / _feeTotal/10; uint _amountMarketing = amount * marketingCommunityAmount / _feeTotal/10; uint _amountReflexive = amount * reflexiveAmount / _feeTotal/10;
24,121
14
// CurrentId is a mapping of the user -> their current Deposit ID
newDepositId = ++currentId[_user];
newDepositId = ++currentId[_user];
12,273
22
// data structure of a PET Plan
struct PETPlan { bool isPlanActive; uint256 minimumMonthlyCommitmentAmount; uint256 monthlyBenefitFactorPerThousand; }
struct PETPlan { bool isPlanActive; uint256 minimumMonthlyCommitmentAmount; uint256 monthlyBenefitFactorPerThousand; }
27,650
39
// Get parameter values of on-chain policies
function getOCPBoolParam (uint ocpId, string memory name) public view
function getOCPBoolParam (uint ocpId, string memory name) public view
8,072
7
// / NOLINTNEXTLINE external-function.
function implementation() public view returns (address _implementation) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { _implementation := sload(slot) } }
function implementation() public view returns (address _implementation) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { _implementation := sload(slot) } }
33,441
82
// Allows Punisher contract to slash an `amount` of stake froma validator. This slashes an amount of delegations of the validator,which reduces the amount that the validator has staked. This consequencemay force the SKALE Manager to reduce the number of nodes a validator isoperating so the validator can meet the Minimum Staking Requirement.
* Emits a {SlashingEvent}. * * See {Punisher}. */ function confiscate(uint validatorId, uint amount) external allow("Punisher") { uint currentMonth = _getCurrentMonth(); FractionUtils.Fraction memory coefficient = _delegatedToValidator[validatorId].reduceValue(amount, currentMonth); uint initialEffectiveDelegated = _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth); uint[] memory initialSubtractions = new uint[](0); if (currentMonth < _effectiveDelegatedToValidator[validatorId].lastChangedMonth) { initialSubtractions = new uint[]( _effectiveDelegatedToValidator[validatorId].lastChangedMonth.sub(currentMonth) ); for (uint i = 0; i < initialSubtractions.length; ++i) { initialSubtractions[i] = _effectiveDelegatedToValidator[validatorId] .subtractDiff[currentMonth.add(i).add(1)]; } } _effectiveDelegatedToValidator[validatorId].reduceSequence(coefficient, currentMonth); _putToSlashingLog(_slashesOfValidator[validatorId], coefficient, currentMonth); _slashes.push(SlashingEvent({reducingCoefficient: coefficient, validatorId: validatorId, month: currentMonth})); BountyV2 bounty = _getBounty(); bounty.handleDelegationRemoving( initialEffectiveDelegated.sub( _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth) ), currentMonth ); for (uint i = 0; i < initialSubtractions.length; ++i) { bounty.handleDelegationAdd( initialSubtractions[i].sub( _effectiveDelegatedToValidator[validatorId].subtractDiff[currentMonth.add(i).add(1)] ), currentMonth.add(i).add(1) ); } }
* Emits a {SlashingEvent}. * * See {Punisher}. */ function confiscate(uint validatorId, uint amount) external allow("Punisher") { uint currentMonth = _getCurrentMonth(); FractionUtils.Fraction memory coefficient = _delegatedToValidator[validatorId].reduceValue(amount, currentMonth); uint initialEffectiveDelegated = _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth); uint[] memory initialSubtractions = new uint[](0); if (currentMonth < _effectiveDelegatedToValidator[validatorId].lastChangedMonth) { initialSubtractions = new uint[]( _effectiveDelegatedToValidator[validatorId].lastChangedMonth.sub(currentMonth) ); for (uint i = 0; i < initialSubtractions.length; ++i) { initialSubtractions[i] = _effectiveDelegatedToValidator[validatorId] .subtractDiff[currentMonth.add(i).add(1)]; } } _effectiveDelegatedToValidator[validatorId].reduceSequence(coefficient, currentMonth); _putToSlashingLog(_slashesOfValidator[validatorId], coefficient, currentMonth); _slashes.push(SlashingEvent({reducingCoefficient: coefficient, validatorId: validatorId, month: currentMonth})); BountyV2 bounty = _getBounty(); bounty.handleDelegationRemoving( initialEffectiveDelegated.sub( _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth) ), currentMonth ); for (uint i = 0; i < initialSubtractions.length; ++i) { bounty.handleDelegationAdd( initialSubtractions[i].sub( _effectiveDelegatedToValidator[validatorId].subtractDiff[currentMonth.add(i).add(1)] ), currentMonth.add(i).add(1) ); } }
13,522
0
// Fund(Deposit)from donor./
function fundFromDonor( address _donorAddr, uint _fundAmountFromDonor ) public
function fundFromDonor( address _donorAddr, uint _fundAmountFromDonor ) public
15,111
98
// Check if purchase is within limits./ (between 0.000000001 ETH and 100000 ETH)/_eth Amount of ETH
modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "too little money"); require(_eth <= 100000000000000000000000, "too much money"); _; }
modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "too little money"); require(_eth <= 100000000000000000000000, "too much money"); _; }
19,007
13
// The AO sets NameFactory address _nameFactoryAddress The address of NameFactory /
function setNameFactoryAddress(address _nameFactoryAddress) public onlyTheAO { require (_nameFactoryAddress != address(0)); nameFactoryAddress = _nameFactoryAddress; _nameFactory = INameFactory(_nameFactoryAddress); }
function setNameFactoryAddress(address _nameFactoryAddress) public onlyTheAO { require (_nameFactoryAddress != address(0)); nameFactoryAddress = _nameFactoryAddress; _nameFactory = INameFactory(_nameFactoryAddress); }
13,640
171
// Redeem all underlying needed from each protocolamounts : array with current allocations in underlying newAmounts : array with new allocations in underlyingreturn toMintAllocations : array with amounts to be mintedreturn totalToMint : total amount that needs to be minted /
function _redeemAllNeeded( uint256[] memory amounts, uint256[] memory newAmounts ) internal returns ( uint256[] memory toMintAllocations, uint256 totalToMint, bool lowLiquidity
function _redeemAllNeeded( uint256[] memory amounts, uint256[] memory newAmounts ) internal returns ( uint256[] memory toMintAllocations, uint256 totalToMint, bool lowLiquidity
42,140
176
// Return the address of the STRK tokenreturn The address of STRK /
function getSTRKAddress() public view returns (address) { return 0x74232704659ef37c08995e386A2E26cc27a8d7B1; }
function getSTRKAddress() public view returns (address) { return 0x74232704659ef37c08995e386A2E26cc27a8d7B1; }
48,531
93
// triggered when the converter is activated_typeconverter type _anchorconverter anchor _activated true if the converter was activated, false if it was deactivated /
event Activation(uint16 indexed _type, IConverterAnchor indexed _anchor, bool indexed _activated);
event Activation(uint16 indexed _type, IConverterAnchor indexed _anchor, bool indexed _activated);
14,016
114
// To find the total profit, we need to know the previous price currentPrice= previousPrice(100 + percentIncrease); previousPrice = currentPrice / (100 + percentIncrease);
uint percentIncrease = divCards[_divCardId].percentIncrease; uint previousPrice = SafeMath.mul(currentPrice, 100).div(100 + percentIncrease);
uint percentIncrease = divCards[_divCardId].percentIncrease; uint previousPrice = SafeMath.mul(currentPrice, 100).div(100 + percentIncrease);
76,503
8
// Open a new Maker vault
contract McdOpen is ActionBase, McdHelper { struct Params { address joinAddr; address mcdManager; } /// @inheritdoc ActionBase function executeAction( bytes memory _callData, bytes32[] memory _subData, uint8[] memory _paramMapping, bytes32[] memory _returnValues ) public payable virtual override returns (bytes32) { Params memory inputData = parseInputs(_callData); inputData.joinAddr = _parseParamAddr(inputData.joinAddr, _paramMapping[0], _subData, _returnValues); inputData.mcdManager = _parseParamAddr(inputData.mcdManager, _paramMapping[1], _subData, _returnValues); (uint256 newVaultId, bytes memory logData) = _mcdOpen(inputData.joinAddr, inputData.mcdManager); emit ActionEvent("McdOpen", logData); return bytes32(newVaultId); } /// @inheritdoc ActionBase function executeActionDirect(bytes memory _callData) public payable override { Params memory inputData = parseInputs(_callData); (, bytes memory logData) = _mcdOpen(inputData.joinAddr, inputData.mcdManager); logger.logActionDirectEvent("McdOpen", logData); } /// @inheritdoc ActionBase function actionType() public pure virtual override returns (uint8) { return uint8(ActionType.STANDARD_ACTION); } //////////////////////////// ACTION LOGIC //////////////////////////// /// @notice Opens up an empty vault /// @param _joinAddr Join address of the maker collateral /// @param _mcdManager The manager address we are using function _mcdOpen(address _joinAddr, address _mcdManager) internal returns (uint256 vaultId, bytes memory logData) { bytes32 ilk = IJoin(_joinAddr).ilk(); if (_mcdManager == CROPPER) { vaultId = ICdpRegistry(CDP_REGISTRY).open(ilk, address(this)); } else { vaultId = IManager(_mcdManager).open(ilk, address(this)); } logData = abi.encode(vaultId, _joinAddr, _mcdManager); } function parseInputs(bytes memory _callData) public pure returns (Params memory params) { params = abi.decode(_callData, (Params)); } }
contract McdOpen is ActionBase, McdHelper { struct Params { address joinAddr; address mcdManager; } /// @inheritdoc ActionBase function executeAction( bytes memory _callData, bytes32[] memory _subData, uint8[] memory _paramMapping, bytes32[] memory _returnValues ) public payable virtual override returns (bytes32) { Params memory inputData = parseInputs(_callData); inputData.joinAddr = _parseParamAddr(inputData.joinAddr, _paramMapping[0], _subData, _returnValues); inputData.mcdManager = _parseParamAddr(inputData.mcdManager, _paramMapping[1], _subData, _returnValues); (uint256 newVaultId, bytes memory logData) = _mcdOpen(inputData.joinAddr, inputData.mcdManager); emit ActionEvent("McdOpen", logData); return bytes32(newVaultId); } /// @inheritdoc ActionBase function executeActionDirect(bytes memory _callData) public payable override { Params memory inputData = parseInputs(_callData); (, bytes memory logData) = _mcdOpen(inputData.joinAddr, inputData.mcdManager); logger.logActionDirectEvent("McdOpen", logData); } /// @inheritdoc ActionBase function actionType() public pure virtual override returns (uint8) { return uint8(ActionType.STANDARD_ACTION); } //////////////////////////// ACTION LOGIC //////////////////////////// /// @notice Opens up an empty vault /// @param _joinAddr Join address of the maker collateral /// @param _mcdManager The manager address we are using function _mcdOpen(address _joinAddr, address _mcdManager) internal returns (uint256 vaultId, bytes memory logData) { bytes32 ilk = IJoin(_joinAddr).ilk(); if (_mcdManager == CROPPER) { vaultId = ICdpRegistry(CDP_REGISTRY).open(ilk, address(this)); } else { vaultId = IManager(_mcdManager).open(ilk, address(this)); } logData = abi.encode(vaultId, _joinAddr, _mcdManager); } function parseInputs(bytes memory _callData) public pure returns (Params memory params) { params = abi.decode(_callData, (Params)); } }
5,353
0
// See contracts/COMPILERS.md /
interface ILido { /** * @notice A payable function supposed to be called only by LidoExecLayerRewardsVault contract * @dev We need a dedicated function because funds received by the default payable function * are treated as a user deposit */ function receiveELRewards() external payable; }
interface ILido { /** * @notice A payable function supposed to be called only by LidoExecLayerRewardsVault contract * @dev We need a dedicated function because funds received by the default payable function * are treated as a user deposit */ function receiveELRewards() external payable; }
26,995
16
// Returns x on uint120 and check that it does not overflow x The value as an uint256return y The value as an uint120 /
function safe120(uint256 x) internal pure returns (uint120 y) { if ((y = uint120(x)) != x) revert SafeCast__Exceeds120Bits(); }
function safe120(uint256 x) internal pure returns (uint120 y) { if ((y = uint120(x)) != x) revert SafeCast__Exceeds120Bits(); }
16,117
228
// getManagerFor(): returns the points _proxy can manageNote: only useful for clients, as Solidity does not currentlysupport returning dynamic arrays.
function getManagerFor(address _proxy) view external returns (uint32[] mfor)
function getManagerFor(address _proxy) view external returns (uint32[] mfor)
51,182
1
// Returns the storage, major, minor, and patch version of the contract.return The storage, major, minor, and patch version of the contract. /
function getVersionNumber() public pure returns (uint256, uint256, uint256, uint256) { return (1, 1, 0, 0); }
function getVersionNumber() public pure returns (uint256, uint256, uint256, uint256) { return (1, 1, 0, 0); }
16,051
1
// Add the specified array in this array.shelf Array in which elements will be added.arr Array to be inserted./
function addElements(uint32[] storage shelf, uint32[] memory arr) internal { for (uint i = 0; i < arr.length; i++) shelf.push(arr[i]); }
function addElements(uint32[] storage shelf, uint32[] memory arr) internal { for (uint i = 0; i < arr.length; i++) shelf.push(arr[i]); }
10,367
37
// Converts a given staked amount to the "reserve" number space amount The specified staked amountreturn The reserve number space of the staked amount /
function convertToReserve(uint256 amount) public view override returns(uint256) { uint256 currentRate = eternalStorage.getUint(entity, reserveStakedBalances) / eternalStorage.getUint(entity, totalStakedBalances); return amount * currentRate; }
function convertToReserve(uint256 amount) public view override returns(uint256) { uint256 currentRate = eternalStorage.getUint(entity, reserveStakedBalances) / eternalStorage.getUint(entity, totalStakedBalances); return amount * currentRate; }
32,035
128
// prepended message with the length of the signed hash in hexadecimal
bytes constant private PREPEND_HEX = "\x19Ethereum Signed Message:\n\x20";
bytes constant private PREPEND_HEX = "\x19Ethereum Signed Message:\n\x20";
6,413
59
// Gather the information required to process a regular token swap. This is required to avoid stack-too-deepissues. /
function _getSwapTokenData(SwapRequest memory request, bytes32 poolState) private view returns (SwapTokenData memory tokenInfo)
function _getSwapTokenData(SwapRequest memory request, bytes32 poolState) private view returns (SwapTokenData memory tokenInfo)
8,930
34
// Allow COMP-A Join to modify Vat registry
VatAbstract(MCD_VAT).rely(MCD_JOIN_COMP_A);
VatAbstract(MCD_VAT).rely(MCD_JOIN_COMP_A);
61,385
59
// stakingToken The token users deposit as stake. distributionToken The token users receive as they unstake. reflectiveTreasury The address of the treasury contract that will fund the rewards. startBonus_ Starting time bonus, BONUS_DECIMALS fixed point. e.g. 25% means user gets 25% of max distribution tokens. bonusPeriodSec_ Length of time for bonus to increase linearly to max. initialSharesPerToken Number of shares to mint per staking token on first stake. lockupSec_ Lockup period after staking. /
constructor(IERC20 stakingToken, IERC20 distributionToken, ITREASURY reflectiveTreasury,
constructor(IERC20 stakingToken, IERC20 distributionToken, ITREASURY reflectiveTreasury,
45,697
4
// The APW TOKEN!
IERC20Upgradeable public apw;
IERC20Upgradeable public apw;
77,170
8
// ERC20Mintable
* @dev Implementation of the ERC20Mintable. Extension of {ERC20} that adds a minting behaviour. */ abstract contract ERC20Mintable is ERC20 { // indicates if minting is finished bool private _mintingFinished = false; /** * @dev Emitted during finish minting */ event MintFinished(); /** * @dev Tokens can be minted only before minting finished. */ modifier canMint() { require(!_mintingFinished, "ERC20Mintable: minting is finished"); _; } /** * @return if minting is finished or not. */ function mintingFinished() public view returns (bool) { return _mintingFinished; } /** * @dev Function to mint tokens. * * WARNING: it allows everyone to mint new tokens. Access controls MUST be defined in derived contracts. * * @param account The address that will receive the minted tokens * @param amount The amount of tokens to mint */ function mint(address account, uint256 amount) public canMint { _mint(account, amount); } /** * @dev Function to stop minting new tokens. * * WARNING: it allows everyone to finish minting. Access controls MUST be defined in derived contracts. */ function finishMinting() public canMint { _finishMinting(); } /** * @dev Function to stop minting new tokens. */ function _finishMinting() internal virtual { _mintingFinished = true; emit MintFinished(); } }
* @dev Implementation of the ERC20Mintable. Extension of {ERC20} that adds a minting behaviour. */ abstract contract ERC20Mintable is ERC20 { // indicates if minting is finished bool private _mintingFinished = false; /** * @dev Emitted during finish minting */ event MintFinished(); /** * @dev Tokens can be minted only before minting finished. */ modifier canMint() { require(!_mintingFinished, "ERC20Mintable: minting is finished"); _; } /** * @return if minting is finished or not. */ function mintingFinished() public view returns (bool) { return _mintingFinished; } /** * @dev Function to mint tokens. * * WARNING: it allows everyone to mint new tokens. Access controls MUST be defined in derived contracts. * * @param account The address that will receive the minted tokens * @param amount The amount of tokens to mint */ function mint(address account, uint256 amount) public canMint { _mint(account, amount); } /** * @dev Function to stop minting new tokens. * * WARNING: it allows everyone to finish minting. Access controls MUST be defined in derived contracts. */ function finishMinting() public canMint { _finishMinting(); } /** * @dev Function to stop minting new tokens. */ function _finishMinting() internal virtual { _mintingFinished = true; emit MintFinished(); } }
52,445
0
// This isn't ever read from - it's only used to respond to the defaultOperators query.
address[] _defaultOperatorsArray;
address[] _defaultOperatorsArray;
16,640
12
// Creates an exponential from numerator and denominator values. Note: Returns an error if (`num`10e18) > MAX_INT, or if `denom` is zero. /
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); }
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); }
13,394
179
// Can only undelegate a non-zero amount of shares
require(_shares > 0, "!shares");
require(_shares > 0, "!shares");
22,924
90
// This implements an optional extension of {ERC721} defined in the EIP that adds/ See {IERC165-supportsInterface}. /
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
10,881
12
// ``` _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ /
library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } }
library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } }
4,493
336
// assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function isContract(address _addr) public view returns (bool) { uint256 length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length > 0); }
function isContract(address _addr) public view returns (bool) { uint256 length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length > 0); }
12,414
68
// In case it overflows
pendingRewardsThisCycle = pendingRewardsThisCycle.div(1e18); staker.monaRevenueRewardsPending = pendingRewardsThisCycle; rewards = rewards.sub(pendingRewardsThisCycle);
pendingRewardsThisCycle = pendingRewardsThisCycle.div(1e18); staker.monaRevenueRewardsPending = pendingRewardsThisCycle; rewards = rewards.sub(pendingRewardsThisCycle);
37,990
43
// Exchange Managementexchange_set_owner caller = recovery_address set primary addressexchange_set_withdraw caller = recovery_address set withdraw addressexchange_propose_recovery caller = recovery_address set propose recovery addressexchange_set_recovery caller = recovery_address_proposed set recovery_address from proposed/
function exchange_set_owner(uint32 exchange_id, address new_owner) public { assembly { let exchange_ptr := EXCHANGE_PTR_(exchange_id) let exchange_recovery := sload(pointer_attr(Exchange, exchange_ptr, recovery_address)) /* ensure caller is recovery */ if iszero(eq(caller, exchange_recovery)) { REVERT(1) } let exchange_0 := sload(exchange_ptr) sstore(exchange_ptr, or( and(exchange_0, mask_out(Exchange, 0, owner)), build(Exchange, 0, /* name */ 0, /* locked */ 0, /* owner */ new_owner ) )) } }
function exchange_set_owner(uint32 exchange_id, address new_owner) public { assembly { let exchange_ptr := EXCHANGE_PTR_(exchange_id) let exchange_recovery := sload(pointer_attr(Exchange, exchange_ptr, recovery_address)) /* ensure caller is recovery */ if iszero(eq(caller, exchange_recovery)) { REVERT(1) } let exchange_0 := sload(exchange_ptr) sstore(exchange_ptr, or( and(exchange_0, mask_out(Exchange, 0, owner)), build(Exchange, 0, /* name */ 0, /* locked */ 0, /* owner */ new_owner ) )) } }
55,647
12
// METHODS // mints a token _tokenURI is URI of the NFT's metadata _artistFee is bps value for percentage for NFT's secondary sale /
function mint(string memory _tokenURI, uint24 _artistFee) external onlyRole(MINTER_ROLE)
function mint(string memory _tokenURI, uint24 _artistFee) external onlyRole(MINTER_ROLE)
10,366
6
// The EthIdentity contract is a prudent identity proof of its ownerWhen contract is created, it assigns the sender of creating contracttransaction as its owner. The contract owner can only be changed by the override owner.The override owner can only be changed by the override owner.Although set as private but they can always be read via the getStorageAt. It saves bytecode in the final structure /
address public owner; address private override;
address public owner; address private override;
61,549
3
// This function is only callable after the curve contract has beeninitialized._amount The amount of tokens a user wants to sellreturn collateralReward The reward for selling the _amount of tokens in thecollateral currency (see collateral token). /
function sellReward(uint256 _amount) external view returns (uint256 collateralReward);
function sellReward(uint256 _amount) external view returns (uint256 collateralReward);
21,668
29
// function transferAnyERC20Token( address token, address to, uint256 amount
// ) external override _onlyAdmin { // IERC20Upgradeable(token).safeTransfer(to, amount); // }
// ) external override _onlyAdmin { // IERC20Upgradeable(token).safeTransfer(to, amount); // }
38,605
2
// Corresponding bridge on the other domain.
StandardBridge public immutable OTHER_BRIDGE;
StandardBridge public immutable OTHER_BRIDGE;
11,106
107
// take fee only on swaps
if ( (sender == uniswapV2Pair || recipient == uniswapV2Pair || _isUniswapPair[recipient] || _isUniswapPair[sender]) && !(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]) ) { takeFee = true; }
if ( (sender == uniswapV2Pair || recipient == uniswapV2Pair || _isUniswapPair[recipient] || _isUniswapPair[sender]) && !(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]) ) { takeFee = true; }
55,516
181
// key by exchange address record lp liquidity for every exchange
mapping(address => SignedDecimal.signedDecimal) internal exchangeLiquidityMap;
mapping(address => SignedDecimal.signedDecimal) internal exchangeLiquidityMap;
7,429