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
9
// Gets the weighted average of two samples and their respective weights sample1 The first encoded sample sample2 The second encoded sample weight1 The weight of the first sample weight2 The weight of the second samplereturn weightedAverageId The weighted average idreturn weightedAverageVolatility The weighted average ...
function getWeightedAverage(bytes32 sample1, bytes32 sample2, uint40 weight1, uint40 weight2) internal pure returns (uint64 weightedAverageId, uint64 weightedAverageVolatility, uint64 weightedAverageBinCrossed)
function getWeightedAverage(bytes32 sample1, bytes32 sample2, uint40 weight1, uint40 weight2) internal pure returns (uint64 weightedAverageId, uint64 weightedAverageVolatility, uint64 weightedAverageBinCrossed)
28,833
460
// The given timestamp must not be greater than `block.timestamp + 1 hour` and at most `optOutPeriod(booster)` seconds old.
uint64 _now = uint64(block.timestamp); uint64 _optOutPeriod = uint64(optOutPeriod); bool notTooFarInFuture = payload.timestamp <= _now + 1 hours; bool belowMaxAge = true;
uint64 _now = uint64(block.timestamp); uint64 _optOutPeriod = uint64(optOutPeriod); bool notTooFarInFuture = payload.timestamp <= _now + 1 hours; bool belowMaxAge = true;
5,357
37
// Maintain a sell quota as the net of all daily buys and sells, plus a predefined threshold
if (_sellThreshold > 0) { uint256 blockTimestamp = block.timestamp; if (_sellQuota.blockMetric == 0 || _sellQuota.blockMetric < blockTimestamp - 1 days) { _sellQuota.blockMetric = blockTimestamp; _sellQuota.amount = int256(_sellThreshold); ...
if (_sellThreshold > 0) { uint256 blockTimestamp = block.timestamp; if (_sellQuota.blockMetric == 0 || _sellQuota.blockMetric < blockTimestamp - 1 days) { _sellQuota.blockMetric = blockTimestamp; _sellQuota.amount = int256(_sellThreshold); ...
37,156
8
// Check horizontally
for(uint i = 0; i<7; i++){ for(uint j = 0; j<4; j++){ if(_board[i][j] != 0 && _board[i][j] == _board[i][j+1] && _board[i][j] == _board[i][j+2] && _board[i][j] == _board[i][j+3]){ return true; }
for(uint i = 0; i<7; i++){ for(uint j = 0; j<4; j++){ if(_board[i][j] != 0 && _board[i][j] == _board[i][j+1] && _board[i][j] == _board[i][j+2] && _board[i][j] == _board[i][j+3]){ return true; }
13,297
8
// called before any token transfer; includes (batched) minting and burning /
) internal override(ERC1155, ERC1155Supply) { super._beforeTokenTransfer(operator, from, to, nftIds, amounts, data); }
) internal override(ERC1155, ERC1155Supply) { super._beforeTokenTransfer(operator, from, to, nftIds, amounts, data); }
25,324
96
// To test with JS and compare with actual encoder. Maintaining for reference.
// t = function() { return IEVMScriptExecutor.at('0x4bcdd59d6c77774ee7317fc1095f69ec84421e49').contract.execScript.getData(...[].slice.call(arguments)).slice(10).match(/.{1,64}/g) } // run = function() { return ScriptHelpers.new().then(sh => { sh.abiEncode.call(...[].slice.call(arguments)).then(a => console.log...
// t = function() { return IEVMScriptExecutor.at('0x4bcdd59d6c77774ee7317fc1095f69ec84421e49').contract.execScript.getData(...[].slice.call(arguments)).slice(10).match(/.{1,64}/g) } // run = function() { return ScriptHelpers.new().then(sh => { sh.abiEncode.call(...[].slice.call(arguments)).then(a => console.log...
2,970
0
// Store address of Smart Wallet Upgrade Beacon Controller as a constant.
address private constant _SMART_WALLET_UPGRADE_BEACON_CONTROLLER = address( 0x00000000002226C940b74d674B85E4bE05539663 );
address private constant _SMART_WALLET_UPGRADE_BEACON_CONTROLLER = address( 0x00000000002226C940b74d674B85E4bE05539663 );
1,677
4
// Proves that an account contained particular info (nonce, balance, codehash) at a particular block.encodedProof the encoded AccountInfoProof /
function _prove(bytes calldata encodedProof) internal view override returns (Fact memory) { AccountInfoProof calldata proof = parseAccountInfoProof(encodedProof); ( bool exists, CoreTypes.BlockHeaderData memory head, CoreTypes.AccountData memory acc ) = ve...
function _prove(bytes calldata encodedProof) internal view override returns (Fact memory) { AccountInfoProof calldata proof = parseAccountInfoProof(encodedProof); ( bool exists, CoreTypes.BlockHeaderData memory head, CoreTypes.AccountData memory acc ) = ve...
21,072
60
// обновляем анкету коровы
user[keccak256(gamer) & keccak256(num_cow)].cow_live = false;
user[keccak256(gamer) & keccak256(num_cow)].cow_live = false;
67,409
242
// _INTERFACE_ID_ERC2981
_registerInterface(0x2a55205a);
_registerInterface(0x2a55205a);
23,047
83
// Hook that is called before any transfer of tokens. This includesminting and burning. Calling conditions: - when `from` and `to` are both non-zero, `amount` of `from`'s tokenswill be to transferred to `to`.- when `from` is zero, `amount` tokens will be minted for `to`.- when `to` is zero, `amount` of `from`'s tokens ...
// function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
// function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
46,909
4
// Set a multiplier for how many tokens to earn each time a block passes.
function setRate(uint256 _rate) external onlyOwner { rate = _rate; }
function setRate(uint256 _rate) external onlyOwner { rate = _rate; }
74,940
23
// RequirePlatform
requirePlatform(); privilegedMinterAddress = _privilegedMinterAddress;
requirePlatform(); privilegedMinterAddress = _privilegedMinterAddress;
26,717
40
// Validate external call params
if (_orderCreation.externalCall.length > 0) { ExternalCall memory externalCall = abi.decode( _orderCreation.externalCall, (ExternalCall) ); if (externalCall.executionFee > _orderCreation.takeAmount) revert ProposedFeeTooHigh(); if (...
if (_orderCreation.externalCall.length > 0) { ExternalCall memory externalCall = abi.decode( _orderCreation.externalCall, (ExternalCall) ); if (externalCall.executionFee > _orderCreation.takeAmount) revert ProposedFeeTooHigh(); if (...
13,512
80
// add y^16(20! / 16!)
z = (z * y) / FIXED_1; res += z * 0x0000000000001ab8;
z = (z * y) / FIXED_1; res += z * 0x0000000000001ab8;
2,513
150
// Updates category details/_categoryId Category id that needs to be updated/_name Category name/_memberRoleToVote Voting Layer sequence in which the voting has to be performed./_allowedToCreateProposal Member roles allowed to create the proposal/_majorityVotePerc Majority Vote threshold for Each voting layer/_quorumPe...
function updateCategory( uint _categoryId, string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress...
function updateCategory( uint _categoryId, string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress...
22,197
7
// The basis points offered by coupon holders to have their coupons redeemed -- default is 200 bps (2%) E.g., offers[_user] = 500 indicates that _user will pay 500 basis points (5%) to the caller
mapping(address => uint256) private offers;
mapping(address => uint256) private offers;
31,943
100
// Get a page of open trades for a specified token symbol - max 30 per page
function getTrades(string calldata symbol, uint256 pageNum, uint256 perPage) external view returns (string memory){ // Check for max per page require(perPage <= 30, "30 is the max page size"); string memory page = '{ "trades":['; require(pageNum > 0, "Page number starts from 1"); ...
function getTrades(string calldata symbol, uint256 pageNum, uint256 perPage) external view returns (string memory){ // Check for max per page require(perPage <= 30, "30 is the max page size"); string memory page = '{ "trades":['; require(pageNum > 0, "Page number starts from 1"); ...
50,712
27
// Migrate lp token to another lp contract.
function replaceMigrate(uint256 _pid) public onlyOwner { PoolInfo storage pool = poolInfo[_pid]; IMigrator migrator = pool.migrator; require(address(migrator) != address(0), "migrate: no migrator"); IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)...
function replaceMigrate(uint256 _pid) public onlyOwner { PoolInfo storage pool = poolInfo[_pid]; IMigrator migrator = pool.migrator; require(address(migrator) != address(0), "migrate: no migrator"); IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)...
26,114
5
// revoke Role adding controle Requirements: - PAUSER_ROLE can't be revoked, it can only be renounced./
function revokeRole(bytes32 role, address account) public override { if(role == PAUSER_ROLE) require(false, "PAUSER_ROLE can't be revoked, it can only be renounced"); super.revokeRole(role,account); }
function revokeRole(bytes32 role, address account) public override { if(role == PAUSER_ROLE) require(false, "PAUSER_ROLE can't be revoked, it can only be renounced"); super.revokeRole(role,account); }
11,112
25
// low level token purchase function
function buyTokens(address beneficiary) payable { require(beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = weiAmount.mul(rate); // update state weiRaised = weiRaised.add(weiAmount); token.mint(ben...
function buyTokens(address beneficiary) payable { require(beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = weiAmount.mul(rate); // update state weiRaised = weiRaised.add(weiAmount); token.mint(ben...
2,289
66
// Modifier to make a function callable only for owner and saleAgent when the contract is paused. /
modifier onlyWhenNotPaused() { if(owner != msg.sender && saleAgent != msg.sender) { require (!paused); } _; }
modifier onlyWhenNotPaused() { if(owner != msg.sender && saleAgent != msg.sender) { require (!paused); } _; }
6,505
40
// if we're not yet working on this operation, switch over and reset the confirmation status.
if (! isOperationActive(_operation)) {
if (! isOperationActive(_operation)) {
13,087
378
// Reveal a previously committed vote for `identifier` at `time`. The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash`that `commitVote()` was called with. Only the committer can reveal their vote. identifier voted on in the commit phase. EG BTC/USD price pair. tim...
function revealVote(
function revealVote(
9,936
5
// Constants/ "Magic" prefix. When prepended to some arbitrary bytecode and used to create a contract, the appended bytecode will be deployed as given.
bytes13 internal constant DEPLOY_CODE_PREFIX = 0x600D380380600D6000396000f3;
bytes13 internal constant DEPLOY_CODE_PREFIX = 0x600D380380600D6000396000f3;
69,047
143
// get the length of supported tokens/ return The quantity of tokens added
function getTokenAddressesLength() external view returns (uint256);
function getTokenAddressesLength() external view returns (uint256);
11,433
34
// Tiers filled
wait = true; endTime = swapTime; WaitStarted(endTime);
wait = true; endTime = swapTime; WaitStarted(endTime);
40,546
332
// Construct the LongShortPair params Constructor params used to initialize the LSP. Key-valued object with the following structure: - `pairName`: Name of the long short pair contract. - `expirationTimestamp`: Unix timestamp of when the contract will expire. - `collateralPerPair`: How many units of collateral are requi...
constructor(ConstructorParams memory params) Testable(params.timerAddress) { finder = params.finder; require(bytes(params.pairName).length > 0, "Pair name cant be empty"); require(params.expirationTimestamp > getCurrentTime(), "Expiration timestamp in past"); require(params.collatera...
constructor(ConstructorParams memory params) Testable(params.timerAddress) { finder = params.finder; require(bytes(params.pairName).length > 0, "Pair name cant be empty"); require(params.expirationTimestamp > getCurrentTime(), "Expiration timestamp in past"); require(params.collatera...
72,742
7
// checks if the instance of market maker contract is open for public/_token address address of the CC token.
modifier marketOpen(address _token) { require(MarketMaker(currencyMap[_token].mmAddress).isOpenForPublic()); _; }
modifier marketOpen(address _token) { require(MarketMaker(currencyMap[_token].mmAddress).isOpenForPublic()); _; }
17,613
19
// update reserves and, on the first call per block, price accumulators
function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private { require(balance0 <= 0xffffffffffffffffffffffffffff && balance1 <= 0xffffffffffffffffffffffffffff, 'UniswapV2: OVERFLOW'); uint32 blockTimestamp = uint32(block.timestamp % 2**32); uint32 timeElapsed...
function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private { require(balance0 <= 0xffffffffffffffffffffffffffff && balance1 <= 0xffffffffffffffffffffffffffff, 'UniswapV2: OVERFLOW'); uint32 blockTimestamp = uint32(block.timestamp % 2**32); uint32 timeElapsed...
34,950
72
// same as restake but for layer 1 stakes
// @param sessionID {uint256} - id of the stake // @param stakingDays {uint256} - number of days to be staked // @param topup {uint256} - amount of AXN to be added as topup to the stake function restakeV1( uint256 sessionId, uint256 stakingDays, uint256 topup ) external pausa...
// @param sessionID {uint256} - id of the stake // @param stakingDays {uint256} - number of days to be staked // @param topup {uint256} - amount of AXN to be added as topup to the stake function restakeV1( uint256 sessionId, uint256 stakingDays, uint256 topup ) external pausa...
24,274
349
// Set royalty basis points
function setRoyaltyBasisPoints(uint256 _basisPoints) public onlyOwner { royaltyBasisPoints = _basisPoints; emit RoyaltyBasisPoints(_basisPoints); }
function setRoyaltyBasisPoints(uint256 _basisPoints) public onlyOwner { royaltyBasisPoints = _basisPoints; emit RoyaltyBasisPoints(_basisPoints); }
29,826
277
// The main minting function
function mint(uint256 amount) public payable { require(isSaleActive, "Sale must be active to mint NFT"); require(amount <= MAX_NFT, "Amount must be less than MAX_NFT"); require(totalSupply().add(amount) <= MAX_NFT, "Total supply + amount must be less than MAX_NFT"); require(nftPrice....
function mint(uint256 amount) public payable { require(isSaleActive, "Sale must be active to mint NFT"); require(amount <= MAX_NFT, "Amount must be less than MAX_NFT"); require(totalSupply().add(amount) <= MAX_NFT, "Total supply + amount must be less than MAX_NFT"); require(nftPrice....
21,459
133
// Establish path from Ether to token.
(address[] memory path, ) = _createPathAndAmounts( _WETH, address(tokenReceived), false );
(address[] memory path, ) = _createPathAndAmounts( _WETH, address(tokenReceived), false );
29,254
23
// Circuit Breaker Storage Library Library for storing and manipulating state related to circuit breakers. The intent of circuit breakers is to halt trading of a given token if its value changes drastically -in either direction - with respect to other tokens in the pool. For instance, a stablecoin might de-pegand go to...
library CircuitBreakerStorageLib { using ValueCompression for uint256; using FixedPoint for uint256; using WordCodec for bytes32; // Store circuit breaker information per token // When the circuit breaker is set, the caller passes in the lower and upper bounds (expressed as percentages), // the...
library CircuitBreakerStorageLib { using ValueCompression for uint256; using FixedPoint for uint256; using WordCodec for bytes32; // Store circuit breaker information per token // When the circuit breaker is set, the caller passes in the lower and upper bounds (expressed as percentages), // the...
22,112
115
// Add time lock, only locker can add/
function _addTimeLock(address account, uint amount, uint expiresAt) internal { require(amount > 0, "Time Lock: lock amount must be greater than 0"); require(expiresAt > block.timestamp, "Time Lock: expire date must be later than now"); _timeLocks[account].push(TimeLock(amount, expiresAt)); emit TimeLo...
function _addTimeLock(address account, uint amount, uint expiresAt) internal { require(amount > 0, "Time Lock: lock amount must be greater than 0"); require(expiresAt > block.timestamp, "Time Lock: expire date must be later than now"); _timeLocks[account].push(TimeLock(amount, expiresAt)); emit TimeLo...
4,354
24
// modifier used to keep track of the dynamic rewards for user each time a deposit or withdraw is made
modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = calculateRewards(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } ...
modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = calculateRewards(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } ...
22,557
129
// ensure all the arrays in the vault are valid
require(_vault.shortOtokens.length <= 1, "MarginCalculator: Too many short otokens in the vault"); require(_vault.longOtokens.length <= 1, "MarginCalculator: Too many long otokens in the vault"); require(_vault.collateralAssets.length <= 1, "MarginCalculator: Too many collateral assets in the va...
require(_vault.shortOtokens.length <= 1, "MarginCalculator: Too many short otokens in the vault"); require(_vault.longOtokens.length <= 1, "MarginCalculator: Too many long otokens in the vault"); require(_vault.collateralAssets.length <= 1, "MarginCalculator: Too many collateral assets in the va...
24,411
0
// /
uint public feePercentage; bool public buysAllowed = true;
uint public feePercentage; bool public buysAllowed = true;
19,387
17
// Emitted when the validator set is updated./nonce Nonce./powerThreshold New voting power threshold./validatorSetHash Hash of new validator set./ See `updateValidatorSet`.
event ValidatorSetUpdatedEvent(uint256 indexed nonce, uint256 powerThreshold, bytes32 validatorSetHash);
event ValidatorSetUpdatedEvent(uint256 indexed nonce, uint256 powerThreshold, bytes32 validatorSetHash);
52,773
105
// {RoleAdminChanged} not being emitted signaling this. _Available since v3.1._/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
36,189
18
// have we got proven consensus?
if(witnessCount >= acceptanceTreshold) { break; }
if(witnessCount >= acceptanceTreshold) { break; }
10,902
81
// Set max delay time for each token/tokens list of tokens to set max delay/maxDelays list of max delay times to set to
function setMaxDelayTimes(address[] calldata tokens, uint[] calldata maxDelays) external onlyGov { require(tokens.length == maxDelays.length, 'tokens & maxDelays length mismatched'); for (uint idx = 0; idx < tokens.length; idx++) { maxDelayTimes[tokens[idx]] = maxDelays[idx]; emit SetMaxDelayTime(...
function setMaxDelayTimes(address[] calldata tokens, uint[] calldata maxDelays) external onlyGov { require(tokens.length == maxDelays.length, 'tokens & maxDelays length mismatched'); for (uint idx = 0; idx < tokens.length; idx++) { maxDelayTimes[tokens[idx]] = maxDelays[idx]; emit SetMaxDelayTime(...
22,766
2
// Array of ERC20 interfaces for balancer flashloan
IERC20[] public globalTokens;
IERC20[] public globalTokens;
21,147
120
// - shift information to the left by a specified number of bits_val - value to be shifted_shift - number of bits to shift return - `_val` shifted `_shift` bits to the left, i.e. multiplied by 2`_shift`
function shiftLeft(uint _val, uint _shift) private pure returns (uint) { return _val * uint(2)**_shift; }
function shiftLeft(uint _val, uint _shift) private pure returns (uint) { return _val * uint(2)**_shift; }
19,782
577
// Converts an internal asset cash value to its underlying token value./ar exchange rate object between asset and underlying/assetBalance amount to convert to underlying
function convertToUnderlying(AssetRateParameters memory ar, int256 assetBalance) internal pure returns (int256)
function convertToUnderlying(AssetRateParameters memory ar, int256 assetBalance) internal pure returns (int256)
3,749
20
// Allows to create market after successful funding/ return Market address
function createMarket() public timedTransitions atStage(Stages.AuctionSuccessful) returns (Market)
function createMarket() public timedTransitions atStage(Stages.AuctionSuccessful) returns (Market)
32,311
116
// Attempt to transfer the total Dai balance to the caller.
_transferMax(_DAI, msg.sender, true);
_transferMax(_DAI, msg.sender, true);
16,731
6
// calculate the trailing zeros on the binary representation of the number
if (d << 128 == 0) { d >>= 128; s += 128; }
if (d << 128 == 0) { d >>= 128; s += 128; }
9,748
22
// transfer erc1155 to seller
IERC1155(token).safeTransferFrom(address(this), seller, id, 1, new bytes(0x0)); ended = true;
IERC1155(token).safeTransferFrom(address(this), seller, id, 1, new bytes(0x0)); ended = true;
3,743
24
// ---------------------------------- External Functions----------------------------------
function setCycleStatusTo_allocateWinner() public onlyWhenInitialising{ cycleStatus = CycleStatus.allocateWinner; }
function setCycleStatusTo_allocateWinner() public onlyWhenInitialising{ cycleStatus = CycleStatus.allocateWinner; }
6,106
140
// reverse-for-loops with unsigned integer/ solium-disable-next-line security/no-modify-for-iter-var / take last decimal digit
bstr[i] = bytes1(uint8(ASCII_ZERO + (j % 10)));
bstr[i] = bytes1(uint8(ASCII_ZERO + (j % 10)));
31,706
98
// Performs transfer from an included account to an excluded account.(included and excluded from receiving reward.) /
function _transferToExcluded(address sender, address recipient, ValuesFromAmount memory values) private { _reflectionBalances[sender] = _reflectionBalances[sender] - values.rAmount; _tokenBalances[recipient] = _tokenBalances[recipient] + values.tTransferAmount; _reflectionBalances[r...
function _transferToExcluded(address sender, address recipient, ValuesFromAmount memory values) private { _reflectionBalances[sender] = _reflectionBalances[sender] - values.rAmount; _tokenBalances[recipient] = _tokenBalances[recipient] + values.tTransferAmount; _reflectionBalances[r...
20,625
14
// 提交人命令清单,数组单向增加
mapping(address => uint256[]) submitterCmds;
mapping(address => uint256[]) submitterCmds;
35,148
251
// reset lockup
totalLockedUpRewards = totalLockedUpRewards.sub(user.rewardLockedUp); user.rewardLockedUp = 0; user.nextHarvestUntil = block.timestamp.add(pool.harvestInterval);
totalLockedUpRewards = totalLockedUpRewards.sub(user.rewardLockedUp); user.rewardLockedUp = 0; user.nextHarvestUntil = block.timestamp.add(pool.harvestInterval);
24,602
271
// initialize storage variables on a new G-UNI pool, only called once/_name name of Vault (immutable)/_symbol symbol of Vault (immutable)/_pool address of Uniswap V3 pool (immutable)/_managerFeeBPS proportion of fees earned that go to manager treasury/_lowerTick initial lowerTick (only changeable with executiveRebalanc...
function initialize( string memory _name, string memory _symbol, address _pool, uint16 _managerFeeBPS, int24 _lowerTick, int24 _upperTick, address _manager_
function initialize( string memory _name, string memory _symbol, address _pool, uint16 _managerFeeBPS, int24 _lowerTick, int24 _upperTick, address _manager_
61,510
0
// int public num = 129;
int public people = 0;
int public people = 0;
46,515
4
// UpgradeabilityStorage This contract holds all the necessary state variables to support the upgrade functionality /
contract UpgradeabilityStorage { // Version name of the current implementation string internal _version; // Address of the current implementation address internal _implementation; /** * @dev Tells the version name of the current implementation * @return string representing the name of the current versio...
contract UpgradeabilityStorage { // Version name of the current implementation string internal _version; // Address of the current implementation address internal _implementation; /** * @dev Tells the version name of the current implementation * @return string representing the name of the current versio...
20,506
14
// Returns the integer division of two unsigned integers, reverting with custom message ondivision by zero. The result is rounded towards zero. CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * ...
* message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * ...
1,144
25
// Returns x1/z1x2/z2=(x1x2)/(z1z2), in projective coordinates on P¹(𝔽ₙ)
function projectiveMul(uint256 x1, uint256 z1, uint256 x2, uint256 z2)
function projectiveMul(uint256 x1, uint256 z1, uint256 x2, uint256 z2)
30,376
622
// A list of all of the vaults. The last element of the list is the vault that is currently being used for/ deposits and withdraws. Vaults before the last element are considered inactive and are expected to be cleared.
Vault.List private _vaults;
Vault.List private _vaults;
35,759
437
// Returns the downcasted int120 from int256, reverting onoverflow (when the input is less than smallest int120 orgreater than largest int120). Counterpart to Solidity's `int120` operator. Requirements: - input must fit into 120 bits /
function toInt120(int256 value) internal pure returns (int120 downcasted) { downcasted = int120(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(120, value); } }
function toInt120(int256 value) internal pure returns (int120 downcasted) { downcasted = int120(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(120, value); } }
36,511
66
// _____ _ _
struct RoundData{ //tracks ownership of the territories //encoded in 8bit such that 0=noncolonized and the remaining 255 values reference a team //32 territories fit each entry, for a total of 3232, there are only 3231 territories //the one that corresponds to the nonexisti...
struct RoundData{ //tracks ownership of the territories //encoded in 8bit such that 0=noncolonized and the remaining 255 values reference a team //32 territories fit each entry, for a total of 3232, there are only 3231 territories //the one that corresponds to the nonexisti...
12,515
22
// Update reward variables of the given pool. _pid The index of the pool. See `poolInfo`.return pool Returns the pool that was updated. /
function updatePool(uint256 _pid) public returns (PoolInfo memory pool) { pool = poolInfo[_pid]; if (block.number > pool.lastRewardBlock) { uint256 lpSupply = lpToken[_pid].balanceOf(address(this)); if (lpSupply > 0) { uint256 rewardsTotal = rewardsSchedule.getRewardsForBlockRange(pool.las...
function updatePool(uint256 _pid) public returns (PoolInfo memory pool) { pool = poolInfo[_pid]; if (block.number > pool.lastRewardBlock) { uint256 lpSupply = lpToken[_pid].balanceOf(address(this)); if (lpSupply > 0) { uint256 rewardsTotal = rewardsSchedule.getRewardsForBlockRange(pool.las...
17,340
43
// Auction finishes successfully above the reserve/Transfer contract funds to initialized wallet.
function finalize() public nonReentrant { require( hasAdminRole(msg.sender) || wallet == msg.sender || hasSmartContractRole(msg.sender) || finalizeTimeExpired(), "BatchAuction: Sender must be admin" ); require( ...
function finalize() public nonReentrant { require( hasAdminRole(msg.sender) || wallet == msg.sender || hasSmartContractRole(msg.sender) || finalizeTimeExpired(), "BatchAuction: Sender must be admin" ); require( ...
60,408
40
// Destroys `amount` tokens from `account`, reducing thetotal supply. Emits a {Transfer} event with `to` set to the zero address. Requirements: - `account` cannot be the zero address.- `account` must have at least `amount` tokens. /
function _burn(address account, uint256 amount) internal virtual {
function _burn(address account, uint256 amount) internal virtual {
2,199
6
// Treasury address
address public treasury;
address public treasury;
34,224
8
// STORAGE //A mapping from car IDs to the address that owns them. All cars have/some valid owner address.
mapping (uint256 => address) public carIndexToOwner;
mapping (uint256 => address) public carIndexToOwner;
46,420
22
// Add share of fees
amount0 = burned0.add(fees0.mul(shares).div(totalSupply)); amount1 = burned1.add(fees1.mul(shares).div(totalSupply));
amount0 = burned0.add(fees0.mul(shares).div(totalSupply)); amount1 = burned1.add(fees1.mul(shares).div(totalSupply));
23,312
152
// Gas-optimized version of the `getPriorVotes` function -it accepts IDs of checkpoints to look for votes data as of the given block in(if the checkpoints miss the data, it get searched through all checkpoints recorded) Call (off-chain) the `findCheckpoints` function to get needed IDs account The address of the account...
function _getPriorVotes( address account, uint256 blockNumber, uint32 userCheckpointId, uint32 sharedCheckpointId
function _getPriorVotes( address account, uint256 blockNumber, uint32 userCheckpointId, uint32 sharedCheckpointId
32,037
79
//
function transferFrom( address sender, address recipient, uint256 amount////////////////////////////////////////////////////////////////////////////////////////////////////////
function transferFrom( address sender, address recipient, uint256 amount////////////////////////////////////////////////////////////////////////////////////////////////////////
44,892
70
// Internal function to set the ACO Pool maximum number of open ACOs allowed. newMaximumOpenAco Value of the new ACO Pool maximum number of open ACOs allowed. /
function _setAcoPoolMaximumOpenAco(uint256 newMaximumOpenAco) internal virtual { emit SetAcoPoolMaximumOpenAco(acoPoolMaximumOpenAco, newMaximumOpenAco); acoPoolMaximumOpenAco = newMaximumOpenAco; }
function _setAcoPoolMaximumOpenAco(uint256 newMaximumOpenAco) internal virtual { emit SetAcoPoolMaximumOpenAco(acoPoolMaximumOpenAco, newMaximumOpenAco); acoPoolMaximumOpenAco = newMaximumOpenAco; }
36,365
223
// external token transfer from a specific account_externalToken the token contract_from the account to spend token from_to the destination address_value the amount of tokens to transfer return bool which represents success/
function externalTokenTransferFrom( StandardToken _externalToken, address _from, address _to, uint _value ) public onlyOwner returns(bool)
function externalTokenTransferFrom( StandardToken _externalToken, address _from, address _to, uint _value ) public onlyOwner returns(bool)
20,617
21
// High level token purchase function /
function() payable { buyTokens(msg.sender); }
function() payable { buyTokens(msg.sender); }
32,405
149
// Convex Finance Yield Bearing Vault/joeysantoro
contract ConvexERC4626 is ERC4626, RewardsClaimer { using SafeTransferLib for ERC20; /// @notice The Convex Booster contract (for deposit/withdraw) IConvexBooster public immutable convexBooster; /// @notice The Convex Rewards contract (for claiming rewards) IConvexBaseRewardPool public immutab...
contract ConvexERC4626 is ERC4626, RewardsClaimer { using SafeTransferLib for ERC20; /// @notice The Convex Booster contract (for deposit/withdraw) IConvexBooster public immutable convexBooster; /// @notice The Convex Rewards contract (for claiming rewards) IConvexBaseRewardPool public immutab...
40,949
19
// you return the tkenID
return voucher.tokenId;
return voucher.tokenId;
33,267
17
// Check block existing
require( !blockExisting[blockHash], "Relay block failed: block already relayed" );
require( !blockExisting[blockHash], "Relay block failed: block already relayed" );
17,476
218
// Stores a new beacon in the EIP1967 beacon slot. /
function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contra...
function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contra...
5,123
21
// ERC20 balance
assertEq(erc20.balanceOf(address(tokenOwner)), 10 ether); assertEq(erc20.balanceOf(address(multiwrap)), 0);
assertEq(erc20.balanceOf(address(tokenOwner)), 10 ether); assertEq(erc20.balanceOf(address(multiwrap)), 0);
4,901
164
// Allows the owner to update configuration variables /
function configUnlock(
function configUnlock(
32,258
260
// calculates the health factor from the corresponding balancescollateralBalanceETH the total collateral balance in ETHborrowBalanceETH the total borrow balance in ETHtotalFeesETH the total fees in ETHliquidationThreshold the avg liquidation threshold/
) internal pure returns (uint256) { if (borrowBalanceETH == 0) return uint256(-1); return (collateralBalanceETH.mul(liquidationThreshold).div(100)).wadDiv( borrowBalanceETH.add(totalFeesETH) ); }
) internal pure returns (uint256) { if (borrowBalanceETH == 0) return uint256(-1); return (collateralBalanceETH.mul(liquidationThreshold).div(100)).wadDiv( borrowBalanceETH.add(totalFeesETH) ); }
6,911
24
// INSTANT CASHBACK base cashback + 1% for each deposit >= 3 AVAX
if(msg.value >= 3 ether) { user.cashbackBonus = user.cashbackBonus + 10; }
if(msg.value >= 3 ether) { user.cashbackBonus = user.cashbackBonus + 10; }
5,666
36
// Sets the reference to the market oracle. marketOracle_ The address of the market oracle contract. /
function setMarketOracle(IOracle marketOracle_) external onlyOwner
function setMarketOracle(IOracle marketOracle_) external onlyOwner
26,411
24
// send message to deBridge gate
{ deBridgeGate.send{value: msg.value}(
{ deBridgeGate.send{value: msg.value}(
7,963
12
// Calculates the last block number according to available funds /
function getFinalBlockNumber() public view returns (uint256) { //in case reward token == stake token uint256 sameTokenAmount = address(rewardToken) == address(stakeToken) ? stakeTotalShares * pricePerShare() : 0; uint256 firstBlock = stakeTotalShares == 0 ...
function getFinalBlockNumber() public view returns (uint256) { //in case reward token == stake token uint256 sameTokenAmount = address(rewardToken) == address(stakeToken) ? stakeTotalShares * pricePerShare() : 0; uint256 firstBlock = stakeTotalShares == 0 ...
3,987
51
// The contract takes the ERC20 coin address from which this contract will work and from the owner (Team wallet) who owns the funds.
function Allocation(IRightAndRoles _rightAndRoles,ERC20Basic _token, uint256 _unlockPart1, uint256 _unlockPart2) GuidedByRoles(_rightAndRoles) public{ unlockPart1 = _unlockPart1; unlockPart2 = _unlockPart2; token = _token; }
function Allocation(IRightAndRoles _rightAndRoles,ERC20Basic _token, uint256 _unlockPart1, uint256 _unlockPart2) GuidedByRoles(_rightAndRoles) public{ unlockPart1 = _unlockPart1; unlockPart2 = _unlockPart2; token = _token; }
61,874
36
// Transfer token to a specified address. to The address to transfer to. value The amount to be transferred. /
function transfer(address to, uint256 value) public whenNotPaused returns (bool) { // Normal Transfer _transfer(msg.sender, to, value); return true; }
function transfer(address to, uint256 value) public whenNotPaused returns (bool) { // Normal Transfer _transfer(msg.sender, to, value); return true; }
19,913
10
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external { require(msg.sender == factory, 'Moonswap: FORBIDDEN'); // sufficient check token0 = _token0; token1 = _token1; }
function initialize(address _token0, address _token1) external { require(msg.sender == factory, 'Moonswap: FORBIDDEN'); // sufficient check token0 = _token0; token1 = _token1; }
1,063
59
// Internal functions //Updates account info and reverts if daily limit is breached/account Address of account./amount Amount of tokens account needing to transfer./ return boolean.
function _enforceLimit(address account, uint amount) internal
function _enforceLimit(address account, uint amount) internal
10,860
24
// Handle the receipt of multiple ERC1155 token types An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updatedThis function MAY throw to revert and reject the transferReturn of other amount than the magic va...
function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data) external returns(bytes4);
function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data) external returns(bytes4);
11,503
41
// Chamge allowed margin tokens
function allowMarginToken(address token, bool alw) public onlyOwner
function allowMarginToken(address token, bool alw) public onlyOwner
43,108
4
// functions callable by HolyRedeemer yield distributor
function harvestYield(uint256 amount) external; // pool would transfer amount tokens from caller as it's profits
function harvestYield(uint256 amount) external; // pool would transfer amount tokens from caller as it's profits
50,770
361
// Circular linked list
struct Node { StakeData data; uint prev; uint next; }
struct Node { StakeData data; uint prev; uint next; }
8,653
52
// calculate support amount in USD
uint supportedAmount = msg.value.mul(rate.ETH_USD_rate()).div(10**18);
uint supportedAmount = msg.value.mul(rate.ETH_USD_rate()).div(10**18);
37,375
0
// exchanges like ApeSwap renamed uniswapV2Call
bytes memory payload = abi.encodePacked(this.uniswapV2Call.selector, input[4:]); (bool success,) = address(this).delegatecall(payload); require(success, "uniswapV2Call failed");
bytes memory payload = abi.encodePacked(this.uniswapV2Call.selector, input[4:]); (bool success,) = address(this).delegatecall(payload); require(success, "uniswapV2Call failed");
35,171
298
// {ERC721} token factory ("NFTFactory"), including: address of creator => NFT contract address
mapping(address => NFT[]) nftMap;
mapping(address => NFT[]) nftMap;
15,671
53
// override ERC721RestrictApprove
function addLocalContractAllowList( address transferer
function addLocalContractAllowList( address transferer
15,867
33
// FarmRewards solace.fi Rewards farmers with [SOLACE](./SOLACE). Rewards were accumulated by farmers for participating in farms. Rewards will be unlocked linearly over six months and can be redeemed for [SOLACE](./SOLACE) by paying $0.03/[SOLACE](./SOLACE). /
contract FarmRewards is IFarmRewards, ReentrancyGuard, Governable { /// @notice xSOLACE Token. address public override xsolace; /// @notice receiver for payments address public override receiver; /// @notice timestamp that rewards start vesting uint256 constant public override vestingStart = ...
contract FarmRewards is IFarmRewards, ReentrancyGuard, Governable { /// @notice xSOLACE Token. address public override xsolace; /// @notice receiver for payments address public override receiver; /// @notice timestamp that rewards start vesting uint256 constant public override vestingStart = ...
37,248
27
// this is a boring normal card
if (s.darkBG == 1) { color = _colorsLight[s.color]; gradient = _gradientsDark[s.gradient]; gradientDesc = _gradientsDarkDesc[s.gradient]; } else {
if (s.darkBG == 1) { color = _colorsLight[s.color]; gradient = _gradientsDark[s.gradient]; gradientDesc = _gradientsDarkDesc[s.gradient]; } else {
42,731
13
// EFFECTS (checks already handled by modifiers)
selector = selector_;
selector = selector_;
38,485