Unnamed: 0
int64
0
7.36k
comments
stringlengths
3
35.2k
code_string
stringlengths
1
527k
code
stringlengths
1
527k
__index_level_0__
int64
0
88.6k
44
// Grant the right to call method `sig` to `who`/Only the root user (granted `ANY_SIG`) is able to call this method/sig Method signature (4Byte)/who Address of who should be able to call `sig`
function allowCaller(bytes32 sig, address who) public override callerIsRoot { _canCall[sig][who] = true; emit AllowCaller(sig, who); }
function allowCaller(bytes32 sig, address who) public override callerIsRoot { _canCall[sig][who] = true; emit AllowCaller(sig, who); }
40,907
343
// 3. Set weighted timestampi) For new _account, set up weighted timestamp
if (oldBalance.weightedTimestamp == 0) { _balances[_account].weightedTimestamp = SafeCastExtended.toUint32(block.timestamp); _mintScaled(_account, _getBalance(_account, _balances[_account])); return; }
if (oldBalance.weightedTimestamp == 0) { _balances[_account].weightedTimestamp = SafeCastExtended.toUint32(block.timestamp); _mintScaled(_account, _getBalance(_account, _balances[_account])); return; }
63,188
28
// Stakes tokens in the pool to earn rewards/amount The amount of tokens to stake
function stake(uint256 amount) external { /// ----------------------------------------------------------------------- /// Validation /// ----------------------------------------------------------------------- if (amount == 0) { return; } /// ----------------------------------------------------------------------- /// Storage loads /// ----------------------------------------------------------------------- uint256 accountBalance = balanceOf[msg.sender]; uint64 lastTimeRewardApplicable_ = lastTimeRewardApplicable(); uint256 totalSupply_ = totalSupply; uint256 rewardPerToken_ = _rewardPerToken( totalSupply_, lastTimeRewardApplicable_, rewardRate ); /// ----------------------------------------------------------------------- /// State updates /// ----------------------------------------------------------------------- // accrue rewards rewardPerTokenStored = rewardPerToken_; lastUpdateTime = lastTimeRewardApplicable_; rewards[msg.sender] = _earned( msg.sender, accountBalance, rewardPerToken_, rewards[msg.sender] ); userRewardPerTokenPaid[msg.sender] = rewardPerToken_; // stake totalSupply = totalSupply_ + amount; balanceOf[msg.sender] = accountBalance + amount; /// ----------------------------------------------------------------------- /// Effects /// ----------------------------------------------------------------------- stakeToken().safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); }
function stake(uint256 amount) external { /// ----------------------------------------------------------------------- /// Validation /// ----------------------------------------------------------------------- if (amount == 0) { return; } /// ----------------------------------------------------------------------- /// Storage loads /// ----------------------------------------------------------------------- uint256 accountBalance = balanceOf[msg.sender]; uint64 lastTimeRewardApplicable_ = lastTimeRewardApplicable(); uint256 totalSupply_ = totalSupply; uint256 rewardPerToken_ = _rewardPerToken( totalSupply_, lastTimeRewardApplicable_, rewardRate ); /// ----------------------------------------------------------------------- /// State updates /// ----------------------------------------------------------------------- // accrue rewards rewardPerTokenStored = rewardPerToken_; lastUpdateTime = lastTimeRewardApplicable_; rewards[msg.sender] = _earned( msg.sender, accountBalance, rewardPerToken_, rewards[msg.sender] ); userRewardPerTokenPaid[msg.sender] = rewardPerToken_; // stake totalSupply = totalSupply_ + amount; balanceOf[msg.sender] = accountBalance + amount; /// ----------------------------------------------------------------------- /// Effects /// ----------------------------------------------------------------------- stakeToken().safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); }
25,153
2
// ==========Constructor========================================/ Deploy this contract with given name, symbol, and decimals the caller of this constructor will become the owner of this contract name_ name of this token symbol_ symbol of this token decimals_ number of decimals this token will be based on /
constructor( string memory name_, string memory symbol_, uint8 decimals_
constructor( string memory name_, string memory symbol_, uint8 decimals_
44,468
10
// Gets 'numBits' consecutive bits from 'self', starting from the bit at 'startIndex'. Returns the bits as a 'uint'. Requires that:- '0 < numBits <= 256'- 'startIndex < 256'- 'numBits + startIndex <= 256'
function bits(uint self, uint8 startIndex, uint16 numBits) internal pure returns (uint) { require(0 < numBits && startIndex < 256 && startIndex + numBits <= 256); return self >> startIndex & ONES >> 256 - numBits; }
function bits(uint self, uint8 startIndex, uint16 numBits) internal pure returns (uint) { require(0 < numBits && startIndex < 256 && startIndex + numBits <= 256); return self >> startIndex & ONES >> 256 - numBits; }
61,232
30
// Contract which oversees inter-pToken operations /
IComptroller public comptroller;
IComptroller public comptroller;
42,896
148
// Get controllers for a given partition. partition Name of the partition.return Array of controllers for partition. /
function controllersByPartition(bytes32 partition) external view returns (address[] memory) { return _controllersByPartition[partition]; }
function controllersByPartition(bytes32 partition) external view returns (address[] memory) { return _controllersByPartition[partition]; }
7,160
44
// Borrower clears the debt then closes the credit line
credits[id] = _close(_repay(credit, id, totalOwed, borrower), id);
credits[id] = _close(_repay(credit, id, totalOwed, borrower), id);
39,084
221
// Get Actual id to mint
uint256 _index = totalSupply(); uint256 _realIndex = getValue(_index) + 1;
uint256 _index = totalSupply(); uint256 _realIndex = getValue(_index) + 1;
20,532
6
// check they haven't voted before
require(!voters[msg.sender]);
require(!voters[msg.sender]);
17,528
220
// copy the bytes from returndata[0:_toCopy]
returndatacopy(add(_returnData, 0x20), 0, _toCopy)
returndatacopy(add(_returnData, 0x20), 0, _toCopy)
40,226
11
// 5% to the devs for being sick cunts
address payable devAddress = owner; devAddress.transfer(amountForDevs);
address payable devAddress = owner; devAddress.transfer(amountForDevs);
39,619
12
// Calculate masks.
uint256 index = _slot / votesPerWord; uint256 offset = (_slot % votesPerWord) * bitsPerVote; uint256 mask = ((1 << bitsPerVote) - 1) << offset;
uint256 index = _slot / votesPerWord; uint256 offset = (_slot % votesPerWord) * bitsPerVote; uint256 mask = ((1 << bitsPerVote) - 1) << offset;
44,186
117
// position is either more safe, or the owner consents
if ((deltaNormalDebt > 0 || deltaCollateral < 0) && !hasDelegate(user, msg.sender)) revert Codex__modifyCollateralAndDebt_notAllowedSender();
if ((deltaNormalDebt > 0 || deltaCollateral < 0) && !hasDelegate(user, msg.sender)) revert Codex__modifyCollateralAndDebt_notAllowedSender();
23,128
16
// Set the maximum id of the honorary token set
_maxHonoryTokenId = maximumHonoraryTokenId;
_maxHonoryTokenId = maximumHonoraryTokenId;
14,063
12
// Create basic chests types
setChestProduct(1, 0, 1, false, 0, 0, 0, 0, 0); setChestProduct(2, 15 finney, 3, false, 0, 0, 0, 0, 0); setChestProduct(3, 20 finney, 5, false, 0, 0, 0, 0, 0);
setChestProduct(1, 0, 1, false, 0, 0, 0, 0, 0); setChestProduct(2, 15 finney, 3, false, 0, 0, 0, 0, 0); setChestProduct(3, 20 finney, 5, false, 0, 0, 0, 0, 0);
17,897
6
// transfer token to owner
ERC20Interface(tokenContractAddress).transfer(owner, order.onchainAmount); order.state = OrderState.Claimed; emit OrderClaimed(orderUUID);
ERC20Interface(tokenContractAddress).transfer(owner, order.onchainAmount); order.state = OrderState.Claimed; emit OrderClaimed(orderUUID);
46,706
28
// must settle funding first
Funding.Growth memory fundingGrowthGlobal = _settleFunding(trader, params.baseToken);
Funding.Growth memory fundingGrowthGlobal = _settleFunding(trader, params.baseToken);
8,247
14
// and remove the proposal
delete props[_propID]; ProposalWithdrawn(_propID);
delete props[_propID]; ProposalWithdrawn(_propID);
12,160
10
// UTILITY FUNCTIONS//Get operating status of contract return A bool that is the current operating status/
function isOperational() external returns(bool)
function isOperational() external returns(bool)
2,373
6
// Transfers a specific NFT (`tokenId`) from one account (`from`) toanother (`to`).Requirements:- `from`, `to` cannot be zero.- `tokenId` must be owned by `from`.- If the caller is not `from`, it must be have been allowed to move thisNFT by either `approve` or `setApproveForAll`. /
function safeTransferFrom(address from, address to, uint256 tokenId) virtual public payable;
function safeTransferFrom(address from, address to, uint256 tokenId) virtual public payable;
10,542
35
// throw if called with SGR token contract address as destination./
modifier blockSGRTokenContractAddress(address _destination) { address sgrTokenContractAddress = getSGRTokenContractAddress(); require(_destination != sgrTokenContractAddress , "SGA cannot be sent directly to the SGRToken smart contract"); _; }
modifier blockSGRTokenContractAddress(address _destination) { address sgrTokenContractAddress = getSGRTokenContractAddress(); require(_destination != sgrTokenContractAddress , "SGA cannot be sent directly to the SGRToken smart contract"); _; }
53,144
235
// Checks if a specific balance decrease is allowed(i.e. doesn't bring the user borrow position health factor under HEALTH_FACTOR_LIQUIDATION_THRESHOLD) asset The address of the underlying asset of the reserve user The address of the user amount The amount to decrease reservesData The data of all the reserves userConfig The user configuration reserves The list of all the active reserves oracle The address of the oracle contractreturn true if the decrease of the balance is allowed /
) external view returns (bool) { if (!userConfig.isBorrowingAny() || !userConfig.isUsingAsCollateral(reservesData[asset].id)) { return true; } balanceDecreaseAllowedLocalVars memory vars; (, vars.liquidationThreshold, , vars.decimals, ) = reservesData[asset] .configuration .getParams(); if (vars.liquidationThreshold == 0) { return true; } ( vars.totalCollateralInETH, vars.totalDebtInETH, , vars.avgLiquidationThreshold, ) = calculateUserAccountData(user, reservesData, userConfig, reserves, reservesCount, oracle); if (vars.totalDebtInETH == 0) { return true; } vars.amountToDecreaseInETH = IPriceOracleGetter(oracle).getAssetPrice(asset).mul(amount).div( 10**vars.decimals ); vars.collateralBalanceAfterDecrease = vars.totalCollateralInETH.sub(vars.amountToDecreaseInETH); //if there is a borrow, there can't be 0 collateral if (vars.collateralBalanceAfterDecrease == 0) { return false; } vars.liquidationThresholdAfterDecrease = vars .totalCollateralInETH .mul(vars.avgLiquidationThreshold) .sub(vars.amountToDecreaseInETH.mul(vars.liquidationThreshold)) .div(vars.collateralBalanceAfterDecrease); uint256 healthFactorAfterDecrease = calculateHealthFactorFromBalances( vars.collateralBalanceAfterDecrease, vars.totalDebtInETH, vars.liquidationThresholdAfterDecrease ); return healthFactorAfterDecrease >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD; }
) external view returns (bool) { if (!userConfig.isBorrowingAny() || !userConfig.isUsingAsCollateral(reservesData[asset].id)) { return true; } balanceDecreaseAllowedLocalVars memory vars; (, vars.liquidationThreshold, , vars.decimals, ) = reservesData[asset] .configuration .getParams(); if (vars.liquidationThreshold == 0) { return true; } ( vars.totalCollateralInETH, vars.totalDebtInETH, , vars.avgLiquidationThreshold, ) = calculateUserAccountData(user, reservesData, userConfig, reserves, reservesCount, oracle); if (vars.totalDebtInETH == 0) { return true; } vars.amountToDecreaseInETH = IPriceOracleGetter(oracle).getAssetPrice(asset).mul(amount).div( 10**vars.decimals ); vars.collateralBalanceAfterDecrease = vars.totalCollateralInETH.sub(vars.amountToDecreaseInETH); //if there is a borrow, there can't be 0 collateral if (vars.collateralBalanceAfterDecrease == 0) { return false; } vars.liquidationThresholdAfterDecrease = vars .totalCollateralInETH .mul(vars.avgLiquidationThreshold) .sub(vars.amountToDecreaseInETH.mul(vars.liquidationThreshold)) .div(vars.collateralBalanceAfterDecrease); uint256 healthFactorAfterDecrease = calculateHealthFactorFromBalances( vars.collateralBalanceAfterDecrease, vars.totalDebtInETH, vars.liquidationThresholdAfterDecrease ); return healthFactorAfterDecrease >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD; }
16,654
126
// Gets the current nonce for a wallet._wallet The target wallet./
function getNonce(address _wallet) external view returns (uint256 nonce) { return relayer[_wallet].nonce; }
function getNonce(address _wallet) external view returns (uint256 nonce) { return relayer[_wallet].nonce; }
26,255
24
// includes:rewards available next periodrewards qualified after the next periodremoves rewards that have been claimed /
uint _totalRewards = currentlyClaimableRewards[_gauge][_token] + _pendingRewardsAmount - currentlyClaimedRewards[_gauge][_token];
uint _totalRewards = currentlyClaimableRewards[_gauge][_token] + _pendingRewardsAmount - currentlyClaimedRewards[_gauge][_token];
23,697
34
// Used only by the wizard to check his commission.
function getCommission() onlywizard constant returns (uint com) { return this.balance-totalBalances; }
function getCommission() onlywizard constant returns (uint com) { return this.balance-totalBalances; }
53,511
181
// Tell the information related to a term based on its ID_termId ID of the term being queried return startTime Term start time return randomnessBN Block number used for randomness in the requested term return randomness Randomness computed for the requested term/
function getTerm(uint64 _termId) external view returns (uint64 startTime, uint64 randomnessBN, bytes32 randomness);
function getTerm(uint64 _termId) external view returns (uint64 startTime, uint64 randomnessBN, bytes32 randomness);
19,441
17
// Transfer tokens Send `_value` tokens to `_to` from your account_to The address of the recipient _value the amount to send /
function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; }
function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; }
9,819
114
// Black addresses for blocking trade
mapping(address => bool) public blacklist;
mapping(address => bool) public blacklist;
1,930
3
// Deatils for a sale. initiatorNFTAddress The address of the initiator's nft contract. initiator The address of the initiator. initiatorNftId The Id of the initiator's token. requestedTokenOwner The address of the requested token's owner. requestedTokenId The Id of the requested token. requestedTokenAddress The address of the requested token's contract. status Boolean indicating the status of the swap. /
struct Swap { address initiatorNFTAddress; address initiator; uint256 initiatorNftId; address requestedTokenOwner; uint256 requestedTokenId; address requestedTokenAddress; bool status; }
struct Swap { address initiatorNFTAddress; address initiator; uint256 initiatorNftId; address requestedTokenOwner; uint256 requestedTokenId; address requestedTokenAddress; bool status; }
23,759
166
// Emitted when the default fee percentage is updated./newDefaultFeePercentage The new default fee percentage.
event DefaultFeePercentageUpdated(address indexed user, uint256 newDefaultFeePercentage);
event DefaultFeePercentageUpdated(address indexed user, uint256 newDefaultFeePercentage);
80,647
50
// CSportsTeam Interface/This interface defines methods required by the CSportsContestCore/ in implementing a contest./CryptoSports
contract CSportsTeam { bool public isTeamContract; /// @dev Define team events event TeamCreated(uint256 teamId, address owner); event TeamUpdated(uint256 teamId); event TeamReleased(uint256 teamId); event TeamScored(uint256 teamId, int32 score, uint32 place); event TeamPaid(uint256 teamId); function setCoreContractAddress(address _address) public; function setLeagueRosterContractAddress(address _address) public; function setContestContractAddress(address _address) public; function createTeam(address _owner, uint32[] _tokenIds) public returns (uint32); function updateTeam(address _owner, uint32 _teamId, uint8[] _indices, uint32[] _tokenIds) public; function releaseTeam(uint32 _teamId) public; function getTeamOwner(uint32 _teamId) public view returns (address); function scoreTeams(uint32[] _teamIds, int32[] _scores, uint32[] _places) public; function getScore(uint32 _teamId) public view returns (int32); function getPlace(uint32 _teamId) public view returns (uint32); function ownsPlayerTokens(uint32 _teamId) public view returns (bool); function refunded(uint32 _teamId) public; function tokenIdsForTeam(uint32 _teamId) public view returns (uint32, uint32[50]); function getTeam(uint32 _teamId) public view returns ( address _owner, int32 _score, uint32 _place, bool _holdsEntryFee, bool _ownsPlayerTokens); }
contract CSportsTeam { bool public isTeamContract; /// @dev Define team events event TeamCreated(uint256 teamId, address owner); event TeamUpdated(uint256 teamId); event TeamReleased(uint256 teamId); event TeamScored(uint256 teamId, int32 score, uint32 place); event TeamPaid(uint256 teamId); function setCoreContractAddress(address _address) public; function setLeagueRosterContractAddress(address _address) public; function setContestContractAddress(address _address) public; function createTeam(address _owner, uint32[] _tokenIds) public returns (uint32); function updateTeam(address _owner, uint32 _teamId, uint8[] _indices, uint32[] _tokenIds) public; function releaseTeam(uint32 _teamId) public; function getTeamOwner(uint32 _teamId) public view returns (address); function scoreTeams(uint32[] _teamIds, int32[] _scores, uint32[] _places) public; function getScore(uint32 _teamId) public view returns (int32); function getPlace(uint32 _teamId) public view returns (uint32); function ownsPlayerTokens(uint32 _teamId) public view returns (bool); function refunded(uint32 _teamId) public; function tokenIdsForTeam(uint32 _teamId) public view returns (uint32, uint32[50]); function getTeam(uint32 _teamId) public view returns ( address _owner, int32 _score, uint32 _place, bool _holdsEntryFee, bool _ownsPlayerTokens); }
23,633
161
// Maximum number of tokens per mint
uint256 public maxMintAmount = 10;
uint256 public maxMintAmount = 10;
80,067
142
// TWAMM
longTermOrders.initialize(_token0); emit LpFeeUpdated(_fee);
longTermOrders.initialize(_token0); emit LpFeeUpdated(_fee);
26,549
44
// pool has less liquidity
if(currentLiquidity < noOfTokens) { noOfTokensAvailable = currentLiquidity; }
if(currentLiquidity < noOfTokens) { noOfTokensAvailable = currentLiquidity; }
10,279
4
// interfaces
import {ILSP4Compatibility} from "./ILSP4Compatibility.sol"; // modules import {ERC725YCore} from "@erc725/smart-contracts/contracts/ERC725YCore.sol"; // constants import "./LSP4Constants.sol"; /** * @title LSP4Compatibility * @author Matthew Stevens * @dev LSP4 extension, for compatibility with clients & tools that expect ERC20/721. */ abstract contract LSP4Compatibility is ILSP4Compatibility, ERC725YCore { // --- Token queries /** * @dev Returns the name of the token. * @return The name of the token */ function name() public view virtual override returns (string memory) { bytes memory data = _getData(_LSP4_TOKEN_NAME_KEY); return string(data); } /** * @dev Returns the symbol of the token, usually a shorter version of the name. * @return The symbol of the token */ function symbol() public view virtual override returns (string memory) { bytes memory data = _getData(_LSP4_TOKEN_SYMBOL_KEY); return string(data); } }
import {ILSP4Compatibility} from "./ILSP4Compatibility.sol"; // modules import {ERC725YCore} from "@erc725/smart-contracts/contracts/ERC725YCore.sol"; // constants import "./LSP4Constants.sol"; /** * @title LSP4Compatibility * @author Matthew Stevens * @dev LSP4 extension, for compatibility with clients & tools that expect ERC20/721. */ abstract contract LSP4Compatibility is ILSP4Compatibility, ERC725YCore { // --- Token queries /** * @dev Returns the name of the token. * @return The name of the token */ function name() public view virtual override returns (string memory) { bytes memory data = _getData(_LSP4_TOKEN_NAME_KEY); return string(data); } /** * @dev Returns the symbol of the token, usually a shorter version of the name. * @return The symbol of the token */ function symbol() public view virtual override returns (string memory) { bytes memory data = _getData(_LSP4_TOKEN_SYMBOL_KEY); return string(data); } }
7,929
27
// Funding was successful for this ruling option.
if (ruling == finalRuling) {
if (ruling == finalRuling) {
10,496
26
// Returns the downcasted uint112 from uint256, reverting onoverflow (when the input is greater than largest uint112). Counterpart to Solidity's `uint112` operator. Requirements: - input must fit into 112 bits _Available since v4.7._ /
function toUint112(uint256 value) internal pure returns (uint112) { require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits"); return uint112(value); }
function toUint112(uint256 value) internal pure returns (uint112) { require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits"); return uint112(value); }
32,144
12
// token id => extra info v2
mapping(uint256 => ExtraInfos.ExtraInfoV2) public extraInfoV2; function initialize(address _admin, string memory _uri) public initializer
mapping(uint256 => ExtraInfos.ExtraInfoV2) public extraInfoV2; function initialize(address _admin, string memory _uri) public initializer
34,086
257
// remove
uint256 remove = staked.sub(total.mul(mean).div(denominator)); IStakingProxy(stakingProxy).withdraw(remove);
uint256 remove = staked.sub(total.mul(mean).div(denominator)); IStakingProxy(stakingProxy).withdraw(remove);
4,951
0
// ================================= only people with tokens
modifier onlyTokenHolders()
modifier onlyTokenHolders()
26,060
21
// Self renounce the address calling the function from admin, minter and burner role /
function renounceAdminAndMinterAndBurner() public virtual override { renounceRole(DEFAULT_ADMIN_ROLE, msg.sender); renounceRole(MINTER_ROLE, msg.sender); renounceRole(BURNER_ROLE, msg.sender); }
function renounceAdminAndMinterAndBurner() public virtual override { renounceRole(DEFAULT_ADMIN_ROLE, msg.sender); renounceRole(MINTER_ROLE, msg.sender); renounceRole(BURNER_ROLE, msg.sender); }
18,132
30
// Second game interval in seconds./
uint256 constant GAME_INTERVAL_TWO = 345600;
uint256 constant GAME_INTERVAL_TWO = 345600;
2,532
15
// Withdraw the member's GRG balance
getGrgContract().transfer(member, balance);
getGrgContract().transfer(member, balance);
13,128
104
// public functions to do things
function transfer(address recipient, uint256 amount) public override returns (bool)
function transfer(address recipient, uint256 amount) public override returns (bool)
9,639
131
// Update a pool, allow to change end timestamp, reward per second _pid: pool id to be renew _endTime: timestamp where the reward ends _rewardPerSeconds: amount of reward token per second for the pool,0 if we want to stop the pool from accumulating rewards /
function updatePool( uint256 _pid, uint32 _endTime, uint256[] calldata _rewardPerSeconds
function updatePool( uint256 _pid, uint32 _endTime, uint256[] calldata _rewardPerSeconds
35,392
97
// Update node status if children sum amount is enough _node Node address _status Node current status /
function updateStatus(address _node, uint8 _status) private { uint refDep = data.referralDeposits(_node); for (uint i = thresholds.length - 1; i > _status; i--) { uint threshold = thresholds[i] * 100; if (refDep >= threshold) { data.setStatus(_node, statusThreshold[threshold]); break; } } }
function updateStatus(address _node, uint8 _status) private { uint refDep = data.referralDeposits(_node); for (uint i = thresholds.length - 1; i > _status; i--) { uint threshold = thresholds[i] * 100; if (refDep >= threshold) { data.setStatus(_node, statusThreshold[threshold]); break; } } }
80,673
19
// ROLES
bytes32 public constant LOCAL_ADMIN_ROLE = keccak256("LOCAL_ADMIN_ROLE");
bytes32 public constant LOCAL_ADMIN_ROLE = keccak256("LOCAL_ADMIN_ROLE");
19,789
125
// Reentrancy protection.
if (_currentIndex != end) revert();
if (_currentIndex != end) revert();
2,387
9
// Note that these will track, but not influence the BP logic.
uint public amountDeposited; uint public amountBurned; uint public amountReleased;
uint public amountDeposited; uint public amountBurned; uint public amountReleased;
50,174
50
// Admin function for setting the voting period newVotingPeriod new voting period, in blocks /
function _setVotingPeriod(uint256 newVotingPeriod) external { if (msg.sender != admin) { revert AdminOnly(); } require( newVotingPeriod >= MIN_VOTING_PERIOD && newVotingPeriod <= MAX_VOTING_PERIOD, 'NounsDAO::_setVotingPeriod: invalid voting period' ); uint256 oldVotingPeriod = votingPeriod; votingPeriod = newVotingPeriod; emit VotingPeriodSet(oldVotingPeriod, votingPeriod); }
function _setVotingPeriod(uint256 newVotingPeriod) external { if (msg.sender != admin) { revert AdminOnly(); } require( newVotingPeriod >= MIN_VOTING_PERIOD && newVotingPeriod <= MAX_VOTING_PERIOD, 'NounsDAO::_setVotingPeriod: invalid voting period' ); uint256 oldVotingPeriod = votingPeriod; votingPeriod = newVotingPeriod; emit VotingPeriodSet(oldVotingPeriod, votingPeriod); }
2,835
1
// ======== Immutable storage =========
address public immutable logic; address public immutable partyDAOMultisig; address public immutable tokenVaultFactory; address public immutable weth;
address public immutable logic; address public immutable partyDAOMultisig; address public immutable tokenVaultFactory; address public immutable weth;
21,046
4
// Events Review events
event MilestoneReviewRequested(); event MilestoneReviewRequestRejected(address reviewer); event MilestoneReviewRequestApproved(address reviewer);
event MilestoneReviewRequested(); event MilestoneReviewRequestRejected(address reviewer); event MilestoneReviewRequestApproved(address reviewer);
39,437
8
// Return calldata for the add liquidity call for a single asset /
function getProvideLiquiditySingleAssetCalldata( address /*_setToken*/, address /*_pool*/, address /*_component*/, uint256 /*_maxTokenIn*/, uint256 /*_minLiquidity*/ ) external view override
function getProvideLiquiditySingleAssetCalldata( address /*_setToken*/, address /*_pool*/, address /*_component*/, uint256 /*_maxTokenIn*/, uint256 /*_minLiquidity*/ ) external view override
2,119
160
// Role Management // Updates the Withdrawal Publisher address, the only address other than the owner thatcan publish / remove withdrawal Merkle tree roots. _newWithdrawalPublisher The address of the new Withdrawal Publisher Error invalid sender. /
function setWithdrawalPublisher(address _newWithdrawalPublisher) external { require(msg.sender == owner(), "Invalid sender"); address oldValue = withdrawalPublisher; withdrawalPublisher = _newWithdrawalPublisher; emit WithdrawalPublisherUpdate(oldValue, withdrawalPublisher); }
function setWithdrawalPublisher(address _newWithdrawalPublisher) external { require(msg.sender == owner(), "Invalid sender"); address oldValue = withdrawalPublisher; withdrawalPublisher = _newWithdrawalPublisher; emit WithdrawalPublisherUpdate(oldValue, withdrawalPublisher); }
9,211
13
// then, calculate the logistic function and rescale to 1e6
return 1e6 * 2**64 / ( 2**64 + expx );
return 1e6 * 2**64 / ( 2**64 + expx );
50,509
5
// 获取账户_spender可以从账户_owner中转出token的数量
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
24,878
16
// add Epic gene
uint[] memory positions = GenesLib.randomGenePositions(EPIC_RANGE, 1, randomValue); newGenes = GenesLib.randomSetGenesToPositions(newGenes, positions, randomValue, false);
uint[] memory positions = GenesLib.randomGenePositions(EPIC_RANGE, 1, randomValue); newGenes = GenesLib.randomSetGenesToPositions(newGenes, positions, randomValue, false);
40,091
104
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
mapping(address => mapping(address => bool)) private _operatorApprovals;
12,125
361
// Calculates how much token0 is entitled for a particular user
function _fee0Earned(address account, uint256 fee0PerShare_) internal view returns (uint256) { UserInfo memory user = userInfo[account]; return balanceOf(account) .mul(fee0PerShare_.sub(user.token0PerSharePaid)) .unsafeDiv(1e18) .add(user.token0Rewards); }
function _fee0Earned(address account, uint256 fee0PerShare_) internal view returns (uint256) { UserInfo memory user = userInfo[account]; return balanceOf(account) .mul(fee0PerShare_.sub(user.token0PerSharePaid)) .unsafeDiv(1e18) .add(user.token0Rewards); }
17,513
141
// |/|/ Allows anyone with a valid signature to transfer _amount amount of a token _id on the bahalf of _from _from Source address _to Target address _id ID of the token type _amount Transfered amount _isGasFee Whether gas is reimbursed to executor or not _data Encodes a meta transfer indicator, signature, gas payment receipt and extra transfer data_data should be encoded as ((bytes32 r, bytes32 s, uint8 v, uint256 nonce, SignatureType sigType),(GasReceipt g, ?bytes transferData))i.e. high level encoding should be (bytes, bytes), where the latter bytes array is a nested bytes array /
function metaSafeTransferFrom( address _from, address _to, uint256 _id, uint256 _amount, bool _isGasFee, bytes memory _data)
function metaSafeTransferFrom( address _from, address _to, uint256 _id, uint256 _amount, bool _isGasFee, bytes memory _data)
13,198
106
// See {IERC1155Inventory-ownerOf(uint256)}.
function ownerOf(uint256 nftId) public view virtual override returns (address) { address owner = address(_owners[nftId]); require(owner != address(0), "Inventory: non-existing NFT"); return owner; }
function ownerOf(uint256 nftId) public view virtual override returns (address) { address owner = address(_owners[nftId]); require(owner != address(0), "Inventory: non-existing NFT"); return owner; }
33,962
3
// Sets the metadata URIs for a batch of tokens./ids The token identifiers./uris The token metadata URIs.
function batchSetTokenURI( Layout storage s, uint256[] calldata ids, string[] calldata uris
function batchSetTokenURI( Layout storage s, uint256[] calldata ids, string[] calldata uris
14,678
49
// messageHash can be used only once
bytes32 messageHash = message(tx.origin, amount, deadline); require(!msgHash[messageHash], "Erne::claim: signature duplicate");
bytes32 messageHash = message(tx.origin, amount, deadline); require(!msgHash[messageHash], "Erne::claim: signature duplicate");
53,107
7
// owner
function setNewApprover(address newApprover) public onlyOwner
function setNewApprover(address newApprover) public onlyOwner
52,418
11
// After one year, LAND can be claimed from an inactive public key
function ping() external;
function ping() external;
12,043
7
// The reserve erc20 token. The reserve token anchors our newly minted redeemable tokens to an existant value system. The weights and balances of the reserve token and the minted token define a dynamic spot price in the AMM.
IERC20 reserve;
IERC20 reserve;
33,258
0
// -------------------------------------------------------------------------- // events // -------------------------------------------------------------------------- // -------------------------------------------------------------------------- //constants // -------------------------------------------------------------------------- // The HelloToken contract /
IERC20 public immutable HELLO_TOKEN;
IERC20 public immutable HELLO_TOKEN;
18,476
19
// Stores a new address in the EIP1967 admin slot. /
function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin; }
function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin; }
990
3
// Thrown when a pool of NFT is not in the whitelist
error InvalidPool();
error InvalidPool();
27,792
124
// deploy instance
instance = Factory._create(callData);
instance = Factory._create(callData);
31,042
2
// Mint all tokens to creator
balances[msg.sender] = INITIAL_SUPPLY; totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY; totalSupply_ = INITIAL_SUPPLY;
20,894
89
// Claims reward set by dev
function ClaimReward() external { claimToken(msg.sender,rewardToken, 0); }
function ClaimReward() external { claimToken(msg.sender,rewardToken, 0); }
27,312
24
// The quantity of tokens minted must be more than zero. /
error MintZeroQuantity();
error MintZeroQuantity();
193
190
// reward hpt
uint256 hptPending = user.amount.mul(pool.accHptPerShare).div(1e12).sub( user.rewardDebt ); safeHptTransfer(msg.sender, hptPending);
uint256 hptPending = user.amount.mul(pool.accHptPerShare).div(1e12).sub( user.rewardDebt ); safeHptTransfer(msg.sender, hptPending);
23,356
55
// Collects the included Gallery artwork for an OKPC./pcId The id of the OKPC being minted.
function _collectIncludedGalleryArt(uint256 pcId) internal { uint256 artId = _includedGalleryArtForOKPC(pcId); artCountForOKPC[pcId] = 1; artCollectedByOKPC[pcId][artId] = true; emit GalleryArtCollected(pcId, artId); activeArtForOKPC[pcId] = artId; clockSpeedData[pcId].artLastChanged = block.timestamp; emit ArtChanged(pcId, artId); }
function _collectIncludedGalleryArt(uint256 pcId) internal { uint256 artId = _includedGalleryArtForOKPC(pcId); artCountForOKPC[pcId] = 1; artCollectedByOKPC[pcId][artId] = true; emit GalleryArtCollected(pcId, artId); activeArtForOKPC[pcId] = artId; clockSpeedData[pcId].artLastChanged = block.timestamp; emit ArtChanged(pcId, artId); }
32,016
91
// Updates a deal by merchant_dealIndex deal index_newRewardRatePpm new reward rate ppm, 100% == 1000000/
function updateDeal(uint _dealIndex, uint _newRewardRatePpm) public onlyMerchant validDealIndex(_dealIndex) activeDeal(_dealIndex) { require(_newRewardRatePpm > 0, "_newRewardRatePpm should be >0."); deals[_dealIndex].rewardRatePpm = _newRewardRatePpm; emit DealUpdated(deals[_dealIndex].dealId, _newRewardRatePpm); }
function updateDeal(uint _dealIndex, uint _newRewardRatePpm) public onlyMerchant validDealIndex(_dealIndex) activeDeal(_dealIndex) { require(_newRewardRatePpm > 0, "_newRewardRatePpm should be >0."); deals[_dealIndex].rewardRatePpm = _newRewardRatePpm; emit DealUpdated(deals[_dealIndex].dealId, _newRewardRatePpm); }
47,724
22
// Transfer tokens from one address to another_from address The address which you want to send tokens from_to address The address which you want to transfer to_value uint256 the amount of tokens to be transferred/
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; }
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; }
1,752
6
// returns frozen state of given account /
{ return _frozenAccounts[_account]; }
{ return _frozenAccounts[_account]; }
29,235
32
// allocationSettings[settingId][expiry] = rewards portion of a pool for settingId
mapping(uint256 => mapping(uint256 => uint256)) public allocationSettings; LatestSetting public latestSetting; mapping(uint256 => ExpiryData) internal expiryData; mapping(uint256 => EpochData) private epochData; mapping(address => UserExpiries) private userExpiries;
mapping(uint256 => mapping(uint256 => uint256)) public allocationSettings; LatestSetting public latestSetting; mapping(uint256 => ExpiryData) internal expiryData; mapping(uint256 => EpochData) private epochData; mapping(address => UserExpiries) private userExpiries;
69,725
18
// netting by doing net balance movement // 1. confirm and dequeue active gridlocked payments/ require(pmtProved(gridlockQueue[j])); // to be changed / Changed
pmt.state = PmtState.Confirmed;
pmt.state = PmtState.Confirmed;
38,163
148
// ERC20 Unlimited Approvals (short-circuits VaultAPI.transferFrom)
uint256 constant UNLIMITED_APPROVAL = type(uint256).max;
uint256 constant UNLIMITED_APPROVAL = type(uint256).max;
41,403
106
// Wrap SURF into vSURF_weiAmount Amount of SURF tokens (in wei) to wrap into vSURF/
function wrap(uint256 _weiAmount)
function wrap(uint256 _weiAmount)
2,411
47
// Getter function for next requestId on queue/request with highest payout at time the function is called return onDeck/info on request with highest payout-- RequestId, Totaltips/
function getVariablesOnDeck(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256, uint256)
function getVariablesOnDeck(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256, uint256)
24,216
25
// Check if given address is dev or not /
function isDev(address _dealer) public view returns(bool)
function isDev(address _dealer) public view returns(bool)
9,710
174
// Update the state
unitContributions[_contributor] = previouslyContributedUnits.add(currentContributionUnits); totalContributedUnits = totalContributedUnits.add(currentContributionUnits); uint256 currentContributionWei = currentContributionUnits.mul(weiPerUnitRate); trustedVault.deposit.value(currentContributionWei)(msg.sender);
unitContributions[_contributor] = previouslyContributedUnits.add(currentContributionUnits); totalContributedUnits = totalContributedUnits.add(currentContributionUnits); uint256 currentContributionWei = currentContributionUnits.mul(weiPerUnitRate); trustedVault.deposit.value(currentContributionWei)(msg.sender);
52,011
36
// Throws if called by any account that's frozen./
modifier notFrozen { require(!frozenAccounts[msg.sender]); _; }
modifier notFrozen { require(!frozenAccounts[msg.sender]); _; }
18,824
184
// reused in constructor
function _setRoyaltiesBasisPoints(uint32 points) private { require(points <= MAX_ROYALTY_BASIS_POINTS, "Royalties too big"); royaltiesBasisPoints = points; }
function _setRoyaltiesBasisPoints(uint32 points) private { require(points <= MAX_ROYALTY_BASIS_POINTS, "Royalties too big"); royaltiesBasisPoints = points; }
65,871
20
// Balances for each account
mapping(address => uint256) balances;
mapping(address => uint256) balances;
43,355
7
// ========== CONSTRUCTOR ========== // Release Schedule must have the same start time./
constructor(address beneficiary_, address rewardToken_, address schedule_, uint256 startTime_) { beneficiary = beneficiary_; rewardToken = IERC20(rewardToken_); schedule = IReleaseSchedule(schedule_); startTime = startTime_; lastWithdrawalTime = IReleaseSchedule(schedule_).getStartOfCycle(1); lifetimeRewards = IReleaseSchedule(schedule_).getTokensForCycle(1).mul(2); }
constructor(address beneficiary_, address rewardToken_, address schedule_, uint256 startTime_) { beneficiary = beneficiary_; rewardToken = IERC20(rewardToken_); schedule = IReleaseSchedule(schedule_); startTime = startTime_; lastWithdrawalTime = IReleaseSchedule(schedule_).getStartOfCycle(1); lifetimeRewards = IReleaseSchedule(schedule_).getTokensForCycle(1).mul(2); }
47,990
103
// block number of liquidation trigger
mapping(address => mapping(address => uint)) public liquidationBlock;
mapping(address => mapping(address => uint)) public liquidationBlock;
31,142
13
// The token which is being bought and sold
ITradeableAsset public tokenContract;
ITradeableAsset public tokenContract;
52,979
4
// ERC721 contract
HunterHound public hunterHound;
HunterHound public hunterHound;
75,494
4
// Transfer asset from this contract to sender./assetData Byte array encoded for the respective asset proxy./amount Amount of asset to transfer to sender.
function transferOut( bytes memory assetData, uint256 amount ) internal
function transferOut( bytes memory assetData, uint256 amount ) internal
44,931
27
// 利用商品编号提取商品数据
Product storage product = stores[productIdInStore[_productId]][_productId];
Product storage product = stores[productIdInStore[_productId]][_productId];
41,880
3
// Any price request submitted to the OptimisticOracle must contain ancillary data no larger than this value. This value must be <= the Voting contract's `ancillaryBytesLimit` constant value otherwise it is possible that a price can be requested to the OptimisticOracle successfully, but cannot be resolved by the DVM which refuses to accept a price request made with ancillary data length over a certain size.
uint256 public constant ancillaryBytesLimit = 8192;
uint256 public constant ancillaryBytesLimit = 8192;
30,287
24
// remove NFT from user's list
userData.userNFTs[i] = userData.userNFTs[userData.userNFTs.length - 1]; userData.userNFTs.pop();
userData.userNFTs[i] = userData.userNFTs[userData.userNFTs.length - 1]; userData.userNFTs.pop();
6,955
38
// Should have enough balance.
if (_balanceOf(_fromId, _symbol) < _value) { _error("Insufficient balance"); return false; }
if (_balanceOf(_fromId, _symbol) < _value) { _error("Insufficient balance"); return false; }
21,863
6
// Precision related
uint256 private PRICE_PRECISION;
uint256 private PRICE_PRECISION;
36,157
163
// Need to make gas fee customizable to future-proof against Ethereum network upgrades.
require(newValue != gasForProcessing, "TENSHI: Cannot update gasForProcessing to same value"); emit GasForProcessingUpdated(newValue, gasForProcessing); gasForProcessing = newValue;
require(newValue != gasForProcessing, "TENSHI: Cannot update gasForProcessing to same value"); emit GasForProcessingUpdated(newValue, gasForProcessing); gasForProcessing = newValue;
27,514