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
19
// decide what to do depending on whether this investor is already authorized
Investor storage investor = investors[msg.sender]; if (!investor.exists) { investor_list.push(msg.sender); investor.exists = true; }
Investor storage investor = investors[msg.sender]; if (!investor.exists) { investor_list.push(msg.sender); investor.exists = true; }
38,203
3
// trigger when deploy
constructor(IERC20 _erc20Token, address _beneficiary, uint256 _floorPrice, uint256 _startTime, uint256 _endTime, uint256 _tokenIssue, uint256 _feePercent, uint256 _redeemQty) { require(_startTime > block.timestamp, 'Auction start timestamp is invalid!'); require(_endTime > block.timestamp && _endTime > _startTime, 'Auction end timestamp can not be the past or invalid!'); require(_beneficiary != address(0x0), 'Beneficiary address is not correct!'); erc20Token = _erc20Token; beneficiary = _beneficiary; floorPrice = _floorPrice; startTime = _startTime; endTime = _endTime;
constructor(IERC20 _erc20Token, address _beneficiary, uint256 _floorPrice, uint256 _startTime, uint256 _endTime, uint256 _tokenIssue, uint256 _feePercent, uint256 _redeemQty) { require(_startTime > block.timestamp, 'Auction start timestamp is invalid!'); require(_endTime > block.timestamp && _endTime > _startTime, 'Auction end timestamp can not be the past or invalid!'); require(_beneficiary != address(0x0), 'Beneficiary address is not correct!'); erc20Token = _erc20Token; beneficiary = _beneficiary; floorPrice = _floorPrice; startTime = _startTime; endTime = _endTime;
18,117
29
// The block at which voting begins: holders must delegate their votes prior to this block
uint256 startBlock;
uint256 startBlock;
13,840
288
// We check that the amount is less than or equal to supplyCurrent If amount is greater than supplyCurrent, this will fail with Error.INTEGER_UNDERFLOW
(err, localResults.userSupplyUpdated) = sub( localResults.userSupplyCurrent, localResults.withdrawAmount ); if (err != Error.NO_ERROR) { return fail( Error.INSUFFICIENT_BALANCE, FailureInfo.WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED );
(err, localResults.userSupplyUpdated) = sub( localResults.userSupplyCurrent, localResults.withdrawAmount ); if (err != Error.NO_ERROR) { return fail( Error.INSUFFICIENT_BALANCE, FailureInfo.WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED );
21,048
11
// Deploys a LmPool/pool The contract address of the PancakeSwap V3 pool
function deploy(IPancakeV3PoolWithLMPool pool) external onlyOwner returns (IPancakeV3LmPool lmPool) { require(whiteList[address(pool)], 'Not in whiteList'); require(!LMPoolUpdateFlag[address(pool)], 'Already Updated'); LMPoolUpdateFlag[address(pool)] = true; address oldLMPool = pool.lmPool(); parameters = Parameters({pool: address(pool), masterChef: masterChef, oldLMPool: oldLMPool}); lmPool = new PancakeV3LmPool{salt: keccak256(abi.encode(address(pool), masterChef, block.timestamp))}(); delete parameters; // Set new LMPool for pancake v3 pool. IPancakeV3Factory(INonfungiblePositionManager(IMasterChefV3(masterChef).nonfungiblePositionManager()).factory()) .setLmPool(address(pool), address(lmPool)); // Initialize the new LMPool. lmPool.initialize(); emit NewLMPool(address(pool), address(lmPool)); }
function deploy(IPancakeV3PoolWithLMPool pool) external onlyOwner returns (IPancakeV3LmPool lmPool) { require(whiteList[address(pool)], 'Not in whiteList'); require(!LMPoolUpdateFlag[address(pool)], 'Already Updated'); LMPoolUpdateFlag[address(pool)] = true; address oldLMPool = pool.lmPool(); parameters = Parameters({pool: address(pool), masterChef: masterChef, oldLMPool: oldLMPool}); lmPool = new PancakeV3LmPool{salt: keccak256(abi.encode(address(pool), masterChef, block.timestamp))}(); delete parameters; // Set new LMPool for pancake v3 pool. IPancakeV3Factory(INonfungiblePositionManager(IMasterChefV3(masterChef).nonfungiblePositionManager()).factory()) .setLmPool(address(pool), address(lmPool)); // Initialize the new LMPool. lmPool.initialize(); emit NewLMPool(address(pool), address(lmPool)); }
38,188
143
// Update state for removal via principal token
if (principal_token_address != address(0x0) && principal_amount > 0) {
if (principal_token_address != address(0x0) && principal_amount > 0) {
17,125
4
// require(ipDatabase[hash]==address(0x0),"Hash doesnt exist");
Property p = Property(address(ipDatabase[hash])); return p.owner();
Property p = Property(address(ipDatabase[hash])); return p.owner();
35,302
2
// Returns full length of the account's data. solana_address Address of an account. /
function length(uint256 solana_address) internal view returns (bool, uint256) { (bool success, bytes memory result) = precompiled.staticcall(abi.encodeWithSignature("length(uint256)", solana_address)); return (success, to_uint256(result)); }
function length(uint256 solana_address) internal view returns (bool, uint256) { (bool success, bytes memory result) = precompiled.staticcall(abi.encodeWithSignature("length(uint256)", solana_address)); return (success, to_uint256(result)); }
4,111
22
// If the order was filled and not unlocked yet, taker from [`TakeState::FulFilled { taker }`] can unlock it and get the give part in [`Order::give::chain_id`] chain/ In the receive chain, the [`dln::source::claim_unlock`] will be called//_orderIds Order ids for unlock. Orders must have the same giveChainId/_beneficiary address that will receive give amount in give chain/_executionFee execution fee for auto claim by keepers/Allowed/ By taker of order only
function sendBatchEvmUnlock( bytes32[] memory _orderIds, address _beneficiary, uint256 _executionFee ) external payable nonReentrant whenNotPaused { if (_orderIds.length == 0) revert UnexpectedBatchSize(); if (_orderIds.length > maxOrderCountPerBatchEvmUnlock) revert UnexpectedBatchSize(); uint256 giveChainId; uint256 length = _orderIds.length;
function sendBatchEvmUnlock( bytes32[] memory _orderIds, address _beneficiary, uint256 _executionFee ) external payable nonReentrant whenNotPaused { if (_orderIds.length == 0) revert UnexpectedBatchSize(); if (_orderIds.length > maxOrderCountPerBatchEvmUnlock) revert UnexpectedBatchSize(); uint256 giveChainId; uint256 length = _orderIds.length;
13,457
42
// Token Ledger /
address[] memory, string[] memory, string[] memory, uint256[] memory){ return headShotTokenLedger.listTokenPart1(limit_, page_); }
address[] memory, string[] memory, string[] memory, uint256[] memory){ return headShotTokenLedger.listTokenPart1(limit_, page_); }
21,999
344
// we update the value
wantBalance = balanceOfWant();
wantBalance = balanceOfWant();
3,252
36
// Internal function that burns an amount of the token of a givenaccount, deducting from the sender's allowance for said account. Uses theinternal burn function.Emits an Approval event (reflecting the reduced allowance). account The account whose tokens will be burnt. value The amount that will be burnt. /
function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); }
function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); }
6,935
93
// Expect given number of calls to an address with the specified msg.value and calldata, and a minimum amount of gas.
function expectCallMinGas(address callee, uint256 msgValue, uint64 minGas, bytes calldata data, uint64 count) external;
function expectCallMinGas(address callee, uint256 msgValue, uint64 minGas, bytes calldata data, uint64 count) external;
17,633
17
// transfer underlying asset back to liquidity provider assuming pool liquidity is still sufficient. the amount returned is the number of cherrytokens multiplied by the current exchange rateThe sender should approve the _amount to this contract address _amount amount of CherryDai to redeemreturn daiRedeemed amount of DAI redeemed /
function redeem(uint256 _amount) external isLongUtilized() isShortUtilized() returns (uint256) { require( _amount <= cherryDai.balanceOf(msg.sender), "CherryPool::redeem request is more than current token balance" ); // get exchange rate from Cherrydai to Dai+fee uint256 _cherryRate; _cherryRate = exchangeRate(); uint256 daiRedeemed = _amount.mul(_cherryRate).div(1e18); require(getCashPrior() < daiRedeemed, "Redeem:insufficient cash"); // pay the message.sender the daiRedeemed amount and burn their _amount of CherryDai payout(msg.sender, daiRedeemed, _amount); emit RedeemCherry(msg.sender, _amount); return daiRedeemed; }
function redeem(uint256 _amount) external isLongUtilized() isShortUtilized() returns (uint256) { require( _amount <= cherryDai.balanceOf(msg.sender), "CherryPool::redeem request is more than current token balance" ); // get exchange rate from Cherrydai to Dai+fee uint256 _cherryRate; _cherryRate = exchangeRate(); uint256 daiRedeemed = _amount.mul(_cherryRate).div(1e18); require(getCashPrior() < daiRedeemed, "Redeem:insufficient cash"); // pay the message.sender the daiRedeemed amount and burn their _amount of CherryDai payout(msg.sender, daiRedeemed, _amount); emit RedeemCherry(msg.sender, _amount); return daiRedeemed; }
34,017
30
// Presale end timestamp
uint64 presaleEnd;
uint64 presaleEnd;
17,350
5,162
// 2583
entry "Heepishly" : ENG_ADVERB
entry "Heepishly" : ENG_ADVERB
23,419
6
// name /
function name() override public view returns (string memory) { return name_; }
function name() override public view returns (string memory) { return name_; }
14,527
16
// Retrieve funds from contract, only as recipient (when sending tokens: have to ask for approval beforehand in web browser interface)
function clearBox(uint _boxIndex, bytes32 _passHash) external payable
function clearBox(uint _boxIndex, bytes32 _passHash) external payable
30,314
59
// Pulls underlyingTokens from msg.sender to this contract. Pushes underlyingTokens to option contract and mints option + redeem tokens to this contract. Warning: calls into msg.sender using `safeTransferFrom`. Msg.sender is not trusted.
(uint256 outputOptions, uint256 outputRedeems) = TraderLib.safeMint(optionToken, quantity, address(this));
(uint256 outputOptions, uint256 outputRedeems) = TraderLib.safeMint(optionToken, quantity, address(this));
27,240
310
// Computes the next gen0 auction starting price, given/the average of the past 5 prices + 50%.
function _computeNextGen0Price() internal view returns (uint256) { uint256 avePrice = saleAuction.averageGen0SalePrice(); // Sanity check to ensure we don't overflow arithmetic require(avePrice == uint256(uint128(avePrice))); uint256 nextPrice = avePrice + (avePrice / 2); // We never auction for less than starting price if (nextPrice < GEN0_STARTING_PRICE) { nextPrice = GEN0_STARTING_PRICE; } return nextPrice; }
function _computeNextGen0Price() internal view returns (uint256) { uint256 avePrice = saleAuction.averageGen0SalePrice(); // Sanity check to ensure we don't overflow arithmetic require(avePrice == uint256(uint128(avePrice))); uint256 nextPrice = avePrice + (avePrice / 2); // We never auction for less than starting price if (nextPrice < GEN0_STARTING_PRICE) { nextPrice = GEN0_STARTING_PRICE; } return nextPrice; }
12,903
57
// Set to zero and disable pool
staker[msg.sender].stake[pool].quantity = 0; staker[msg.sender].stake[pool].active = false; staker[msg.sender].closed_pools.push(pool);
staker[msg.sender].stake[pool].quantity = 0; staker[msg.sender].stake[pool].active = false; staker[msg.sender].closed_pools.push(pool);
28,303
5
// Returns array of TREE_DEPTH zero hashes/ return _zeroes Array of TREE_DEPTH zero hashes
function zeroHashes() internal pure returns (bytes32[TREE_DEPTH] memory _zeroes)
function zeroHashes() internal pure returns (bytes32[TREE_DEPTH] memory _zeroes)
4,746
58
// load the bytes from memory
mload(add(_postBytes, 0x20)),
mload(add(_postBytes, 0x20)),
15,751
214
// We calculate the newSupplyIndex and user’s supplyCurrent (includes interest)
(err, localResults.newSupplyIndex) = calculateInterestIndex(currentMarket.supplyIndex, currentMarket.supplyRateMantissa, currentMarket.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return (err, 0, 0); }
(err, localResults.newSupplyIndex) = calculateInterestIndex(currentMarket.supplyIndex, currentMarket.supplyRateMantissa, currentMarket.blockNumber, getBlockNumber()); if (err != Error.NO_ERROR) { return (err, 0, 0); }
3,648
134
// re-calibrate the end claim period based on the actual number of periods to claim. nextClaim.period will be updated to this value after exiting the loop
endClaimPeriod = nextClaim.period + claim.periods;
endClaimPeriod = nextClaim.period + claim.periods;
46,466
23
// Hook that is called after emote is added or removed. collection Address of the collection smart contract containing the token being emoted tokenId ID of the token being emoted emoji Unicode identifier of the emoji state Boolean value signifying whether to emote (`true`) or undo (`false`) emote /
function _afterEmote( address collection, uint256 tokenId, string memory emoji, bool state
function _afterEmote( address collection, uint256 tokenId, string memory emoji, bool state
13,272
156
// The RNT TOKEN!
Farming public rnt;
Farming public rnt;
12,835
28
// set the next prize time to the next payout time (MidnightRun)
nextPrizeTime = getNextPayoutTime(); if (currentPrizeStakeID > 5) { uint toPay = midnightPrize; midnightPrize = 0; if (toPay > address(this).balance){ toPay = address(this).balance; }
nextPrizeTime = getNextPayoutTime(); if (currentPrizeStakeID > 5) { uint toPay = midnightPrize; midnightPrize = 0; if (toPay > address(this).balance){ toPay = address(this).balance; }
27,319
313
// update open notional after closing position
Decimal.decimal memory openNotional = _quoteAssetAmount.mulD(_leverage).subD(closePositionResp.exchangedQuoteAssetAmount);
Decimal.decimal memory openNotional = _quoteAssetAmount.mulD(_leverage).subD(closePositionResp.exchangedQuoteAssetAmount);
10,251
306
// check rates volatility result
require(!tooVolatile, "exchange rates too volatile"); (uint destinationAmount, , ) = exchangeRates().effectiveValueAndRates(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); amountReceived = _deductFeesFromAmount(destinationAmount, exchangeFeeRate); fee = destinationAmount.sub(amountReceived);
require(!tooVolatile, "exchange rates too volatile"); (uint destinationAmount, , ) = exchangeRates().effectiveValueAndRates(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); amountReceived = _deductFeesFromAmount(destinationAmount, exchangeFeeRate); fee = destinationAmount.sub(amountReceived);
24,479
3
// Function sending money
function sendMoney() public payable { // Increase the balance by the amount refunded balanceReceived[msg.sender] += msg.value; }
function sendMoney() public payable { // Increase the balance by the amount refunded balanceReceived[msg.sender] += msg.value; }
37,861
61
// See {IGovernor-castVoteWithReasonAndParams}. /
function castVoteWithReasonAndParams( uint256 proposalId, uint8 support, string calldata reason, bytes memory params ) public virtual override returns (uint256) { address voter = _msgSender(); return _castVote(proposalId, voter, support, reason, params); }
function castVoteWithReasonAndParams( uint256 proposalId, uint8 support, string calldata reason, bytes memory params ) public virtual override returns (uint256) { address voter = _msgSender(); return _castVote(proposalId, voter, support, reason, params); }
1,754
58
// registered contracts (to prevent loss of token via transfer function)
mapping (address => bool) private _contracts;
mapping (address => bool) private _contracts;
30,545
6
// ETH VAR
mapping(uint256 => uint256) WITHDRAWALS;
mapping(uint256 => uint256) WITHDRAWALS;
21,738
73
// TokenSafeA multi-bundle token safe contract that contains locked tokens released after a date for the specific bundle type. /
contract TokenSafe { using SafeMath for uint; struct AccountsBundle { // The total number of tokens locked. uint lockedTokens; // The release date for the locked tokens // Note: Unix timestamp fits uint32, however block.timestamp is uint uint releaseDate; // The balances for the 🍕 locked token accounts. mapping (address => uint) balances; } // The account bundles of locked tokens grouped by release date mapping (uint8 => AccountsBundle) public bundles; // The `ERC20TokenInterface` contract. ERC20TokenInterface token; /** * @dev The constructor. * * @param _token The address of the EOS Pizza Slices (donation) contract. */ function TokenSafe(address _token) public { token = ERC20TokenInterface(_token); } /** * @dev The function initializes the bundle of accounts with a release date. * * @param _type Bundle type. * @param _releaseDate Unix timestamp of the time after which the tokens can be released */ function initBundle(uint8 _type, uint _releaseDate) internal { bundles[_type].releaseDate = _releaseDate; } /** * @dev Add new account with locked token balance to the specified bundle type. * * @param _type Bundle type. * @param _account The address of the account to be added. * @param _balance The number of tokens to be locked. */ function addLockedAccount(uint8 _type, address _account, uint _balance) internal { var bundle = bundles[_type]; bundle.balances[_account] = bundle.balances[_account].plus(_balance); bundle.lockedTokens = bundle.lockedTokens.plus(_balance); } /** * @dev Allows an account to be released if it meets the time constraints. * * @param _type Bundle type. * @param _account The address of the account to be released. */ function releaseAccount(uint8 _type, address _account) internal { var bundle = bundles[_type]; require(now >= bundle.releaseDate); uint tokens = bundle.balances[_account]; require(tokens > 0); bundle.balances[_account] = 0; bundle.lockedTokens = bundle.lockedTokens.minus(tokens); if (!token.transfer(_account, tokens)) { revert(); } } }
contract TokenSafe { using SafeMath for uint; struct AccountsBundle { // The total number of tokens locked. uint lockedTokens; // The release date for the locked tokens // Note: Unix timestamp fits uint32, however block.timestamp is uint uint releaseDate; // The balances for the 🍕 locked token accounts. mapping (address => uint) balances; } // The account bundles of locked tokens grouped by release date mapping (uint8 => AccountsBundle) public bundles; // The `ERC20TokenInterface` contract. ERC20TokenInterface token; /** * @dev The constructor. * * @param _token The address of the EOS Pizza Slices (donation) contract. */ function TokenSafe(address _token) public { token = ERC20TokenInterface(_token); } /** * @dev The function initializes the bundle of accounts with a release date. * * @param _type Bundle type. * @param _releaseDate Unix timestamp of the time after which the tokens can be released */ function initBundle(uint8 _type, uint _releaseDate) internal { bundles[_type].releaseDate = _releaseDate; } /** * @dev Add new account with locked token balance to the specified bundle type. * * @param _type Bundle type. * @param _account The address of the account to be added. * @param _balance The number of tokens to be locked. */ function addLockedAccount(uint8 _type, address _account, uint _balance) internal { var bundle = bundles[_type]; bundle.balances[_account] = bundle.balances[_account].plus(_balance); bundle.lockedTokens = bundle.lockedTokens.plus(_balance); } /** * @dev Allows an account to be released if it meets the time constraints. * * @param _type Bundle type. * @param _account The address of the account to be released. */ function releaseAccount(uint8 _type, address _account) internal { var bundle = bundles[_type]; require(now >= bundle.releaseDate); uint tokens = bundle.balances[_account]; require(tokens > 0); bundle.balances[_account] = 0; bundle.lockedTokens = bundle.lockedTokens.minus(tokens); if (!token.transfer(_account, tokens)) { revert(); } } }
71,540
11
// Returns the amount which _spender is still allowed to withdraw from _owner.
function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; }
function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; }
2,645
28
// yearn vaults ✓ yearn lps✓ yearn pools✓ yearn gauges ✓ all gauges ✓ all lps✓ all pools✓ all tokens x vault > lp ✓ vault > pool x vault > gaugex lp > vault x lp > poolx lp > gauge x lp > tokens✓ pool > vault x pool > lp✓ pool > gauge ✓ pool > tokensx
address public yearnAddressesProviderAddress; address public curveAddressesProviderAddress; address public crvAddress; address public cvxAddress; IYearnAddressesProvider internal yearnAddressesProvider; ICurveAddressesProvider internal curveAddressesProvider; constructor(
address public yearnAddressesProviderAddress; address public curveAddressesProviderAddress; address public crvAddress; address public cvxAddress; IYearnAddressesProvider internal yearnAddressesProvider; ICurveAddressesProvider internal curveAddressesProvider; constructor(
31,487
14
// Delete _price from stockBuyOrderPrices[_node][] if it&39;s the last order
if (self.stockBuyOrders[_node][_price].length == 0) { uint _fromArg = 99999; for (_iii = 0; _iii < self.stockBuyOrderPrices[_node].length - 1; _iii++) { if (self.stockBuyOrderPrices[_node][_iii] == _price) { _fromArg = _iii; }
if (self.stockBuyOrders[_node][_price].length == 0) { uint _fromArg = 99999; for (_iii = 0; _iii < self.stockBuyOrderPrices[_node].length - 1; _iii++) { if (self.stockBuyOrderPrices[_node][_iii] == _price) { _fromArg = _iii; }
40,596
478
// Get the market index of a current position to calculate the real cash valuation _maturity, Maturity of the position to value _activeMarkets, All current active markets for the currencyIDreturn uint256 result, market index of the position to value /
function _getMarketIndexForMaturity( uint256 _maturity
function _getMarketIndexForMaturity( uint256 _maturity
2,385
137
// Derive the correct next start time from the base.
uint256 _start = _deriveStart( _baseFundingCycle, _latestPermanentFundingCycle, _mustStartOnOrAfter );
uint256 _start = _deriveStart( _baseFundingCycle, _latestPermanentFundingCycle, _mustStartOnOrAfter );
27,394
29
// change the Ownership from current owner to newOwner address
function ownerTransfership(address newOwner) public onlyOwner returns(bool){ require(newOwner != address(0), "Ownable: new owner is the zero address"); owner = newOwner; emit OwnershipTransferred(owner, newOwner); return true; }
function ownerTransfership(address newOwner) public onlyOwner returns(bool){ require(newOwner != address(0), "Ownable: new owner is the zero address"); owner = newOwner; emit OwnershipTransferred(owner, newOwner); return true; }
69,352
230
// Standard ERC223 function that will handle incoming token transfers./_fromToken sender address./_value Amount of tokens./_dataTransaction metadata.
function tokenFallback(address _from, uint _value, bytes _data) external;
function tokenFallback(address _from, uint _value, bytes _data) external;
45,472
44
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals; bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
mapping (address => mapping (address => bool)) private _operatorApprovals; bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
73,806
256
// Kaiju earn 10000 $FOOD per day
uint256 public constant DAILY_FOOD_RATE = 10000 ether; //10000 ether;
uint256 public constant DAILY_FOOD_RATE = 10000 ether; //10000 ether;
21,997
22
// Triggers stopped state. Requirements: - The contract must not be paused./
function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); }
function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); }
32,315
0
// object with information to set new required confirmations chainId id of the origin chain requiredConfirmations required confirmations to set a message as confirmed /
struct ConfirmationInput { uint256 chainId; uint8 requiredConfirmations; }
struct ConfirmationInput { uint256 chainId; uint8 requiredConfirmations; }
17,421
15
// Events
event ClaimedTokens(address indexed _token, address indexed _controller, uint256 _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event Approval(address indexed _owner, address indexed _spender, uint256 _amount);
event ClaimedTokens(address indexed _token, address indexed _controller, uint256 _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event Approval(address indexed _owner, address indexed _spender, uint256 _amount);
10,987
67
// Present in ERC777
mapping (address => uint256) internal _balances;
mapping (address => uint256) internal _balances;
19,560
34
// 购买token
function () public payable { require(isFunding); require(msg.value != 0); require(block.number >= fundingStartBlock); require(block.number <= fundingStopBlock); uint256 tokens = safeMult(msg.value, tokenExchangeRate); require(tokens + tokenRaised <= currentSupply); tokenRaised = safeAdd(tokenRaised, tokens); balances[msg.sender] += tokens; emit IssueToken(msg.sender, tokens); //记录日志 }
function () public payable { require(isFunding); require(msg.value != 0); require(block.number >= fundingStartBlock); require(block.number <= fundingStopBlock); uint256 tokens = safeMult(msg.value, tokenExchangeRate); require(tokens + tokenRaised <= currentSupply); tokenRaised = safeAdd(tokenRaised, tokens); balances[msg.sender] += tokens; emit IssueToken(msg.sender, tokens); //记录日志 }
42,871
22
// Declare variables to hold the values of v, r and s in the signature
uint8 v; bytes32 r; bytes32 s;
uint8 v; bytes32 r; bytes32 s;
26,240
192
// Whether the rate plan is exist _vendorId The vendor id _rpid The rate plan idreturn If the rate plan of the vendor is exist returns true otherwise return false /
function ratePlanIsExist(uint256 _vendorId, uint256 _rpid) public view
function ratePlanIsExist(uint256 _vendorId, uint256 _rpid) public view
14,509
879
// Offset to block_auxiliaryData[i]
let auxOffset := mload(add(block_auxiliaryData, add(32, mul(32, i))))
let auxOffset := mload(add(block_auxiliaryData, add(32, mul(32, i))))
32,813
100
// the constructor takes organization name, native token and reputation system/
constructor(string memory _orgName, DAOToken _nativeToken, Reputation _nativeReputation) public { orgName = _orgName; nativeToken = _nativeToken; nativeReputation = _nativeReputation; }
constructor(string memory _orgName, DAOToken _nativeToken, Reputation _nativeReputation) public { orgName = _orgName; nativeToken = _nativeToken; nativeReputation = _nativeReputation; }
45,098
36
// mapping between stable asset and price
mapping(address => uint256) internal stablePrice;
mapping(address => uint256) internal stablePrice;
31,676
99
// Store the original amount to get a refund.
_status = RE_NOT_ENTERED;
_status = RE_NOT_ENTERED;
58,442
5
// Transfers token from one address to another/NOTE: this function handles tokens that have transfer function not strictly compatible with ERC20 standard/NOTE: call `transferFrom` to this token may return (bool) or nothing/_token Token address/_from Address of sender/_to Address of recipient/_amount Amount of tokens to transfer/ return bool flag indicating that transfer is successful
function transferFromERC20( IERC20 _token, address _from, address _to, uint256 _amount
function transferFromERC20( IERC20 _token, address _from, address _to, uint256 _amount
26,909
69
// deprecated, backward compatibility, use `getConvertibleTokenAnchorCount` /
function getConvertibleTokenSmartTokenCount(IReserveToken convertibleToken) public view returns (uint256) { return getConvertibleTokenAnchorCount(convertibleToken); }
function getConvertibleTokenSmartTokenCount(IReserveToken convertibleToken) public view returns (uint256) { return getConvertibleTokenAnchorCount(convertibleToken); }
38,461
20
// Returns the contract addressReturn contract address /
function getContractAddress() public view returns (address){ return address(this); }
function getContractAddress() public view returns (address){ return address(this); }
45,720
16
// gather fees
function collectFees() external; function checkFeeBalance() external view returns (uint256); function checkRoyalty(address creator) external view returns (uint256);
function collectFees() external; function checkFeeBalance() external view returns (uint256); function checkRoyalty(address creator) external view returns (uint256);
52,767
18
// Returns worth (in quote token) of each collateral deposit of a user/_priceProvidersRepository address of IPriceProvidersRepository where prices are read/_params `Solvency.SolvencyParams` struct with needed params for calculation/ return collateralValues worth of each collateral deposit of a user as an array
function getUserCollateralValues(IPriceProvidersRepository _priceProvidersRepository, SolvencyParams memory _params) internal view returns(uint256[] memory collateralValues)
function getUserCollateralValues(IPriceProvidersRepository _priceProvidersRepository, SolvencyParams memory _params) internal view returns(uint256[] memory collateralValues)
26,927
36
// Function to be called by top level contract after initialization has finished./
function initialized() internal onlyInit { initializationBlock = getBlockNumber(); }
function initialized() internal onlyInit { initializationBlock = getBlockNumber(); }
27,576
13
// transfer NFTs from escrow to second user
for (uint256 i = 0; i < swap.initiatorNftIds.length; i++) { safeTransferFrom( address(this), swap.secondUser, swap.initiatorNftAddresses[i], swap.initiatorNftIds[i], swap.initiatorNftAmounts[i], "" ); }
for (uint256 i = 0; i < swap.initiatorNftIds.length; i++) { safeTransferFrom( address(this), swap.secondUser, swap.initiatorNftAddresses[i], swap.initiatorNftIds[i], swap.initiatorNftAmounts[i], "" ); }
21,581
102
// Subtracts from the contract balance tracking var
function subContractBalance(uint divRate, uint sub) internal { contractBalance[divRate] = contractBalance[divRate].sub(sub); }
function subContractBalance(uint divRate, uint sub) internal { contractBalance[divRate] = contractBalance[divRate].sub(sub); }
51,269
86
// Guardians must either be an EOA or a contract with an owner() method that returns an address with a 25000 gas stipend. Note that this test is not meant to be strict and can be bypassed by custom malicious contracts.
(bool success,) = _guardian.call{gas: 25000}(abi.encodeWithSignature("owner()"));
(bool success,) = _guardian.call{gas: 25000}(abi.encodeWithSignature("owner()"));
29,279
5
// line 219 of NFTMarketReserveAuction, logic within placeBid() function (not exposed publicly)
IFoundationMarket.ReserveAuction memory _auction = market.getReserveAuction(auctionId); return _auction.amount != 0;
IFoundationMarket.ReserveAuction memory _auction = market.getReserveAuction(auctionId); return _auction.amount != 0;
19,987
132
// reflections are "reflected" back to hodlers via a mechanism which seeks to simply remove the amount of the tax from the total reflection pool. since the token balance is a simple product of the amount of reflections a hodler has in their account to the ratio of all the reflections to the total token supply, removing reflections is a gas efficient way of applying a benefit to all hodlers pro rata as it lowers the denominator in the ratio thus increasing the result of the product. in other words, by removing reflections the numbers folks care about go up.
function _takeReflectionTax(uint256 reflectionsToRemove) private { _totalReflections = _totalReflections.sub(reflectionsToRemove); _totalTaxesReflectedToHodlers = _totalTaxesReflectedToHodlers.add( reflectionsToRemove ); }
function _takeReflectionTax(uint256 reflectionsToRemove) private { _totalReflections = _totalReflections.sub(reflectionsToRemove); _totalTaxesReflectedToHodlers = _totalTaxesReflectedToHodlers.add( reflectionsToRemove ); }
63,789
49
// freelancer getters
function getFreelancerName( address _freelancerAddress
function getFreelancerName( address _freelancerAddress
21,698
16
// return Address of DataCompressor
function getDataCompressor() external view override returns (address) { return _getAddress(DATA_COMPRESSOR); // F:[AP-7] }
function getDataCompressor() external view override returns (address) { return _getAddress(DATA_COMPRESSOR); // F:[AP-7] }
21,201
1
// amount of kryptonite after depositing 1 ring for 1 month default: 10000 RING for 1 year is 1 KTON. uint public unitInterest_; interst of per ring per month, 0.0005 ring recommended
bytes32 public constant UINT_BANK_UNIT_INTEREST = "UINT_BANK_UNIT_INTEREST";
bytes32 public constant UINT_BANK_UNIT_INTEREST = "UINT_BANK_UNIT_INTEREST";
12,510
14
// Receive the response in the form of uint256 /
function fulfill(bytes32 _requestId, string memory _volume) public recordChainlinkFulfillment(_requestId)
function fulfill(bytes32 _requestId, string memory _volume) public recordChainlinkFulfillment(_requestId)
40,137
441
// add invested wei to total fund
fundRaised = fundRaised.add(_investInWei);
fundRaised = fundRaised.add(_investInWei);
36,852
33
// require(msg.sender != bondOwner[_bond]);
bondBlockNumber[_bond] = block.number; //reset block number for this bond for half life calculations
bondBlockNumber[_bond] = block.number; //reset block number for this bond for half life calculations
1,359
33
// Structure that holds trade values, used inside the trade() function
struct FuturesTradeValues { uint256 qty; // amount to be trade uint256 makerProfit; // holds maker profit value uint256 makerLoss; // holds maker loss value uint256 takerProfit; // holds taker profit value uint256 takerLoss; // holds taker loss value uint256 makerBalance; // holds maker balance value uint256 takerBalance; // holds taker balance value uint256 makerReserve; // holds taker reserved value uint256 takerReserve; // holds taker reserved value }
struct FuturesTradeValues { uint256 qty; // amount to be trade uint256 makerProfit; // holds maker profit value uint256 makerLoss; // holds maker loss value uint256 takerProfit; // holds taker profit value uint256 takerLoss; // holds taker loss value uint256 makerBalance; // holds maker balance value uint256 takerBalance; // holds taker balance value uint256 makerReserve; // holds taker reserved value uint256 takerReserve; // holds taker reserved value }
14,571
84
// return current price of cToken in underlying /
function getPriceInToken() external view
function getPriceInToken() external view
28,143
17
// the function returns the oracle value of the given `amount` of the `token` in the last token of the OracleParams::tokens array.
function getPrice(address token, uint256 amount) public view returns (uint256) { OracleParams memory oracleParams_ = _oracleParams; uint256 tokenIndex = type(uint256).max; for (uint256 i = 0; i < oracleParams_.tokens.length; i++) { if (oracleParams_.tokens[i] == token) { tokenIndex = i; break; } } address[] memory tokens; uint256[] memory tokenAmounts; bytes[] memory securityParams; if (tokenIndex == type(uint256).max) { tokens = new address[](oracleParams_.tokens.length + 1); tokens[0] = token; tokenAmounts = new uint256[](oracleParams_.tokens.length + 1); tokenAmounts[0] = amount; securityParams = new bytes[](oracleParams_.tokens.length + 1); for (uint256 i = 0; i < oracleParams_.tokens.length; i++) { tokens[i + 1] = oracleParams_.tokens[i]; securityParams[i + 1] = oracleParams_.securityParams[i]; } } else { tokens = oracleParams_.tokens; tokenAmounts = new uint256[](tokens.length); tokenAmounts[tokenIndex] = amount; securityParams = oracleParams_.securityParams; } return oracleParams_.oracle.quote(tokens, tokenAmounts, securityParams); }
function getPrice(address token, uint256 amount) public view returns (uint256) { OracleParams memory oracleParams_ = _oracleParams; uint256 tokenIndex = type(uint256).max; for (uint256 i = 0; i < oracleParams_.tokens.length; i++) { if (oracleParams_.tokens[i] == token) { tokenIndex = i; break; } } address[] memory tokens; uint256[] memory tokenAmounts; bytes[] memory securityParams; if (tokenIndex == type(uint256).max) { tokens = new address[](oracleParams_.tokens.length + 1); tokens[0] = token; tokenAmounts = new uint256[](oracleParams_.tokens.length + 1); tokenAmounts[0] = amount; securityParams = new bytes[](oracleParams_.tokens.length + 1); for (uint256 i = 0; i < oracleParams_.tokens.length; i++) { tokens[i + 1] = oracleParams_.tokens[i]; securityParams[i + 1] = oracleParams_.securityParams[i]; } } else { tokens = oracleParams_.tokens; tokenAmounts = new uint256[](tokens.length); tokenAmounts[tokenIndex] = amount; securityParams = oracleParams_.securityParams; } return oracleParams_.oracle.quote(tokens, tokenAmounts, securityParams); }
25,311
12
// for me
uint256 mine = funds[msg.sender] / 2; funds[parents[msg.sender]] += (funds[msg.sender] - mine); funds[msg.sender] = 0; msg.sender.transfer(mine); getFundsEvent(msg.sender, mine); lastActivity[msg.sender] = now;
uint256 mine = funds[msg.sender] / 2; funds[parents[msg.sender]] += (funds[msg.sender] - mine); funds[msg.sender] = 0; msg.sender.transfer(mine); getFundsEvent(msg.sender, mine); lastActivity[msg.sender] = now;
58,511
43
// Check range: 1 - MAX_NUMBER
for(uint8 i = 0; i < numbers.length; i++) { if(numbers[i] < 1 || numbers[i] > MAX_NUMBER) { err = true; break; }
for(uint8 i = 0; i < numbers.length; i++) { if(numbers[i] < 1 || numbers[i] > MAX_NUMBER) { err = true; break; }
48,464
22
// Whether `a` is less than `b`. a a FixedPoint. b a uint256.return True if `a < b`, or False. /
function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool)
function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool)
30,145
6
// c / lowbit
c := div(c, lowbit)
c := div(c, lowbit)
30,592
62
// Settle the auction and send the highest bid to the beneficiary.
function _settleAuction(uint256 tokenId) internal { require(block.timestamp / 1 days > tokenId, "Auction not yet ended"); require(_highestBidder[tokenId] != address(0) && _highestBid[tokenId] > 0, "There should be at least a bid for the date"); require(!_exists(tokenId), "Should not reclaim the auction"); // It cannot be a safeMint. The Auction will never ends. _mint(_highestBidder[tokenId], tokenId); _foundation.transfer(_highestBid[tokenId]); emit AuctionSettled(tokenId, _highestBidder[tokenId], _highestBid[tokenId]); }
function _settleAuction(uint256 tokenId) internal { require(block.timestamp / 1 days > tokenId, "Auction not yet ended"); require(_highestBidder[tokenId] != address(0) && _highestBid[tokenId] > 0, "There should be at least a bid for the date"); require(!_exists(tokenId), "Should not reclaim the auction"); // It cannot be a safeMint. The Auction will never ends. _mint(_highestBidder[tokenId], tokenId); _foundation.transfer(_highestBid[tokenId]); emit AuctionSettled(tokenId, _highestBidder[tokenId], _highestBid[tokenId]); }
18,939
45
// Once the program is over, cannot fund
require(getCurrentEpochId() <= numberOfEpochs, "LAST_EPOCH_OVER"); uint256 nNewEpochs = _rewards.length; uint256 totalFunded;
require(getCurrentEpochId() <= numberOfEpochs, "LAST_EPOCH_OVER"); uint256 nNewEpochs = _rewards.length; uint256 totalFunded;
20,160
62
// Event for token purchase logging purchaser who paid for the tokens beneficiary who got the tokens value weis paid for purchase amount amount of tokens purchased /
event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
35,879
2
// SafeMath by OpenZeppelinMath operations with safety checks that throw on error/
library SafeMath { function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
library SafeMath { function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
12,701
50
// Accepts Admin for timelock of admin rights.Admin function for transferring admin to accept role and update admin/
function _AcceptTimelockAdmin() external { timelock.acceptAdmin(); }
function _AcceptTimelockAdmin() external { timelock.acceptAdmin(); }
46,080
138
// solhint-enable multiple-sends, reentrancy // Exchange ETH to pUSD while insisting on a particular rate. This allows a user toexchange while protecting against frontrunning by the contract owner on the exchange rate. guaranteedRate The exchange rate (ether price) which must be honored or the call will revert. /
function exchangeEtherForPynthsAtRate(uint guaranteedRate) external payable rateNotInvalid(ETH) notPaused returns ( uint // Returns the number of Pynths (pUSD) received )
function exchangeEtherForPynthsAtRate(uint guaranteedRate) external payable rateNotInvalid(ETH) notPaused returns ( uint // Returns the number of Pynths (pUSD) received )
30,938
2
// constructor is setting the implementation authority of the factory
constructor(address implementationAuthority_) { setImplementationAuthority(implementationAuthority_); }
constructor(address implementationAuthority_) { setImplementationAuthority(implementationAuthority_); }
29,676
5
// Loads a storage slot from an address
function load(address target, bytes32 slot) external view returns (bytes32 data);
function load(address target, bytes32 slot) external view returns (bytes32 data);
12,832
73
// Compute and return the upcoming redemption ratemarketPrice The system coin market priceredemptionPrice The system coin redemption priceaccumulatedLeak The total leak applied to priceDeviationCumulative before it is summed with the proportionalTerm/
function getNextRedemptionRate(uint marketPrice, uint redemptionPrice, uint accumulatedLeak)
function getNextRedemptionRate(uint marketPrice, uint redemptionPrice, uint accumulatedLeak)
5,722
300
// Record vesting entry for claiming address and amount SNX already minted to rewardEscrow balance
rewardEscrow().appendVestingEntry(account, snxAmount);
rewardEscrow().appendVestingEntry(account, snxAmount);
4,768
3
// Allows for safely dividing two numbers. Source --> https:github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol
function _safeMathDivide(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "_safeMathDivide : Denominator is 0"); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // require(a == b * c + a % b, "_safeMathDivide : Division Overflow"); // There is no case in which this doesn't hold return c; }
function _safeMathDivide(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "_safeMathDivide : Denominator is 0"); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // require(a == b * c + a % b, "_safeMathDivide : Division Overflow"); // There is no case in which this doesn't hold return c; }
7,709
17
// code to Start Pre-Sale.
function start_presale(uint _startdate,uint _enddate,uint token_for_presale,uint price) public onlyOwner{ if(_startdate <= _enddate && _startdate > now && token_for_presale < ico){ for(uint start=0; start < presale_detail.length; start++) { if(presale_detail[start].endDate >= _startdate) { revert("Another Sale is running"); } } presale memory p= presale(_startdate,_enddate,token_for_presale*decimal_price,price); presale_detail.push(p); total_presale_token += token_for_presale*decimal_price; balances[owner] -= token_for_presale*decimal_price; total_crowdsale_token = ico-total_presale_token; crowdsale_detail.crowd_token = total_crowdsale_token; } else{ revert("Presale not set"); } }
function start_presale(uint _startdate,uint _enddate,uint token_for_presale,uint price) public onlyOwner{ if(_startdate <= _enddate && _startdate > now && token_for_presale < ico){ for(uint start=0; start < presale_detail.length; start++) { if(presale_detail[start].endDate >= _startdate) { revert("Another Sale is running"); } } presale memory p= presale(_startdate,_enddate,token_for_presale*decimal_price,price); presale_detail.push(p); total_presale_token += token_for_presale*decimal_price; balances[owner] -= token_for_presale*decimal_price; total_crowdsale_token = ico-total_presale_token; crowdsale_detail.crowd_token = total_crowdsale_token; } else{ revert("Presale not set"); } }
42,472
28
// Emitted by the `cancel` function to signal that a ballot is canceled./ballotId The id of the canceled ballot.
event Canceled(uint256 ballotId);
event Canceled(uint256 ballotId);
54,751
167
// who gets all fees
address public beneficiary; I1Inch3 public _1Inch;
address public beneficiary; I1Inch3 public _1Inch;
13,278
210
// get the total supply of gen-0
function getGenZeroSupply() external view returns (uint256);
function getGenZeroSupply() external view returns (uint256);
3,083
5
// Reverts the current transaction with a "BadFraction" error message. /
function _revertBadFraction() pure { assembly { // Store left-padded selector with push4 (reduces bytecode), // mem[28:32] = selector mstore(0, BadFraction_error_selector) // revert(abi.encodeWithSignature("BadFraction()")) revert(Error_selector_offset, BadFraction_error_length) } }
function _revertBadFraction() pure { assembly { // Store left-padded selector with push4 (reduces bytecode), // mem[28:32] = selector mstore(0, BadFraction_error_selector) // revert(abi.encodeWithSignature("BadFraction()")) revert(Error_selector_offset, BadFraction_error_length) } }
20,778
24
// We're gonna just set the weight as full tokens. Ensures grantedToken were entered correctly as well.
require(sum == totalTokens, "Weight does not match tokens being distributed.");
require(sum == totalTokens, "Weight does not match tokens being distributed.");
37,688
78
// Receives ETH amount, converts it to WETH and joins it into the safeEngine
ethJoin_join(ethJoin, address(this), value);
ethJoin_join(ethJoin, address(this), value);
4,632
7
// Add the stable USD tokens to the stableCoins array using the _addStableUsdTokens() internal helper function
_addStableUsdTokens(_stableUsdTokens);
_addStableUsdTokens(_stableUsdTokens);
30,440
0
// Implementation of a traditional copyright contract using CopyrightBase
contract Copyright is CopyrightBase { using IdCounters for IdCounters.IdCounter; constructor() CopyrightBase("CRPL COPYRIGHT BACKED BY PIPO") payable {} }
contract Copyright is CopyrightBase { using IdCounters for IdCounters.IdCounter; constructor() CopyrightBase("CRPL COPYRIGHT BACKED BY PIPO") payable {} }
15,186
245
// XXX: pragma solidity ^0.5.16;
pragma solidity 0.6.12;
pragma solidity 0.6.12;
47,412