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
29
// Update balance of receiving address
balances[_to] = balances[_to].add(_value);
balances[_to] = balances[_to].add(_value);
83,678
23
// Since we already have a true random seed, we will use it to create more /
function getRandomForPlacing(uint seed, uint place) private pure returns (uint256) { return uint256(keccak256(abi.encode(seed, place))); }
function getRandomForPlacing(uint seed, uint place) private pure returns (uint256) { return uint256(keccak256(abi.encode(seed, place))); }
29,174
146
// season
_seasonWeiRewarded[_season] = _seasonWeiRewarded[_season].add(__weiReward);
_seasonWeiRewarded[_season] = _seasonWeiRewarded[_season].add(__weiReward);
8,078
29
// Track all registered oracles
mapping(address => Oracle) private oracles;
mapping(address => Oracle) private oracles;
43,507
29
// if employee is terminated but we calc options before term, simulate employed again
if (calcAtTime < employee.terminatedAt && employee.terminatedAt > 0) { employee.state = EmployeeState.Employed; }
if (calcAtTime < employee.terminatedAt && employee.terminatedAt > 0) { employee.state = EmployeeState.Employed; }
16,531
100
// allocate funds to advisors
token.mint(vestingApplicature, 1500000 * tokenPrecision); token.mint(vestingSimonCocking, 750000 * tokenPrecision); token.mint(vestingNathanChristian, 750000 * tokenPrecision); token.mint(vestingEdwinVanBerg, 300000 * tokenPrecision);
token.mint(vestingApplicature, 1500000 * tokenPrecision); token.mint(vestingSimonCocking, 750000 * tokenPrecision); token.mint(vestingNathanChristian, 750000 * tokenPrecision); token.mint(vestingEdwinVanBerg, 300000 * tokenPrecision);
38,484
141
// UNI
IUniswapV2Factory uniFactory = IUniswapV2Factory(factory); IUniswapV2Exchange pair = uniFactory.getPair(_from, _to); if (address(pair) != address(0)) { (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); (address token0, ) = sortTokens(fromAddress, toAddress); (reserveA, reserveB) = fromAddress == token0 ? (reserve0, reserve1)
IUniswapV2Factory uniFactory = IUniswapV2Factory(factory); IUniswapV2Exchange pair = uniFactory.getPair(_from, _to); if (address(pair) != address(0)) { (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); (address token0, ) = sortTokens(fromAddress, toAddress); (reserveA, reserveB) = fromAddress == token0 ? (reserve0, reserve1)
50,465
59
// In the event that a feed is failed over to Uniswap TWAP, this function can be calledby anyone to update the TWAP price. This only works if the feed represented by the symbolHash is failed over, and will revert otherwise symbolHash bytes32 /
function pokeFailedOverPrice(bytes32 symbolHash) public { PriceData memory priceData = prices[symbolHash]; require(priceData.failoverActive, "Failover must be active"); TokenConfig memory config = getTokenConfigBySymbolHash(symbolHash); uint anchorPrice = calculateAnchorPriceFromEthPrice(config); require(anchorPrice < 2**248, "Anchor price too large"); prices[config.symbolHash].price = uint248(anchorPrice); emit PriceUpdated(config.symbolHash, anchorPrice); }
function pokeFailedOverPrice(bytes32 symbolHash) public { PriceData memory priceData = prices[symbolHash]; require(priceData.failoverActive, "Failover must be active"); TokenConfig memory config = getTokenConfigBySymbolHash(symbolHash); uint anchorPrice = calculateAnchorPriceFromEthPrice(config); require(anchorPrice < 2**248, "Anchor price too large"); prices[config.symbolHash].price = uint248(anchorPrice); emit PriceUpdated(config.symbolHash, anchorPrice); }
66,221
54
// Number of real (i.e. non-virtual) tokens in circulation. /
uint256 internal tokensCount;
uint256 internal tokensCount;
29,673
0
// 토큰 배포할 양
_mint(msg.sender, 2100 * 10000);
_mint(msg.sender, 2100 * 10000);
9,092
186
// Logic code implementation contact constructorMUST be called by deployer only if contract has not been initialized before/
function init( string memory _name, string memory _symbol, address _proxyRegistryAddress, string memory baseURI, address _owner,
function init( string memory _name, string memory _symbol, address _proxyRegistryAddress, string memory baseURI, address _owner,
4,512
904
// impl by NFToken contract, mint an NFT with id and uri to user or burn
function mint( address to, uint256 id, string memory uri ) external; function burn(uint256 id) external;
function mint( address to, uint256 id, string memory uri ) external; function burn(uint256 id) external;
5,419
32
// 2. check whether or not a user's rDAI balance is the same as hoodie contract's
uint256 _userRDaiBalance = rDAIContract.balanceOf(_userAddress); require(_userRDaiBalance >= _user.daiDeposited, "user's rDAI balance is smaller than the hoodie contract's"); return true;
uint256 _userRDaiBalance = rDAIContract.balanceOf(_userAddress); require(_userRDaiBalance >= _user.daiDeposited, "user's rDAI balance is smaller than the hoodie contract's"); return true;
11,902
28
// Add a new reward token to the pool Can only be called by the owner. DO NOT add the same token more than once. Rewards will be messed up if you do. allocPoint Number of allocation points to allot to this token/pool token The token that will be staked for rewards withUpdate if specified, update all pools before adding new pool _depositFeeBp If true, users get voting power for deposits /
function add( uint256 allocPoint, address token, bool withUpdate, uint16 _depositFeeBp
function add( uint256 allocPoint, address token, bool withUpdate, uint16 _depositFeeBp
34,229
271
// Governance contract initialization. Can be external because Proxy contract intercepts illegal calls of this function./initializationParameters Encoded representation of initialization parameters:/ _networkGovernor The address of network governor
function initialize(bytes calldata initializationParameters) external { address _networkGovernor = abi.decode(initializationParameters, (address)); networkGovernor = _networkGovernor; }
function initialize(bytes calldata initializationParameters) external { address _networkGovernor = abi.decode(initializationParameters, (address)); networkGovernor = _networkGovernor; }
9,047
33
// Called by subscription owner to init withdraw sales /
function initWithdraw() external onlyEOA { uint256 index = idolIndex[msg.sender]; IdolProfile storage Idols = idolData[index]; require(Idols.idolAddress == msg.sender, "not owner"); PublicLock publock = PublicLock(Idols.lockAddress); uint256 lockBalance = address(Idols.lockAddress).balance; require(lockBalance > 0, "low balance"); try publock.withdraw(address(0), payable(address(this)), 0) {} catch Error(string memory _err) { emit ErrorWithdraw(_err); revert(); }
function initWithdraw() external onlyEOA { uint256 index = idolIndex[msg.sender]; IdolProfile storage Idols = idolData[index]; require(Idols.idolAddress == msg.sender, "not owner"); PublicLock publock = PublicLock(Idols.lockAddress); uint256 lockBalance = address(Idols.lockAddress).balance; require(lockBalance > 0, "low balance"); try publock.withdraw(address(0), payable(address(this)), 0) {} catch Error(string memory _err) { emit ErrorWithdraw(_err); revert(); }
26,495
12
// mintToCouncilOathRings mint council to token to_ address to mint quantity_ quantity per mint /
function mintToCouncilOathRings(address to_, uint256 quantity_) public onlyMinter { require(councilCount.current() + quantity_ - COUNT_OFFSET <= councilQuantity, 'quantity exceeds max supply'); for (uint256 i; i < quantity_; i++) { _safeMint(to_, councilCount.current()); councilCount.increment(); totalCount.increment(); } }
function mintToCouncilOathRings(address to_, uint256 quantity_) public onlyMinter { require(councilCount.current() + quantity_ - COUNT_OFFSET <= councilQuantity, 'quantity exceeds max supply'); for (uint256 i; i < quantity_; i++) { _safeMint(to_, councilCount.current()); councilCount.increment(); totalCount.increment(); } }
14,060
28
// tien lai
if (_contract.terms.loanAsset == address(0)) {
if (_contract.terms.loanAsset == address(0)) {
35,524
50
// players use this to change back to one of your old names.tip, you'llstill need to push that info to existing games.-functionhash- 0xb9291296 _nameString the name you want to use /
function useMyOldName(string _nameString) isHuman() public
function useMyOldName(string _nameString) isHuman() public
33,590
6
// The address of the Compound governance token
GAMERInterface public gamer;
GAMERInterface public gamer;
10,298
332
// Convert all LP tokens back into the pair of underlying assets. Also convert any Sushi equally into both tranches. The senior tranche is expecting to get paid some hurdle rate above where they started. Here are the possible outcomes:- If the senior tranche doesn't have enough, then sell some orall junior tokens to get the senior to the expectedreturns. In the worst case, the senior tranche could suffera loss and the junior tranche will be wiped out.- If the senior tranche has more than enough, reduce this tranche to the expected payoff. The excess senior tokens should be converted to
function redeem( uint256 _vaultId, uint256 _seniorExpected, uint256 _seniorMinReceived, uint256 _juniorMinReceived ) external override nonReentrant whenNotPaused
function redeem( uint256 _vaultId, uint256 _seniorExpected, uint256 _seniorMinReceived, uint256 _juniorMinReceived ) external override nonReentrant whenNotPaused
61,332
9
// The description of the project
string public projectDescription = "ASCIIWall is a blockchain-based shared canvas. Anyone can write on it. It's like latrinalia, but in the blockchain. Each mint captures the current state of the wall. Future mints can overwrite and augment the wall.";
string public projectDescription = "ASCIIWall is a blockchain-based shared canvas. Anyone can write on it. It's like latrinalia, but in the blockchain. Each mint captures the current state of the wall. Future mints can overwrite and augment the wall.";
24,863
171
// console.log("rand snak %s", snk.snakiness_s);
snk.snakiness_d = (random(seed, "snakiness__D") % 30) + 20; if (snk.snakiness_d < 25) { snk.snakiness_d = 0; }
snk.snakiness_d = (random(seed, "snakiness__D") % 30) + 20; if (snk.snakiness_d < 25) { snk.snakiness_d = 0; }
49,577
76
// transfer new token to sender
IHero( enabledModifications[modifierContract][modifierId].destinitionContract ).transferFrom(address(this), msg.sender, newToken);
IHero( enabledModifications[modifierContract][modifierId].destinitionContract ).transferFrom(address(this), msg.sender, newToken);
18,716
443
// Total supply of the nToken
uint96 totalSupply;
uint96 totalSupply;
6,045
2
// Event data structure
struct Event { address eventOwner; string eventName; string location; uint price; uint numAvail; string eventDate; }
struct Event { address eventOwner; string eventName; string location; uint price; uint numAvail; string eventDate; }
12,823
142
// Note that this can cascade so AuctionActive -> AuctionPending in one update, when auctionCooldown = 0.
if ( stage == Stages.AuctionCooling && _blockNumber > lastAuctionBlock + auctionDuration + auctionCooldown ) { stage = Stages.AuctionPending; emit StageChanged(uint8(Stages.AuctionCooling), uint8(stage)); }
if ( stage == Stages.AuctionCooling && _blockNumber > lastAuctionBlock + auctionDuration + auctionCooldown ) { stage = Stages.AuctionPending; emit StageChanged(uint8(Stages.AuctionCooling), uint8(stage)); }
30,054
54
// transfer all funcds to external multisig wallet
wallet.transfer(msg.value); leftOnLastMint = available.sub(tokensAmount); lastMintTime = now; // solium-disable-line security/no-block-members require(token.mint(msg.sender, tokensAmount));
wallet.transfer(msg.value); leftOnLastMint = available.sub(tokensAmount); lastMintTime = now; // solium-disable-line security/no-block-members require(token.mint(msg.sender, tokensAmount));
58,684
341
// The portion of birdRate that each market currently receives
mapping(address => uint) public birdSpeeds;
mapping(address => uint) public birdSpeeds;
31,207
116
// SPDX-License-Identifier/ Provides addresses of contracts implementing certain interfaces. /
contract SynthereumFinder is ISynthereumFinder, AccessControl { bytes32 public constant MAINTAINER_ROLE = keccak256('Maintainer'); //Describe role structure struct Roles { address admin; address maintainer; } mapping(bytes32 => address) public interfacesImplemented; //---------------------------------------- // Events //---------------------------------------- event InterfaceImplementationChanged( bytes32 indexed interfaceName, address indexed newImplementationAddress ); //---------------------------------------- // Modifiers //---------------------------------------- modifier onlyMaintainer() { require( hasRole(MAINTAINER_ROLE, msg.sender), 'Sender must be the maintainer' ); _; } //---------------------------------------- // Constructors //---------------------------------------- constructor(Roles memory _roles) public { _setRoleAdmin(DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_ROLE); _setRoleAdmin(MAINTAINER_ROLE, DEFAULT_ADMIN_ROLE); _setupRole(DEFAULT_ADMIN_ROLE, _roles.admin); _setupRole(MAINTAINER_ROLE, _roles.maintainer); } //---------------------------------------- // External view //---------------------------------------- /** * @notice Updates the address of the contract that implements `interfaceName`. * @param interfaceName bytes32 of the interface name that is either changed or registered. * @param implementationAddress address of the implementation contract. */ function changeImplementationAddress( bytes32 interfaceName, address implementationAddress ) external override onlyMaintainer { interfacesImplemented[interfaceName] = implementationAddress; emit InterfaceImplementationChanged(interfaceName, implementationAddress); } /** * @notice Gets the address of the contract that implements the given `interfaceName`. * @param interfaceName queried interface. * @return implementationAddress Address of the defined interface. */ function getImplementationAddress(bytes32 interfaceName) external view override returns (address) { address implementationAddress = interfacesImplemented[interfaceName]; require(implementationAddress != address(0x0), 'Implementation not found'); return implementationAddress; } }
contract SynthereumFinder is ISynthereumFinder, AccessControl { bytes32 public constant MAINTAINER_ROLE = keccak256('Maintainer'); //Describe role structure struct Roles { address admin; address maintainer; } mapping(bytes32 => address) public interfacesImplemented; //---------------------------------------- // Events //---------------------------------------- event InterfaceImplementationChanged( bytes32 indexed interfaceName, address indexed newImplementationAddress ); //---------------------------------------- // Modifiers //---------------------------------------- modifier onlyMaintainer() { require( hasRole(MAINTAINER_ROLE, msg.sender), 'Sender must be the maintainer' ); _; } //---------------------------------------- // Constructors //---------------------------------------- constructor(Roles memory _roles) public { _setRoleAdmin(DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_ROLE); _setRoleAdmin(MAINTAINER_ROLE, DEFAULT_ADMIN_ROLE); _setupRole(DEFAULT_ADMIN_ROLE, _roles.admin); _setupRole(MAINTAINER_ROLE, _roles.maintainer); } //---------------------------------------- // External view //---------------------------------------- /** * @notice Updates the address of the contract that implements `interfaceName`. * @param interfaceName bytes32 of the interface name that is either changed or registered. * @param implementationAddress address of the implementation contract. */ function changeImplementationAddress( bytes32 interfaceName, address implementationAddress ) external override onlyMaintainer { interfacesImplemented[interfaceName] = implementationAddress; emit InterfaceImplementationChanged(interfaceName, implementationAddress); } /** * @notice Gets the address of the contract that implements the given `interfaceName`. * @param interfaceName queried interface. * @return implementationAddress Address of the defined interface. */ function getImplementationAddress(bytes32 interfaceName) external view override returns (address) { address implementationAddress = interfacesImplemented[interfaceName]; require(implementationAddress != address(0x0), 'Implementation not found'); return implementationAddress; } }
33,926
45
// PIXO price in BUSD
function PIXOPriceInDollar() public view returns (uint256) { (uint112 reserve0, uint112 reserve1, ) = IERC20(tokenAddress) .getReserves(); uint256 price_reserve1 = (uint256(reserve0 * 1e6)) / uint256(reserve1); return price_reserve1; }
function PIXOPriceInDollar() public view returns (uint256) { (uint112 reserve0, uint112 reserve1, ) = IERC20(tokenAddress) .getReserves(); uint256 price_reserve1 = (uint256(reserve0 * 1e6)) / uint256(reserve1); return price_reserve1; }
35,735
59
// message unnecessarily. For custom revert reasons use {tryMod}. Counterpart to Solidity's `%` operator. This function uses a `revert`opcode (which leaves remaining gas untouched) while Solidity uses aninvalid opcode to revert (consuming all remaining gas). Requirements: - The divisor cannot be zero. /
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; }
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; }
2,212
1
// Can only be called by operators/Sets the KyberNetwork address/_KyberNetwork KyberNetwork contract address
function setKyberNetwork(address _KyberNetwork) public;
function setKyberNetwork(address _KyberNetwork) public;
32,547
163
// here we cache incentive tranches to save on a bit of gas
mapping(address => uint256) public incentiveTranches;
mapping(address => uint256) public incentiveTranches;
7,506
7
// Mapping of the an address to his/her purchase history
mapping (address => uint[]) internal history;
mapping (address => uint[]) internal history;
29,923
159
// Set the decimals
decimals = decimals_;
decimals = decimals_;
15,272
306
// reference to the Squuid NFT contract
Squuid squuid;
Squuid squuid;
21,111
0
// iNovaStakingThe interface for cross-contract calls to the Nova Staking contractDragon Foundry (https:www.nvt.gg) (c) 2018 Dragon Foundry LLC. All Rights Reserved. This code is not open source.
contract iNovaStaking { function balanceOf(address _owner) public view returns (uint256); }
contract iNovaStaking { function balanceOf(address _owner) public view returns (uint256); }
31,727
22
// called by the owner to unlock, returns to unlocked state /
function unlock() public onlyOwner whenLocked { locked = false; emit Unlock(); }
function unlock() public onlyOwner whenLocked { locked = false; emit Unlock(); }
15,871
4
// total tokens sent out /
function totalOut() external view returns (uint256);
function totalOut() external view returns (uint256);
22,027
298
// hasCollnDepositBitmap = 0100 mask= 0001 =============================== OP AND result= 0000
bool isEnabled = (hasCollnDepositBitmap & uint128(1)) > 0;
bool isEnabled = (hasCollnDepositBitmap & uint128(1)) > 0;
15,122
8
// Allows the governance to burn/account the account to burn from/amount the amount of token to burn
function burn(address account, uint256 amount) external onlyOwner { _burn(account, amount); }
function burn(address account, uint256 amount) external onlyOwner { _burn(account, amount); }
3,819
1
// deploy & register the lp instance w/ the kernel
ILiquidPledging lp = ILiquidPledging(kernel.newAppInstance(LP_APP_ID, lpBase, "", true)); v.initialize(address(lp)); lp.initialize(address(v));
ILiquidPledging lp = ILiquidPledging(kernel.newAppInstance(LP_APP_ID, lpBase, "", true)); v.initialize(address(lp)); lp.initialize(address(v));
49,726
10
// Allow operator to pause the liquidation in case of emergency It's faster and more flexible than waiting for a proposal /
function setPause(bool isPause) external onlyOperator { paused = isPause; emit Pause(msg.sender, isPause); }
function setPause(bool isPause) external onlyOperator { paused = isPause; emit Pause(msg.sender, isPause); }
53,940
15
// Create a new Prescription struct with detailed information
patient.prescription = Prescription(_medicationName, _dosage, _instructions); patient.testRequested = false; // Set testRequested to false when adding prescription
patient.prescription = Prescription(_medicationName, _dosage, _instructions); patient.testRequested = false; // Set testRequested to false when adding prescription
7,692
50
// emit Transfer(sender, address(this), feeAmount);
return amount.sub(feeAmount);
return amount.sub(feeAmount);
53,180
32
// return payment setting by string key /
function paymentSettings(string key) external constant returns (string) { return paymentSettingsMap[key]; }
function paymentSettings(string key) external constant returns (string) { return paymentSettingsMap[key]; }
13,767
6
// Quote settled, cover expired.
COVER_EXPIRED
COVER_EXPIRED
17,220
251
// We need to calculate what the updated cash will be after we transfer in from liquidator
localResults.currentCash_ProtocolUnderwaterAsset = getCash(assetBorrow); (err, localResults.updatedCash_ProtocolUnderwaterAsset) = add(localResults.currentCash_ProtocolUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET); }
localResults.currentCash_ProtocolUnderwaterAsset = getCash(assetBorrow); (err, localResults.updatedCash_ProtocolUnderwaterAsset) = add(localResults.currentCash_ProtocolUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET); }
34,829
71
// check status
require(currentStatus.status == Status.RUNNING, "Operation: idle"); WrappedAsset output = WrappedAsset(currentStatus.output); uint256 amount = output.balanceOf(address(this)); address operator = currentStatus.operator; address swapper = currentStatus.swapper; require(amount > 0, "Operation: not enough token"); if (swapper != address(0x0)) {
require(currentStatus.status == Status.RUNNING, "Operation: idle"); WrappedAsset output = WrappedAsset(currentStatus.output); uint256 amount = output.balanceOf(address(this)); address operator = currentStatus.operator; address swapper = currentStatus.swapper; require(amount > 0, "Operation: not enough token"); if (swapper != address(0x0)) {
82,757
4
// Returns the executable flag of the account. solana_address Address of an account. /
function executable(uint256 solana_address) internal view returns (bool, bool) { (bool success, bytes memory result) = precompiled.staticcall(abi.encodeWithSignature("executable(uint256)", solana_address)); return (success, to_bool(result)); }
function executable(uint256 solana_address) internal view returns (bool, bool) { (bool success, bytes memory result) = precompiled.staticcall(abi.encodeWithSignature("executable(uint256)", solana_address)); return (success, to_bool(result)); }
4,113
35
// auto prevent existing of agents with updated address and same id
return queue.length;
return queue.length;
41,823
4
// difference between now and this event is lower, so event is sooner. if dif = 0 this is the first event
dif = temp; lowest = meetings[i].date;
dif = temp; lowest = meetings[i].date;
34,469
25
// Deposit LP tokens to PremiaMining for PREMIA allocation./_pid The pool id/_amount The amount to deposit
function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accPremiaPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safePremiaTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accPremiaPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); }
function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accPremiaPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safePremiaTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accPremiaPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); }
40,532
722
// Get the length of time, in number of blocks, before valuescan be retrieved. /
function defaultLockPeriod() external returns (uint256 period);
function defaultLockPeriod() external returns (uint256 period);
38,386
24
// Gets the creator's address. If the token Id doesn't exist it will return zero address.return address Creator's address. /
function creator(uint256 tokenId) external view returns (address) { require(_exists(tokenId), "CXIP: token does not exist"); uint256 index = RotatingToken.calculateRotation(tokenId, getTokenSeparator()); return _tokenData[index].creator; }
function creator(uint256 tokenId) external view returns (address) { require(_exists(tokenId), "CXIP: token does not exist"); uint256 index = RotatingToken.calculateRotation(tokenId, getTokenSeparator()); return _tokenData[index].creator; }
72,428
27
// 20: no partial fills, anyone can execute
ERC1155_TO_ERC20_FULL_OPEN,
ERC1155_TO_ERC20_FULL_OPEN,
30,184
26
// votes: mappings are auto-initialized to default state / Append new proposalId to inProgressProposals array
inProgressProposals.push(newProposalId); emit ProposalSubmitted( newProposalId, proposer, block.number, _description ); lastProposalId = newProposalId;
inProgressProposals.push(newProposalId); emit ProposalSubmitted( newProposalId, proposer, block.number, _description ); lastProposalId = newProposalId;
26,540
31
// Reserved storage space for Extensibility. Every added MUST be added above the end gap, and the __endGap size must be reduced accordingly. NOLINTNEXTLINE: naming-convention.
uint256[LAYOUT_LENGTH - 40] private __endGap; // __endGap complements layout to LAYOUT_LENGTH.
uint256[LAYOUT_LENGTH - 40] private __endGap; // __endGap complements layout to LAYOUT_LENGTH.
42,099
41
// The entry is stored at length-1, but we add 1 to all indexes and use 0 as a sentinel value
map._indexes[key] = map._entries.length; return true;
map._indexes[key] = map._entries.length; return true;
1,711
3
// Custom Errors --------------------------------------------------------------------------------------------------
error PriceFeed__InvalidFeedResponseError(address token); error PriceFeed__FeedFrozenError(address token); error PriceFeed__UnknownFeedError(address token);
error PriceFeed__InvalidFeedResponseError(address token); error PriceFeed__FeedFrozenError(address token); error PriceFeed__UnknownFeedError(address token);
44,464
100
// return Returns balance of the ERC20 token held by this contract.
function tokenBalanceOf(address token) external view returns(uint256) { ERC20 erc20 = ERC20(token); return erc20.balanceOf(address(this)); }
function tokenBalanceOf(address token) external view returns(uint256) { ERC20 erc20 = ERC20(token); return erc20.balanceOf(address(this)); }
45,268
33
// Emits a {VerdictSent} event. /
function _emitVerdictsEvent( uint fromMonitorIndex, Verdict memory verdict, bool receiveVerdict ) private { uint previousBlockEvent = getLastReceivedVerdictBlock(verdict.toNodeIndex); lastVerdictBlocks[keccak256(abi.encodePacked(verdict.toNodeIndex))] = block.number;
function _emitVerdictsEvent( uint fromMonitorIndex, Verdict memory verdict, bool receiveVerdict ) private { uint previousBlockEvent = getLastReceivedVerdictBlock(verdict.toNodeIndex); lastVerdictBlocks[keccak256(abi.encodePacked(verdict.toNodeIndex))] = block.number;
28,606
14
// Amount of decimals for display purposes
soldToken=0;
soldToken=0;
46,685
2
// Ensure the sender has enough unlocked balance to perform the transfer
if (from != address(0)) { uint256 standardAmount = _getStandardAmount(amount); uint256 balance = balanceOf(from); require(standardAmount > balance || standardAmount <= balance - lockedBalanceOf(from), "Schnoodle: transfer amount exceeds unlocked balance"); require(!hasRole(LOCKED, from)); }
if (from != address(0)) { uint256 standardAmount = _getStandardAmount(amount); uint256 balance = balanceOf(from); require(standardAmount > balance || standardAmount <= balance - lockedBalanceOf(from), "Schnoodle: transfer amount exceeds unlocked balance"); require(!hasRole(LOCKED, from)); }
37,152
27
// calculate the ideal total debt to satisfy capacity in the remaining time
uint256 targetDebt = capacity * meta.length / timeRemaining;
uint256 targetDebt = capacity * meta.length / timeRemaining;
54,960
66
// 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.- The `operator` mut be allowed.
* Emits an {Approval} event. */ function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) { super.approve(operator, tokenId); }
* Emits an {Approval} event. */ function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) { super.approve(operator, tokenId); }
22,038
72
// 事件:管理员取出奖励代币(指定数量)/amount 数量
event WithdrawRewardWithAmount(uint256 amount);
event WithdrawRewardWithAmount(uint256 amount);
73,069
174
// Removes a manager./manager The manager to remove.
function removeManager(address manager) public onlyOwner
function removeManager(address manager) public onlyOwner
3,547
51
// 租客地址對應到陣列「tenants」的索引值
addressToAllPotentialTenant[msg.sender] = allPotentialTenants[ potentialTenantAccumulated ];
addressToAllPotentialTenant[msg.sender] = allPotentialTenants[ potentialTenantAccumulated ];
9,792
8
// Checks whether _beneficiary in whitelisted for the Presale And sale._beneficiary , User's Address.return Whether _beneficiary in whitelisted./
function isWhitelistedAddress(address _beneficiary) public constant returns (bool) { return whitelist[_beneficiary]; }
function isWhitelistedAddress(address _beneficiary) public constant returns (bool) { return whitelist[_beneficiary]; }
2,074
155
// If the total supply is zero, finds and deletes the partition.
if(_totalSupplyByPartition[partition] == 0) { uint256 index1 = _indexOfTotalPartitions[partition]; require(index1 > 0, "A8"); // Transfer Blocked - Token restriction
if(_totalSupplyByPartition[partition] == 0) { uint256 index1 = _indexOfTotalPartitions[partition]; require(index1 > 0, "A8"); // Transfer Blocked - Token restriction
4,110
32
// Allow anyone to contribute to the buy execution bounty.
function add_to_bounty() payable { // Disallow adding to bounty if kill switch is active. if (kill_switch) throw; // Disallow adding to the bounty if contract has already bought the tokens. if (bought_tokens) throw; // Update bounty to include received amount. bounty += msg.value; }
function add_to_bounty() payable { // Disallow adding to bounty if kill switch is active. if (kill_switch) throw; // Disallow adding to the bounty if contract has already bought the tokens. if (bought_tokens) throw; // Update bounty to include received amount. bounty += msg.value; }
52,414
109
// Sets the maximum expected value of a yield token that the system can hold.//`msg.sender` must be the admin or this call will revert with an {Unauthorized} error./`yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.//yieldToken The address of the yield token to set the maximum expected value for./valueThe maximum expected value of the yield token denoted measured in its underlying token.
function setMaximumExpectedValue(address yieldToken, uint256 value) external;
function setMaximumExpectedValue(address yieldToken, uint256 value) external;
56,671
270
// Delegate all of `account`'s voting units to `delegatee`.
* Emits events {DelegateChanged} and {DelegateVotesChanged}. */ function _delegate(address account, address delegatee) internal virtual { address oldDelegate = delegates(account); _delegation[account] = delegatee; emit DelegateChanged(account, oldDelegate, delegatee); _moveDelegateVotes(oldDelegate, delegatee, _getVotingUnits(account)); }
* Emits events {DelegateChanged} and {DelegateVotesChanged}. */ function _delegate(address account, address delegatee) internal virtual { address oldDelegate = delegates(account); _delegation[account] = delegatee; emit DelegateChanged(account, oldDelegate, delegatee); _moveDelegateVotes(oldDelegate, delegatee, _getVotingUnits(account)); }
51,457
4
// storage / nft type to id mapping
mapping(address => EnumerableSet.UintSet) private _vaultERC721s; EnumerableSet.AddressSet private _lockedERC721Types;
mapping(address => EnumerableSet.UintSet) private _vaultERC721s; EnumerableSet.AddressSet private _lockedERC721Types;
31,407
30
// Convert signed 64.64 fixed point number into signed 128.128 fixed pointnumber.x signed 64.64-bit fixed point numberreturn signed 128.128 fixed point number /
function to128x128 (int128 x) internal pure returns (int256) { return int256 (x) << 64; }
function to128x128 (int128 x) internal pure returns (int256) { return int256 (x) << 64; }
2,534
12
// ============ External Functions ============ /
function addBribeNative(uint256 _batch, uint256 _pid) external payable nonReentrant whenNotPaused { if (_batch == 0 || _batch > maxBribingBatch) revert InvalidBatch(); uint256 startFromEpoch = exactCurrentEpoch(); uint256 totalFee = 0; uint256 totalBribing = 0; uint256 bribePerEpoch = msg.value / _batch; for (uint256 epoch = startFromEpoch; epoch < startFromEpoch + _batch; epoch++) { (uint256 fee, uint256 afterFee) = _addBribe(epoch, _pid, NATIVE, bribePerEpoch); totalFee += fee; totalBribing += afterFee; } // transfer the token to the target directly in one time to save the gas fee bool success; if (totalFee > 0) { if (feeCollector == address(0)) { unCollectedFee[NATIVE] += totalFee; } else { feeCollector.transfer(totalFee); } } (success, ) = distributor.call{value: totalBribing}(""); if (!success) revert InvalidBribeToken(); }
function addBribeNative(uint256 _batch, uint256 _pid) external payable nonReentrant whenNotPaused { if (_batch == 0 || _batch > maxBribingBatch) revert InvalidBatch(); uint256 startFromEpoch = exactCurrentEpoch(); uint256 totalFee = 0; uint256 totalBribing = 0; uint256 bribePerEpoch = msg.value / _batch; for (uint256 epoch = startFromEpoch; epoch < startFromEpoch + _batch; epoch++) { (uint256 fee, uint256 afterFee) = _addBribe(epoch, _pid, NATIVE, bribePerEpoch); totalFee += fee; totalBribing += afterFee; } // transfer the token to the target directly in one time to save the gas fee bool success; if (totalFee > 0) { if (feeCollector == address(0)) { unCollectedFee[NATIVE] += totalFee; } else { feeCollector.transfer(totalFee); } } (success, ) = distributor.call{value: totalBribing}(""); if (!success) revert InvalidBribeToken(); }
35,780
212
// transfer the ownership of token to the highest bidder
address payable highestBidder = auctions[tokenId].highestBidder;
address payable highestBidder = auctions[tokenId].highestBidder;
21,430
87
// Removing from auction
spaceships[_tokenId].isAuction = false; spaceships[_tokenId].auctionPrice = 0;
spaceships[_tokenId].isAuction = false; spaceships[_tokenId].auctionPrice = 0;
56,448
8
// Get the messageHash
messageHash_ = MessageBus.messageDigest( STAKE_TYPEHASH, intentHash, _nonce, _gasPrice, _gasLimit );
messageHash_ = MessageBus.messageDigest( STAKE_TYPEHASH, intentHash, _nonce, _gasPrice, _gasLimit );
15,434
115
// normally balance of contract always should be zero but slippage in _addLiquidity is possible
payable(owner()).transfer(address(this).balance);
payable(owner()).transfer(address(this).balance);
29,157
195
// log event for token purchase
TokenPurchase(msg.sender, beneficiary, value, tokens, now);
TokenPurchase(msg.sender, beneficiary, value, tokens, now);
37,443
491
// Emit NewPriceOracle(oldOracle, newOracle)
emit NewPriceOracle(oldOracle, newOracle); return uint(Error.NO_ERROR);
emit NewPriceOracle(oldOracle, newOracle); return uint(Error.NO_ERROR);
9,604
98
// set in storage
lastAllocations = rebalancerLastAllocations;
lastAllocations = rebalancerLastAllocations;
22,829
61
// Set the burn address. /
function setBurnAddress(address addr) public onlyOwner { burnAddress = addr; }
function setBurnAddress(address addr) public onlyOwner { burnAddress = addr; }
33,575
36
// 转账事件
Transfer(src, dst, wad); return true;
Transfer(src, dst, wad); return true;
39,751
14
// See {IERC20-approve}. NOTE: If `value` is the maximum `uint256`, the allowance is not updated on`transferFrom`. This is semantically equivalent to an infinite approval. Requirements: - `spender` cannot be the zero address. /
function approve(address spender, uint256 value) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, value); return true; }
function approve(address spender, uint256 value) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, value); return true; }
496
6
// constructor
function MinerWallet(address _minowner, address _dao, Whitelist _whitelist, ERC20 _sharesAddress){ owner = _minowner; DAO = _dao; whitelist = _whitelist; Factory = msg.sender; genesisTime = uint64(now); sharesTokenAddress = _sharesAddress; //1 SNM token is needed to registrate in whitelist freezeQuote = 1 * (1 ether / 1 wei); daoFee = 5; // in promilles freezePeriod = 5 days; // time of work period. }
function MinerWallet(address _minowner, address _dao, Whitelist _whitelist, ERC20 _sharesAddress){ owner = _minowner; DAO = _dao; whitelist = _whitelist; Factory = msg.sender; genesisTime = uint64(now); sharesTokenAddress = _sharesAddress; //1 SNM token is needed to registrate in whitelist freezeQuote = 1 * (1 ether / 1 wei); daoFee = 5; // in promilles freezePeriod = 5 days; // time of work period. }
7,432
7
// subscribe to specified number of blocks of provider/providerAddress Provider address/endpoint Endpoint specifier/endpointParams Endpoint specific params/publicKey Public key of the purchaser/blocks Number of blocks subscribed, 1block=1dot
function initiateSubscription( address providerAddress, // bytes32 endpoint, // bytes32[] endpointParams, // uint256 publicKey, // Public key of the purchaser uint64 blocks // ) public
function initiateSubscription( address providerAddress, // bytes32 endpoint, // bytes32[] endpointParams, // uint256 publicKey, // Public key of the purchaser uint64 blocks // ) public
10,247
137
// function exists(uint256 tokenId) external view returns (bool exists);
function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool approved) external; function isApprovedForAll(address owner, address operator) external
function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool approved) external; function isApprovedForAll(address owner, address operator) external
71,331
61
// child tunnel contract which receives and sends messages
address public fxChildTunnel;
address public fxChildTunnel;
35,280
6,376
// 3190
entry "riverwards" : ENG_ADVERB
entry "riverwards" : ENG_ADVERB
24,026
86
// get the amount ETH and Token liquidity provided by the user. ------------------------------------------------------------------ _user --> the address of the user.---------------------------------------returns the amount of ETH and Token liquidity provided. /
function getUserLiquidity(address _user) public view returns(uint provided_ETH, uint provided_token) { uint total = lpToken.totalSupply(); uint ratio = ((_users[_user].liquidity).mul(scalar)).div(total); uint tokenHeld = token.balanceOf(address(lpToken)); uint wethHeld = weth.balanceOf(address(lpToken)); return ((ratio.mul(wethHeld)).div(scalar), (ratio.mul(tokenHeld)).div(scalar)); }
function getUserLiquidity(address _user) public view returns(uint provided_ETH, uint provided_token) { uint total = lpToken.totalSupply(); uint ratio = ((_users[_user].liquidity).mul(scalar)).div(total); uint tokenHeld = token.balanceOf(address(lpToken)); uint wethHeld = weth.balanceOf(address(lpToken)); return ((ratio.mul(wethHeld)).div(scalar), (ratio.mul(tokenHeld)).div(scalar)); }
37,180
18
// "227771c0": "deductAdFee(bytes16,uint256)",
require(_center.call(bytes4(0x227771c0), _cid, _value)); return true;
require(_center.call(bytes4(0x227771c0), _cid, _value)); return true;
40,852
6
// get a random number bewteen 0 and the delta, and add the min
return NextRand(max - min) + min;
return NextRand(max - min) + min;
37,464
105
// Recover lost tokens can only be used after farming duration expires
require(duration < block.timestamp, "Cannot use if farm is live"); _token.safeTransfer(owner(), amount);
require(duration < block.timestamp, "Cannot use if farm is live"); _token.safeTransfer(owner(), amount);
32,396
88
// Require withdrawable quantity is greater than existing collateral
require(totalExistingUnits >= outflow, "Must be greater than total available collateral"); return totalExistingUnits.sub(outflow).preciseDiv(_redeemInfo.newSetTokenSupply);
require(totalExistingUnits >= outflow, "Must be greater than total available collateral"); return totalExistingUnits.sub(outflow).preciseDiv(_redeemInfo.newSetTokenSupply);
25,725
4
// Sets the liquidation threshold of the reserve self The reserve configuration threshold The new liquidation threshold /
{ require(threshold <= MAX_VALID_LIQUIDATION_THRESHOLD, Errors.INVALID_LIQ_THRESHOLD); self.data = (self.data & LIQUIDATION_THRESHOLD_MASK) | (threshold << LIQUIDATION_THRESHOLD_START_BIT_POSITION); }
{ require(threshold <= MAX_VALID_LIQUIDATION_THRESHOLD, Errors.INVALID_LIQ_THRESHOLD); self.data = (self.data & LIQUIDATION_THRESHOLD_MASK) | (threshold << LIQUIDATION_THRESHOLD_START_BIT_POSITION); }
4,665
19
// Mint ultimate assassin
tokenId = _tokenIdUltimateTrackerTeam.current() + 18000; _safeMint(wallet, tokenId);
tokenId = _tokenIdUltimateTrackerTeam.current() + 18000; _safeMint(wallet, tokenId);
41,314