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
34
// Atomically decreases the allowance granted to `spender` by the caller./
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; }
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; }
27,626
19
// Reinvest /
) internal view returns (uint256) { uint256 swapFee = IBaseV2Pair(underlying).feeRatio(); uint256 swapFeeFactor = uint256(1000000).sub(swapFee); uint256 a = uint256(1000000).add(swapFeeFactor).mul(_reserveA); uint256 b = _amountA.mul(1000000).mul(_reserveA).mul(4).mul(swapFeeFactor); uint256 c = Math.sqrt(a.mul(a).add(b)); uint256 d = uint256(2).mul(swapFeeFactor); return c.sub(a).div(d); }
) internal view returns (uint256) { uint256 swapFee = IBaseV2Pair(underlying).feeRatio(); uint256 swapFeeFactor = uint256(1000000).sub(swapFee); uint256 a = uint256(1000000).add(swapFeeFactor).mul(_reserveA); uint256 b = _amountA.mul(1000000).mul(_reserveA).mul(4).mul(swapFeeFactor); uint256 c = Math.sqrt(a.mul(a).add(b)); uint256 d = uint256(2).mul(swapFeeFactor); return c.sub(a).div(d); }
19,019
4
// records you use the referral program or not
mapping (address => uint) public referrerOn;
mapping (address => uint) public referrerOn;
38,150
12
// give delveoper the money left behind
SentDeveloperFee(remain, this.balance); developer.transfer(remain); numguesses = 0; for (i = 0; i < stasticsarrayitems; i++) { statistics[i] = 0; }
SentDeveloperFee(remain, this.balance); developer.transfer(remain); numguesses = 0; for (i = 0; i < stasticsarrayitems; i++) { statistics[i] = 0; }
49,102
12
// Goldilocks prime field
uint256 internal constant _GOLDILOCKS_PRIME_FIELD = 0xFFFFFFFF00000001; // 2 ** 64 - 2 ** 32 + 1
uint256 internal constant _GOLDILOCKS_PRIME_FIELD = 0xFFFFFFFF00000001; // 2 ** 64 - 2 ** 32 + 1
39,354
13
// need to be enabled to allow investor to participate in the ico
bool public icoEnabled;
bool public icoEnabled;
774
5
// Contract constructor
constructor( address payable _feeRecipient, uint256 _platformFee
constructor( address payable _feeRecipient, uint256 _platformFee
72,839
32
// Division of two int256 variables and fails on overflow. /
function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; }
function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; }
21,407
51
// Submit a batch of commits in a single transaction. Using `encryptedVote` is optional. If included then commitment is emitted in an event.Look at `project-root/common/Constants.js` for the tested maximum number ofcommitments that can fit in one transaction. commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. /
function batchCommit(Commitment[] calldata commits) external override { for (uint256 i = 0; i < commits.length; i++) { if (commits[i].encryptedVote.length == 0) { commitVote(commits[i].identifier, commits[i].time, commits[i].hash); } else { commitAndEmitEncryptedVote(commits[i].identifier, commits[i].time, commits[i].hash, commits[i].encryptedVote); } } }
function batchCommit(Commitment[] calldata commits) external override { for (uint256 i = 0; i < commits.length; i++) { if (commits[i].encryptedVote.length == 0) { commitVote(commits[i].identifier, commits[i].time, commits[i].hash); } else { commitAndEmitEncryptedVote(commits[i].identifier, commits[i].time, commits[i].hash, commits[i].encryptedVote); } } }
10,395
5
// 维护需要从chainlink取价格的token 地址 => chainlink 价格合约地址的映射
mapping(address => address) public tokenChainlinkMap;
mapping(address => address) public tokenChainlinkMap;
39,497
324
// Safe Token // Gets balance of this contract in terms of the underlying This excludes the value of the current message, if anyreturn The quantity of underlying tokens owned by this contract /
function getCashPrior() internal view returns (uint) { EIP20Interface token = EIP20Interface(underlying); return token.balanceOf(address(this)); }
function getCashPrior() internal view returns (uint) { EIP20Interface token = EIP20Interface(underlying); return token.balanceOf(address(this)); }
671
26
// Updates the storage variable for vaults to query/_vaults An array of the new vaults to store
function updateVaults(address[] memory _vaults) external onlyAuthorized { // reset our array in storage vaults = new IVotingVault[](_vaults.length); // populate with each vault passed into the method for (uint256 i = 0; i < _vaults.length; i++) { vaults[i] = IVotingVault(_vaults[i]); } }
function updateVaults(address[] memory _vaults) external onlyAuthorized { // reset our array in storage vaults = new IVotingVault[](_vaults.length); // populate with each vault passed into the method for (uint256 i = 0; i < _vaults.length; i++) { vaults[i] = IVotingVault(_vaults[i]); } }
21,809
42
// ----------HELPERS AND CALCULATORS----------/ Find out if your friend is playing or not...
function playerStatus(address _player) public view returns (bool) { return activatedPlayer_[_player]; }
function playerStatus(address _player) public view returns (bool) { return activatedPlayer_[_player]; }
18,261
60
// Gets fix fee/Allowed to be overriden for specific chain implementations/ return fixFee amount of fixFee in notional units
function _getFixFee(uint256) internal view virtual returns (uint256 fixFee) { return 0; }
function _getFixFee(uint256) internal view virtual returns (uint256 fixFee) { return 0; }
16,024
77
// Allow the owner to withdraw tokens from the Foundation reserve
allowed[foundationReserve][msg.sender] = balanceOf(foundationReserve);
allowed[foundationReserve][msg.sender] = balanceOf(foundationReserve);
46,798
30
// transfer the amount from the recipient
balances[dst] -= amount; emit Transfer(dst, address(0), amount);
balances[dst] -= amount; emit Transfer(dst, address(0), amount);
74,283
10
// Returns the amount of tokens owned by a given account. account_ Account that owns the tokens. return balance_ Amount of tokens owned by a given account. /
function balanceOf(address account_) external view returns (uint256 balance_);
function balanceOf(address account_) external view returns (uint256 balance_);
10,948
9
// Wrap x to be in between min and max, inclusive source: https:github.com/Rari-Capital/solmate/blob/32edfe8cf8e163515a30b1214d0480029f6094cd/src/test/utils/DSTestPlus.solL114-L133
function bound(uint256 x, uint256 min, uint256 max) internal pure returns (uint256 result) { require(max >= min, "MAX_LESS_THAN_MIN"); uint256 size = max - min; if (max != type(uint256).max) size++; // Make the max inclusive. if (size == 0) return min; // Using max would be equivalent as well. // Ensure max is inclusive in cases where x != 0 and max is at uint max. if (max == type(uint256).max && x != 0) x--; // Accounted for later. if (x < min) x += size * (((min - x) / size) + 1); result = min + ((x - min) % size); // Account for decrementing x to make max inclusive. if (max == type(uint256).max && x != 0) result++; }
function bound(uint256 x, uint256 min, uint256 max) internal pure returns (uint256 result) { require(max >= min, "MAX_LESS_THAN_MIN"); uint256 size = max - min; if (max != type(uint256).max) size++; // Make the max inclusive. if (size == 0) return min; // Using max would be equivalent as well. // Ensure max is inclusive in cases where x != 0 and max is at uint max. if (max == type(uint256).max && x != 0) x--; // Accounted for later. if (x < min) x += size * (((min - x) / size) + 1); result = min + ((x - min) % size); // Account for decrementing x to make max inclusive. if (max == type(uint256).max && x != 0) result++; }
28,025
5
// The TokenSold event is fired whenever a token is sold.
event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 newPrice, address prevOwner, address winner, string name);
event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 newPrice, address prevOwner, address winner, string name);
21,305
11
// are factory pools! (e.g. dusd)/
function isMetaPool(address swapAddress) public view returns (bool) { if (isCurvePool(swapAddress)) { uint256[2] memory poolTokenCounts = CurveRegistry.get_n_coins(swapAddress); if (poolTokenCounts[0] == poolTokenCounts[1]) return false; else return true; } if (isFactoryPool(swapAddress)) return true; return false; }
function isMetaPool(address swapAddress) public view returns (bool) { if (isCurvePool(swapAddress)) { uint256[2] memory poolTokenCounts = CurveRegistry.get_n_coins(swapAddress); if (poolTokenCounts[0] == poolTokenCounts[1]) return false; else return true; } if (isFactoryPool(swapAddress)) return true; return false; }
74,576
16
// amount of Neumarks reserved for Ether whitelist investors
uint256 private _whitelistEtherNmk = 0;
uint256 private _whitelistEtherNmk = 0;
19,623
34
// Increase the amount of tokens that an owner allowed to a spender. approve should be called when allowed[_spender] == 0. To increment allowed value is better to use this function to avoid 2 calls (and wait until the first transaction is mined) From MonolithDAO Token.sol_spender The address which will spend the funds._addedValue The amount of tokens to increase the allowance by./
function increaseApproval(address _spender, uint256 _addedValue) public ifUnrestricted onlyPayloadSize(2) returns (bool) { require(_addedValue > 0); allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
function increaseApproval(address _spender, uint256 _addedValue) public ifUnrestricted onlyPayloadSize(2) returns (bool) { require(_addedValue > 0); allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
8,430
31
// flag which tracks if an submission period received a valid solution
bool public gotFullValidSolution;
bool public gotFullValidSolution;
22,618
5
// 0 is used for checking existence(voted or not)
mapping(string => MobVoteHistory) mobVoteHistory; mapping(string => ItemVoteHistory) itemVoteHistory;
mapping(string => MobVoteHistory) mobVoteHistory; mapping(string => ItemVoteHistory) itemVoteHistory;
23,944
15
// Main function for initiating and completing a game
function play(uint8 playerMove) public payable requireUnpaused requireMoney checkPlay(playerMove)
function play(uint8 playerMove) public payable requireUnpaused requireMoney checkPlay(playerMove)
47,186
101
// Admin can unpause token sell /
function emergencyUnpause() external onlyOwner { emergencyPaused = false; }
function emergencyUnpause() external onlyOwner { emergencyPaused = false; }
18,923
23
// Managment events
event SetName(string _prev, string _new); event SetHeap(address _prev, address _new); event WhitelistTo(address _addr, bool _whitelisted); uint256 override public totalSupply = 52500000000000000 ; bytes32 private constant BALANCE_KEY = keccak256("balance");
event SetName(string _prev, string _new); event SetHeap(address _prev, address _new); event WhitelistTo(address _addr, bool _whitelisted); uint256 override public totalSupply = 52500000000000000 ; bytes32 private constant BALANCE_KEY = keccak256("balance");
44,828
60
// Gets credit account parameters
( uint256 borrowedAmount, uint256 cumulativeIndexAtCreditAccountOpen_RAY ) = getCreditAccountParameters(creditAccount); // T:[CM-13] return _calcClosePaymentsPure( totalValue, isLiquidated, borrowedAmount,
( uint256 borrowedAmount, uint256 cumulativeIndexAtCreditAccountOpen_RAY ) = getCreditAccountParameters(creditAccount); // T:[CM-13] return _calcClosePaymentsPure( totalValue, isLiquidated, borrowedAmount,
36,098
9
// Modified getAllGames function to filter out expired games
function getAllGames() external view returns (GameDetails[] memory) { uint256 count = 0; for (uint256 i = 0; i < gameId.current(); i++) { if (gameMapping[i].state != GAME_STATE.EXPIRED) { count++; } } GameDetails[] memory allGames = new GameDetails[](count); uint256 index = 0; for (uint256 i = 0; i < gameId.current(); i++) { if (gameMapping[i].state != GAME_STATE.EXPIRED) { Game memory game = gameMapping[i]; allGames[index] = GameDetails( game.id, // Round ID game.player1, game.player2, // Player 2 wallet game.player1Option, game.player2Option, game.state, // Status of the game game.prize, game.winner ); index++; } } return allGames; }
function getAllGames() external view returns (GameDetails[] memory) { uint256 count = 0; for (uint256 i = 0; i < gameId.current(); i++) { if (gameMapping[i].state != GAME_STATE.EXPIRED) { count++; } } GameDetails[] memory allGames = new GameDetails[](count); uint256 index = 0; for (uint256 i = 0; i < gameId.current(); i++) { if (gameMapping[i].state != GAME_STATE.EXPIRED) { Game memory game = gameMapping[i]; allGames[index] = GameDetails( game.id, // Round ID game.player1, game.player2, // Player 2 wallet game.player1Option, game.player2Option, game.state, // Status of the game game.prize, game.winner ); index++; } } return allGames; }
16,298
8
// Transfer the total donated amount to the recipient
recipient.transfer(totalDonated);
recipient.transfer(totalDonated);
14,193
8
// Enables or disables approval for a third party ("operator") to manage all of`msg.sender`'s assets. It also emits the ApprovalForAll event. The contract MUST allow multiple operators per owner. _operator Address to add to the set of authorized operators. _approved True if the operators is approved, false to revoke approval. /
function setApprovalForAll(
function setApprovalForAll(
29,045
45
// zero out the 32 bytes slice we are about to returnwe need to do it because Solidity does not garbage collect
mstore(tempBytes, 0) mstore(0x40, add(tempBytes, 0x20))
mstore(tempBytes, 0) mstore(0x40, add(tempBytes, 0x20))
10,247
17
// sell fees
uint256 baseRewardsFee = rewardsFee; uint256 baseDevFee = devFee; if (to == uniswapV2Pair) { devFee = sellDevFee; rewardsFee = sellRewardsFee; if (launchSellFeeDeadline >= block.timestamp) { devFee = devFee.add(launchSellFee); }
uint256 baseRewardsFee = rewardsFee; uint256 baseDevFee = devFee; if (to == uniswapV2Pair) { devFee = sellDevFee; rewardsFee = sellRewardsFee; if (launchSellFeeDeadline >= block.timestamp) { devFee = devFee.add(launchSellFee); }
68,602
22
// Updates the address of the communityAdmin_newCommunityAdmin address of the new communityAdmin used only for testing the new community upgrade flow /
function updateCommunityAdmin(ICommunityAdmin _newCommunityAdmin) external onlyOwner { communityAdmin = _newCommunityAdmin; }
function updateCommunityAdmin(ICommunityAdmin _newCommunityAdmin) external onlyOwner { communityAdmin = _newCommunityAdmin; }
29,255
20
// Burn tokens and return the price paid to the token owner if the funding target was not reachedCan be called starting 1 day after funding duration ends _tokenIds The ids of the tokens to be refunded /
function burnToRefund(uint256[] calldata _tokenIds) external nonReentrant { HeyMintStorage.State storage state = HeyMintStorage.state(); // Prevent refunding tokens on a contract where conditional funding has not been enabled require(state.cfg.fundingEndsAt > 0, "NOT_CONFIGURED"); require( block.timestamp > uint256(state.cfg.fundingEndsAt) + 1 days, "FUNDING_PERIOD_STILL_ACTIVE" ); require(!state.data.fundingTargetReached, "FUNDING_TARGET_WAS_MET"); require( address(this).balance < fundingTargetInWei(), "FUNDING_TARGET_WAS_MET" ); uint256 totalRefund = 0; for (uint256 i = 0; i < _tokenIds.length; i++) { require(ownerOf(_tokenIds[i]) == msg.sender, "MUST_OWN_TOKEN"); require( state.data.pricePaid[_tokenIds[i]] > 0, "TOKEN_WAS_NOT_PURCHASED" ); safeTransferFrom( msg.sender, 0x000000000000000000000000000000000000dEaD, _tokenIds[i] ); totalRefund += state.data.pricePaid[_tokenIds[i]]; } (bool success, ) = payable(msg.sender).call{value: totalRefund}(""); require(success, "TRANSFER_FAILED"); }
function burnToRefund(uint256[] calldata _tokenIds) external nonReentrant { HeyMintStorage.State storage state = HeyMintStorage.state(); // Prevent refunding tokens on a contract where conditional funding has not been enabled require(state.cfg.fundingEndsAt > 0, "NOT_CONFIGURED"); require( block.timestamp > uint256(state.cfg.fundingEndsAt) + 1 days, "FUNDING_PERIOD_STILL_ACTIVE" ); require(!state.data.fundingTargetReached, "FUNDING_TARGET_WAS_MET"); require( address(this).balance < fundingTargetInWei(), "FUNDING_TARGET_WAS_MET" ); uint256 totalRefund = 0; for (uint256 i = 0; i < _tokenIds.length; i++) { require(ownerOf(_tokenIds[i]) == msg.sender, "MUST_OWN_TOKEN"); require( state.data.pricePaid[_tokenIds[i]] > 0, "TOKEN_WAS_NOT_PURCHASED" ); safeTransferFrom( msg.sender, 0x000000000000000000000000000000000000dEaD, _tokenIds[i] ); totalRefund += state.data.pricePaid[_tokenIds[i]]; } (bool success, ) = payable(msg.sender).call{value: totalRefund}(""); require(success, "TRANSFER_FAILED"); }
21,078
4
// The hash is constructed from left to right.
uint256 result; uint16 cursor = 256;
uint256 result; uint16 cursor = 256;
39,601
23
// record the lock for the user
UserInfo storage user = users[_withdrawer]; user.lockedTokens.add(_lpToken); uint256[] storage user_locks = user.locksForToken[_lpToken]; user_locks.push(token_lock.lockID); emit onDeposit(_lpToken, msg.sender, token_lock.amount, token_lock.lockDate, token_lock.unlockDate);
UserInfo storage user = users[_withdrawer]; user.lockedTokens.add(_lpToken); uint256[] storage user_locks = user.locksForToken[_lpToken]; user_locks.push(token_lock.lockID); emit onDeposit(_lpToken, msg.sender, token_lock.amount, token_lock.lockDate, token_lock.unlockDate);
13,018
70
// Retrieve the total token supply. /
function totalSupply() public view returns(uint256)
function totalSupply() public view returns(uint256)
3,266
46
// BaseAuthorizer: Authorizer paused.
string constant AUTHORIZER_PAUSED = "E46";
string constant AUTHORIZER_PAUSED = "E46";
22,995
22
// Ensure that there was no member found with the given id / address.
if ((entrant != address(0)) && (!member) && (memberAddress == address(0))) {
if ((entrant != address(0)) && (!member) && (memberAddress == address(0))) {
40,737
18
// Message sender declares it as a super app configWord The super app manifest configuration, flags are defined in`SuperAppDefinitions` /
function registerApp(uint256 configWord) external;
function registerApp(uint256 configWord) external;
6,104
1
// Maximum allowed value is 10000 (1%)Examples:poolFee =3000 =>3000 / 1e6 = 0.003 = 0.3%poolFee = 10000 => 10000 / 1e6 =0.01 = 1.0% /
uint256 public poolFee = 3000; // Init the uniswap pool fee to 0.3% address public hopTokenAddress; //Initially DAI, could potentially be USDC
uint256 public poolFee = 3000; // Init the uniswap pool fee to 0.3% address public hopTokenAddress; //Initially DAI, could potentially be USDC
51,523
214
// Interval blocks to reduce mining volume.
uint256 public reduceIntervalBlock;
uint256 public reduceIntervalBlock;
38,348
292
// Transfer rewards
stakingContract.stakeRewards(rewardsForClaimer, _claimer);
stakingContract.stakeRewards(rewardsForClaimer, _claimer);
7,467
17
// EtherOutPlan: network owner can define as much plan as possible max up to 256 for ex main, auto-pool, unilevel, dividend and any other 0 = to parent, ( ex 1,1,1,1 on payoutTo will send to each parent above up to 4th) 1 = to referrer, ( ex 1,1,1,1 on payoutTo will send to each referrer above up to 4th) 2 = to certain id given in the list, for ex (2365,3099,1,5)3 = to the id referenced back from the joiner like if number is 1,,3,6 and joiner is 515 then payment will go to 514, 512, 5094 = to defined
struct etherOutPlan
struct etherOutPlan
3,065
10
// IERC20(_erc20).safeTransfer(donates[_id].owner, donates[_id].amount);
payable(donates[_id].owner).send(donates[_id].amount); donates[_id].amount = 0;
payable(donates[_id].owner).send(donates[_id].amount); donates[_id].amount = 0;
41,695
204
// Dividend paying SDVD supply on each snapshot id.
mapping(uint256 => uint256) private _dividendPayingSDVDSupplySnapshots;
mapping(uint256 => uint256) private _dividendPayingSDVDSupplySnapshots;
19,168
28
// ------------------------------------------------------------------------ Burn the ``value` amount of tokens from the `account` ------------------------------------------------------------------------
function burnTokens(uint256 value) internal{ require(_totalSupply >= value); // burn only unsold tokens _totalSupply = _totalSupply.sub(value); emit Transfer(msg.sender, address(0), value); }
function burnTokens(uint256 value) internal{ require(_totalSupply >= value); // burn only unsold tokens _totalSupply = _totalSupply.sub(value); emit Transfer(msg.sender, address(0), value); }
5,065
72
// how many token units a buyer gets per wei
uint256 public rate;
uint256 public rate;
17,615
59
// /
require(bought_tokens && bonus_received); uint256 contract_token_balance = token.balanceOf(address(this)); require(contract_token_balance != 0); uint256 tokens_to_withdraw = SafeMath.div(SafeMath.mul(balances_bonus[msg.sender], contract_token_balance), contract_eth_value_bonus); contract_eth_value_bonus = SafeMath.sub(contract_eth_value_bonus, balances_bonus[msg.sender]); balances_bonus[msg.sender] = 0; require(token.transfer(msg.sender, tokens_to_withdraw));
require(bought_tokens && bonus_received); uint256 contract_token_balance = token.balanceOf(address(this)); require(contract_token_balance != 0); uint256 tokens_to_withdraw = SafeMath.div(SafeMath.mul(balances_bonus[msg.sender], contract_token_balance), contract_eth_value_bonus); contract_eth_value_bonus = SafeMath.sub(contract_eth_value_bonus, balances_bonus[msg.sender]); balances_bonus[msg.sender] = 0; require(token.transfer(msg.sender, tokens_to_withdraw));
13,219
80
// Function for automated buyback settings. Set in percentages for example: 50% = 50% to buyback and 50% to marketing wallet
function changeBuyBackSettings(bool _buyBackEnabled, uint256 _percentForMarketing) external onlyOwner { require(_percentForMarketing <= 100, "Must be set below 100%"); percentForMarketing = _percentForMarketing; buyBackEnabled = _buyBackEnabled; }
function changeBuyBackSettings(bool _buyBackEnabled, uint256 _percentForMarketing) external onlyOwner { require(_percentForMarketing <= 100, "Must be set below 100%"); percentForMarketing = _percentForMarketing; buyBackEnabled = _buyBackEnabled; }
38,580
20
// Tell the network, successful function - how much in the pool now?
emit onDonate(msg.sender, _amount, block.timestamp); return dripPoolBalance;
emit onDonate(msg.sender, _amount, block.timestamp); return dripPoolBalance;
21,275
145
// Update Uniswap pair
try IUniswapV2Pair(uniswapPair).sync() {} catch (bytes memory uniswapRevertReason) { emit FailedUniswapPairSync(uniswapRevertReason); }
try IUniswapV2Pair(uniswapPair).sync() {} catch (bytes memory uniswapRevertReason) { emit FailedUniswapPairSync(uniswapRevertReason); }
49,672
38
// True if the initial token supply is over
bool initialTokenSupplyDone;
bool initialTokenSupplyDone;
7,435
23
// Verify if _from is the signer
require(isValidSignature(_from, data, sig), "ERC1155Meta#_validateTransferSignature: INVALID_SIGNATURE");
require(isValidSignature(_from, data, sig), "ERC1155Meta#_validateTransferSignature: INVALID_SIGNATURE");
15,911
85
// Returns the address of the owner of the NFT. NFTs assigned to zero address are considered invalid, and queries about them do throw._tokenId The identifier for an NFT. return _owner Address of _tokenId owner./
function ownerOf( uint256 _tokenId) external override view returns (address _owner) { _owner = idToOwner[_tokenId]; require(_owner != address(0)); }
function ownerOf( uint256 _tokenId) external override view returns (address _owner) { _owner = idToOwner[_tokenId]; require(_owner != address(0)); }
17,983
1
// player[0] : player0 and [1] : player 2
uint public numOfPlayers; uint currentPlayer; Player[] players; Player plyn; State state; address[2] public plyradd; constructor() public{ shiplen[0] = 0;
uint public numOfPlayers; uint currentPlayer; Player[] players; Player plyn; State state; address[2] public plyradd; constructor() public{ shiplen[0] = 0;
18,986
116
// Mint a single NFT to address
_mint(receiver, id, 1, ""); supply++;
_mint(receiver, id, 1, ""); supply++;
12,718
4
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
result := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff )
result := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff )
22,710
35
// Run this first to set the contract owner.
function initVotingAlpha() public { require(!members.isInitialised()); _initOperated(msg.sender); }
function initVotingAlpha() public { require(!members.isInitialised()); _initOperated(msg.sender); }
9,256
2
// This emits when ownership of any iNFT changes by any mechanism
event iNFTTransfer(address indexed _from, address indexed _to, bytes32 indexed _infoHash);
event iNFTTransfer(address indexed _from, address indexed _to, bytes32 indexed _infoHash);
8,902
110
// excluder exclude any wallet for contact buy fees
function excludeFromBuyFees(address _address, bool _exclude) external onlyOwner { _isExcludedFromBuyFees[_address] = _exclude; }
function excludeFromBuyFees(address _address, bool _exclude) external onlyOwner { _isExcludedFromBuyFees[_address] = _exclude; }
48,131
18
// 0.1% fee if a user deposits and withdraws after 4 weeks.
uint256 userWithdrawFee = amount*(userFeeStage[7])/10000; stakingToken.safeTransfer(address(msg.sender), userWithdrawFee); stakingToken.safeTransfer(address(devaddr), amount-userWithdrawFee); user.lastWithdrawBlock = block.number;
uint256 userWithdrawFee = amount*(userFeeStage[7])/10000; stakingToken.safeTransfer(address(msg.sender), userWithdrawFee); stakingToken.safeTransfer(address(devaddr), amount-userWithdrawFee); user.lastWithdrawBlock = block.number;
17,596
583
// They're allowed to issue up to issuanceRatio of that value
return (destinationValue.multiplyDecimal(getIssuanceRatio()), isInvalid);
return (destinationValue.multiplyDecimal(getIssuanceRatio()), isInvalid);
3,790
29
// This famous algorithm is called "exponentiation by squaring" and calculates x^n with x as fixed-point and n as regular unsigned. It&39;s O(log n), instead of O(n) for naive repeated multiplication. These facts are why it works:If n is even, then x^n = (x^2)^(n/2).If n is odd,then x^n = xx^(n-1), and applying the equation for even x givesx^n = x(x^2)^((n-1) / 2).Also, EVM division is flooring andfloor[(n-1) / 2] = floor[n / 2].
z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); }
z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); }
16,021
49
// Load the bounds of our binary search
uint256 maxIndex = length - 1; uint256 minIndex = startingMinIndex; uint256 staleIndex = 0;
uint256 maxIndex = length - 1; uint256 minIndex = startingMinIndex; uint256 staleIndex = 0;
34,806
5
// SignedSafeMath Signed math operations with safety checks that revert on error. /
library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } }
library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } }
4,732
109
// address existingTokenOwner = existingToken.owner();
uint existingTokenSupply = existingToken.totalSupply(); uint8 expDecimals = existingToken.decimals();
uint existingTokenSupply = existingToken.totalSupply(); uint8 expDecimals = existingToken.decimals();
21,899
232
// Divides one `Signed` by an `Signed`, reverting on overflow or division by 0. This will "floor" the quotient. a a FixedPoint numerator. b a FixedPoint denominator.return the quotient of `a` divided by `b`. /
function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as an int256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue)); }
function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as an int256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue)); }
61,874
4
// "ERC20Base" is the standard ERC-20 implementation that allows its minter to mint tokens. Both BandToken and/ CommunityToken extend from ERC20Base. In addition to the standard functions, the class provides `transferAndCall`/ function, which performs a transfer and invokes the given function using the provided data. If the destination/ contract uses "ERC20Acceptor" interface, it can verify that the caller properly sends appropriate amount of tokens.
contract ERC20Base is ERC20Interface, ERC20, MinterRole { string public name; string public symbol; uint8 public decimals = 18; constructor(string memory _name, string memory _symbol) public { name = _name; symbol = _symbol; } function transferAndCall( address to, uint256 value, bytes4 sig, bytes memory data ) public returns (bool) { require(to != address(this)); _transfer(msg.sender, to, value); (bool success, ) = to.call( abi.encodePacked(sig, uint256(msg.sender), value, data) ); require(success); return true; } function mint(address to, uint256 value) public onlyMinter returns (bool) { _mint(to, value); return true; } function burn(address from, uint256 value) public onlyMinter returns (bool) { _burn(from, value); return true; } }
contract ERC20Base is ERC20Interface, ERC20, MinterRole { string public name; string public symbol; uint8 public decimals = 18; constructor(string memory _name, string memory _symbol) public { name = _name; symbol = _symbol; } function transferAndCall( address to, uint256 value, bytes4 sig, bytes memory data ) public returns (bool) { require(to != address(this)); _transfer(msg.sender, to, value); (bool success, ) = to.call( abi.encodePacked(sig, uint256(msg.sender), value, data) ); require(success); return true; } function mint(address to, uint256 value) public onlyMinter returns (bool) { _mint(to, value); return true; } function burn(address from, uint256 value) public onlyMinter returns (bool) { _burn(from, value); return true; } }
6,887
165
// Allows only the contract owner to update the URI of a specifictoken. _tokenId The token to update. _newTokenURI The new URI for the specified token. /
function updateTokenURI( uint256 _tokenId, string memory _newTokenURI
function updateTokenURI( uint256 _tokenId, string memory _newTokenURI
75,495
412
// expmods_and_points.points[28] = -(g^32z).
mstore(add(expmodsAndPoints, 0x740), point)
mstore(add(expmodsAndPoints, 0x740), point)
77,624
4
// owner -> nonce mapping used in {permit}.
mapping(address => uint256) public nonces; constructor() { DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256(bytes("1")), block.chainid, address(this)
mapping(address => uint256) public nonces; constructor() { DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256(bytes("1")), block.chainid, address(this)
27,193
7
// expmods[2] = point^(trace_length / 2).
mstore(0x4480, expmod(point, div(/*trace_length*/ mload(0x80), 2), PRIME))
mstore(0x4480, expmod(point, div(/*trace_length*/ mload(0x80), 2), PRIME))
20,582
3
// Commission reward for recruiting people
uint256 internal constant COMMISSION_REWARD = 50 * 10**18;
uint256 internal constant COMMISSION_REWARD = 50 * 10**18;
13,241
102
// slippage tolerance
uint public constant SLIPPAGE_TOLERANCE_X_100 = 100;
uint public constant SLIPPAGE_TOLERANCE_X_100 = 100;
9,106
10
// Abstract contract for the full ERC 20 Token standard /
contract Token { /** This is a slight change to the ERC20 base standard. function totalSupply() view returns (uint supply); is replaced map: uint public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public view returns (uint balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint _value) public returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint _value) public returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint _value) public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public view returns (uint remaining); event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); }
contract Token { /** This is a slight change to the ERC20 base standard. function totalSupply() view returns (uint supply); is replaced map: uint public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public view returns (uint balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint _value) public returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint _value) public returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint _value) public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public view returns (uint remaining); event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); }
31,028
17
// The address corresponding to a private key used to sign placeBet commits.
address public secretSigner;
address public secretSigner;
14,170
113
// loop over array to find if already member,and record a potential openPosition
for (uint16 k = 0; k<setting_maxInvestors; k++) {
for (uint16 k = 0; k<setting_maxInvestors; k++) {
50,275
56
// coinmarketcap.com 14.08.2017
uint constant ETH_PRICE_IN_USD = 300;
uint constant ETH_PRICE_IN_USD = 300;
5,666
3
// Store Candidate Count
uint public candidatesCount ;
uint public candidatesCount ;
9,723
15
// Ends public sale forever, callable by owner /
function endSaleForever() external onlyOwner { publicSaleEnded = true; }
function endSaleForever() external onlyOwner { publicSaleEnded = true; }
36,834
62
// Start perpetual prank from an address that has some ether
function startHoax(address who) internal virtual { vm.deal(who, 1 << 128); vm.startPrank(who); }
function startHoax(address who) internal virtual { vm.deal(who, 1 << 128); vm.startPrank(who); }
21,614
142
// Returns a URI for a given token ID's metadata /
function tokenURI(uint256 _tokenId) public view override returns (string memory) { return string(abi.encodePacked(_baseTokenURI, Strings.toString(_tokenId))); }
function tokenURI(uint256 _tokenId) public view override returns (string memory) { return string(abi.encodePacked(_baseTokenURI, Strings.toString(_tokenId))); }
12,473
46
// Get hash for a revocation. _sigToRevoke The signature to be revoked. _gasPrice The amount to be paid to delegate for sending this tx./
{ return keccak256(revokeSignatureSig, _sigToRevoke, _gasPrice); }
{ return keccak256(revokeSignatureSig, _sigToRevoke, _gasPrice); }
25,104
31
// 允许交易所和项目放方批量转币_funds: 批量转币地址_amounts: 每个地址的转币数量,长度必须跟_funds的长度相同 /
function batchTransfer(address[] _funds, uint256[] _amounts) public whenNotPaused whenPrivateFundEnabled returns (bool) { require(allowedBatchTransfers[msg.sender]); uint256 fundslen = _funds.length; uint256 amountslen = _amounts.length; require(fundslen == amountslen && fundslen > 0 && fundslen < 300); uint256 totalAmount = 0; for (uint i = 0; i < amountslen; ++i){ totalAmount = totalAmount.add(_amounts[i]); } require(balances[msg.sender] >= totalAmount); for (uint j = 0; j < amountslen; ++j) { balances[_funds[j]] = balances[_funds[j]].add(_amounts[j]); emit Transfer(msg.sender, _funds[j], _amounts[j]); } balances[msg.sender] = balances[msg.sender].sub(totalAmount); return true; }
function batchTransfer(address[] _funds, uint256[] _amounts) public whenNotPaused whenPrivateFundEnabled returns (bool) { require(allowedBatchTransfers[msg.sender]); uint256 fundslen = _funds.length; uint256 amountslen = _amounts.length; require(fundslen == amountslen && fundslen > 0 && fundslen < 300); uint256 totalAmount = 0; for (uint i = 0; i < amountslen; ++i){ totalAmount = totalAmount.add(_amounts[i]); } require(balances[msg.sender] >= totalAmount); for (uint j = 0; j < amountslen; ++j) { balances[_funds[j]] = balances[_funds[j]].add(_amounts[j]); emit Transfer(msg.sender, _funds[j], _amounts[j]); } balances[msg.sender] = balances[msg.sender].sub(totalAmount); return true; }
62,484
261
// 6. Check that the new amount does not put them under the minimum c ratio.
require(collateralRatio(loan) > minCratio, "Cratio too low");
require(collateralRatio(loan) > minCratio, "Cratio too low");
55,064
455
// Estimates the remaining blocks until the prize given a number of seconds per block/secondsPerBlockMantissa The number of seconds per block to use for the calculation.Should be a fixed point 18 number like Ether./ return The estimated number of blocks remaining until the prize can be awarded.
function estimateRemainingBlocksToPrize(uint256 secondsPerBlockMantissa) public view returns (uint256) { return FixedPoint.divideUintByMantissa( _prizePeriodRemainingSeconds(), secondsPerBlockMantissa ); }
function estimateRemainingBlocksToPrize(uint256 secondsPerBlockMantissa) public view returns (uint256) { return FixedPoint.divideUintByMantissa( _prizePeriodRemainingSeconds(), secondsPerBlockMantissa ); }
74,053
161
// Calculate call option price for the current priceIf reversed oracle is set to aggregator, return reversed strike price /
function calcCallStrikePrice( uint256 currentPriceE8, uint64 priceUnit, bool isReversedOracle
function calcCallStrikePrice( uint256 currentPriceE8, uint64 priceUnit, bool isReversedOracle
28,104
5
// require(msg.sender == governance, "UNAUTHORIZED");
require(wantToken != address(0), "INVALID INPUT"); uint256 index = whiteListIndexForWantToken[wantToken]; require( (index > 0 && !isListed) || (index == 0 && isListed), "AlREADY SET" ); if (index > 0 && !isListed) { if (index < wantTokenWhiteList.length) { whiteListIndexForWantToken[
require(wantToken != address(0), "INVALID INPUT"); uint256 index = whiteListIndexForWantToken[wantToken]; require( (index > 0 && !isListed) || (index == 0 && isListed), "AlREADY SET" ); if (index > 0 && !isListed) { if (index < wantTokenWhiteList.length) { whiteListIndexForWantToken[
31,574
18
// set the price of the point in the registry to 0 and clear the associated address. 'asset' already declared in memory so not using the utility function this time
asset = ListedAsset({ addr: address(0), price: 0 });
asset = ListedAsset({ addr: address(0), price: 0 });
32,777
25
// Modifier to check whether the `msg.sender` is the admin.If it is, it will run the function. Otherwise, fails. /
modifier ifAdmin() { require(msg.sender == _admin(), "sender not admin"); _; }
modifier ifAdmin() { require(msg.sender == _admin(), "sender not admin"); _; }
36,987
84
// Calc base ticks depending on base threshold and tickspacing
function baseTicks(int24 currentTick, int24 baseThreshold, int24 tickSpacing) internal pure returns(int24 tickLower, int24 tickUpper) { int24 tickFloor = floor(currentTick, tickSpacing); tickLower = tickFloor - baseThreshold; tickUpper = tickFloor + baseThreshold; }
function baseTicks(int24 currentTick, int24 baseThreshold, int24 tickSpacing) internal pure returns(int24 tickLower, int24 tickUpper) { int24 tickFloor = floor(currentTick, tickSpacing); tickLower = tickFloor - baseThreshold; tickUpper = tickFloor + baseThreshold; }
1,184
10
// Calculates exchange fee charge based off an estimate of the predictedorder flow on this leg of the swap.Note that the process of collecting the exchange fee itself alters thestructure of the curve, because those fees assimilate as liquidity into the curve new liquidity. As such the flow used to pro-rate fees is only an estimateof the actual flow that winds up executed. This means that fees are not exact relative to realized flows. But because fees only have a small impact on the curve, they'll tend to be very close. Getting fee exactly correct doesn't matter, and either over or
returns (int128, int128, uint128) { (uint128 liqFees, uint128 exchFees) = calcFeeOverSwap (curve, swapQty, pool.feeRate_, pool.protocolTake_, inBaseQty, limitPrice); /* We can guarantee that the price shift associated with the liquidity * assimilation is safe. The limit price boundary is by definition within the * tick price boundary of the locally stable AMM curve (see determineLimit() * function). The liquidity assimilation flow is mathematically capped within * the limit price flow, because liquidity fees are a small fraction of swap * flows. */ curve.assimilateLiq(liqFees, inBaseQty); return assignFees(liqFees, exchFees, inBaseQty); }
returns (int128, int128, uint128) { (uint128 liqFees, uint128 exchFees) = calcFeeOverSwap (curve, swapQty, pool.feeRate_, pool.protocolTake_, inBaseQty, limitPrice); /* We can guarantee that the price shift associated with the liquidity * assimilation is safe. The limit price boundary is by definition within the * tick price boundary of the locally stable AMM curve (see determineLimit() * function). The liquidity assimilation flow is mathematically capped within * the limit price flow, because liquidity fees are a small fraction of swap * flows. */ curve.assimilateLiq(liqFees, inBaseQty); return assignFees(liqFees, exchFees, inBaseQty); }
13,641
611
// Accrue XVS to the market by updating the supply index vToken The market whose supply index to update /
function updateVenusSupplyIndex(address vToken) internal { VenusMarketState storage supplyState = venusSupplyState[vToken]; uint supplySpeed = venusSpeeds[vToken]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(supplyState.block)); if (deltaBlocks > 0 && supplySpeed > 0) { uint supplyTokens = VToken(vToken).totalSupply(); uint venusAccrued = mul_(deltaBlocks, supplySpeed); Double memory ratio = supplyTokens > 0 ? fraction(venusAccrued, supplyTokens) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: supplyState.index}), ratio); venusSupplyState[vToken] = VenusMarketState({ index: safe224(index.mantissa, "new index overflows"), block: safe32(blockNumber, "block number overflows") }); } else if (deltaBlocks > 0) { supplyState.block = safe32(blockNumber, "block number overflows"); } }
function updateVenusSupplyIndex(address vToken) internal { VenusMarketState storage supplyState = venusSupplyState[vToken]; uint supplySpeed = venusSpeeds[vToken]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(supplyState.block)); if (deltaBlocks > 0 && supplySpeed > 0) { uint supplyTokens = VToken(vToken).totalSupply(); uint venusAccrued = mul_(deltaBlocks, supplySpeed); Double memory ratio = supplyTokens > 0 ? fraction(venusAccrued, supplyTokens) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: supplyState.index}), ratio); venusSupplyState[vToken] = VenusMarketState({ index: safe224(index.mantissa, "new index overflows"), block: safe32(blockNumber, "block number overflows") }); } else if (deltaBlocks > 0) { supplyState.block = safe32(blockNumber, "block number overflows"); } }
14,736
28
// 60%
if (level == 2) { return 60; }
if (level == 2) { return 60; }
47,872
22
// Check the token roots reported by Witnet match the rest of token's metadata, including the image digest:
{ (_resultOk, _resultBytes) = __requests.tokenRoots.read(); require(_resultOk, "WittyPixelsToken: token roots failed"); WittyPixels.ERC721TokenRoots memory _roots = abi.decode(_resultBytes, (WittyPixels.ERC721TokenRoots)); require( _roots.image == __token.theRoots.image && _roots.stats == keccak256(abi.encode( __token.theStats, _roots.scores )), "WittyPixelsToken: tooken roots mismatch"
{ (_resultOk, _resultBytes) = __requests.tokenRoots.read(); require(_resultOk, "WittyPixelsToken: token roots failed"); WittyPixels.ERC721TokenRoots memory _roots = abi.decode(_resultBytes, (WittyPixels.ERC721TokenRoots)); require( _roots.image == __token.theRoots.image && _roots.stats == keccak256(abi.encode( __token.theStats, _roots.scores )), "WittyPixelsToken: tooken roots mismatch"
14,108
27
// rate helper need for correct calculation of reward rate, for example when there is small tax or small number of total staked amount
uint256 currentTaxRate = tax.mul(RATE_HELPER).div(_totalStaked); // here will be rate multiplied by 10^9 _currentRewardRateFromStart = _currentRewardRateFromStart.add(currentTaxRate);
uint256 currentTaxRate = tax.mul(RATE_HELPER).div(_totalStaked); // here will be rate multiplied by 10^9 _currentRewardRateFromStart = _currentRewardRateFromStart.add(currentTaxRate);
14,653
71
// tax for initial sending
_balances[taxReciever] = _totalSupply.mul(19).mul(2).div(100).div(100);
_balances[taxReciever] = _totalSupply.mul(19).mul(2).div(100).div(100);
3,095
5
// Use to verify the validity of a cToken. The logic of this function is similar to how Compound verify an address is cToken
function verifyCToken(address _underlyingAsset, address _cTokenAddress) internal { require( comptroller.markets(_cTokenAddress).isListed && ICToken(_cTokenAddress).isCToken() && ICToken(_cTokenAddress).underlying() == _underlyingAsset, "INVALID_CTOKEN_DATA" ); }
function verifyCToken(address _underlyingAsset, address _cTokenAddress) internal { require( comptroller.markets(_cTokenAddress).isListed && ICToken(_cTokenAddress).isCToken() && ICToken(_cTokenAddress).underlying() == _underlyingAsset, "INVALID_CTOKEN_DATA" ); }
38,716