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
7
// update votecount
candidates[_candidateId].voteCount++; emit electionUpdates( _candidateId, candidates[_candidateId].name, candidates[_candidateId].voteCount); emit votedEvent(_candidateId);
candidates[_candidateId].voteCount++; emit electionUpdates( _candidateId, candidates[_candidateId].name, candidates[_candidateId].voteCount); emit votedEvent(_candidateId);
11,149
19
// holds Availability information for each specific mining address/ unavailability happens if a validator gets voted to become a pending validator,/ but misses out the sending of the ACK or PART within the given timeframe./ validators are required to declare availability,/ in order to become available for voting again./ the value is of type timestamp
mapping(address => uint256) public validatorAvailableSince;
mapping(address => uint256) public validatorAvailableSince;
47,463
25
// when the accrue started since contract creation
uint256 public accrueStart;
uint256 public accrueStart;
10,335
58
// 5th week
return 2000;
return 2000;
64,645
215
// Returns whether `tokenId` exists.
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view returns (bool) { return _tokenOwners.contains(tokenId); }
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view returns (bool) { return _tokenOwners.contains(tokenId); }
35,591
15
// data ordered from leaves to root. index bits: right bit correspond leaves
struct Proof { uint32 index; Slice slice; address item; bytes data; }
struct Proof { uint32 index; Slice slice; address item; bytes data; }
5,069
37
// Function to change founder address./newAddress Address of new founder.
function changeFounder(address newAddress) public onlyFounder returns (bool)
function changeFounder(address newAddress) public onlyFounder returns (bool)
31,099
47
// In order to minimize calls to transfer(), aggregate how much is owed to a single plot owner for all of their subPlots (this isuseful in the case that the buyer is overlaping with a single plot in a non-rectangular manner)
uint256 owedToSeller = 0; for (uint256 areaIndicesIndex = 0; areaIndicesIndex < areaIndices.length; areaIndicesIndex++) {
uint256 owedToSeller = 0; for (uint256 areaIndicesIndex = 0; areaIndicesIndex < areaIndices.length; areaIndicesIndex++) {
54,975
15
// store tokens
mapping(address => uint256) balances;
mapping(address => uint256) balances;
31,702
7
// ensure this pair is a univ2 pair by querying the factory
address possibleFactoryAddress; if (acceptOnlyLp || _isLpToken) { possibleFactoryAddress = _checkIfValidLP(_token); }
address possibleFactoryAddress; if (acceptOnlyLp || _isLpToken) { possibleFactoryAddress = _checkIfValidLP(_token); }
39,686
6
// Adds a new validator Only admin can call it /
function addValidator(address _account) external onlyAdmin { require(!validators.contains(_account), "already validator"); validators.add(_account); emit ValidatorAdded(_account); }
function addValidator(address _account) external onlyAdmin { require(!validators.contains(_account), "already validator"); validators.add(_account); emit ValidatorAdded(_account); }
16,314
97
// _weights[i] = percentage100
_reset(_owner); uint256 _tokenCnt = _tokenVote.length; uint256 _weight = DILL.balanceOf(_owner); uint256 _totalVoteWeight = 0; uint256 _usedWeight = 0; for (uint256 i = 0; i < _tokenCnt; i ++) { _totalVoteWeight = _totalVoteWeight.add(_weights[i]); }
_reset(_owner); uint256 _tokenCnt = _tokenVote.length; uint256 _weight = DILL.balanceOf(_owner); uint256 _totalVoteWeight = 0; uint256 _usedWeight = 0; for (uint256 i = 0; i < _tokenCnt; i ++) { _totalVoteWeight = _totalVoteWeight.add(_weights[i]); }
65,029
13
// Don't revert everything, even if the buyback fails. We want the overall transaction to continue regardless. We don't need to look at the return data, since the amount will be above the minExpected.
(bool success, bytes memory data) = uniswapAddr.call( abi.encodeWithSignature( "exactInput((bytes,address,uint256,uint256,uint256))", params ) ); if (!success) { emit BuybackFailed(data); }
(bool success, bytes memory data) = uniswapAddr.call( abi.encodeWithSignature( "exactInput((bytes,address,uint256,uint256,uint256))", params ) ); if (!success) { emit BuybackFailed(data); }
11,959
8
// MultiSig Wu Di Implement execute and multi-sig functions from ERC725 spec /
contract MultiSig is KeyPausable { event ExecutionFailed( uint256 indexed executionId, address indexed to, uint256 indexed value, bytes data ); /** * @dev Generate a unique ID for an execution request * @param _to address being called (msg.sender) * @param _value ether being sent (msg.value) * @param _data ABI encoded call data (msg.data) */ function execute(address _to, uint256 _value, bytes _data) public whenNotPaused returns (uint256 executionId) { return executions.add(_to, _value, _data); } /** * @dev Approves an execution. * Approving multiple times will work i.e. used to trigger an execution if * it failed the first time. * Disapproving multiple times will work i.e. not do anything. * The approval could potentially trigger an execution (if the threshold is met). * @param _id Execution ID * @param _approve `true` if it's an approval, `false` if it's a disapproval * @return `false` if it's a disapproval and there's no previous approval from the sender OR * if it's an approval that triggered a failed execution. `true` if it's a disapproval that * undos a previous approval from the sender OR if it's an approval that succeeded OR * if it's an approval that triggered a successful execution */ function approve(uint256 _id, bool _approve) public whenNotPaused returns (bool success) { return executions.approve(_id, _approve); } /** * @dev Change multi-sig threshold for MANAGEMENT_KEY * @param threshold New threshold to change it to (will throw if 0 or * larger than available keys) */ function changeManagementThreshold(uint threshold) public whenNotPaused onlyManagementOrSelf { executions.changeManagementThreshold(threshold); } /** * @dev Change multi-sig threshold for ACTION_KEY * @param threshold New threshold to change it to (will throw if 0 or * larger than available keys) */ function changeActionThreshold(uint threshold) public whenNotPaused onlyManagementOrSelf { executions.changeActionThreshold(threshold); } }
contract MultiSig is KeyPausable { event ExecutionFailed( uint256 indexed executionId, address indexed to, uint256 indexed value, bytes data ); /** * @dev Generate a unique ID for an execution request * @param _to address being called (msg.sender) * @param _value ether being sent (msg.value) * @param _data ABI encoded call data (msg.data) */ function execute(address _to, uint256 _value, bytes _data) public whenNotPaused returns (uint256 executionId) { return executions.add(_to, _value, _data); } /** * @dev Approves an execution. * Approving multiple times will work i.e. used to trigger an execution if * it failed the first time. * Disapproving multiple times will work i.e. not do anything. * The approval could potentially trigger an execution (if the threshold is met). * @param _id Execution ID * @param _approve `true` if it's an approval, `false` if it's a disapproval * @return `false` if it's a disapproval and there's no previous approval from the sender OR * if it's an approval that triggered a failed execution. `true` if it's a disapproval that * undos a previous approval from the sender OR if it's an approval that succeeded OR * if it's an approval that triggered a successful execution */ function approve(uint256 _id, bool _approve) public whenNotPaused returns (bool success) { return executions.approve(_id, _approve); } /** * @dev Change multi-sig threshold for MANAGEMENT_KEY * @param threshold New threshold to change it to (will throw if 0 or * larger than available keys) */ function changeManagementThreshold(uint threshold) public whenNotPaused onlyManagementOrSelf { executions.changeManagementThreshold(threshold); } /** * @dev Change multi-sig threshold for ACTION_KEY * @param threshold New threshold to change it to (will throw if 0 or * larger than available keys) */ function changeActionThreshold(uint threshold) public whenNotPaused onlyManagementOrSelf { executions.changeActionThreshold(threshold); } }
28,305
32
// Process non-guaranteed ids
while (quantitySent < settings.maxQuantityPerOpen) { uint256 quantityOfRandomized = 1; Class class = _pickRandomClass(settings.classProbabilities); _sendTokenWithClass(class, _toAddress, quantityOfRandomized); quantitySent += quantityOfRandomized; }
while (quantitySent < settings.maxQuantityPerOpen) { uint256 quantityOfRandomized = 1; Class class = _pickRandomClass(settings.classProbabilities); _sendTokenWithClass(class, _toAddress, quantityOfRandomized); quantitySent += quantityOfRandomized; }
2,699
2
// Set implementation contract/impl New implementation contract address
function upgradeTo(address impl) external override onlyOwner { require(impl != address(0), "Stake2VaultProxy: input is zero"); require(_implementation() != impl, "Stake2VaultProxy: same"); _setImplementation(impl); emit Upgraded(impl); }
function upgradeTo(address impl) external override onlyOwner { require(impl != address(0), "Stake2VaultProxy: input is zero"); require(_implementation() != impl, "Stake2VaultProxy: same"); _setImplementation(impl); emit Upgraded(impl); }
80,748
17
// Make sure the user owns or has staked the Crystal
uint32[] memory contractTokenIDs = new uint32[](crystalIDs.length); for (uint256 i = 0; i < crystalIDs.length; i++) { uint32 tokenId = crystalIDs[i]; require(crystals.ownerOf(tokenId) == msg.sender, "NotYourCrystal"); (uint8 currentCrystalSize, , uint8 currentSym, , ) = crystals.crystals(tokenId); require(currentCrystalSize == 100, "NeedFullyGrownCrystal"); require(currentSym >= 5, "NeedAtLeast5Sym");
uint32[] memory contractTokenIDs = new uint32[](crystalIDs.length); for (uint256 i = 0; i < crystalIDs.length; i++) { uint32 tokenId = crystalIDs[i]; require(crystals.ownerOf(tokenId) == msg.sender, "NotYourCrystal"); (uint8 currentCrystalSize, , uint8 currentSym, , ) = crystals.crystals(tokenId); require(currentCrystalSize == 100, "NeedFullyGrownCrystal"); require(currentSym >= 5, "NeedAtLeast5Sym");
51,960
15
// Is the line available to be claimed?
function info_CanBeClaimed(uint256 _tokenId) external view returns(bool){ require(_tokenId < listTINAmotleyTotalSupply); if (listTINAmotleyIndexToAddress[_tokenId] == address(0)) return true; else return false; }
function info_CanBeClaimed(uint256 _tokenId) external view returns(bool){ require(_tokenId < listTINAmotleyTotalSupply); if (listTINAmotleyIndexToAddress[_tokenId] == address(0)) return true; else return false; }
27,586
64
// The number of tranches required for the contract to fully vest.
uint256 immutable internal maxTranches;
uint256 immutable internal maxTranches;
21,823
27
// set _tokensMetadataFields of the field
_tokensMetadataFields[fieldName].SCinterface = SCinterface; _tokensMetadataFields[fieldName].SCaddress = SCaddress; emit TokenOnchainMetadataFieldAdded(fieldName, _tokensMetadataFields[fieldName]);
_tokensMetadataFields[fieldName].SCinterface = SCinterface; _tokensMetadataFields[fieldName].SCaddress = SCaddress; emit TokenOnchainMetadataFieldAdded(fieldName, _tokensMetadataFields[fieldName]);
18,423
0
// MAP OF ALL USERS, [ADDRESS => INTERFACE]
mapping (address => User) public users;
mapping (address => User) public users;
39,599
51
// Returns phases information filter 1: active, 2: ended, 3: all /
function getPhases(uint256 phaseFrom, uint256 phaseTo, uint256 filter) external view returns (uint256[] memory, PhaseInfo[] memory)
function getPhases(uint256 phaseFrom, uint256 phaseTo, uint256 filter) external view returns (uint256[] memory, PhaseInfo[] memory)
39,247
23
// push the lottery to the past lotteries
pastLotteries.push( PastLottery(currentPrizePoolAmount, winningTicket, winner, currentTime) );
pastLotteries.push( PastLottery(currentPrizePoolAmount, winningTicket, winner, currentTime) );
36,260
10
// SETTERS FOR STRINGS
function setWholeURI(string memory _newWholeURI) public onlyOwner { wholeURI = _newWholeURI; }
function setWholeURI(string memory _newWholeURI) public onlyOwner { wholeURI = _newWholeURI; }
41,505
35
// 数据源名称+数据源链接
string source;
string source;
4,359
3
// Swaps `amountIn` of one token for as much as possible of another token tokenIn The token address being swapped from tokenInCurrencyKey The synth currency key for `tokenIn`, set to zero if `tokenIn` is not a synth amountIn The amount of `tokenIn` to be swapped swaps The swap route encoded into an array of `Swap` structs amountOutMinimum The minimum amount of the last `Swap` struct `tokenOut` token that must be returnedreturn amountOut The amount of the received token /
function swap( IERC20 tokenIn, bytes32 tokenInCurrencyKey, uint amountIn, Swap[] calldata swaps, uint amountOutMinimum
function swap( IERC20 tokenIn, bytes32 tokenInCurrencyKey, uint amountIn, Swap[] calldata swaps, uint amountOutMinimum
17,230
81
// Official record of token balances for each account /
mapping (address => uint256) accountTokens;
mapping (address => uint256) accountTokens;
11,345
33
// Checks whether primary sale recipient can be set in the given execution context.
function _canSetPrimarySaleRecipient() internal view virtual override returns (bool) { return msg.sender == owner(); }
function _canSetPrimarySaleRecipient() internal view virtual override returns (bool) { return msg.sender == owner(); }
24,714
97
// getEscapeRequestsCount(): returns the number of points _sponsoris providing service to
function getEscapeRequestsCount(uint32 _sponsor) view external returns (uint256 count)
function getEscapeRequestsCount(uint32 _sponsor) view external returns (uint256 count)
19,530
13
// Mints an amount of the token to the defined treasury account/token The token for which to mint tokens. If token does not exist, transaction results in/INVALID_TOKEN_ID/amount Applicable to tokens of type FUNGIBLE_COMMON. The amount to mint to the Treasury Account./ Amount must be a positive non-zero number represented in the lowest denomination of the/ token. The new supply must be lower than 2^63./metadata Applicable to tokens of type NON_FUNGIBLE_UNIQUE. A list of metadata that are being created./ Maximum allowed size of each metadata is 100 bytes/ return responseCode The response code for the status of the request. SUCCESS is 22./
function mintToken( address token, uint64 amount, bytes[] memory metadata ) external returns ( int256 responseCode, uint64 newTotalSupply, int64[] memory serialNumbers
function mintToken( address token, uint64 amount, bytes[] memory metadata ) external returns ( int256 responseCode, uint64 newTotalSupply, int64[] memory serialNumbers
21,851
17
// update address contribution + total contributions.
_contributions[msg.sender] = _contributions[msg.sender].add(amount); _numberOfContributions[msg.sender] = _numberOfContributions[msg.sender].add(1);
_contributions[msg.sender] = _contributions[msg.sender].add(amount); _numberOfContributions[msg.sender] = _numberOfContributions[msg.sender].add(1);
12,182
15
// approve should be called when allowed[_spender] == 0. To increment allowed value is better to use this function to avoid 2 calls (and wait until the first transaction is mined) From MonolithDAO Token.sol/
function increaseApproval(address _spender, uint256 _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
function increaseApproval(address _spender, uint256 _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
18,778
154
// Test 1
for (uint256 i = 0; i < collateral_addresses.length; i++){ balance_tally += freeCollatBalance(i).mul(10 ** missing_decimals[i]).mul(collateral_prices[i]).div(PRICE_PRECISION); }
for (uint256 i = 0; i < collateral_addresses.length; i++){ balance_tally += freeCollatBalance(i).mul(10 ** missing_decimals[i]).mul(collateral_prices[i]).div(PRICE_PRECISION); }
62,180
50
// Returns the weighted apr in an hypothetical world where the strategy splits its nav/ in respect to shares/shares List of shares (in bps of the nav) that should be allocated to each lender
function estimatedAPR(uint64[] memory shares) public view returns (uint256 weightedAPR, int256[] memory lenderAdjustedAmounts)
function estimatedAPR(uint64[] memory shares) public view returns (uint256 weightedAPR, int256[] memory lenderAdjustedAmounts)
17,975
68
// Emitted when meta pool tokens are withdrawn from convex.//amountThe amount of meta pool tokens that were withdrawn./success If the operation was successful.
event WithdrawMetaPoolTokens(uint256 amount, bool success);
event WithdrawMetaPoolTokens(uint256 amount, bool success);
55,686
2
// Emitted after the grace period is updated newGracePeriod The new grace period value /
event GracePeriodUpdated(uint256 newGracePeriod);
event GracePeriodUpdated(uint256 newGracePeriod);
25,531
36
// Passes a transaction to the modifier assuming the specified role./to Destination address of module transaction/value Ether value of module transaction/data Data payload of module transaction/operation Operation type of module transaction/role Identifier of the role to assume for this transaction/shouldRevert Should the function revert on inner execution returning success false?/Can only be called by enabled modules
function execTransactionWithRole( address to, uint256 value, bytes calldata data, Enum.Operation operation, uint16 role, bool shouldRevert
function execTransactionWithRole( address to, uint256 value, bytes calldata data, Enum.Operation operation, uint16 role, bool shouldRevert
28,222
825
// Total number of tokens in existence /
function totalSupply() public view returns (uint256) { // Immutable static call from target contract return IERC20(address(target)).totalSupply(); }
function totalSupply() public view returns (uint256) { // Immutable static call from target contract return IERC20(address(target)).totalSupply(); }
34,387
337
// pause crypto DODO contract stops any further hatching. /
function pause() external onlyOwner { _pause(); }
function pause() external onlyOwner { _pause(); }
7,674
18
// Approve an address to spend another addresses' tokens. owner The address that owns the tokens. spender The address that will spend the tokens. value The number of tokens that can be spent. /
function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0), "Cannot approve to the zero address"); require(owner != address(0), "Setter cannot be a zero address"); _allowed[owner][spender] = value; emit Approval(owner, spender, value); }
function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0), "Cannot approve to the zero address"); require(owner != address(0), "Setter cannot be a zero address"); _allowed[owner][spender] = value; emit Approval(owner, spender, value); }
914
75
// allowed 1 year later after stage1 tokens trading is enabled
uint32 stage0_locked_year= 1; bool is_debug= false; // change to false if this contract source is release version if(is_debug==false && block.timestamp < stage0_locked_year*365*24*60*60 + when_public_allowed_to_trade_started ) revert(); if(is_debug==true && block.timestamp < stage0_locked_year*10*60 + when_public_allowed_to_trade_started ) revert();
uint32 stage0_locked_year= 1; bool is_debug= false; // change to false if this contract source is release version if(is_debug==false && block.timestamp < stage0_locked_year*365*24*60*60 + when_public_allowed_to_trade_started ) revert(); if(is_debug==true && block.timestamp < stage0_locked_year*10*60 + when_public_allowed_to_trade_started ) revert();
46,101
201
// The SMTY TOKEN!
SMTYToken public smty; VotingEscrow public veSMTY;
SMTYToken public smty; VotingEscrow public veSMTY;
26,556
6
// This overrides the private method inside the ERC20 contract and lets this contractloop in to tax tokens during the transfer process _from The address tokens should be transferred from _to The address tokens should be transferred to _amount The amount of tokens that should be transferred (to 18 decimal places) /
function _transfer( address _from, address _to, uint256 _amount
function _transfer( address _from, address _to, uint256 _amount
30,727
11
// Disable self-destruction
selfDestructionDisabled = true;
selfDestructionDisabled = true;
39,953
90
// 68 = 32 bytes data length + 4-byte selector + 32 bytes offset
reason := add(data, 68)
reason := add(data, 68)
14,414
319
// Used to recover a stuck token. /
function recoverERC721(address token, address recipient, uint256 tokenId) external onlyOwner { return IERC721(token).transferFrom(address(this), recipient, tokenId); }
function recoverERC721(address token, address recipient, uint256 tokenId) external onlyOwner { return IERC721(token).transferFrom(address(this), recipient, tokenId); }
22,827
123
// transfers the oracle's LINK to another address. Can only be calledby the oracle's admin. _oracle is the oracle whose LINK is transferred _recipient is the address to send the LINK to _amount is the amount of LINK to send /
function withdrawPayment(address _oracle, address _recipient, uint256 _amount) external
function withdrawPayment(address _oracle, address _recipient, uint256 _amount) external
17,177
11
// 还原签名人
address signer = ECDSAUpgradeable.recover(hash, signature); require(owner == signer, "Permit: invalid signature"); _approve(owner, spender, value);
address signer = ECDSAUpgradeable.recover(hash, signature); require(owner == signer, "Permit: invalid signature"); _approve(owner, spender, value);
11,863
6
// Returns the first bit in the given leaves that is strictly lower than the given bit.It will return type(uint256).max if there is no such bit. leaves The leaves bit The bitreturn The first bit in the given leaves that is strictly lower than the given bit /
function _closestBitRight(bytes32 leaves, uint8 bit) private pure returns (uint256) { unchecked { return uint256(leaves).closestBitRight(bit - 1); } }
function _closestBitRight(bytes32 leaves, uint8 bit) private pure returns (uint256) { unchecked { return uint256(leaves).closestBitRight(bit - 1); } }
12,937
141
// Returns the address for tokenB /
function tokenB() public override view returns (address) { return _tokenB; }
function tokenB() public override view returns (address) { return _tokenB; }
18,749
9
// Some curvePools have themselves a dependent lpToken "root" which this contract accommodates zapping through. This flag indicates if such an action is necessary
bool needsChildZap;
bool needsChildZap;
53,590
6
// if(balances[msg.sender]>=q){
require(balances[msg.sender]>=quantity); // this is a better alternative to an IF. If require fails, the entire function fails and any ether send is returned balances[msg.sender]-=quantity; balances[receiver]+=quantity;
require(balances[msg.sender]>=quantity); // this is a better alternative to an IF. If require fails, the entire function fails and any ether send is returned balances[msg.sender]-=quantity; balances[receiver]+=quantity;
3,241
222
// Returns wrapped TWAB index. In order to navigate the TWAB circular buffer, we need to use the modulo operator. For example, if `_index` is equal to 32 and the TWAB circular buffer is of `_cardinality` 32, it will return 0 and will point to the first element of the array._index Index used to navigate through the TWAB circular buffer._cardinality TWAB buffer cardinality. return TWAB index./
function wrap(uint256 _index, uint256 _cardinality) internal pure returns (uint256) { return _index % _cardinality; }
function wrap(uint256 _index, uint256 _cardinality) internal pure returns (uint256) { return _index % _cardinality; }
49,776
163
// Add markets to compMarkets, allowing them to earn COMP in the flywheel cTokens The addresses of the markets to add /
function _addCompMarkets(address[] memory cTokens) public { require(adminOrInitializing(), "only admin can add comp market"); for (uint i = 0; i < cTokens.length; i++) { _addCompMarketInternal(cTokens[i]); } refreshCompSpeedsInternal(); }
function _addCompMarkets(address[] memory cTokens) public { require(adminOrInitializing(), "only admin can add comp market"); for (uint i = 0; i < cTokens.length; i++) { _addCompMarketInternal(cTokens[i]); } refreshCompSpeedsInternal(); }
12,437
152
// Providing USDC to the AMM Liquidity Pool by the sender on behalf of beneficiary./Emits {ProvideLiquidity} event and transfers ERC20 tokens from the sender to the AmmTreasury,/ emits {Transfer} event from ERC20 asset, emits {Mint} event from ipToken./beneficiary Account receiving receive ipUSDT liquidity tokens./assetAmount Amount of ERC20 tokens transferred from the sender to the AmmTreasury. Represented in decimals specific for asset. Value represented in 18 decimals.
function provideLiquidityUsdc(address beneficiary, uint256 assetAmount) external;
function provideLiquidityUsdc(address beneficiary, uint256 assetAmount) external;
43,026
6
// Cancel functionallows only creator of payment to cancel paymentId The paymentId of the payment to cancelæ /
function cancel(address paymentId) public { require( payments[paymentId].paymentSender == msg.sender, "Can only be called by creator" ); uint256 value = payments[paymentId].paymentAmount; address asset = payments[paymentId].asset; _withdraw(paymentId, value, asset); emit PaymentCancel(msg.sender, paymentId, value, asset); }
function cancel(address paymentId) public { require( payments[paymentId].paymentSender == msg.sender, "Can only be called by creator" ); uint256 value = payments[paymentId].paymentAmount; address asset = payments[paymentId].asset; _withdraw(paymentId, value, asset); emit PaymentCancel(msg.sender, paymentId, value, asset); }
29,775
79
// calculate LP values actually provided
LpQuantity zapInLps; { LpQuantity maiCandidate = mulDiv(maiAmount, lpTotalSupply, maiReserves); LpQuantity usdcCandidate = mulDiv(usdcAmount, lpTotalSupply, usdcReserves); zapInLps = min(maiCandidate, usdcCandidate); }
LpQuantity zapInLps; { LpQuantity maiCandidate = mulDiv(maiAmount, lpTotalSupply, maiReserves); LpQuantity usdcCandidate = mulDiv(usdcAmount, lpTotalSupply, usdcReserves); zapInLps = min(maiCandidate, usdcCandidate); }
31,186
24
// Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. _spender The address which will spend the funds. _value The amount of tokens to be spent. /
function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; }
function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; }
4,276
5
// Mime type for token's animated content (if any)
string animationMimeType;
string animationMimeType;
32,552
8
// gets the purposes of a key_key The public key.for non-hex and long keys, its the Keccak256 hash of the key return _purposes Returns the purposes of the specified key/
function getKeyPurposes(bytes32 _key) public override view returns(uint256[] memory _purposes)
function getKeyPurposes(bytes32 _key) public override view returns(uint256[] memory _purposes)
18,467
4
// ========== EVENTS ========== // ========== FUNCTIONS ========== /
{ require(price > 0, "MRKT: Price must be > 0"); IERC721 nftContract = IERC721(nftAddress); require( nftContract.isApprovedForAll(msg.sender, address(this)) || nftContract.getApproved(tokenId) == address(this), "MRKT: No approval for NFT" ); listings[nftAddress][tokenId] = Listing({ price: price, seller: msg.sender }); emit ListingCreated(nftAddress, tokenId, price, msg.sender); }
{ require(price > 0, "MRKT: Price must be > 0"); IERC721 nftContract = IERC721(nftAddress); require( nftContract.isApprovedForAll(msg.sender, address(this)) || nftContract.getApproved(tokenId) == address(this), "MRKT: No approval for NFT" ); listings[nftAddress][tokenId] = Listing({ price: price, seller: msg.sender }); emit ListingCreated(nftAddress, tokenId, price, msg.sender); }
22,526
6
// lay ten cac thanh vien trong nhom tac gia
function lay_ten_tac_gia() public view returns(string memory auth1, string memory auth2, string memory auth3){ (auth1, auth2, auth3) = (authors[0].name, authors[1].name, authors[2].name); }
function lay_ten_tac_gia() public view returns(string memory auth1, string memory auth2, string memory auth3){ (auth1, auth2, auth3) = (authors[0].name, authors[1].name, authors[2].name); }
1,731
28
// get balance after exitswap
uint256 balanceAfter = IERC20(tokenOut).balanceOf(address(this));
uint256 balanceAfter = IERC20(tokenOut).balanceOf(address(this));
30,260
366
// Emitted when the implementation is upgraded. implementation Address of the new implementation. /
event Upgraded(address indexed implementation); function initialize() public;
event Upgraded(address indexed implementation); function initialize() public;
3,303
22
// check if lp token exist
function lpTokenExist(IERC20 _lpToken) public view returns (bool) { return lpTokens[address(_lpToken)]; }
function lpTokenExist(IERC20 _lpToken) public view returns (bool) { return lpTokens[address(_lpToken)]; }
11,214
43
// ============ External Functions ============ //Get natural unit of Set returnuint256 Natural unit of Set /
function naturalUnit() external view returns (uint256);
function naturalUnit() external view returns (uint256);
39,483
17
// Mapping task id to current "active" nonce for executing task changes
mapping (uint256 => uint256) taskChangeNonces;
mapping (uint256 => uint256) taskChangeNonces;
2,741
100
// Current price calculator
IPriceCalculator calculator;
IPriceCalculator calculator;
68,716
33
// Gives permission to `to` to transfer `tokenId` token to another account.The approval is cleared when the token is transferred. Only a single account can be approved at a time, so approving thezero address clears previous approvals. Requirements: - The caller must own the token or be an approved operator.- `tokenId` must exist. Emits an {Approval} event. /
function approve(address to, uint256 tokenId) external payable;
function approve(address to, uint256 tokenId) external payable;
40,125
102
// Approve the passed address to spend the specified amount of tokens on behalf of msg.senderand then call `onApprovalReceived` on spender.Beware that changing an allowance with this method brings the risk that someone may use both the oldand the new allowance by unfortunate transaction ordering. One possible solution to mitigate thisrace condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: spender address The address which will spend the funds amount uint256 The amount of tokens to be spent data bytes Additional data with no specified format, sent in call to `spender` /
function approveAndCall(address spender, uint256 amount, bytes calldata data) external returns (bool);
function approveAndCall(address spender, uint256 amount, bytes calldata data) external returns (bool);
2,156
242
// Calculate the final taxAmount
taxAmount = userRefundingAmount.mul(taxOverflow).div(1e12);
taxAmount = userRefundingAmount.mul(taxOverflow).div(1e12);
21,434
6
// ! ],! "expected": [! "-128"! ]
//! }, { //! "name": "overflow_positive", //! "input": [ //! { //! "entry": "main", //! "calldata": [ //! "1000" //! ] //! }
//! }, { //! "name": "overflow_positive", //! "input": [ //! { //! "entry": "main", //! "calldata": [ //! "1000" //! ] //! }
20,440
64
// This can't overflow because this addition is less than or equal to data.protocolFees
data.harvestedProtocolFees += harvestedFees;
data.harvestedProtocolFees += harvestedFees;
26,874
19
// This method relies on extcodesize/address.code.length, which returns 0 for contracts in construction, since the code is only stored at the end of the constructor execution.
return account.code.length > 0;
return account.code.length > 0;
11,005
153
// Current price
uint256 currentPrice;
uint256 currentPrice;
11,519
7
// Disable minting if max supply of tokens is reached
if (totalSupply() == maxSupply) { mintingIsActive = false; }
if (totalSupply() == maxSupply) { mintingIsActive = false; }
11,673
19
// reverse quote is not supported/ haircut is calculated in the fromToken when swapping tokens for credit
function quoteSwapTokensForCredit( IAsset fromAsset, uint256 fromAmount, uint256 ampFactor, uint256 scaleFactor, uint256 haircutRate, uint256 startCovRatio, uint256 endCovRatio
function quoteSwapTokensForCredit( IAsset fromAsset, uint256 fromAmount, uint256 ampFactor, uint256 scaleFactor, uint256 haircutRate, uint256 startCovRatio, uint256 endCovRatio
30,233
70
// Consumes an amount of reflection (rOwned) held by the sender, redistributing it to all holders This could be considered something like an "airdrop" or "making it rain" Since excluded accounts use the token system (tOwned) and not reflection, they cannot call this function
function reflect(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); }
function reflect(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); }
36,045
23
// Safely transfers the ownership of a given token ID to another address If the target address is a contract, it must implement `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 operatorfrom 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 _data bytes data to send along with a safe transfer check /
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public;
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public;
27,643
4
// Unique tokenId for each FM
mapping(uint256 => FantasticMoment) private _fmCollection;
mapping(uint256 => FantasticMoment) private _fmCollection;
32,284
80
// Proof of collateral split contract/Verifies that contract is a collateral split contract/ return true if contract is a collateral split contract
function isCollateralSplit() external pure returns(bool);
function isCollateralSplit() external pure returns(bool);
35,820
255
// Transfer tokens from one address to another. from The address which you want to send tokens from to The address which you want to transfer to value the amount of tokens to be transferredreturn A boolean that indicates if the operation was successful. /
function transferFrom(address from, address to, uint256 value) public virtual override(ERC20) canTransfer(from) returns (bool) { return super.transferFrom(from, to, value); }
function transferFrom(address from, address to, uint256 value) public virtual override(ERC20) canTransfer(from) returns (bool) { return super.transferFrom(from, to, value); }
14,330
348
// ============ External Getter Functions ============ //Get enabled assets for SetToken. Returns an array of enabled cTokens that are collateral assets and anarray of underlying that are borrow assets. returnCollateral cToken assets that are enabledreturnUnderlying borrowed assets that are enabled. /
function getEnabledAssets(ISetToken _setToken) external view returns(address[] memory, address[] memory) { return ( enabledAssets[_setToken].collateralCTokens, enabledAssets[_setToken].borrowAssets ); }
function getEnabledAssets(ISetToken _setToken) external view returns(address[] memory, address[] memory) { return ( enabledAssets[_setToken].collateralCTokens, enabledAssets[_setToken].borrowAssets ); }
2,868
10
// Interface for the optional metadata functions from the TRC20 standard. _Available since v4.1._ /
interface ITRC20Metadata is ITRC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); }
interface ITRC20Metadata is ITRC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); }
27,105
118
// == Events ==
event ExchangeStakeDeposited(address exchangeAddr, uint amount); event ExchangeStakeWithdrawn(address exchangeAddr, uint amount); event ExchangeStakeBurned(address exchangeAddr, uint amount); event SettingsUpdated(uint time);
event ExchangeStakeDeposited(address exchangeAddr, uint amount); event ExchangeStakeWithdrawn(address exchangeAddr, uint amount); event ExchangeStakeBurned(address exchangeAddr, uint amount); event SettingsUpdated(uint time);
31,435
107
// Event for crowdsale extending newClosingTime new closing time prevClosingTime old closing time /
event TimedCrowdsaleExtended(uint256 prevClosingTime, uint256 newClosingTime);
event TimedCrowdsaleExtended(uint256 prevClosingTime, uint256 newClosingTime);
24,436
110
// increase hurdle rate by 0.01%
info.nextHurdleRate = Math.min(HURDLE_RATE_MAX, info.nextHurdleRate.add(1));
info.nextHurdleRate = Math.min(HURDLE_RATE_MAX, info.nextHurdleRate.add(1));
23,723
304
// intermediate variable for user fee token1 calculation
uint256 public token1PerShareStored;
uint256 public token1PerShareStored;
5,321
83
// increase length by the double of the memory bytes length
mul(mlength, 2) ) ) )
mul(mlength, 2) ) ) )
22,664
157
// verify the token ID is "tiny" (32 bits long at most)
require(uint32(_tokenId) == _tokenId, "token ID overflow");
require(uint32(_tokenId) == _tokenId, "token ID overflow");
38,714
12
// ensure minting the amount entered would not mint over the max supply
require( totalSupply + amount < MAX_SUPPLY, "mint amount would be out of range." ); _safeMint(_msgSender(), amount);
require( totalSupply + amount < MAX_SUPPLY, "mint amount would be out of range." ); _safeMint(_msgSender(), amount);
24,710
64
// stake weight formula rewards for locking
uint256 stakeWeight = (((lockUntil - lockFrom) * WEIGHT_MULTIPLIER) / 365 days + WEIGHT_MULTIPLIER) * addedAmount;
uint256 stakeWeight = (((lockUntil - lockFrom) * WEIGHT_MULTIPLIER) / 365 days + WEIGHT_MULTIPLIER) * addedAmount;
48,612
55
// token = createTokenContract();
startTime = _startTime; endTime = _endTime; ETHtoZCOrate = _ETHtoZCOrate; wallet = _wallet; minTransAmount = _minTransAmount; tokenDecimals = 8; mintedTokensCap = _mintedTokensCap.mul(10**tokenDecimals); // mintedTokensCap is in Zwei
startTime = _startTime; endTime = _endTime; ETHtoZCOrate = _ETHtoZCOrate; wallet = _wallet; minTransAmount = _minTransAmount; tokenDecimals = 8; mintedTokensCap = _mintedTokensCap.mul(10**tokenDecimals); // mintedTokensCap is in Zwei
25,539
81
// check WasteType
require(trucks[msg.sender].wasteType == stations[_disposalStation].allowedWasteType, "You are at the wrong station!"); emit Deposited(msg.sender, trucks[msg.sender].wasteType, trucks[msg.sender].totWeight, _disposalStation); trucks[msg.sender].depositedStation = trucks[msg.sender].totWeight; trucks[msg.sender].totWeight = 0;
require(trucks[msg.sender].wasteType == stations[_disposalStation].allowedWasteType, "You are at the wrong station!"); emit Deposited(msg.sender, trucks[msg.sender].wasteType, trucks[msg.sender].totWeight, _disposalStation); trucks[msg.sender].depositedStation = trucks[msg.sender].totWeight; trucks[msg.sender].totWeight = 0;
43,685
10
// determine the address where the contract will be deployed.
deploymentAddress = address( uint160( // downcast to match the address type. uint256( // convert to uint to truncate upper digits. keccak256( // compute the CREATE2 hash using 4 inputs. abi.encodePacked( // pack all inputs to the hash together. hex"ff", // start with 0xff to distinguish from RLP. address(this), // this contract will be the caller. salt, // pass in the supplied salt value. keccak256( // pass in the hash of initialization code. abi.encodePacked(
deploymentAddress = address( uint160( // downcast to match the address type. uint256( // convert to uint to truncate upper digits. keccak256( // compute the CREATE2 hash using 4 inputs. abi.encodePacked( // pack all inputs to the hash together. hex"ff", // start with 0xff to distinguish from RLP. address(this), // this contract will be the caller. salt, // pass in the supplied salt value. keccak256( // pass in the hash of initialization code. abi.encodePacked(
18,580
48
// free claimer
require(_free_claimer[msg.sender], "Cannot claim with this wallet.");
require(_free_claimer[msg.sender], "Cannot claim with this wallet.");
14,657
71
// Converts token passed as an argument to WETH
function _toWETH(address token) internal returns (uint256) { // If the passed token is Sushi, don't convert anything if (token == sushi) { uint amount = IERC20(token).balanceOf(address(this)); _safeTransfer(token, bar, amount); return 0; } // If the passed token is WETH, don't convert anything if (token == weth) { uint amount = IERC20(token).balanceOf(address(this)); _safeTransfer(token, factory.getPair(weth, sushi), amount); return amount; } // If the target pair doesn't exist, don't convert anything IUniswapV2Pair pair = IUniswapV2Pair(factory.getPair(token, weth)); if (address(pair) == address(0)) { return 0; } // Choose the correct reserve to swap from (uint reserve0, uint reserve1,) = pair.getReserves(); address token0 = pair.token0(); (uint reserveIn, uint reserveOut) = token0 == token ? (reserve0, reserve1) : (reserve1, reserve0); // Calculate information required to swap uint amountIn = IERC20(token).balanceOf(address(this)); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); uint amountOut = numerator / denominator; (uint amount0Out, uint amount1Out) = token0 == token ? (uint(0), amountOut) : (amountOut, uint(0)); // Swap the token for WETH _safeTransfer(token, address(pair), amountIn); pair.swap(amount0Out, amount1Out, factory.getPair(weth, sushi), new bytes(0)); return amountOut; }
function _toWETH(address token) internal returns (uint256) { // If the passed token is Sushi, don't convert anything if (token == sushi) { uint amount = IERC20(token).balanceOf(address(this)); _safeTransfer(token, bar, amount); return 0; } // If the passed token is WETH, don't convert anything if (token == weth) { uint amount = IERC20(token).balanceOf(address(this)); _safeTransfer(token, factory.getPair(weth, sushi), amount); return amount; } // If the target pair doesn't exist, don't convert anything IUniswapV2Pair pair = IUniswapV2Pair(factory.getPair(token, weth)); if (address(pair) == address(0)) { return 0; } // Choose the correct reserve to swap from (uint reserve0, uint reserve1,) = pair.getReserves(); address token0 = pair.token0(); (uint reserveIn, uint reserveOut) = token0 == token ? (reserve0, reserve1) : (reserve1, reserve0); // Calculate information required to swap uint amountIn = IERC20(token).balanceOf(address(this)); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); uint amountOut = numerator / denominator; (uint amount0Out, uint amount1Out) = token0 == token ? (uint(0), amountOut) : (amountOut, uint(0)); // Swap the token for WETH _safeTransfer(token, address(pair), amountIn); pair.swap(amount0Out, amount1Out, factory.getPair(weth, sushi), new bytes(0)); return amountOut; }
29,683
127
// Buy and burn only applies up to 50k tokens burned
buyNBurn(ethToSwap);
buyNBurn(ethToSwap);
47,197
40
// Allows CryptoChunk owners to accept bids for their Chunks /
{ if (chunkIndex >= 10000) revert("token index not valid"); if (chunksContract.ownerOf(chunkIndex) != msg.sender) revert("you do not own this token"); address seller = msg.sender; Bid memory bid = chunkBids[chunkIndex]; if (bid.value == 0) revert("cannot enter bid of zero"); if (bid.value < minPrice) revert("your bid is too low"); address bidder = bid.bidder; if (seller == bidder) revert("you already own this token"); chunksOfferedForSale[chunkIndex] = Offer( false, chunkIndex, bidder, 0, address(0x0) ); uint256 amount = bid.value; chunkBids[chunkIndex] = Bid(false, chunkIndex, address(0x0), 0); chunksContract.safeTransferFrom(msg.sender, bidder, chunkIndex); pendingWithdrawals[seller] += amount; emit ChunkBought(chunkIndex, bid.value, seller, bidder); }
{ if (chunkIndex >= 10000) revert("token index not valid"); if (chunksContract.ownerOf(chunkIndex) != msg.sender) revert("you do not own this token"); address seller = msg.sender; Bid memory bid = chunkBids[chunkIndex]; if (bid.value == 0) revert("cannot enter bid of zero"); if (bid.value < minPrice) revert("your bid is too low"); address bidder = bid.bidder; if (seller == bidder) revert("you already own this token"); chunksOfferedForSale[chunkIndex] = Offer( false, chunkIndex, bidder, 0, address(0x0) ); uint256 amount = bid.value; chunkBids[chunkIndex] = Bid(false, chunkIndex, address(0x0), 0); chunksContract.safeTransferFrom(msg.sender, bidder, chunkIndex); pendingWithdrawals[seller] += amount; emit ChunkBought(chunkIndex, bid.value, seller, bidder); }
61,813
7
// See ICrossChain. /
function setTokenContract(address _address) external onlyOwner { }
function setTokenContract(address _address) external onlyOwner { }
16,612