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
211
// returns the delegatee of an user delegator the address of the delegator /
{ (, , mapping(address => address) storage delegates) = _getDelegationDataByType(delegationType); return _getDelegatee(delegator, delegates); }
{ (, , mapping(address => address) storage delegates) = _getDelegationDataByType(delegationType); return _getDelegatee(delegator, delegates); }
18,505
52
// release all available for release freezing tokens. Gas usage is not deterministic! return how many tokens was released/
function releaseAll() public returns (uint tokens) { uint release; uint balance; (release, balance) = getFreezing(msg.sender, 0); while (release != 0 && block.timestamp > release) { releaseOnce(); tokens += balance; (release, balance) = getFreezing(msg.sender, 0); } }
function releaseAll() public returns (uint tokens) { uint release; uint balance; (release, balance) = getFreezing(msg.sender, 0); while (release != 0 && block.timestamp > release) { releaseOnce(); tokens += balance; (release, balance) = getFreezing(msg.sender, 0); } }
20,069
308
// If we fully depleted the strategy:
if (strategyBalanceAfterWithdrawal == 0) {
if (strategyBalanceAfterWithdrawal == 0) {
55,535
149
// The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
mapping (address => uint32) public numCheckpoints;
100
9
// Match an ERC721 order using `safeTransferFrom`, ensuring that the supplied proof demonstrates inclusion of the tokenId in the associated merkle root./from The account to transfer the ERC721 token from — this token must first be approved on the seller's AuthenticatedProxy contract./to The account to transfer the ERC721 token to./token The ERC721 token to transfer./tokenId The ERC721 tokenId to transfer./root A merkle root derived from each valid tokenId — set to 0 to indicate a collection-level or tokenId-specific order./proof A proof that the supplied tokenId is contained within the associated merkle root. Must be length 0 if root is not set./
function matchERC721WithSafeTransferUsingCriteria( address from, address to, IERC721 token, uint256 tokenId, bytes32 root, bytes32[] proof
function matchERC721WithSafeTransferUsingCriteria( address from, address to, IERC721 token, uint256 tokenId, bytes32 root, bytes32[] proof
26,089
30
// Allows a user to withdraw any balance granted to them by licenses./
function withdrawBalance() public { address payee = msg.sender; uint256 payment = 0; uint256[] memory tokens = tokensOf(payee); for (uint i = 0; i < tokens.length; i++) { payment = payment.add(tokenBalances[tokens[i]]); tokenBalances[tokens[i]] = 0; } require(payment != 0); require(this.balance >= payment); assert(payee.send(payment)); }
function withdrawBalance() public { address payee = msg.sender; uint256 payment = 0; uint256[] memory tokens = tokensOf(payee); for (uint i = 0; i < tokens.length; i++) { payment = payment.add(tokenBalances[tokens[i]]); tokenBalances[tokens[i]] = 0; } require(payment != 0); require(this.balance >= payment); assert(payee.send(payment)); }
15,412
135
// mintpass function for public => check if current user has mintpass or not.
function hasMintPass(address sender) public view returns (bool){ if(sender==address(0)){ return false; } else if (isWhitelisted(sender)) { return true; } return false; }
function hasMintPass(address sender) public view returns (bool){ if(sender==address(0)){ return false; } else if (isWhitelisted(sender)) { return true; } return false; }
65,347
494
// bytes4(keccak256("transferFrom(address,address,uint256)")) = 0x23b872dd
bytes memory callData = abi.encodeWithSelector( bytes4(0x23b872dd), from, to, value );
bytes memory callData = abi.encodeWithSelector( bytes4(0x23b872dd), from, to, value );
9,371
97
// Mod x by y. Note this will return 0 instead of reverting if y is zero.
z := mod(x, y)
z := mod(x, y)
37,312
514
// Compute remainder as before
uint256 remainder = mulmod( target, numerator, denominator ); remainder = denominator.safeSub(remainder) % denominator; isError = remainder.safeMul(1000) >= numerator.safeMul(target); return isError;
uint256 remainder = mulmod( target, numerator, denominator ); remainder = denominator.safeSub(remainder) % denominator; isError = remainder.safeMul(1000) >= numerator.safeMul(target); return isError;
54,946
47
// Allow sending money to the contract (without calldata).
receive() external payable {} /// @notice Allows the owner to withdraw funds from the contract. function withdraw() external { require(msg.sender == owner); owner.transfer(address(this).balance); }
receive() external payable {} /// @notice Allows the owner to withdraw funds from the contract. function withdraw() external { require(msg.sender == owner); owner.transfer(address(this).balance); }
33,835
909
// NEURON tokens created per block.
uint256 public neuronTokenPerBlock;
uint256 public neuronTokenPerBlock;
51,050
349
// Smart contract owner only function.ERC2981 royalty standard implementation function.Function resets the individual tokenId level royalties to collection level royalties.Enter the tokenIds whose royalties are to be reset in an array form.For example, the tokenIds array would be like this [3,5,7]. /
function resetToCollectionLevelRoyalties(uint256[] calldata tokenIds) public onlyOwner { for (uint256 i = 0; i < tokenIds.length; ++i) { _resetTokenRoyalty(tokenIds[i]); } }
function resetToCollectionLevelRoyalties(uint256[] calldata tokenIds) public onlyOwner { for (uint256 i = 0; i < tokenIds.length; ++i) { _resetTokenRoyalty(tokenIds[i]); } }
27,429
375
// lastAssetValueEachMarketPerBlock
function setLastAssetValueEachMarketPerBlock(address _market, uint256 value) external
function setLastAssetValueEachMarketPerBlock(address _market, uint256 value) external
29,194
29
// This event is fired when some of the terms of a loan are being renegotiated.loanId - The unique identifier for the loan to be renegotiated newLoanDuration - The new amount of time (measured in seconds) that can elapse before the lender canliquidate the loan and seize the underlying collateral NFT. newMaximumRepaymentAmount - The new maximum amount of money that the borrower would be required toretrieve their collateral, measured in the smallest units of the ERC20 currency used for the loan. Theborrower will always have to pay this amount to retrieve their collateral, regardless of whether they repayearly. renegotiationFee Agreed upon
event LoanRenegotiated(
event LoanRenegotiated(
59,450
51
// - Roco Fee's (will never be used!) Maximum Roco Fee Value (always 0%) cannot be changed/
uint256 private constant _MaxRocoFee = 0; uint256 private _tRocoFeeTotal; //- Total Roco Fee uint256 private _RocoFee = 0; //- Current Roco Fee uint256 private _RocoFeePrevious = _RocoFee; //- Previous Roco Fee
uint256 private constant _MaxRocoFee = 0; uint256 private _tRocoFeeTotal; //- Total Roco Fee uint256 private _RocoFee = 0; //- Current Roco Fee uint256 private _RocoFeePrevious = _RocoFee; //- Previous Roco Fee
30,648
36
// require(msg.sender == address(this));
if (task == 1) { //withdraw eth to withdrawEth(to, amount); }
if (task == 1) { //withdraw eth to withdrawEth(to, amount); }
375
317
// Calculate the fully filled results for both orders.
matchedFillResults.left.makerAssetFilledAmount = leftMakerAssetAmountRemaining; matchedFillResults.left.takerAssetFilledAmount = leftTakerAssetAmountRemaining; matchedFillResults.right.makerAssetFilledAmount = rightMakerAssetAmountRemaining; matchedFillResults.right.takerAssetFilledAmount = rightTakerAssetAmountRemaining; return matchedFillResults;
matchedFillResults.left.makerAssetFilledAmount = leftMakerAssetAmountRemaining; matchedFillResults.left.takerAssetFilledAmount = leftTakerAssetAmountRemaining; matchedFillResults.right.makerAssetFilledAmount = rightMakerAssetAmountRemaining; matchedFillResults.right.takerAssetFilledAmount = rightTakerAssetAmountRemaining; return matchedFillResults;
1,640
160
// Returns the max quantity for a token ID _id uint256 ID of the token to queryreturn amount of token in existence /
function maxSupply(uint256 _id) public view returns (uint256) { return tokenMaxSupply[_id]; }
function maxSupply(uint256 _id) public view returns (uint256) { return tokenMaxSupply[_id]; }
61,206
113
// Add a new offer with a new user if needed to the list_asset The address of the erc20 to exchange, pass 0x0 for Eth_contactData Contact Data ContactType:UserId_location The location on earth_currency The currency the user want to receive (USD, EUR...)_username The username of the user_paymentMethods The list of the payment methods the user accept_limitL Lower limit accepted_limitU Upper limit accepted_margin The margin for the user_arbitrator The arbitrator used by the offer/
function addOffer( address _asset, string memory _contactData, string memory _location, string memory _currency, string memory _username, uint[] memory _paymentMethods, uint _limitL, uint _limitU, int16 _margin,
function addOffer( address _asset, string memory _contactData, string memory _location, string memory _currency, string memory _username, uint[] memory _paymentMethods, uint _limitL, uint _limitU, int16 _margin,
46,208
18
// loop through trenches
for(uint256 i = trenchIndex[user]; i < trenches.length; i++){
for(uint256 i = trenchIndex[user]; i < trenches.length; i++){
57,738
68
// Send `_value` tokens to `_to` from `_from` on the condition it is approved by `_from`_from The address holding the tokens being transferred_to The address of the recipient_value The amount of tokens to be transferred return True if the transfer was successful/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(!paused, "token is paused"); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); doTransfer(_from, _to, _value); return true; }
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(!paused, "token is paused"); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); doTransfer(_from, _to, _value); return true; }
48,048
7
// Avoids the daily adjust to run more than necessary /
modifier canAdjustDaily() { uint256 day = 1 days; // 1 day in seconds // compares today must be valid according to math bellow require(now >= (startDate + (day * dailyAdjust))); _; }
modifier canAdjustDaily() { uint256 day = 1 days; // 1 day in seconds // compares today must be valid according to math bellow require(now >= (startDate + (day * dailyAdjust))); _; }
24,211
23
// Check sender's allocation
require( sarcoAllocation > 0, "FundingExecutor: sender does not have a SARCO allocation" );
require( sarcoAllocation > 0, "FundingExecutor: sender does not have a SARCO allocation" );
69,120
128
// Returns the length of a null-terminated bytes32 string. self The value to find the length of.return The length of the string, from 0 to 32. /
function len(bytes32 self) internal returns (uint) { uint ret; if (self == 0) return 0; if (self & 0xffffffffffffffffffffffffffffffff == 0) { ret += 16; self = bytes32(uint(self) / 0x100000000000000000000000000000000); } if (self & 0xffffffffffffffff == 0) { ret += 8; self = bytes32(uint(self) / 0x10000000000000000); } if (self & 0xffffffff == 0) { ret += 4; self = bytes32(uint(self) / 0x100000000); } if (self & 0xffff == 0) { ret += 2; self = bytes32(uint(self) / 0x10000); } if (self & 0xff == 0) { ret += 1; } return 32 - ret; }
function len(bytes32 self) internal returns (uint) { uint ret; if (self == 0) return 0; if (self & 0xffffffffffffffffffffffffffffffff == 0) { ret += 16; self = bytes32(uint(self) / 0x100000000000000000000000000000000); } if (self & 0xffffffffffffffff == 0) { ret += 8; self = bytes32(uint(self) / 0x10000000000000000); } if (self & 0xffffffff == 0) { ret += 4; self = bytes32(uint(self) / 0x100000000); } if (self & 0xffff == 0) { ret += 2; self = bytes32(uint(self) / 0x10000); } if (self & 0xff == 0) { ret += 1; } return 32 - ret; }
9,382
203
// 1. Make sure the collateral rate is valid.
require(!_exchangeRates().rateIsInvalid(collateralKey), "Collateral rate is invalid");
require(!_exchangeRates().rateIsInvalid(collateralKey), "Collateral rate is invalid");
29,967
74
// Increment Amount Purchased
contractToWLVendingItems[contract_][index_].amountPurchased++; emit WLVendingItemPurchased(contract_, msg.sender, index_, _object);
contractToWLVendingItems[contract_][index_].amountPurchased++; emit WLVendingItemPurchased(contract_, msg.sender, index_, _object);
79,099
68
// Numerator for constraints 'rc_builtin/addr_step', 'checkpoints/required_pc_next_addr', 'checkpoints/req_pc', 'checkpoints/req_fp'. numerators[7] = point - trace_generator^(256(trace_length / 256 - 1)).
mstore(0x3e40, addmod( point, sub(PRIME, /*trace_generator^(256 * (trace_length / 256 - 1))*/ mload(0x3740)), PRIME))
mstore(0x3e40, addmod( point, sub(PRIME, /*trace_generator^(256 * (trace_length / 256 - 1))*/ mload(0x3740)), PRIME))
60,023
71
// Get the total amount of tokens staked by the indexer. _indexer Address of the indexerreturn Amount of tokens staked by the indexer /
function getIndexerStakedTokens(address _indexer) external view override returns (uint256) { return stakes[_indexer].tokensStaked; }
function getIndexerStakedTokens(address _indexer) external view override returns (uint256) { return stakes[_indexer].tokensStaked; }
9,340
165
// Deposit variant with proof for merkle guest list
function deposit(uint256 _amount, bytes32[] memory proof) public whenNotPaused { _defend(); _blockLocked(); _lockForBlock(msg.sender); _depositWithAuthorization(_amount, proof); }
function deposit(uint256 _amount, bytes32[] memory proof) public whenNotPaused { _defend(); _blockLocked(); _lockForBlock(msg.sender); _depositWithAuthorization(_amount, proof); }
5,189
249
// Mapping to specify which tokenId is bred
mapping(uint256 => bool)internal isBred;
mapping(uint256 => bool)internal isBred;
50,425
8
// Returns the account stored at the specified account id. /
function load(uint128 id) internal pure returns (Data storage account) { bytes32 s = keccak256(abi.encode("io.synthetix.synthetix.Account", id)); assembly { account.slot := s } }
function load(uint128 id) internal pure returns (Data storage account) { bytes32 s = keccak256(abi.encode("io.synthetix.synthetix.Account", id)); assembly { account.slot := s } }
25,940
5
// keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ),
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f,
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f,
31,151
60
// increase total supply
totalSupply = totalSupply.add(tokenAmount);
totalSupply = totalSupply.add(tokenAmount);
14,534
3
// returns price of ETH in USD (6 decimals) /
function chainlinkPriceETHUSD() public view returns (uint256) { return IChainlinkOracle(CHAINLINK_ORACLE).latestAnswer() / 100; // chainlink answer is 8 decimals }
function chainlinkPriceETHUSD() public view returns (uint256) { return IChainlinkOracle(CHAINLINK_ORACLE).latestAnswer() / 100; // chainlink answer is 8 decimals }
34,921
34
// list of executives for the governance contracts. execs may execute accepted proposals and pause the governance in case of emergencies. they are obliged to obey to governance decision and supposed to execute accepted proposals.
mapping(address => bool) public isExecutive;
mapping(address => bool) public isExecutive;
10,344
58
// Allocate memory for AdvancedOrder head and OrderParameters head.
mPtr = malloc(AdvancedOrderPlusOrderParameters_head_size);
mPtr = malloc(AdvancedOrderPlusOrderParameters_head_size);
21,038
7
// Withdraw tokens in case functions exceed gas cost
function withdrawRewardToken(uint256 amountDPX, uint256 amountRDPX) public onlyOwner returns (uint256, uint256)
function withdrawRewardToken(uint256 amountDPX, uint256 amountRDPX) public onlyOwner returns (uint256, uint256)
72,647
29
// Private: Set the permission to the account
function _setAuth(address _account, address _permission) private returns (bool)
function _setAuth(address _account, address _permission) private returns (bool)
32,934
184
// returntrue if the provided `proxy` is globally trusted and may interact with the yield farming contract on a user's behalf or false otherwise. /
function isGloballyTrustedProxy( address proxy ) external view returns (bool);
function isGloballyTrustedProxy( address proxy ) external view returns (bool);
29,937
44
// the amount purchased
function calculateAmountPurchased(uint256 _value) public view returns (uint256) { return _value.mul(BP).div(price).mul(1e18).div(BP); }
function calculateAmountPurchased(uint256 _value) public view returns (uint256) { return _value.mul(BP).div(price).mul(1e18).div(BP); }
29,187
280
// check if the total value sent is enough to cover the min prices of all the tokens
require( msg.value >= totalAmount, "Insufficient funds for the transaction" ); pendingWithdrawals += msg.value;
require( msg.value >= totalAmount, "Insufficient funds for the transaction" ); pendingWithdrawals += msg.value;
948
0
// ! "name": "complex",! "input": [
//! { //! "entry": "get", //! "calldata": [ //! ], //! "expected": [ //! "0" //! ] //! }, { //! "entry": "set", //! "calldata": [ //! "1" //! ] //! }, { //! "entry": "status", //! "calldata": [ //! ], //! "expected": [ //! "1" //! ] //! }, { //! "entry": "cancel", //! "calldata": [ //! ] //! }, { //! "entry": "get", //! "calldata": [ //! ], //! "expected": [ //! "4" //! ] //! }, { //! "entry": "set", //! "calldata": [ //! "3" //! ] //! }, { //! "entry": "get", //! "calldata": [ //! ] //! }
//! { //! "entry": "get", //! "calldata": [ //! ], //! "expected": [ //! "0" //! ] //! }, { //! "entry": "set", //! "calldata": [ //! "1" //! ] //! }, { //! "entry": "status", //! "calldata": [ //! ], //! "expected": [ //! "1" //! ] //! }, { //! "entry": "cancel", //! "calldata": [ //! ] //! }, { //! "entry": "get", //! "calldata": [ //! ], //! "expected": [ //! "4" //! ] //! }, { //! "entry": "set", //! "calldata": [ //! "3" //! ] //! }, { //! "entry": "get", //! "calldata": [ //! ] //! }
13,169
6
// Distribute fee in ether_amountFee target amount in wei return Distributed fee amount in wei/
function distributeFees(uint256 _amount) internal returns (uint256) { uint256 _heroFee = getHeroFee(_amount); uint256 _teamFee = getTeamFee(_amount); hero_wallet.transfer(_heroFee); team_wallet.transfer(_teamFee); return safeAdd(_heroFee, _teamFee); }
function distributeFees(uint256 _amount) internal returns (uint256) { uint256 _heroFee = getHeroFee(_amount); uint256 _teamFee = getTeamFee(_amount); hero_wallet.transfer(_heroFee); team_wallet.transfer(_teamFee); return safeAdd(_heroFee, _teamFee); }
6,343
104
// The address that should receive funds once the NFT is sold.
address payable fundsRecipient;
address payable fundsRecipient;
44,555
26
// changeCoolDownTime - make the game go faster or slower, cooldown to be set in hours (min 1; max 24) -- call fee level 2
function updateCoolDown(uint256 newCoolDown) public onlyFlipper cooledDown { require(_isGameActive, "Eeee! You need to wait for the game to start first"); require(newCoolDown <= 24 && newCoolDown >= 1, "Eeee! Minimum cooldown is 1 hour, maximum is 24 hours"); transfer(address(this), _feeLevel2); callsAlwaysPaySnatch(_feeLevel2); _coolDownTime = newCoolDown * 1 hours; _lastUpdated = now; }
function updateCoolDown(uint256 newCoolDown) public onlyFlipper cooledDown { require(_isGameActive, "Eeee! You need to wait for the game to start first"); require(newCoolDown <= 24 && newCoolDown >= 1, "Eeee! Minimum cooldown is 1 hour, maximum is 24 hours"); transfer(address(this), _feeLevel2); callsAlwaysPaySnatch(_feeLevel2); _coolDownTime = newCoolDown * 1 hours; _lastUpdated = now; }
11,494
247
// automatically added as a prefix to the value returned in {tokenURI},or to the token ID if {tokenURI} is empty. /
function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; }
function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; }
6,359
18
// DEPOSIT BENEFICIARY STAKE/
function BeneficiaryStake(uint256 _bondnum) payable external returns(bool){ /*integrity checks*/ if(msg.value <= 0) revert(); require(spec[_bondnum].BondBeneficiary == msg.sender); require(spec[_bondnum].ExpirationBlock >= block.number); require(spec[_bondnum].Activated == false); require(settle[_bondnum].WriterSettled == false); require(msg.value >= spec[_bondnum].BeneficiaryStake); /*change record*/ spec[_bondnum].Activated = true; spec[_bondnum].BeneficiaryDeposit = msg.value; return true; }
function BeneficiaryStake(uint256 _bondnum) payable external returns(bool){ /*integrity checks*/ if(msg.value <= 0) revert(); require(spec[_bondnum].BondBeneficiary == msg.sender); require(spec[_bondnum].ExpirationBlock >= block.number); require(spec[_bondnum].Activated == false); require(settle[_bondnum].WriterSettled == false); require(msg.value >= spec[_bondnum].BeneficiaryStake); /*change record*/ spec[_bondnum].Activated = true; spec[_bondnum].BeneficiaryDeposit = msg.value; return true; }
51,024
27
// setting parameters
campaigns[campaignId].param.name = _name; campaigns[campaignId].param.campaignId = campaignId; campaigns[campaignId].param.tweetUrl = _tweetUrl; campaigns[campaignId].param.shareText = _shareText; campaigns[campaignId].param.via = _via; campaigns[campaignId].param.hashtag = _hashtag; campaigns[campaignId].param.bountyAmount = _bountyAmount; campaigns[campaignId].param.maxBounty = _maxBounty; campaigns[campaignId].param.startTimeStamp = _startTimeStamp; campaigns[campaignId].param.duration = _duration;
campaigns[campaignId].param.name = _name; campaigns[campaignId].param.campaignId = campaignId; campaigns[campaignId].param.tweetUrl = _tweetUrl; campaigns[campaignId].param.shareText = _shareText; campaigns[campaignId].param.via = _via; campaigns[campaignId].param.hashtag = _hashtag; campaigns[campaignId].param.bountyAmount = _bountyAmount; campaigns[campaignId].param.maxBounty = _maxBounty; campaigns[campaignId].param.startTimeStamp = _startTimeStamp; campaigns[campaignId].param.duration = _duration;
31,796
201
// move the last item into the index being vacated
bytes32 lastValue = _totalPartitions[_totalPartitions.length - 1]; _totalPartitions[index1 - 1] = lastValue; // adjust for 1-based indexing _indexOfTotalPartitions[lastValue] = index1;
bytes32 lastValue = _totalPartitions[_totalPartitions.length - 1]; _totalPartitions[index1 - 1] = lastValue; // adjust for 1-based indexing _indexOfTotalPartitions[lastValue] = index1;
33,790
31
// mapping of EIN to hydro token deposits
mapping (uint => uint) public deposits;
mapping (uint => uint) public deposits;
52,107
12
// Accept transferOwnership. /
function acceptOwnership() public { if (msg.sender == newOwner) { emit OwnershipTransferred(owner, newOwner); owner = newOwner; } }
function acceptOwnership() public { if (msg.sender == newOwner) { emit OwnershipTransferred(owner, newOwner); owner = newOwner; } }
1,786
33
// User can mint Pay SAND price for minting
if (mintPrice > 0) { payMintPrice(mintPrice); }
if (mintPrice > 0) { payMintPrice(mintPrice); }
31,092
15
// Sets the permission to lock to `_canLock`
function setCanLock(bool _canLock) external;
function setCanLock(bool _canLock) external;
1,618
228
// check balance equivalence on Migrator siderequire(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
pool.lpToken = newLpToken;
38,767
95
// Block at which the migration was initated
uint256 public InitiatedInBlock;
uint256 public InitiatedInBlock;
16,789
91
// Validate that the sum of the proposed provider BPS, does not exceed 10_000 BPS.
require( (_renderProviderSecondarySalesBPS + _platformProviderSecondarySalesBPS) <= MAX_PROVIDER_SECONDARY_SALES_BPS, "Over max sum of BPS" ); renderProviderSecondarySalesBPS = _renderProviderSecondarySalesBPS; platformProviderSecondarySalesBPS = _platformProviderSecondarySalesBPS; emit PlatformUpdated(FIELD_PROVIDER_SECONDARY_SALES_BPS);
require( (_renderProviderSecondarySalesBPS + _platformProviderSecondarySalesBPS) <= MAX_PROVIDER_SECONDARY_SALES_BPS, "Over max sum of BPS" ); renderProviderSecondarySalesBPS = _renderProviderSecondarySalesBPS; platformProviderSecondarySalesBPS = _platformProviderSecondarySalesBPS; emit PlatformUpdated(FIELD_PROVIDER_SECONDARY_SALES_BPS);
13,043
66
// Emit the Transfer event
emit Transfer(msg.sender, _to, _value); return true;
emit Transfer(msg.sender, _to, _value); return true;
13,743
91
// Returns whether round 2 has ended or not./
function hasR2Ended() external view returns (bool) { return _hasEnded[1]; }
function hasR2Ended() external view returns (bool) { return _hasEnded[1]; }
5,185
249
// number of Nodes for Test Skale-chain (4 Nodes)
uint public constant NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN = 4;
uint public constant NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN = 4;
28,988
416
// 209
entry "semiflexed" : ENG_ADJECTIVE
entry "semiflexed" : ENG_ADJECTIVE
16,821
14
// modifier to allow actions only when the contract IS NOT paused /
modifier whenPaused { require(paused); _; }
modifier whenPaused { require(paused); _; }
47,133
15
// Deploys the smart contract sets all the address/Assigns `_msgSender()` as an admin and a minter
constructor( address _nftContractAddress, address _tokenContractAddress, address _stableTokenAddress, address _cpFeeAddress, address _bufferPoolAddress, address _nonProfitAddress, address _sellerAddress ) nonZeroAddress(_nftContractAddress)
constructor( address _nftContractAddress, address _tokenContractAddress, address _stableTokenAddress, address _cpFeeAddress, address _bufferPoolAddress, address _nonProfitAddress, address _sellerAddress ) nonZeroAddress(_nftContractAddress)
37,937
255
// calculate dev
uint256 _dev = (_eth.mul(fees_[_team].giveDev)) / 100;
uint256 _dev = (_eth.mul(fees_[_team].giveDev)) / 100;
14,658
126
// Checks if a purchase is considered valid / return bool If the purchase is valid or not
function validPurchase() internal constant returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value > 0; bool withinTokenLimit = tokensRaised < maxTokensRaised; bool minimumPurchase = msg.value >= minPurchase; bool hasBalanceAvailable = crowdsaleBalances[msg.sender] < maxPurchase; // We want to limit the gas to avoid giving priority to the biggest paying contributors //bool limitGas = tx.gasprice <= limitGasPrice; return withinPeriod && nonZeroPurchase && withinTokenLimit && minimumPurchase && hasBalanceAvailable; }
function validPurchase() internal constant returns(bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value > 0; bool withinTokenLimit = tokensRaised < maxTokensRaised; bool minimumPurchase = msg.value >= minPurchase; bool hasBalanceAvailable = crowdsaleBalances[msg.sender] < maxPurchase; // We want to limit the gas to avoid giving priority to the biggest paying contributors //bool limitGas = tx.gasprice <= limitGasPrice; return withinPeriod && nonZeroPurchase && withinTokenLimit && minimumPurchase && hasBalanceAvailable; }
27,242
620
// ProxiableVaultLib Contract/Enzyme Council <security@enzyme.finance>/A contract that defines the upgrade behavior for VaultLib instances/The recommended implementation of the target of a proxy according to EIP-1822 and EIP-1967/ Code position in storage is `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`,/ which is "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc".
abstract contract ProxiableVaultLib {
abstract contract ProxiableVaultLib {
44,230
26
// A map of strategy addresses to details
mapping(Strategy => StrategyInfo) public strategies; uint256 constant MAX_BPS = 10_000;
mapping(Strategy => StrategyInfo) public strategies; uint256 constant MAX_BPS = 10_000;
18,272
36
// Returns the name of the token./
function name() public view returns (string memory) { return _name; }
function name() public view returns (string memory) { return _name; }
10,541
27
// Set Uint value in InstaMemory Contract./
function setUint(uint setId, uint val) internal { if (setId != 0) MemoryInterface(getMemoryAddr()).setUint(setId, val); }
function setUint(uint setId, uint val) internal { if (setId != 0) MemoryInterface(getMemoryAddr()).setUint(setId, val); }
41,501
101
// Value collateral
uint256 collateralValue = _tradingPairAllocator.CALCULATECOLLATERALSETVALUE480( collateralSet );
uint256 collateralValue = _tradingPairAllocator.CALCULATECOLLATERALSETVALUE480( collateralSet );
4,398
129
// Forward funds to vault
forwardFunds();
forwardFunds();
12,795
235
// Assert Leaf Hash is base of Merkle Proof
assertOrInvalidProof(eq( constructTransactionLeafHash(transactionData), // constructed computedHash // proof provided ), ErrorCode_TransactionLeafHashInvalid)
assertOrInvalidProof(eq( constructTransactionLeafHash(transactionData), // constructed computedHash // proof provided ), ErrorCode_TransactionLeafHashInvalid)
21,558
99
// See {TRC20-_burn} and {TRC20-allowance}. Requirements: - the caller must have allowance for ``accounts``'s tokens of at least`amount`. /
function burnFrom(address account, uint256 amount) external { uint256 decreasedAllowance = allowance(account, _msgSender()).sub( amount, "ERC20: burn amount exceeds allowance" ); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); }
function burnFrom(address account, uint256 amount) external { uint256 decreasedAllowance = allowance(account, _msgSender()).sub( amount, "ERC20: burn amount exceeds allowance" ); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); }
27,093
2
// See {IERC20-maxSupply}. /
function maxSupply() external view returns (uint256);
function maxSupply() external view returns (uint256);
9,267
122
// View function to see pending ERC20s for a user.
function pending(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accERC20PerShare = pool.accERC20PerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 lastBlock = block.number < endBlock ? block.number : endBlock; uint256 nrOfBlocks = lastBlock.sub(pool.lastRewardBlock); uint256 erc20Reward = nrOfBlocks.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accERC20PerShare = accERC20PerShare.add(erc20Reward.mul(1e36).div(lpSupply)); } return user.amount.mul(accERC20PerShare).div(1e36).sub(user.rewardDebt); }
function pending(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accERC20PerShare = pool.accERC20PerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 lastBlock = block.number < endBlock ? block.number : endBlock; uint256 nrOfBlocks = lastBlock.sub(pool.lastRewardBlock); uint256 erc20Reward = nrOfBlocks.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accERC20PerShare = accERC20PerShare.add(erc20Reward.mul(1e36).div(lpSupply)); } return user.amount.mul(accERC20PerShare).div(1e36).sub(user.rewardDebt); }
10,828
115
// updateWeight and pokeWeights are unavoidably long/ solhint-disable function-max-lines // Update the weight of an existing token Refactored to library to make CRPFactory deployable self - ConfigurableRightsPool instance calling the library bPool - Core BPool the CRP is wrapping token - token to be reweighted newWeight - new weight of the token/
function updateWeight( IConfigurableRightsPool self, IBPool bPool, address token, uint newWeight ) external
function updateWeight( IConfigurableRightsPool self, IBPool bPool, address token, uint newWeight ) external
33,518
283
// Check that the current state of the pricelessPositionManager is Open. This prevents multiple calls to `expire` and `EmergencyShutdown` post expiration.
modifier onlyOpenState() { _onlyOpenState(); _; }
modifier onlyOpenState() { _onlyOpenState(); _; }
5,395
12
// Updates farming center address/_farmingCenter The new farming center contract address
function setFarmingCenterAddress(address _farmingCenter) external;
function setFarmingCenterAddress(address _farmingCenter) external;
28,166
42
// Toggles project `_projectId` as active/inactive. /
function toggleProjectIsActive(uint256 _projectId) public onlyWhitelisted { projects[_projectId].active = !projects[_projectId].active; }
function toggleProjectIsActive(uint256 _projectId) public onlyWhitelisted { projects[_projectId].active = !projects[_projectId].active; }
11,195
3
// Returns whether the Pool is currently in Recovery Mode. poolState - The byte32 state of the Pool. /
function getRecoveryModeEnabled(bytes32 poolState) internal pure returns (bool) { return poolState.decodeBool(_RECOVERY_MODE_OFFSET); }
function getRecoveryModeEnabled(bytes32 poolState) internal pure returns (bool) { return poolState.decodeBool(_RECOVERY_MODE_OFFSET); }
22,216
49
// Votes on a proposal in the referendum stage. proposal The proposal struct. proposalId The ID of the proposal to vote on. index The index of the proposal ID in `dequeued`. account Account based on signer. yesVotes The yes votes weight. noVotes The no votes weight. abstainVotes The abstain votes weight.return Whether or not the proposal is passing. /
function _vote( Proposals.Proposal storage proposal, uint256 proposalId, uint256 index, address account, uint256 yesVotes, uint256 noVotes, uint256 abstainVotes
function _vote( Proposals.Proposal storage proposal, uint256 proposalId, uint256 index, address account, uint256 yesVotes, uint256 noVotes, uint256 abstainVotes
24,146
18
// Calculates the gas price of this transaction and compares it againts the specified profit./profit Profit to be compared to the cost of gas./ return "true" if the gas price (mult. to "profitFactor" is lower than the strategy profit, in USD).
function _checkGasPriceAgainstProfit(uint256 profit) internal view returns (bool)
function _checkGasPriceAgainstProfit(uint256 profit) internal view returns (bool)
10,403
2
// checks-effects-interactions pattern or using {ReentrancyGuard}.payee The address whose funds will be withdrawn and transferred to. /
function withdraw(address payable payee) public virtual onlyOwner { uint256 payment = _deposits[payee]; _deposits[payee] = 0; payee.sendValue(payment); emit Withdrawn(payee, payment); }
function withdraw(address payable payee) public virtual onlyOwner { uint256 payment = _deposits[payee]; _deposits[payee] = 0; payee.sendValue(payment); emit Withdrawn(payee, payment); }
703
131
// check if there's balance to transfer
require(amount != 0, "Balance is 0");
require(amount != 0, "Balance is 0");
8,716
27
// Accept and save the commitment
validationData[currentId] = ValidationData( msg.sender, commitmentHash, block.number, validatorClaimsBitfield ); emit InitialVerificationSuccessful(msg.sender, block.number, currentId); currentId = currentId + 1;
validationData[currentId] = ValidationData( msg.sender, commitmentHash, block.number, validatorClaimsBitfield ); emit InitialVerificationSuccessful(msg.sender, block.number, currentId); currentId = currentId + 1;
32,735
9
// Events
event UserRegistered(address payable parent, address payable child, uint level); event PoolDischarged(uint poolValue, uint usersCount, uint time);
event UserRegistered(address payable parent, address payable child, uint level); event PoolDischarged(uint poolValue, uint usersCount, uint time);
19,087
28
// special cases: cliff = period: all claimable after the cliff
function create(address _token, address payable _beneficiary, uint256 _cliff, uint256 _vesting, uint256 _amount, bool _irrevocable) public returns (uint256 ticketId) { /// @dev sender needs to approve this contract to fund the claim require(_beneficiary != address(0), "Beneficiary is required"); require(_amount > 0, "Amount is required"); require(_vesting >= _cliff, "Vesting period should be equal or longer to the cliff"); ERC20 token = ERC20(_token); require(token.balanceOf(_msgSender()) >= _amount, "Insufficient balance"); require(token.transferFrom(_msgSender(), address(this), _amount), "Funding failed."); ticketId = ++currentId; Ticket storage ticket = tickets[ticketId]; ticket.token = _token; ticket.grantor = _msgSender(); ticket.beneficiary = _beneficiary; ticket.cliff = _cliff; ticket.vesting = _vesting; ticket.amount = _amount; ticket.balance = _amount; ticket.createdAt = block.timestamp; ticket.irrevocable = _irrevocable; grantorTickets[_msgSender()].push(ticketId); beneficiaryTickets[_beneficiary].push(ticketId); emit TicketCreated(ticketId, _token, _amount, _irrevocable); }
function create(address _token, address payable _beneficiary, uint256 _cliff, uint256 _vesting, uint256 _amount, bool _irrevocable) public returns (uint256 ticketId) { /// @dev sender needs to approve this contract to fund the claim require(_beneficiary != address(0), "Beneficiary is required"); require(_amount > 0, "Amount is required"); require(_vesting >= _cliff, "Vesting period should be equal or longer to the cliff"); ERC20 token = ERC20(_token); require(token.balanceOf(_msgSender()) >= _amount, "Insufficient balance"); require(token.transferFrom(_msgSender(), address(this), _amount), "Funding failed."); ticketId = ++currentId; Ticket storage ticket = tickets[ticketId]; ticket.token = _token; ticket.grantor = _msgSender(); ticket.beneficiary = _beneficiary; ticket.cliff = _cliff; ticket.vesting = _vesting; ticket.amount = _amount; ticket.balance = _amount; ticket.createdAt = block.timestamp; ticket.irrevocable = _irrevocable; grantorTickets[_msgSender()].push(ticketId); beneficiaryTickets[_beneficiary].push(ticketId); emit TicketCreated(ticketId, _token, _amount, _irrevocable); }
30,509
12
// 增加管理员
function addOwner(address _onwer) public onlyOwner{ owners[_onwer] = true; }
function addOwner(address _onwer) public onlyOwner{ owners[_onwer] = true; }
2,306
66
// If y = 1, the fractional part is zero.
if (y == SCALE) { return result * sign; }
if (y == SCALE) { return result * sign; }
16,123
35
// Set the service fee percentage
serviceFeeBps = _percentage;
serviceFeeBps = _percentage;
17,117
31
// ---------------------------------------------------------------------------- Initiates dispute of the Escrow contract. Once requester or provider disputeFavor because they cannot agree on completion, the C4F system can arbitrate the Escrow based on the internal juror system. ----------------------------------------------------------------------------
function disputeFavor() public onlyProviderOrRequester returns (bool success) { if(msg.sender == requester) { requesterDisputed = true; } if(msg.sender == provider) { providerDisputed = true; providerLocked = true; } favorDisputed(msg.sender); return true; }
function disputeFavor() public onlyProviderOrRequester returns (bool success) { if(msg.sender == requester) { requesterDisputed = true; } if(msg.sender == provider) { providerDisputed = true; providerLocked = true; } favorDisputed(msg.sender); return true; }
62,658
164
// Pull the creator address before removing the auction.
address curator = auctions[tokenId].curator;
address curator = auctions[tokenId].curator;
24,507
151
// spotDailySupplyRateProvider() + (spotDailyDistributionRateProvider() - fraction lost to harvest)
return spotDailySupplyRateProvider().add(expectedSpotDailyDistributionRate);
return spotDailySupplyRateProvider().add(expectedSpotDailyDistributionRate);
52,597
212
// after all investor latch fci, controller change round state withdrawable now investor can withdraw NAC from NetfRevenue funds of this round and auto switch to unpause phrase/
function changeWithdrawableNetfRe(uint _roundIndex) onlyController public { require(isPause == true && NetfRevenue[_roundIndex].isOpen == true); NetfRevenue[_roundIndex].withdrawable = true; isPause = false; }
function changeWithdrawableNetfRe(uint _roundIndex) onlyController public { require(isPause == true && NetfRevenue[_roundIndex].isOpen == true); NetfRevenue[_roundIndex].withdrawable = true; isPause = false; }
17,224
102
// 1
require( warmupContract == address(0), "Warmup cannot be set more than once" ); warmupContract = _address;
require( warmupContract == address(0), "Warmup cannot be set more than once" ); warmupContract = _address;
8,325
14
// multiplies two wad, rounding half up to the nearest wada wadb wad return the result of ab, in wad/
function wadMul(uint256 a, uint256 b) internal pure returns (uint256) { return halfWAD.add(a.mul(b)).div(WAD); }
function wadMul(uint256 a, uint256 b) internal pure returns (uint256) { return halfWAD.add(a.mul(b)).div(WAD); }
34,785
16
// bet 구조체에 값을 채워넣기
bet.amount = amount; bet.numOfBetBit = numOfBetBit; bet.placeBlockNumber = block.number; bet.mask = betMask; bet.gambler = msg.sender;
bet.amount = amount; bet.numOfBetBit = numOfBetBit; bet.placeBlockNumber = block.number; bet.mask = betMask; bet.gambler = msg.sender;
31,629
163
// Transfers ownership of the contract to a new account (`newOwner`).Can only be called by the current owner. /
function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); }
function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); }
433
48
// ERC 20 Token Standard Interface /
interface EIP20Interface { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool success); /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external returns (bool success); /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); }
interface EIP20Interface { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool success); /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external returns (bool success); /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); }
3,291
104
// Calculate the cumulative reward per token from lastUpdateTime to lastTimeRewardApplicable()such time span could be divided into 3 parts by halve intervals:(lastUpdateTime, firstIntervalEnd), (firstIntervalEnd, lastIntervalStart), (lastIntervalStart, lastTimeRewardApplicable()) /
function getRewardPerTokenAmount() public view returns (uint256, uint256) { uint256 _timestamp = lastTimeRewardApplicable(); uint256 _distributionTime = distributionTime; uint256 _lastUpdateTime = lastUpdateTime; if (_timestamp < _distributionTime || _timestamp == _lastUpdateTime) return (0, 0); uint256 _lastUpdateTimeOffset = _lastUpdateTime.sub(_distributionTime) % halveInterval; uint256 _firstIntervalEnd = _lastUpdateTime .sub(_lastUpdateTimeOffset) .add(halveInterval); // The time span is too short that it has not reach _firstIntervalEnd // if (_timestamp < _firstIntervalEnd) // return // _timestamp.sub(_lastUpdateTime).mul( // getFixedRewardRate(_lastUpdateTime) // ); // The amount from _lastUpdateTime to _firstIntervalEnd // uint256 _rewardPerTokenAmount = halveInterval // .sub(_lastUpdateTimeOffset) // .mul(getFixedRewardRate(_lastUpdateTime)); // The amount from _firstIntervalEnd to last interval start, it may contains n full halve interval (n >= 0) // n = 0 if _firstIntervalEnd and _timestamp lay in the same halve interval // _currentRewardRate represents 1/2 of the reward rate of last full interval // uint256 _currentRewardRate = getFixedRewardRate(_timestamp); // _rewardPerTokenAmount = _rewardPerTokenAmount.add( // ( // halveInterval.mul( // getFixedRewardRate(_firstIntervalEnd).sub( // _currentRewardRate // ) // ) // ) << 1 // ); // Finally, the amount from last interval start to timestamp // return // _rewardPerTokenAmount.add( // (_timestamp.sub(_distributionTime) % halveInterval).mul( // _currentRewardRate // ) // ); // The time span is too short that it has not reach _firstIntervalEnd if (_timestamp < _firstIntervalEnd) { uint256 _eBTCResult = _timestamp.sub(_lastUpdateTime).mul(getFixedRewardRatePerToken(_lastUpdateTime)[0]); uint256 _eETHResult = _timestamp.sub(_lastUpdateTime).mul(getFixedRewardRatePerToken(_lastUpdateTime)[1]); return (_eBTCResult, _eETHResult); } // The amount from _lastUpdateTime to _firstIntervalEnd uint256 _eBTCRewardPerTokenAmount = halveInterval.sub(_lastUpdateTimeOffset).mul(getFixedRewardRatePerToken(_lastUpdateTime)[0]); uint256 _eETHRewardPerTokenAmount = halveInterval.sub(_lastUpdateTimeOffset).mul(getFixedRewardRatePerToken(_lastUpdateTime)[1]); // The amount from _firstIntervalEnd to last interval start, it may contains n full halve interval (n >= 0) // n = 0 if _firstIntervalEnd and _timestamp lay in the same halve interval // _currentRewardRate represents 1/2 of the reward rate of last full interval uint256[] memory _currentRewardRate = getFixedRewardRatePerToken(_timestamp); _eBTCRewardPerTokenAmount = _eBTCRewardPerTokenAmount.add( ( halveInterval.mul(getFixedRewardRatePerToken(_firstIntervalEnd)[0].sub(_currentRewardRate[0])) ) << 1 ); _eETHRewardPerTokenAmount = _eETHRewardPerTokenAmount.add( ( halveInterval.mul(getFixedRewardRatePerToken(_firstIntervalEnd)[1].sub(_currentRewardRate[1])) ) << 1 ); // Finally, the amount from last interval start to timestamp uint256 _eBTCResult = _eBTCRewardPerTokenAmount.add( (_timestamp.sub(_distributionTime) % halveInterval).mul(_currentRewardRate[0]) ); uint256 _eETHResult = _eETHRewardPerTokenAmount.add( (_timestamp.sub(_distributionTime) % halveInterval).mul(_currentRewardRate[1]) ); return (_eBTCResult, _eETHResult); }
function getRewardPerTokenAmount() public view returns (uint256, uint256) { uint256 _timestamp = lastTimeRewardApplicable(); uint256 _distributionTime = distributionTime; uint256 _lastUpdateTime = lastUpdateTime; if (_timestamp < _distributionTime || _timestamp == _lastUpdateTime) return (0, 0); uint256 _lastUpdateTimeOffset = _lastUpdateTime.sub(_distributionTime) % halveInterval; uint256 _firstIntervalEnd = _lastUpdateTime .sub(_lastUpdateTimeOffset) .add(halveInterval); // The time span is too short that it has not reach _firstIntervalEnd // if (_timestamp < _firstIntervalEnd) // return // _timestamp.sub(_lastUpdateTime).mul( // getFixedRewardRate(_lastUpdateTime) // ); // The amount from _lastUpdateTime to _firstIntervalEnd // uint256 _rewardPerTokenAmount = halveInterval // .sub(_lastUpdateTimeOffset) // .mul(getFixedRewardRate(_lastUpdateTime)); // The amount from _firstIntervalEnd to last interval start, it may contains n full halve interval (n >= 0) // n = 0 if _firstIntervalEnd and _timestamp lay in the same halve interval // _currentRewardRate represents 1/2 of the reward rate of last full interval // uint256 _currentRewardRate = getFixedRewardRate(_timestamp); // _rewardPerTokenAmount = _rewardPerTokenAmount.add( // ( // halveInterval.mul( // getFixedRewardRate(_firstIntervalEnd).sub( // _currentRewardRate // ) // ) // ) << 1 // ); // Finally, the amount from last interval start to timestamp // return // _rewardPerTokenAmount.add( // (_timestamp.sub(_distributionTime) % halveInterval).mul( // _currentRewardRate // ) // ); // The time span is too short that it has not reach _firstIntervalEnd if (_timestamp < _firstIntervalEnd) { uint256 _eBTCResult = _timestamp.sub(_lastUpdateTime).mul(getFixedRewardRatePerToken(_lastUpdateTime)[0]); uint256 _eETHResult = _timestamp.sub(_lastUpdateTime).mul(getFixedRewardRatePerToken(_lastUpdateTime)[1]); return (_eBTCResult, _eETHResult); } // The amount from _lastUpdateTime to _firstIntervalEnd uint256 _eBTCRewardPerTokenAmount = halveInterval.sub(_lastUpdateTimeOffset).mul(getFixedRewardRatePerToken(_lastUpdateTime)[0]); uint256 _eETHRewardPerTokenAmount = halveInterval.sub(_lastUpdateTimeOffset).mul(getFixedRewardRatePerToken(_lastUpdateTime)[1]); // The amount from _firstIntervalEnd to last interval start, it may contains n full halve interval (n >= 0) // n = 0 if _firstIntervalEnd and _timestamp lay in the same halve interval // _currentRewardRate represents 1/2 of the reward rate of last full interval uint256[] memory _currentRewardRate = getFixedRewardRatePerToken(_timestamp); _eBTCRewardPerTokenAmount = _eBTCRewardPerTokenAmount.add( ( halveInterval.mul(getFixedRewardRatePerToken(_firstIntervalEnd)[0].sub(_currentRewardRate[0])) ) << 1 ); _eETHRewardPerTokenAmount = _eETHRewardPerTokenAmount.add( ( halveInterval.mul(getFixedRewardRatePerToken(_firstIntervalEnd)[1].sub(_currentRewardRate[1])) ) << 1 ); // Finally, the amount from last interval start to timestamp uint256 _eBTCResult = _eBTCRewardPerTokenAmount.add( (_timestamp.sub(_distributionTime) % halveInterval).mul(_currentRewardRate[0]) ); uint256 _eETHResult = _eETHRewardPerTokenAmount.add( (_timestamp.sub(_distributionTime) % halveInterval).mul(_currentRewardRate[1]) ); return (_eBTCResult, _eETHResult); }
30,585