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
28
// The timelocked balances for each user
mapping(address => uint256) internal _timelockBalances;
mapping(address => uint256) internal _timelockBalances;
7,764
147
// Extend this library for child contracts
library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } /** * @dev Compara two numbers, and return the bigger one. */ function max(int256 a, int256 b) internal pure returns (int256) { if (a > b) { return a; } else { return b; } } /** * @dev Compara two numbers, and return the bigger one. */ function min(int256 a, int256 b) internal pure returns (int256) { if (a < b) { return a; } else { return b; } } }
library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } /** * @dev Compara two numbers, and return the bigger one. */ function max(int256 a, int256 b) internal pure returns (int256) { if (a > b) { return a; } else { return b; } } /** * @dev Compara two numbers, and return the bigger one. */ function min(int256 a, int256 b) internal pure returns (int256) { if (a < b) { return a; } else { return b; } } }
14,647
162
// Send LP to dividends
uint256 dividends = lpBalance; if (dividends > 0) { bool success = IERC20(pair).transfer( address(dividendTracker), dividends ); if (success) { dividendTracker.distributeLPDividends(dividends); emit SendDividends(tokens, dividends);
uint256 dividends = lpBalance; if (dividends > 0) { bool success = IERC20(pair).transfer( address(dividendTracker), dividends ); if (success) { dividendTracker.distributeLPDividends(dividends); emit SendDividends(tokens, dividends);
33,197
137
// force Swap back if slippage above 49% for launch. fix router clog
function forceSwapBack() external onlyOwner { uint256 contractBalance = balanceOf(address(this)); require( contractBalance >= totalSupply() / 100, "Can only swap back if more than 1% of tokens stuck on contract" ); swapBack(); emit OwnerForcedSwapBack(block.timestamp); }
function forceSwapBack() external onlyOwner { uint256 contractBalance = balanceOf(address(this)); require( contractBalance >= totalSupply() / 100, "Can only swap back if more than 1% of tokens stuck on contract" ); swapBack(); emit OwnerForcedSwapBack(block.timestamp); }
40,161
8
// erc20-token cEUR (https:alfajores-blockscout.celo-testnet.org/token/0x10c892A6EC43a53E45D0B916B4b7D383B1b78C0F)
cEUR = IERC20(_cEUR);
cEUR = IERC20(_cEUR);
36,933
15
// Returns the subtraction of two unsigned integers, reverting on overflow (when the result is negative). Counterpart to Solidity's `-` operator. Requirements: - Subtraction cannot overflow./
function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); }
function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); }
367
10
// maker deposit, anyone could deposit but only maker could withdraw
function makerDeposit(address token) external nonReentrant poolOngoing { require(ID3Oracle(state._ORACLE_).isFeasible(token), Errors.TOKEN_NOT_FEASIBLE); if (!state.hasDepositedToken[token]) { state.hasDepositedToken[token] = true; state.depositedTokenList.push(token); } // transfer in from proxies uint256 tokenInAmount = IERC20(token).balanceOf(address(this)) - state.balances[token]; _updateReserve(token); // if token in tokenlist, approve max, ensure vault could force liquidate uint256 allowance = IERC20(token).allowance(address(this), state._D3_VAULT_); if(_checkTokenInTokenlist(token) && allowance < type(uint256).max) { IERC20(token).forceApprove(state._D3_VAULT_, type(uint256).max); } require(checkSafe(), Errors.NOT_SAFE); emit MakerDeposit(token, tokenInAmount); }
function makerDeposit(address token) external nonReentrant poolOngoing { require(ID3Oracle(state._ORACLE_).isFeasible(token), Errors.TOKEN_NOT_FEASIBLE); if (!state.hasDepositedToken[token]) { state.hasDepositedToken[token] = true; state.depositedTokenList.push(token); } // transfer in from proxies uint256 tokenInAmount = IERC20(token).balanceOf(address(this)) - state.balances[token]; _updateReserve(token); // if token in tokenlist, approve max, ensure vault could force liquidate uint256 allowance = IERC20(token).allowance(address(this), state._D3_VAULT_); if(_checkTokenInTokenlist(token) && allowance < type(uint256).max) { IERC20(token).forceApprove(state._D3_VAULT_, type(uint256).max); } require(checkSafe(), Errors.NOT_SAFE); emit MakerDeposit(token, tokenInAmount); }
17,229
315
// Check if data was not requested and provided yet
require(!dataRequested[oracleId][timestamp] && !dataExist[oracleId][timestamp], ERROR_ORACLE_AGGREGATOR_QUERY_WAS_ALREADY_MADE);
require(!dataRequested[oracleId][timestamp] && !dataExist[oracleId][timestamp], ERROR_ORACLE_AGGREGATOR_QUERY_WAS_ALREADY_MADE);
59,302
187
// convert to correct decimals for collateral
uint256 collateralAmount = oneAmount.mul(reserveRatio).div(MAX_RESERVE_RATIO).mul(10 ** collateralDecimals[collateral]).div(10 ** DECIMALS); collateralAmount = collateralAmount.mul(10 ** 9).div(getCollateralUsd(collateral)); if (address(oneTokenOracle) == address(0)) return (collateralAmount, 0); uint256 stimulusUsd = getStimulusOracle(); // 10 ** 9 uint256 stimulusAmountInOneStablecoin = oneAmount.mul(MAX_RESERVE_RATIO.sub(reserveRatio)).div(MAX_RESERVE_RATIO); uint256 stimulusAmount = stimulusAmountInOneStablecoin.mul(10 ** 9).div(stimulusUsd).mul(10 ** stimulusDecimals).div(10 ** DECIMALS); // must be 10 ** stimulusDecimals
uint256 collateralAmount = oneAmount.mul(reserveRatio).div(MAX_RESERVE_RATIO).mul(10 ** collateralDecimals[collateral]).div(10 ** DECIMALS); collateralAmount = collateralAmount.mul(10 ** 9).div(getCollateralUsd(collateral)); if (address(oneTokenOracle) == address(0)) return (collateralAmount, 0); uint256 stimulusUsd = getStimulusOracle(); // 10 ** 9 uint256 stimulusAmountInOneStablecoin = oneAmount.mul(MAX_RESERVE_RATIO.sub(reserveRatio)).div(MAX_RESERVE_RATIO); uint256 stimulusAmount = stimulusAmountInOneStablecoin.mul(10 ** 9).div(stimulusUsd).mul(10 ** stimulusDecimals).div(10 ** DECIMALS); // must be 10 ** stimulusDecimals
41,716
7
// subtract two decimals
function subD(decimal memory x, decimal memory y) internal pure returns (decimal memory) { decimal memory t; t.d = x.d.sub(y.d); return t; }
function subD(decimal memory x, decimal memory y) internal pure returns (decimal memory) { decimal memory t; t.d = x.d.sub(y.d); return t; }
35,624
74
// If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},which is called upon a safe transfer, and return the magic value`bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,the transfer is reverted.Requires the msg.sender to be the owner, approved, or operator from current owner of the token to address to receive the ownership of the given token ID tokenId uint256 ID of the token to be transferred /
function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); }
function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); }
238
1
// Set idle address
idle = idle_; _owner = owner_; recipient = recipient_; lastUpdate = block.timestamp; vestingPeriod = vestingPeriod_;
idle = idle_; _owner = owner_; recipient = recipient_; lastUpdate = block.timestamp; vestingPeriod = vestingPeriod_;
63,062
59
// Calculate pointer to length of OrderFulfilled consideration array.
let eventConsiderationArrPtr := add( OrderFulfilled_consideration_length_baseOffset, mul(totalAdditionalRecipients, OneWord) )
let eventConsiderationArrPtr := add( OrderFulfilled_consideration_length_baseOffset, mul(totalAdditionalRecipients, OneWord) )
14,791
66
// Return reward multiplier over the given "from" to "to" block. from block to start calculating reward to block to finish calculating rewardreturn the multiplier for the period /
function _getMultiplier(uint256 from, uint256 to) internal view returns (uint256) { if (to <= endBlock) { return to - from; } else if (from >= endBlock) { return 0; } else { return endBlock - from; } }
function _getMultiplier(uint256 from, uint256 to) internal view returns (uint256) { if (to <= endBlock) { return to - from; } else if (from >= endBlock) { return 0; } else { return endBlock - from; } }
15,132
97
// Check if an options contract exist based on the passed parameters. optionTerms is the terms of the option contract /
function optionsExist(ProtocolAdapterTypes.OptionTerms calldata optionTerms)
function optionsExist(ProtocolAdapterTypes.OptionTerms calldata optionTerms)
18,747
17
// If the self-destruction delay has elapsed, destroy this contract andremit any ether it owns to the beneficiary address. Only the contract owner may call this. /
function selfDestruct() external onlyOwner
function selfDestruct() external onlyOwner
5,921
60
// Resumes gas metering (i.e. gas usage is counted again). Noop if already on.
function resumeGasMetering() external;
function resumeGasMetering() external;
30,492
4
// ---------------------------------------------------------------------------- Safe Math Library ----------------------------------------------------------------------------
contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } }
contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } }
7,373
668
// This function returns the initial proposal bond for this request, which can be customized by calling setBond() with the same identifier and timestamp.
return finalFee.mul(2);
return finalFee.mul(2);
12,201
8
// Admin booleans for emergencies
bool public yieldCollectionPaused = false; // For emergencies
bool public yieldCollectionPaused = false; // For emergencies
16,253
23
// authorize
require(price <= msg.value || allowed[_launchpassId], "ETH incorrect"); require(IERC721(launchpassAddress).ownerOf(_launchpassId) == msg.sender, "Not owner");
require(price <= msg.value || allowed[_launchpassId], "ETH incorrect"); require(IERC721(launchpassAddress).ownerOf(_launchpassId) == msg.sender, "Not owner");
24,282
6
// Moves `amount` tokens from the caller's account to `recipient`. If send or receive hooks are registered for the caller and `recipient`,the corresponding functions will be called with `data` and empty`operatorData`. See {IERC777Sender} and {IERC777Recipient}. Emits a {Sent} event. Requirements - the caller must have at least `amount` tokens.- `recipient` cannot be the zero address.- if `recipient` is a contract, it must implement the {IERC777Recipient}interface. /
function send(
function send(
22,614
95
// Modifier throws if called by any account other than the pendingOwner.
modifier onlyPendingOwner() { require(msg.sender == pendingOwner, "UNAUTHORIZED"); _; }
modifier onlyPendingOwner() { require(msg.sender == pendingOwner, "UNAUTHORIZED"); _; }
23,940
11
// Constructor. _mainstreetCrowdfund Address of crowdfund contract. _intellisys Address to receive intellisys' tokens. _start Timestamp when the token becomes active. /
function MainstreetToken(address _mainstreetCrowdfund, address _intellisys, uint _start, bool _testing) { mainstreetCrowdfund = _mainstreetCrowdfund; intellisys = _intellisys; start = _start; testing = _testing; }
function MainstreetToken(address _mainstreetCrowdfund, address _intellisys, uint _start, bool _testing) { mainstreetCrowdfund = _mainstreetCrowdfund; intellisys = _intellisys; start = _start; testing = _testing; }
38,039
164
// split the liquidity balance into halves
uint256 half = accumulatedForLiquid .div(2); uint256 otherHalf = accumulatedForLiquid.sub(half); uint256 swapAmount = half.add(accumulatedForMarketing).add(accumulatedForDev);
uint256 half = accumulatedForLiquid .div(2); uint256 otherHalf = accumulatedForLiquid.sub(half); uint256 swapAmount = half.add(accumulatedForMarketing).add(accumulatedForDev);
14,722
2
// _mint(AIRDROP_ADDRESS, MAX_TOTAL_AIR_DROP + MAX_TOTAL_LIQUID);
_mint(AIRDROP_ADDRESS_1, MAX_AIR_DROP_ROUND_1); _mint(AIRDROP_ADDRESS_2, MAX_AIR_DROP_ROUND_2); _mint(AIRDROP_ADDRESS_3, MAX_AIR_DROP_ROUND_3); _mint(AIRDROP_ADDRESS_4, MAX_AIR_DROP_ROUND_4); _mint(LP_ADDRESS, MAX_TOTAL_SUPPLY - MAX_TOTAL_AIR_DROP - MAX_TOTAL_LIQUID);
_mint(AIRDROP_ADDRESS_1, MAX_AIR_DROP_ROUND_1); _mint(AIRDROP_ADDRESS_2, MAX_AIR_DROP_ROUND_2); _mint(AIRDROP_ADDRESS_3, MAX_AIR_DROP_ROUND_3); _mint(AIRDROP_ADDRESS_4, MAX_AIR_DROP_ROUND_4); _mint(LP_ADDRESS, MAX_TOTAL_SUPPLY - MAX_TOTAL_AIR_DROP - MAX_TOTAL_LIQUID);
778
11
// Symbol of token
string public constant symbol = "IDM"; uint8 public constant decimals = 18; uint public _totalsupply = 35000000 * 10 ** 18; // 35 Million IDM Coins uint256 constant public _price_tokn = 0.00075 ether; uint256 no_of_tokens; uint256 bonus_token; uint256 total_token; uint256 tokensold; uint256 public total_token_sold; bool stopped = false;
string public constant symbol = "IDM"; uint8 public constant decimals = 18; uint public _totalsupply = 35000000 * 10 ** 18; // 35 Million IDM Coins uint256 constant public _price_tokn = 0.00075 ether; uint256 no_of_tokens; uint256 bonus_token; uint256 total_token; uint256 tokensold; uint256 public total_token_sold; bool stopped = false;
4,493
1
// The minimum setable proposal threshold
uint public constant MIN_PROPOSAL_THRESHOLD = 50000e18; // 50,000 Comp
uint public constant MIN_PROPOSAL_THRESHOLD = 50000e18; // 50,000 Comp
23,795
1
// uint8 storage and setter
contract FunctionNames_1 { function ThisIsMyReallyReallyLongFunctionName() public { } }
contract FunctionNames_1 { function ThisIsMyReallyReallyLongFunctionName() public { } }
45,485
5
// _market_id id of the market_market name of the market/
constructor(uint32 _market_id, string memory _market) public { market_id = _market_id; market = _market; }
constructor(uint32 _market_id, string memory _market) public { market_id = _market_id; market = _market; }
20,179
189
// We implicitly trust these wallets not to do reentrancy (although what they could do is limited)
Address.sendValue(payable(devWallet), ethAmt.mul(6).div(19)); Address.sendValue(payable(marketingWallet), ethAmt.mul(10).div(19));
Address.sendValue(payable(devWallet), ethAmt.mul(6).div(19)); Address.sendValue(payable(marketingWallet), ethAmt.mul(10).div(19));
69,263
23
// Technical variables to store statistical data
uint public StatsMinted = 0;//Minted tokens amount uint public StatsTotal = 0;//Overall tokens amount
uint public StatsMinted = 0;//Minted tokens amount uint public StatsTotal = 0;//Overall tokens amount
41,873
3
// Helpful to tell us what amount of ether is on sale
function onSale() constant returns(uint) { return this.balance - nextSale; }
function onSale() constant returns(uint) { return this.balance - nextSale; }
3,079
171
// Update the Target price given the auction results. 0 values are used to indicate missing data. /
function updateGivenAuctionResults( uint256 round, uint256 lastAuctionBlock, uint256 floatMarketPrice, uint256 basketFactor ) external returns (uint256 targetPriceInEth);
function updateGivenAuctionResults( uint256 round, uint256 lastAuctionBlock, uint256 floatMarketPrice, uint256 basketFactor ) external returns (uint256 targetPriceInEth);
13,527
189
//
function setBaseExtension(string memory _newBaseExtension) external onlyOwner
function setBaseExtension(string memory _newBaseExtension) external onlyOwner
4,873
1
// Same ERC20 behavior, but require the token to be unlocked/_spender address The address which will spend the funds./_value uint256 The amount of tokens to be spent.
function approve(address _spender, uint256 _value) public onlyMintingFinished returns (bool) { return super.approve(_spender, _value); }
function approve(address _spender, uint256 _value) public onlyMintingFinished returns (bool) { return super.approve(_spender, _value); }
39,036
11
// Human supply. Genesis token categories from 1 to 10
uint256[11] private humansSupplyRobotsOwners = [ 0, 100, 100, 100, 100, 100, 100, 100, 100,
uint256[11] private humansSupplyRobotsOwners = [ 0, 100, 100, 100, 100, 100, 100, 100, 100,
21,042
112
// development fund
address public devAddr;
address public devAddr;
50,269
160
// The token will query the isTransferAllowed function contained in this contract
trustedToken.setController(this); trustedVault = new Vault( _wallet, _vaultInitialDisburseWei, _vaultDisbursementWei, // disbursement amount _vaultDisbursementDuration );
trustedToken.setController(this); trustedVault = new Vault( _wallet, _vaultInitialDisburseWei, _vaultDisbursementWei, // disbursement amount _vaultDisbursementDuration );
21,647
37
// Add this additional check to prevent any soft locks at round end, as the base balance must be 0 to end the round.
if (optionMarket.getLiveBoards().length == 0) { lockedCollateral.base = 0; }
if (optionMarket.getLiveBoards().length == 0) { lockedCollateral.base = 0; }
9,663
102
// Invests all underlying assets into active strategy /
function _investAllUnderlying() internal { if (!investActivated) { return; } uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this)); if (activeStrategy != ZERO_ADDRESS) { if (underlyingBalance > 0) { // deposits the entire balance to active strategy IERC20(underlying).safeTransfer( activeStrategy, underlyingBalance ); } IStrategy(activeStrategy).doHardWork(); } }
function _investAllUnderlying() internal { if (!investActivated) { return; } uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this)); if (activeStrategy != ZERO_ADDRESS) { if (underlyingBalance > 0) { // deposits the entire balance to active strategy IERC20(underlying).safeTransfer( activeStrategy, underlyingBalance ); } IStrategy(activeStrategy).doHardWork(); } }
11,768
0
// Initial distribution for the first 24h genesis pools
uint256 public constant INITIAL_GENESIS_POOL_DISTRIBUTION = 2400 ether;
uint256 public constant INITIAL_GENESIS_POOL_DISTRIBUTION = 2400 ether;
5,933
16
// Token claimed
function _setTokenDistributed(uint256 tokenId) internal { _tokensDistributed[tokenId] = true; }
function _setTokenDistributed(uint256 tokenId) internal { _tokensDistributed[tokenId] = true; }
23,213
23
// Token events
event TokenRewardSet(uint256 tokenReward); event TokenPaid(address riderAddress, uint256 amount);
event TokenRewardSet(uint256 tokenReward); event TokenPaid(address riderAddress, uint256 amount);
43,681
74
// Change to a new token sale address. (token owner only) _tokenSaleAddress address The new token sale address. /
function changeTokenSaleAddress(address _tokenSaleAddress) public onlyOwner validRecipient(_tokenSaleAddress)
function changeTokenSaleAddress(address _tokenSaleAddress) public onlyOwner validRecipient(_tokenSaleAddress)
8,651
172
// Contract state and constants
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); uint256 private _tokenIdCounter = 1; uint256 private _burnCounter; IFighterURIHandler private _handler;
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); uint256 private _tokenIdCounter = 1; uint256 private _burnCounter; IFighterURIHandler private _handler;
11,918
9
// Mints new tokens, increasing totalSupply, initSupply, and a users balance.Limited to onlyMinter modifier/
function mint(address to, uint256 amount) external onlyMinter returns (bool)
function mint(address to, uint256 amount) external onlyMinter returns (bool)
29,238
57
// Use _mint() instead of _safeMint() since any contract calling this must be directly doing so.
_mint(msg.sender, mintIndex);
_mint(msg.sender, mintIndex);
15,340
44
// Booster Pool
uint256 poolState = _boosterOld.migrateInitialize(cfolio); if ((poolState & 1) != 0) {
uint256 poolState = _boosterOld.migrateInitialize(cfolio); if ((poolState & 1) != 0) {
30,851
275
// Expire prior coupons
for (uint256 i = 0; i < expiringCoupons(epoch()); i++) { expireCouponsForEpoch(expiringCouponsAtIndex(epoch(), i)); }
for (uint256 i = 0; i < expiringCoupons(epoch()); i++) { expireCouponsForEpoch(expiringCouponsAtIndex(epoch(), i)); }
16,629
4
// 检查是否可以成功将该token转到红包合约地址下
require(token.transferFrom(msg.sender, address(this), _amount), "Token transfer fail");
require(token.transferFrom(msg.sender, address(this), _amount), "Token transfer fail");
26,846
191
// if _endTime == 0 so Event is endless
eventum.eventTimeToVotingClosing = _endTime == 0 ? timeToVotingClosing : 0; eventum.language = _language; TimeSettings memory _timeSettings; _timeSettings.endTime = _endTime; _timeSettings.canBeRestarted = _canBeRestarted; eventum.timeSettings = _timeSettings; allEvents[lastEventId] = eventum;
eventum.eventTimeToVotingClosing = _endTime == 0 ? timeToVotingClosing : 0; eventum.language = _language; TimeSettings memory _timeSettings; _timeSettings.endTime = _endTime; _timeSettings.canBeRestarted = _canBeRestarted; eventum.timeSettings = _timeSettings; allEvents[lastEventId] = eventum;
3,230
57
// check parents and grandparents
if (_parents[0] == _parents_1_2[0] || _parents[0] == _parents_1_2[1]) { _relatives = _relatives.add(1); }
if (_parents[0] == _parents_1_2[0] || _parents[0] == _parents_1_2[1]) { _relatives = _relatives.add(1); }
44,111
469
// Set the voter's submission.
voteSubmission.revealHash = keccak256(abi.encode(price));
voteSubmission.revealHash = keccak256(abi.encode(price));
51,836
230
// dont withdraw dust
if (_amount < debtThreshold) { return 0; }
if (_amount < debtThreshold) { return 0; }
27,458
110
// Units:[1e-18ether][cent/ether] / [cent/token] => [1e-18token]
uint amount = msg.value.mul(etherRate).div(tokenPrice); require(amount <= tokenRemainingForPublicSale, "Not enough tokens available"); require(amount >= tokenPurchaseMinimum, "Investment is too low");
uint amount = msg.value.mul(etherRate).div(tokenPrice); require(amount <= tokenRemainingForPublicSale, "Not enough tokens available"); require(amount >= tokenPurchaseMinimum, "Investment is too low");
20,135
64
// Returns the current ETH balance of account `account`account Account to return ETH balance for return Account's balance of ETH /
function getETHBalance(address account) external view returns (uint256) { return ethBalances[account] + (splits[account].hash != 0 ? account.balance : 0); }
function getETHBalance(address account) external view returns (uint256) { return ethBalances[account] + (splits[account].hash != 0 ? account.balance : 0); }
24,810
2,888
// 1446
entry "hatlessly" : ENG_ADVERB
entry "hatlessly" : ENG_ADVERB
22,282
69
// we need to represent the tokens with included decimals `2640(10 ^ 18)` not `2640`
if (remainingPreSaleTokens > 0) { remainingPreSaleTokens = remainingPreSaleTokens * (uint256(10) ** decimals); balances[owner] = balances[owner].sub(remainingPreSaleTokens); balances[ecosystemWallet] = balances[ecosystemWallet].add(remainingPreSaleTokens); Transfer(0, ecosystemWallet, remainingPreSaleTokens); }
if (remainingPreSaleTokens > 0) { remainingPreSaleTokens = remainingPreSaleTokens * (uint256(10) ** decimals); balances[owner] = balances[owner].sub(remainingPreSaleTokens); balances[ecosystemWallet] = balances[ecosystemWallet].add(remainingPreSaleTokens); Transfer(0, ecosystemWallet, remainingPreSaleTokens); }
21,327
87
// MarshmallowMarshmallow - Collect limited edition NFTs from Marshmallow /
contract MarshmallowMatic is ERC1155Tradable, ContextMixin, NativeMetaTransaction { constructor(string memory uri_) ERC1155Tradable(uri_, "XYZ", uri_) { _initializeEIP712(uri_); // uri_合约名 } /** * This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea. */ function _msgSender() internal override view returns (address payable sender) { return ContextMixin.msgSender(); } function contractURI() public view returns (string memory) { return ""; } }
contract MarshmallowMatic is ERC1155Tradable, ContextMixin, NativeMetaTransaction { constructor(string memory uri_) ERC1155Tradable(uri_, "XYZ", uri_) { _initializeEIP712(uri_); // uri_合约名 } /** * This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea. */ function _msgSender() internal override view returns (address payable sender) { return ContextMixin.msgSender(); } function contractURI() public view returns (string memory) { return ""; } }
16,207
33
// Role Management
function _roleHas(string memory _role, address _address) internal view returns (bool)
function _roleHas(string memory _role, address _address) internal view returns (bool)
14,309
8
// Returns ETH reward for specified tokenID in gwei, divide result by 10e18 for ETH value
function ethRewardForID(uint256 tokenId) public view returns (uint256) { return totalRewardPerToken - claimedReward[tokenId]; }
function ethRewardForID(uint256 tokenId) public view returns (uint256) { return totalRewardPerToken - claimedReward[tokenId]; }
54,544
6
// Array of vestings where the index is the vesting ID
Vesting[] public vestings;
Vesting[] public vestings;
59,378
20
// Gets the redeem threshold of the NFT self The NFT configurationreturn The redeem threshold /
function getRedeemThreshold(DataTypes.NftConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~REDEEM_THRESHOLD_MASK) >> REDEEM_THRESHOLD_START_BIT_POSITION; }
function getRedeemThreshold(DataTypes.NftConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~REDEEM_THRESHOLD_MASK) >> REDEEM_THRESHOLD_START_BIT_POSITION; }
13,587
10
// If no judge is specified, anybody can call this. If a judge is specified, then only the judge or winning bidder may call.
function finalize() public { if (judgeAddress == 0) { finalized = true; withdraw(); } else { if (msg.sender == judgeAddress || msg.sender == winnerAddress) { finalized = true; withdraw(); } else { revert('Unauthorized call.'); } } }
function finalize() public { if (judgeAddress == 0) { finalized = true; withdraw(); } else { if (msg.sender == judgeAddress || msg.sender == winnerAddress) { finalized = true; withdraw(); } else { revert('Unauthorized call.'); } } }
36,594
16
// DVM price request identifier that is resolved based on the validity of a relay attempt.
bytes32 public identifier;
bytes32 public identifier;
7,960
273
// Return whether a transcoder was active during a round _transcoder Transcoder address _round Round number /
function isActiveTranscoder(address _transcoder, uint256 _round) public view returns (bool) { return activeTranscoderSet[_round].isActive[_transcoder]; }
function isActiveTranscoder(address _transcoder, uint256 _round) public view returns (bool) { return activeTranscoderSet[_round].isActive[_transcoder]; }
24,758
357
// Returns the downcasted uint64 from uint256, reverting onoverflow (when the input is greater than largest uint64). Counterpart to Solidity's `uint64` operator. Requirements: - input must fit into 64 bits /
function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); }
function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); }
9,304
63
// return decimals' value
function getDecimals() public view returns (uint256) { return decimals; }
function getDecimals() public view returns (uint256) { return decimals; }
17,554
16
// ======================================STAKING POOL=========================================
address public Axiatoken; address public administrator; bool public stakingEnabled; uint256 constant private FLOAT_SCALAR = 2**64; uint256 public MINIMUM_STAKE = 1000000000000000000; // 1000 AXIA Tokens uint256 public MIN_DIVIDENDS_DUR = 86400; uint256 private UNSTAKE_FEE = 1; //1% burns when you unstake
address public Axiatoken; address public administrator; bool public stakingEnabled; uint256 constant private FLOAT_SCALAR = 2**64; uint256 public MINIMUM_STAKE = 1000000000000000000; // 1000 AXIA Tokens uint256 public MIN_DIVIDENDS_DUR = 86400; uint256 private UNSTAKE_FEE = 1; //1% burns when you unstake
8,298
2
// Emitted when the ACO fee has been changed. previousAcoFee Value of the previous ACO fee. newAcoFee Value of the new ACO fee. /
event SetAcoFee(uint256 previousAcoFee, uint256 newAcoFee);
event SetAcoFee(uint256 previousAcoFee, uint256 newAcoFee);
991
26
// Pass an active join adapter to the registry to add it to the set
function add(address adapter) external { JoinLike _join = JoinLike(adapter); // Validate adapter require(_join.vat() == address(vat), "IlkRegistry/invalid-join-adapter-vat"); require(vat.wards(address(_join)) == 1, "IlkRegistry/adapter-not-authorized"); // Validate ilk bytes32 _ilk = _join.ilk(); require(_ilk != 0, "IlkRegistry/ilk-adapter-invalid"); require(ilkData[_ilk].join == address(0), "IlkRegistry/ilk-already-exists"); (address _pip,) = spot.ilks(_ilk); require(_pip != address(0), "IlkRegistry/pip-invalid"); (address _xlip,,,) = dog.ilks(_ilk); uint96 _class = 1; if (_xlip == address(0)) { (_xlip,,) = cat.ilks(_ilk); require(_xlip != address(0), "IlkRegistry/invalid-auction-contract"); _class = 2; } string memory name = bytes32ToStr(_ilk); try gemInfo.name(_join.gem()) returns (string memory _name) { if (bytes(_name).length != 0) { name = _name; } } catch { emit NameError(_ilk); } string memory symbol = bytes32ToStr(_ilk); try gemInfo.symbol(_join.gem()) returns (string memory _symbol) { if (bytes(_symbol).length != 0) { symbol = _symbol; } } catch { emit SymbolError(_ilk); } require(ilks.length < uint96(-1), "IlkRegistry/too-many-ilks"); ilks.push(_ilk); ilkData[ilks[ilks.length - 1]] = Ilk({ pos: uint96(ilks.length - 1), join: address(_join), gem: _join.gem(), dec: uint8(_join.dec()), class: _class, pip: _pip, xlip: _xlip, name: name, symbol: symbol }); emit AddIlk(_ilk); }
function add(address adapter) external { JoinLike _join = JoinLike(adapter); // Validate adapter require(_join.vat() == address(vat), "IlkRegistry/invalid-join-adapter-vat"); require(vat.wards(address(_join)) == 1, "IlkRegistry/adapter-not-authorized"); // Validate ilk bytes32 _ilk = _join.ilk(); require(_ilk != 0, "IlkRegistry/ilk-adapter-invalid"); require(ilkData[_ilk].join == address(0), "IlkRegistry/ilk-already-exists"); (address _pip,) = spot.ilks(_ilk); require(_pip != address(0), "IlkRegistry/pip-invalid"); (address _xlip,,,) = dog.ilks(_ilk); uint96 _class = 1; if (_xlip == address(0)) { (_xlip,,) = cat.ilks(_ilk); require(_xlip != address(0), "IlkRegistry/invalid-auction-contract"); _class = 2; } string memory name = bytes32ToStr(_ilk); try gemInfo.name(_join.gem()) returns (string memory _name) { if (bytes(_name).length != 0) { name = _name; } } catch { emit NameError(_ilk); } string memory symbol = bytes32ToStr(_ilk); try gemInfo.symbol(_join.gem()) returns (string memory _symbol) { if (bytes(_symbol).length != 0) { symbol = _symbol; } } catch { emit SymbolError(_ilk); } require(ilks.length < uint96(-1), "IlkRegistry/too-many-ilks"); ilks.push(_ilk); ilkData[ilks[ilks.length - 1]] = Ilk({ pos: uint96(ilks.length - 1), join: address(_join), gem: _join.gem(), dec: uint8(_join.dec()), class: _class, pip: _pip, xlip: _xlip, name: name, symbol: symbol }); emit AddIlk(_ilk); }
23,969
198
// Withdraw the fTokens
IRewardPool(vaultFarm).withdraw(_wrappedWithdrawnFromFarm);
IRewardPool(vaultFarm).withdraw(_wrappedWithdrawnFromFarm);
24,470
206
// Penalize a relay that signed two transactions using the same nonce (making only the first one valid) anddifferent data (gas price, gas limit, etc. may be different). The (unsigned) transaction data and signature for both transactions must be provided. /
function penalizeRepeatedNonce(bytes memory unsignedTx1, bytes memory signature1, bytes memory unsignedTx2, bytes memory signature2) public;
function penalizeRepeatedNonce(bytes memory unsignedTx1, bytes memory signature1, bytes memory unsignedTx2, bytes memory signature2) public;
16,388
42
// --------------------------------------------------------- Существительные, допускающие правое предложное дополнение с предлогом TO ---------------------------------------------------------
wordentry_set Noun2Noun_TO=eng_noun:{ duty, // Duty on automobiles depends on their value. right, // The right to equal treatment in the criminal justice system regard, // The sentence is translated without regard to the context. home, // Alberta is home to many large carnivores. quota, // There is no quota to South Korean citizens. release, // Initial releases into Florida failed. response, // Jejune responses to our problems. way, // John will be speeding on his way to Paris answer, // Find an answer to it. solution, // Find a solution to it. dislike, // Although he tried to hide it, the headmaster took a strong dislike to George and me. (сущ+предлог to) threat, // The threats to computing science trip, // He warmed to the idea of a trip to Antarctica. contributor, successor, // The successor to Delors was Jacques Santer. limitation, // What is the MAJOR limitation to the use of robots? approach, // Two approaches to synthesis are used commercially. train // She hopped a train to Chicago. }
wordentry_set Noun2Noun_TO=eng_noun:{ duty, // Duty on automobiles depends on their value. right, // The right to equal treatment in the criminal justice system regard, // The sentence is translated without regard to the context. home, // Alberta is home to many large carnivores. quota, // There is no quota to South Korean citizens. release, // Initial releases into Florida failed. response, // Jejune responses to our problems. way, // John will be speeding on his way to Paris answer, // Find an answer to it. solution, // Find a solution to it. dislike, // Although he tried to hide it, the headmaster took a strong dislike to George and me. (сущ+предлог to) threat, // The threats to computing science trip, // He warmed to the idea of a trip to Antarctica. contributor, successor, // The successor to Delors was Jacques Santer. limitation, // What is the MAJOR limitation to the use of robots? approach, // Two approaches to synthesis are used commercially. train // She hopped a train to Chicago. }
19,354
11
// Modifiers:
modifier onlyRegisteredScheme() { require(schemes[msg.sender].permissions&bytes4(0x00000001) == bytes4(0x00000001)); _; }
modifier onlyRegisteredScheme() { require(schemes[msg.sender].permissions&bytes4(0x00000001) == bytes4(0x00000001)); _; }
10,449
31
// Approves the specified amount of tokens to the specified spender. owner The owner of the tokens. spender The spender to approve for spending the tokens. amount The amount of tokens to approve. /
function _approve(address owner, address spender, uint256 amount) private { // Make sure the owner and spender addresses are not zero require(owner != address(0) && spender != address(0), "Err"); // Set the allowance for the specified owner and spender _allowances[owner][spender] = amount; // Emit an Approval event emit Approval(owner, spender, amount); }
function _approve(address owner, address spender, uint256 amount) private { // Make sure the owner and spender addresses are not zero require(owner != address(0) && spender != address(0), "Err"); // Set the allowance for the specified owner and spender _allowances[owner][spender] = amount; // Emit an Approval event emit Approval(owner, spender, amount); }
26,407
1
// Create Ownable MultiSig Timelock wallet with chosen approvers and amount of approvals needed for quorum//_approvers addresses which are approvers of the Multi-Sig/_quorum amount of approvers needed to send transfer/_beneficiary only address which can request a 'send transfer' and 'close wallet' function.
constructor(address[] memory _approvers, uint _quorum, address payable _beneficiary) validRequirement(_approvers.length, _quorum) { approvers = _approvers; quorum = _quorum; beneficiary = _beneficiary; }
constructor(address[] memory _approvers, uint _quorum, address payable _beneficiary) validRequirement(_approvers.length, _quorum) { approvers = _approvers; quorum = _quorum; beneficiary = _beneficiary; }
2,591
127
// https:docs.synthetix.io/contracts/source/contracts/binaryoption
contract BinaryOption is IERC20, IBinaryOption { /* ========== LIBRARIES ========== */ using SafeMath for uint; using SafeDecimalMath for uint; /* ========== STATE VARIABLES ========== */ string public constant name = "SNX Binary Option"; string public constant symbol = "sOPT"; uint8 public constant decimals = 18; BinaryOptionMarket public market; mapping(address => uint) public bidOf; uint public totalBids; mapping(address => uint) public balanceOf; uint public totalSupply; // The argument order is allowance[owner][spender] mapping(address => mapping(address => uint)) public allowance; // Enforce a 1 cent minimum bid balance uint internal constant _MINIMUM_BID = 1e16; /* ========== CONSTRUCTOR ========== */ constructor(address initialBidder, uint initialBid) public { market = BinaryOptionMarket(msg.sender); bidOf[initialBidder] = initialBid; totalBids = initialBid; } /* ========== VIEWS ========== */ function _claimableBalanceOf( uint _bid, uint price, uint exercisableDeposits ) internal view returns (uint) { uint owed = _bid.divideDecimal(price); uint supply = _totalClaimableSupply(exercisableDeposits); /* The last claimant might be owed slightly more or less than the actual remaining deposit based on rounding errors with the price. Therefore if the user's bid is the entire rest of the pot, just give them everything that's left. If there is no supply, then this option lost, and we'll return 0. */ if ((_bid == totalBids && _bid != 0) || supply == 0) { return supply; } /* Note that option supply on the losing side and deposits can become decoupled, but losing options are not claimable, therefore we only need to worry about the situation where supply < owed on the winning side. If somehow a user who is not the last bidder is owed more than what's available, subsequent bidders will be disadvantaged. Given that the minimum bid is 10^16 wei, this should never occur in reality. */ require(owed <= supply, "supply < claimable"); return owed; } function claimableBalanceOf(address account) external view returns (uint) { (uint price, uint exercisableDeposits) = market.senderPriceAndExercisableDeposits(); return _claimableBalanceOf(bidOf[account], price, exercisableDeposits); } function _totalClaimableSupply(uint exercisableDeposits) internal view returns (uint) { uint _totalSupply = totalSupply; // We'll avoid throwing an exception here to avoid breaking any dapps, but this case // should never occur given the minimum bid size. if (exercisableDeposits <= _totalSupply) { return 0; } return exercisableDeposits.sub(_totalSupply); } function totalClaimableSupply() external view returns (uint) { (, uint exercisableDeposits) = market.senderPriceAndExercisableDeposits(); return _totalClaimableSupply(exercisableDeposits); } /* ========== MUTATIVE FUNCTIONS ========== */ function _requireMinimumBid(uint bid) internal pure returns (uint) { require(bid >= _MINIMUM_BID || bid == 0, "Balance < $0.01"); return bid; } // This must only be invoked during bidding. function bid(address bidder, uint newBid) external onlyMarket { bidOf[bidder] = _requireMinimumBid(bidOf[bidder].add(newBid)); totalBids = totalBids.add(newBid); } // This must only be invoked during bidding. function refund(address bidder, uint newRefund) external onlyMarket { // The safe subtraction will catch refunds that are too large. bidOf[bidder] = _requireMinimumBid(bidOf[bidder].sub(newRefund)); totalBids = totalBids.sub(newRefund); } // This must only be invoked after bidding. function claim( address claimant, uint price, uint depositsRemaining ) external onlyMarket returns (uint optionsClaimed) { uint _bid = bidOf[claimant]; uint claimable = _claimableBalanceOf(_bid, price, depositsRemaining); // No options to claim? Nothing happens. if (claimable == 0) { return 0; } totalBids = totalBids.sub(_bid); bidOf[claimant] = 0; totalSupply = totalSupply.add(claimable); balanceOf[claimant] = balanceOf[claimant].add(claimable); // Increment rather than assigning since a transfer may have occurred. emit Transfer(address(0), claimant, claimable); emit Issued(claimant, claimable); return claimable; } // This must only be invoked after maturity. function exercise(address claimant) external onlyMarket { uint balance = balanceOf[claimant]; if (balance == 0) { return; } balanceOf[claimant] = 0; totalSupply = totalSupply.sub(balance); emit Transfer(claimant, address(0), balance); emit Burned(claimant, balance); } // This must only be invoked after the exercise window is complete. // Note that any options which have not been exercised will linger. function expire(address payable beneficiary) external onlyMarket { selfdestruct(beneficiary); } /* ---------- ERC20 Functions ---------- */ // This should only operate after bidding; // Since options can't be claimed until after bidding, all balances are zero until that time. // So we don't need to explicitly check the timestamp to prevent transfers. function _transfer( address _from, address _to, uint _value ) internal returns (bool success) { market.requireActiveAndUnpaused(); require(_to != address(0) && _to != address(this), "Invalid address"); uint fromBalance = balanceOf[_from]; require(_value <= fromBalance, "Insufficient balance"); balanceOf[_from] = fromBalance.sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(_from, _to, _value); return true; } function transfer(address _to, uint _value) external returns (bool success) { return _transfer(msg.sender, _to, _value); } function transferFrom( address _from, address _to, uint _value ) external returns (bool success) { uint fromAllowance = allowance[_from][msg.sender]; require(_value <= fromAllowance, "Insufficient allowance"); allowance[_from][msg.sender] = fromAllowance.sub(_value); return _transfer(_from, _to, _value); } function approve(address _spender, uint _value) external returns (bool success) { require(_spender != address(0)); allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /* ========== MODIFIERS ========== */ modifier onlyMarket() { require(msg.sender == address(market), "Only market allowed"); _; } /* ========== EVENTS ========== */ event Issued(address indexed account, uint value); event Burned(address indexed account, uint value); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); }
contract BinaryOption is IERC20, IBinaryOption { /* ========== LIBRARIES ========== */ using SafeMath for uint; using SafeDecimalMath for uint; /* ========== STATE VARIABLES ========== */ string public constant name = "SNX Binary Option"; string public constant symbol = "sOPT"; uint8 public constant decimals = 18; BinaryOptionMarket public market; mapping(address => uint) public bidOf; uint public totalBids; mapping(address => uint) public balanceOf; uint public totalSupply; // The argument order is allowance[owner][spender] mapping(address => mapping(address => uint)) public allowance; // Enforce a 1 cent minimum bid balance uint internal constant _MINIMUM_BID = 1e16; /* ========== CONSTRUCTOR ========== */ constructor(address initialBidder, uint initialBid) public { market = BinaryOptionMarket(msg.sender); bidOf[initialBidder] = initialBid; totalBids = initialBid; } /* ========== VIEWS ========== */ function _claimableBalanceOf( uint _bid, uint price, uint exercisableDeposits ) internal view returns (uint) { uint owed = _bid.divideDecimal(price); uint supply = _totalClaimableSupply(exercisableDeposits); /* The last claimant might be owed slightly more or less than the actual remaining deposit based on rounding errors with the price. Therefore if the user's bid is the entire rest of the pot, just give them everything that's left. If there is no supply, then this option lost, and we'll return 0. */ if ((_bid == totalBids && _bid != 0) || supply == 0) { return supply; } /* Note that option supply on the losing side and deposits can become decoupled, but losing options are not claimable, therefore we only need to worry about the situation where supply < owed on the winning side. If somehow a user who is not the last bidder is owed more than what's available, subsequent bidders will be disadvantaged. Given that the minimum bid is 10^16 wei, this should never occur in reality. */ require(owed <= supply, "supply < claimable"); return owed; } function claimableBalanceOf(address account) external view returns (uint) { (uint price, uint exercisableDeposits) = market.senderPriceAndExercisableDeposits(); return _claimableBalanceOf(bidOf[account], price, exercisableDeposits); } function _totalClaimableSupply(uint exercisableDeposits) internal view returns (uint) { uint _totalSupply = totalSupply; // We'll avoid throwing an exception here to avoid breaking any dapps, but this case // should never occur given the minimum bid size. if (exercisableDeposits <= _totalSupply) { return 0; } return exercisableDeposits.sub(_totalSupply); } function totalClaimableSupply() external view returns (uint) { (, uint exercisableDeposits) = market.senderPriceAndExercisableDeposits(); return _totalClaimableSupply(exercisableDeposits); } /* ========== MUTATIVE FUNCTIONS ========== */ function _requireMinimumBid(uint bid) internal pure returns (uint) { require(bid >= _MINIMUM_BID || bid == 0, "Balance < $0.01"); return bid; } // This must only be invoked during bidding. function bid(address bidder, uint newBid) external onlyMarket { bidOf[bidder] = _requireMinimumBid(bidOf[bidder].add(newBid)); totalBids = totalBids.add(newBid); } // This must only be invoked during bidding. function refund(address bidder, uint newRefund) external onlyMarket { // The safe subtraction will catch refunds that are too large. bidOf[bidder] = _requireMinimumBid(bidOf[bidder].sub(newRefund)); totalBids = totalBids.sub(newRefund); } // This must only be invoked after bidding. function claim( address claimant, uint price, uint depositsRemaining ) external onlyMarket returns (uint optionsClaimed) { uint _bid = bidOf[claimant]; uint claimable = _claimableBalanceOf(_bid, price, depositsRemaining); // No options to claim? Nothing happens. if (claimable == 0) { return 0; } totalBids = totalBids.sub(_bid); bidOf[claimant] = 0; totalSupply = totalSupply.add(claimable); balanceOf[claimant] = balanceOf[claimant].add(claimable); // Increment rather than assigning since a transfer may have occurred. emit Transfer(address(0), claimant, claimable); emit Issued(claimant, claimable); return claimable; } // This must only be invoked after maturity. function exercise(address claimant) external onlyMarket { uint balance = balanceOf[claimant]; if (balance == 0) { return; } balanceOf[claimant] = 0; totalSupply = totalSupply.sub(balance); emit Transfer(claimant, address(0), balance); emit Burned(claimant, balance); } // This must only be invoked after the exercise window is complete. // Note that any options which have not been exercised will linger. function expire(address payable beneficiary) external onlyMarket { selfdestruct(beneficiary); } /* ---------- ERC20 Functions ---------- */ // This should only operate after bidding; // Since options can't be claimed until after bidding, all balances are zero until that time. // So we don't need to explicitly check the timestamp to prevent transfers. function _transfer( address _from, address _to, uint _value ) internal returns (bool success) { market.requireActiveAndUnpaused(); require(_to != address(0) && _to != address(this), "Invalid address"); uint fromBalance = balanceOf[_from]; require(_value <= fromBalance, "Insufficient balance"); balanceOf[_from] = fromBalance.sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(_from, _to, _value); return true; } function transfer(address _to, uint _value) external returns (bool success) { return _transfer(msg.sender, _to, _value); } function transferFrom( address _from, address _to, uint _value ) external returns (bool success) { uint fromAllowance = allowance[_from][msg.sender]; require(_value <= fromAllowance, "Insufficient allowance"); allowance[_from][msg.sender] = fromAllowance.sub(_value); return _transfer(_from, _to, _value); } function approve(address _spender, uint _value) external returns (bool success) { require(_spender != address(0)); allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /* ========== MODIFIERS ========== */ modifier onlyMarket() { require(msg.sender == address(market), "Only market allowed"); _; } /* ========== EVENTS ========== */ event Issued(address indexed account, uint value); event Burned(address indexed account, uint value); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); }
14,473
0
// A call to simulate
struct Call { address target; uint256 value; bytes callData; }
struct Call { address target; uint256 value; bytes callData; }
20,681
161
// Read ticket variable /
function getTicket() external view returns (ITicket);
function getTicket() external view returns (ITicket);
69,798
90
// Update lockedTokens amount before using it in computations after.
updateAccounting(); uint256 lockedTokens = totalLocked(); uint256 mintedLockedShares = (lockedTokens > 0) ? totalLockedShares.mul(amount).div(lockedTokens) : amount.mul(_initialSharesPerToken); UnlockSchedule memory schedule; schedule.initialLockedShares = mintedLockedShares; schedule.lastUnlockTimestampSec = now;
updateAccounting(); uint256 lockedTokens = totalLocked(); uint256 mintedLockedShares = (lockedTokens > 0) ? totalLockedShares.mul(amount).div(lockedTokens) : amount.mul(_initialSharesPerToken); UnlockSchedule memory schedule; schedule.initialLockedShares = mintedLockedShares; schedule.lastUnlockTimestampSec = now;
32,020
32
// Function to handle fee-free transfers
function _handleFeeFreeTransfer(address sender, address recipient, uint256 amount, bool isTransferFrom) internal { if (isTransferFrom) { super.transferFrom(sender, recipient, amount); } else { super.transfer(recipient, amount); } }
function _handleFeeFreeTransfer(address sender, address recipient, uint256 amount, bool isTransferFrom) internal { if (isTransferFrom) { super.transferFrom(sender, recipient, amount); } else { super.transfer(recipient, amount); } }
2,737
99
// for everything but the last hat level, check the admin of `_newAdminHat`'s theoretical child hat, since either wearer or admin of `_newAdminHat` can approve
if (getHatLevel(_newAdminHat) < MAX_LEVELS) { _checkAdmin(buildHatId(_newAdminHat, 1)); } else {
if (getHatLevel(_newAdminHat) < MAX_LEVELS) { _checkAdmin(buildHatId(_newAdminHat, 1)); } else {
21,998
1
// uint for unsigned integet value
uint8 u8 = 1; uint u = 111; // default size is 256
uint8 u8 = 1; uint u = 111; // default size is 256
53,111
179
// bit things
uint256 BITSHIFT_AMOUNT = 8;
uint256 BITSHIFT_AMOUNT = 8;
79,048
142
// Reentrancy guard. Allow owner to drain the pool even if frozen.
require(_status == RE_NOT_ENTERED || (_status == RE_FROZEN && msg.sender == _owner)); _status = RE_ENTERED;
require(_status == RE_NOT_ENTERED || (_status == RE_FROZEN && msg.sender == _owner)); _status = RE_ENTERED;
9,205
170
// Whether `a` is less than or equal to `b`. a a FixedPoint. b a uint256.return True if `a <= b`, or False. /
function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledUint(b).rawValue; }
function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledUint(b).rawValue; }
53,784
333
// _key the key for the contract address _value the contract address /
function setAddress(bytes32 _key, address _value) private { // main map for cheap lookup addressStorage[_key] = _value; // keep track of contract address history addressStorageHistory[_key].push(_value); }
function setAddress(bytes32 _key, address _value) private { // main map for cheap lookup addressStorage[_key] = _value; // keep track of contract address history addressStorageHistory[_key].push(_value); }
55,935
1
// how many votes this address has sent out this cycle
uint voterCycleKey = createKey(_nextPublishTime, _voter); return outgoingPostBackings[voterCycleKey];
uint voterCycleKey = createKey(_nextPublishTime, _voter); return outgoingPostBackings[voterCycleKey];
42,537
37
// Temporary - Migrating Native// Adds native token balance to the account. This is meant to allow for native tokento be migrated from an old gateway to a new gateway.NOTE: This is left for one upgrade only so we are able to receive the migrated native tokenfrom the old contract /
function donateNative() external payable {} }
function donateNative() external payable {} }
29,260
48
// Because the iteration is bounded by `tokenAmount`, and no tokens are registered or deregistered here, we know `i` is a valid token index and can use `unchecked_valueAt` to save storage reads.
bytes32 balance = poolBalances.unchecked_valueAt(i); currentBalances[i] = balance.total(); request.lastChangeBlock = Math.max(request.lastChangeBlock, balance.lastChangeBlock()); if (i == indexIn) { tokenInBalance = balance; } else if (i == indexOut) {
bytes32 balance = poolBalances.unchecked_valueAt(i); currentBalances[i] = balance.total(); request.lastChangeBlock = Math.max(request.lastChangeBlock, balance.lastChangeBlock()); if (i == indexIn) { tokenInBalance = balance; } else if (i == indexOut) {
19,433
4
// Removes a User/_user The address of the User contract to remove/This function removes from the storage the User contract and then removes from the map of addresses the attached User contract. The User contract is still alive, its destruction depends on its owner
function deleteUser(User _user) external { require(userAddresses[msg.sender] == _user, "You cannot remove other's user's contracts"); delete userAddresses[msg.sender]; users.remove(address(_user)); }
function deleteUser(User _user) external { require(userAddresses[msg.sender] == _user, "You cannot remove other's user's contracts"); delete userAddresses[msg.sender]; users.remove(address(_user)); }
13,297
158
// Returns the EIP712 domain separator. /
function getDomainSeparator() external view returns (bytes32);
function getDomainSeparator() external view returns (bytes32);
1,593
5
// _owner The address of the account owning tokens/_spender The address of the account able to transfer the tokens/ return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint remaining) {}
function allowance(address _owner, address _spender) constant returns (uint remaining) {}
2,301
51
// --- Treasury Maintenance ---/ Transfer surplus stability fees to the extraSurplusReceiver. This is here to make sure that the treasury /
function transferSurplusFunds() external { require(now >= addition(latestSurplusTransferTime, surplusTransferDelay), "StabilityFeeTreasury/transfer-cooldown-not-passed"); // Compute latest expenses uint256 latestExpenses = subtract(expensesAccumulator, accumulatorTag); // Check if we need to keep more funds than the total capacity uint256 remainingFunds = (treasuryCapacity <= divide(multiply(expensesMultiplier, latestExpenses), HUNDRED)) ? divide(multiply(expensesMultiplier, latestExpenses), HUNDRED) : treasuryCapacity; // Make sure to keep at least minimum funds remainingFunds = (divide(multiply(expensesMultiplier, latestExpenses), HUNDRED) <= minimumFundsRequired) ? minimumFundsRequired : remainingFunds; // Set internal vars accumulatorTag = expensesAccumulator; latestSurplusTransferTime = now; // Join all coins in system joinAllCoins(); // Settle outstanding bad debt settleDebt(); // Check that there's no bad debt left require(safeEngine.debtBalance(address(this)) == 0, "StabilityFeeTreasury/outstanding-bad-debt"); // Check if we have too much money if (safeEngine.coinBalance(address(this)) > remainingFunds) { // Make sure that we still keep min SF in treasury uint256 fundsToTransfer = subtract(safeEngine.coinBalance(address(this)), remainingFunds); // Transfer surplus to accounting engine safeEngine.transferInternalCoins(address(this), extraSurplusReceiver, fundsToTransfer); // Emit event emit TransferSurplusFunds(extraSurplusReceiver, fundsToTransfer); } }
function transferSurplusFunds() external { require(now >= addition(latestSurplusTransferTime, surplusTransferDelay), "StabilityFeeTreasury/transfer-cooldown-not-passed"); // Compute latest expenses uint256 latestExpenses = subtract(expensesAccumulator, accumulatorTag); // Check if we need to keep more funds than the total capacity uint256 remainingFunds = (treasuryCapacity <= divide(multiply(expensesMultiplier, latestExpenses), HUNDRED)) ? divide(multiply(expensesMultiplier, latestExpenses), HUNDRED) : treasuryCapacity; // Make sure to keep at least minimum funds remainingFunds = (divide(multiply(expensesMultiplier, latestExpenses), HUNDRED) <= minimumFundsRequired) ? minimumFundsRequired : remainingFunds; // Set internal vars accumulatorTag = expensesAccumulator; latestSurplusTransferTime = now; // Join all coins in system joinAllCoins(); // Settle outstanding bad debt settleDebt(); // Check that there's no bad debt left require(safeEngine.debtBalance(address(this)) == 0, "StabilityFeeTreasury/outstanding-bad-debt"); // Check if we have too much money if (safeEngine.coinBalance(address(this)) > remainingFunds) { // Make sure that we still keep min SF in treasury uint256 fundsToTransfer = subtract(safeEngine.coinBalance(address(this)), remainingFunds); // Transfer surplus to accounting engine safeEngine.transferInternalCoins(address(this), extraSurplusReceiver, fundsToTransfer); // Emit event emit TransferSurplusFunds(extraSurplusReceiver, fundsToTransfer); } }
28,358
24
// @TODO should we allow setting to any arb value here?
privileges[addrs[i]] = bytes32(uint(1)); emit LogPrivilegeChanged(addrs[i], bytes32(uint(1)));
privileges[addrs[i]] = bytes32(uint(1)); emit LogPrivilegeChanged(addrs[i], bytes32(uint(1)));
37,949
15
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0);
uint256 _tokens = purchaseTokens(_dividends, 0x0);
44,007
54
// Calles by Jury.Online to retrieve commission
function withdrawEther() public { if (msg.sender == juryOperator) { require(juryOnlineWallet.send(etherAllowance)); //require(jotter.call.value(jotAllowance)(abi.encodeWithSignature("swapMe()"))); etherAllowance = 0; jotAllowance = 0; } }
function withdrawEther() public { if (msg.sender == juryOperator) { require(juryOnlineWallet.send(etherAllowance)); //require(jotter.call.value(jotAllowance)(abi.encodeWithSignature("swapMe()"))); etherAllowance = 0; jotAllowance = 0; } }
135
290
// Amount of rewards that can be harvested in the underlying. Includes rewards for CRV, CVX & Extra Rewards.return Estimated amount of underlying available to harvest. /
function harvestable() external view override returns (uint256) { IRewardStaking rewards_ = rewards; uint256 crvAmount_ = rewards_.earned(address(this)); if (crvAmount_ == 0) return 0; uint256 harvestable_ = _underlyingAmountOut( address(_CRV), crvAmount_.scaledMul(ScaledMath.ONE - crvCommunityReserveShare) ) + _underlyingAmountOut( address(_CVX), getCvxMintAmount(crvAmount_).scaledMul(ScaledMath.ONE - cvxCommunityReserveShare) ); uint256 length_ = _rewardTokens.length(); for (uint256 i; i < length_; i = i.uncheckedInc()) { IRewardStaking extraRewards_ = IRewardStaking(rewards_.extraRewards(i)); address rewardToken_ = extraRewards_.rewardToken(); if (!_rewardTokens.contains(rewardToken_)) continue; harvestable_ += _underlyingAmountOut(rewardToken_, extraRewards_.earned(address(this))); } return harvestable_; }
function harvestable() external view override returns (uint256) { IRewardStaking rewards_ = rewards; uint256 crvAmount_ = rewards_.earned(address(this)); if (crvAmount_ == 0) return 0; uint256 harvestable_ = _underlyingAmountOut( address(_CRV), crvAmount_.scaledMul(ScaledMath.ONE - crvCommunityReserveShare) ) + _underlyingAmountOut( address(_CVX), getCvxMintAmount(crvAmount_).scaledMul(ScaledMath.ONE - cvxCommunityReserveShare) ); uint256 length_ = _rewardTokens.length(); for (uint256 i; i < length_; i = i.uncheckedInc()) { IRewardStaking extraRewards_ = IRewardStaking(rewards_.extraRewards(i)); address rewardToken_ = extraRewards_.rewardToken(); if (!_rewardTokens.contains(rewardToken_)) continue; harvestable_ += _underlyingAmountOut(rewardToken_, extraRewards_.earned(address(this))); } return harvestable_; }
31,690