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
131
// blacklist v3 pools; can unblacklist() down the road to suit project and community
function blacklistLiquidityPool(address lpAddress) public onlyOwner { require(!blacklistRenounced, "Team has revoked blacklist rights"); require( lpAddress != address(uniswapV2Pair) && lpAddress != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "Cannot blacklist token's v2 router or v2 pool." ); blacklisted[lpAddress] = true; }
function blacklistLiquidityPool(address lpAddress) public onlyOwner { require(!blacklistRenounced, "Team has revoked blacklist rights"); require( lpAddress != address(uniswapV2Pair) && lpAddress != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "Cannot blacklist token's v2 router or v2 pool." ); blacklisted[lpAddress] = true; }
3,846
443
// res += valcoefficients[98].
res := addmod(res, mulmod(val, /*coefficients[98]*/ mload(0x1040), PRIME), PRIME)
res := addmod(res, mulmod(val, /*coefficients[98]*/ mload(0x1040), PRIME), PRIME)
58,997
44
// Constructor of the contract _ceo address the CEO (owner) of the contract /
constructor (address payable _ceo) public { CEO = _ceo; totalTokenSupply = 1001000; tokenPrice = 3067484662576687; // (if eth = 163USD, 0.5 USD for token) }
constructor (address payable _ceo) public { CEO = _ceo; totalTokenSupply = 1001000; tokenPrice = 3067484662576687; // (if eth = 163USD, 0.5 USD for token) }
25,087
78
// Failsafe transfer tokens for the team to given account
function withdrawTokens()onlyOwner public returns(bool) { require(this.transfer(owner, balances[this])); uint256 bonusTokens = balances[address(bonusScheme)]; balances[address(bonusScheme)] = 0; if (bonusTokens > 0) { // If there are no tokens left in bonus scheme, we do not need transaction. balances[owner] = balances[owner].add(bonusTokens); emit Transfer(address(bonusScheme), owner, bonusTokens); } return true; }
function withdrawTokens()onlyOwner public returns(bool) { require(this.transfer(owner, balances[this])); uint256 bonusTokens = balances[address(bonusScheme)]; balances[address(bonusScheme)] = 0; if (bonusTokens > 0) { // If there are no tokens left in bonus scheme, we do not need transaction. balances[owner] = balances[owner].add(bonusTokens); emit Transfer(address(bonusScheme), owner, bonusTokens); } return true; }
82,552
11
// Emitted when the implementation of the proxy registered with id is updated id The identifier of the contract proxyAddress The address of the proxy contract oldImplementationAddress The address of the old implementation contract newImplementationAddress The address of the new implementation contract /
event AddressSetAsProxy(
event AddressSetAsProxy(
25,738
17
// Pre calculation
uint[3][8] memory PREC; // P, 3P, 5P, 7P, 9P, 11P, 13P, 15P PREC[0] = [P[0], P[1], 1]; uint[3] memory X = _double(PREC[0]); PREC[1] = _addMixed(X, P); PREC[2] = _add(X, PREC[1]); PREC[3] = _add(X, PREC[2]); PREC[4] = _add(X, PREC[3]); PREC[5] = _add(X, PREC[4]); PREC[6] = _add(X, PREC[5]); PREC[7] = _add(X, PREC[6]);
uint[3][8] memory PREC; // P, 3P, 5P, 7P, 9P, 11P, 13P, 15P PREC[0] = [P[0], P[1], 1]; uint[3] memory X = _double(PREC[0]); PREC[1] = _addMixed(X, P); PREC[2] = _add(X, PREC[1]); PREC[3] = _add(X, PREC[2]); PREC[4] = _add(X, PREC[3]); PREC[5] = _add(X, PREC[4]); PREC[6] = _add(X, PREC[5]); PREC[7] = _add(X, PREC[6]);
25,955
21
// Scale factor equivalent to 1 ether in Solidity to handle the fractional values
let scale := 0x0de0b6b3a7640000 // 10^18 in hexadecimal
let scale := 0x0de0b6b3a7640000 // 10^18 in hexadecimal
8,826
8
// emit
emit onOpenNewBet(bID,bIDBet_[bID].owner,_check,_unit,_now);
emit onOpenNewBet(bID,bIDBet_[bID].owner,_check,_unit,_now);
3,704
23
// Allows to execute a Safe transaction confirmed by required number of owners and then pays the account that submitted the transaction./Note: The fees are always transferred, even if the user transaction fails./to Destination address of Safe transaction./value Ether value of Safe transaction./data Data payload of Safe transaction./operation Operation type of Safe transaction./safeTxGas Gas that should be used for the Safe transaction./baseGas Gas costs that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund)/gasPrice Gas price that should be used for the payment calculation./gasToken Token address (or 0 if ETH) that is used for the
/// @param signatures Packed signature data ({bytes32 r}{bytes32 s}{uint8 v}) /// @param nonce unique random nonce function execTransaction( address to, uint256 value, bytes calldata data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address payable refundReceiver, bytes memory signatures, bytes32 nonce ) public payable virtual returns (bool success) { bytes32 txHash; // Use scope here to limit variable lifetime and prevent `stack too deep` errors { require(!usedNonces[nonce], "Nonce already used"); bytes memory txHashData = encodeTransactionData( // Transaction info to, value, data, operation, safeTxGas, // Payment info baseGas, gasPrice, gasToken, refundReceiver, // Signature info nonce ); // mark nonce as used and execute transaction. usedNonces[nonce] = true; txHash = keccak256(txHashData); checkSignatures(txHash, txHashData, signatures); } // Ripped out transaction guard because the extra variable on the stack was causing the stack too deep error // We require some gas to emit the events (at least 2500) after the execution and some to perform code until the execution (500) // We also include the 1/64 in the check that is not send along with a call to counteract potential shortings because of EIP-150 require(gasleft() >= ((safeTxGas * 64) / 63).max(safeTxGas + 2500) + 500, "GS010"); // Use scope here to limit variable lifetime and prevent `stack too deep` errors { uint256 gasUsed = gasleft(); // If the gasPrice is 0 we assume that nearly all available gas can be used (it is always more than safeTxGas) // We only substract 2500 (compared to the 3000 before) to ensure that the amount passed is still higher than safeTxGas success = execute(to, value, data, operation, gasPrice == 0 ? (gasleft() - 2500) : safeTxGas); gasUsed = gasUsed.sub(gasleft()); // If no safeTxGas and no gasPrice was set (e.g. both are 0), then the internal tx is required to be successful // This makes it possible to use `estimateGas` without issues, as it searches for the minimum gas where the tx doesn't revert require(success || safeTxGas != 0 || gasPrice != 0, "GS013"); // We transfer the calculated tx costs to the tx.origin to avoid sending it to intermediate contracts that have made calls uint256 payment = 0; if (gasPrice > 0) { payment = handlePayment(gasUsed, baseGas, gasPrice, gasToken, refundReceiver); } if (success) emit ExecutionSuccess(txHash, payment); else emit ExecutionFailure(txHash, payment); } }
/// @param signatures Packed signature data ({bytes32 r}{bytes32 s}{uint8 v}) /// @param nonce unique random nonce function execTransaction( address to, uint256 value, bytes calldata data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address payable refundReceiver, bytes memory signatures, bytes32 nonce ) public payable virtual returns (bool success) { bytes32 txHash; // Use scope here to limit variable lifetime and prevent `stack too deep` errors { require(!usedNonces[nonce], "Nonce already used"); bytes memory txHashData = encodeTransactionData( // Transaction info to, value, data, operation, safeTxGas, // Payment info baseGas, gasPrice, gasToken, refundReceiver, // Signature info nonce ); // mark nonce as used and execute transaction. usedNonces[nonce] = true; txHash = keccak256(txHashData); checkSignatures(txHash, txHashData, signatures); } // Ripped out transaction guard because the extra variable on the stack was causing the stack too deep error // We require some gas to emit the events (at least 2500) after the execution and some to perform code until the execution (500) // We also include the 1/64 in the check that is not send along with a call to counteract potential shortings because of EIP-150 require(gasleft() >= ((safeTxGas * 64) / 63).max(safeTxGas + 2500) + 500, "GS010"); // Use scope here to limit variable lifetime and prevent `stack too deep` errors { uint256 gasUsed = gasleft(); // If the gasPrice is 0 we assume that nearly all available gas can be used (it is always more than safeTxGas) // We only substract 2500 (compared to the 3000 before) to ensure that the amount passed is still higher than safeTxGas success = execute(to, value, data, operation, gasPrice == 0 ? (gasleft() - 2500) : safeTxGas); gasUsed = gasUsed.sub(gasleft()); // If no safeTxGas and no gasPrice was set (e.g. both are 0), then the internal tx is required to be successful // This makes it possible to use `estimateGas` without issues, as it searches for the minimum gas where the tx doesn't revert require(success || safeTxGas != 0 || gasPrice != 0, "GS013"); // We transfer the calculated tx costs to the tx.origin to avoid sending it to intermediate contracts that have made calls uint256 payment = 0; if (gasPrice > 0) { payment = handlePayment(gasUsed, baseGas, gasPrice, gasToken, refundReceiver); } if (success) emit ExecutionSuccess(txHash, payment); else emit ExecutionFailure(txHash, payment); } }
3,245
56
// send the fee to the contract
if (feeswap > 0) { uint256 feeAmount = (amount * feeswap) / 100; super._transfer(sender, address(this), feeAmount); }
if (feeswap > 0) { uint256 feeAmount = (amount * feeswap) / 100; super._transfer(sender, address(this), feeAmount); }
3,164
69
// Reflect
uint256 private constant totalReflectTax = 10;
uint256 private constant totalReflectTax = 10;
12,533
79
// set NftItem
_nftItems[nftContract][tokenId] = NftItem(nftContract, tokenId, msg.sender ,cost, true);
_nftItems[nftContract][tokenId] = NftItem(nftContract, tokenId, msg.sender ,cost, true);
12,907
76
// Retrieve the dividend balance of any single address. /
function dividendsOf(address _customerAddress) view public returns(uint256)
function dividendsOf(address _customerAddress) view public returns(uint256)
4,287
8
// Overriding this function changes the behavior of the {onlyRole} modifier. Format of the revert message is described in {_checkRole}. _Available since v4.6._ /
function _checkRole(bytes32 role) internal view virtual { __checkRole(role, _msgSender()); }
function _checkRole(bytes32 role) internal view virtual { __checkRole(role, _msgSender()); }
2,795
6
// Update age
function updateAge(uint petId, uint8 newAge) public onlyPetOwner(petId)returns (uint8){ petInfo[petId].age = newAge; return petInfo[petId].age; }
function updateAge(uint petId, uint8 newAge) public onlyPetOwner(petId)returns (uint8){ petInfo[petId].age = newAge; return petInfo[petId].age; }
2,560
92
// Make sure each ratio is co-prime to prevent overflow
for (uint256 i = 0; i < _ratios.length; i+= 2) { uint256 divA = SafeMath.div(_ratios[i], _ratios[i+1]); // Non-zero checked by SafteMath.div uint256 divB = SafeMath.div(_ratios[i+1], _ratios[i]); // Non-zero checked by SafteMath.div if (_ratios[i] == 1) { require(divB == _ratios[i+1]); } else if (_ratios[i+1] == 1) {
for (uint256 i = 0; i < _ratios.length; i+= 2) { uint256 divA = SafeMath.div(_ratios[i], _ratios[i+1]); // Non-zero checked by SafteMath.div uint256 divB = SafeMath.div(_ratios[i+1], _ratios[i]); // Non-zero checked by SafteMath.div if (_ratios[i] == 1) { require(divB == _ratios[i+1]); } else if (_ratios[i+1] == 1) {
59,667
18
// The sensitive operator can update the tenguSwapRouter and the locker address It will be transferred to a second timelock contract w/ a much longer duration/
address private _sensitiveOperator;
address private _sensitiveOperator;
13,012
15
// This is how you buy bonds on the primary market /
{ /* We don't issue bonds cheaper than MinNominalBondPrice*/ require(msg.value >= MinNominalBondPrice); /* We don't issue bonds out of allowed maturity range */ require( maturityTimeInDays >= MinMaturityTimeInDays && maturityTimeInDays <= MaxMaturityTimeInDays ); /* You can have a bonus on your first deal if specify an agent */ bool hasRefBonus = false; /* On your first deal ... */ if (Users[msg.sender].agent == 0 && Users[msg.sender].totalBonds == 0) { /* ... you may specify an agent and get a bonus for this ... */ if (agent != 0) { /* ... the agent should have some bonds behind him */ if (Users[agent].totalBonds > 0) { Users[msg.sender].agent = agent; hasRefBonus = true; } else { agent = 0; } } } /* On all your next deals you will have the same agent as on the first one */ else { agent = Users[msg.sender].agent; } /* Issuing a new bond */ Bond memory newBond; newBond.id = NextBondID; newBond.owner = msg.sender; newBond.issueTime = uint32(block.timestamp); newBond.canBeRedeemedPrematurely = canBeRedeemedPrematurely; /* You cant redeem your bond for profit untill this date */ newBond.maturityTime = newBond.issueTime + maturityTimeInDays*24*60*60; /* Your time to redeem is limited */ newBond.maxRedeemTime = newBond.maturityTime + (hasExtraRedeemRange?ExtraRedeemRangeInDays:RedeemRangeInDays)*24*60*60; newBond.nominalPrice = msg.value; newBond.maturityPrice = MaturityPrice( newBond.nominalPrice, maturityTimeInDays, hasExtraRedeemRange, canBeRedeemedPrematurely, hasRefBonus ); Bonds[newBond.id] = newBond; NextBondID += 1; /* Linking the bond to the owner so later he can easily find it */ var user = Users[newBond.owner]; user.bonds[user.totalBonds] = newBond.id; user.totalBonds += 1; /* Notify all users about the issuing event */ Issued(newBond.id, newBond.owner); /* Founder's fee */ uint moneyToFounder = div( mul(newBond.nominalPrice, FounderFeeInPercent), 100 ); /* Agent bonus */ uint moneyToAgent = div( mul(newBond.nominalPrice, AgentBonusInPercent), 100 ); if (agent != 0 && moneyToAgent > 0) { /* Agent can potentially block user's trading attempts, so we dont use just .transfer*/ Balances[agent] = add(Balances[agent], moneyToAgent); } /* Founder always gets his fee */ require(moneyToFounder > 0); Founder.transfer(moneyToFounder); }
{ /* We don't issue bonds cheaper than MinNominalBondPrice*/ require(msg.value >= MinNominalBondPrice); /* We don't issue bonds out of allowed maturity range */ require( maturityTimeInDays >= MinMaturityTimeInDays && maturityTimeInDays <= MaxMaturityTimeInDays ); /* You can have a bonus on your first deal if specify an agent */ bool hasRefBonus = false; /* On your first deal ... */ if (Users[msg.sender].agent == 0 && Users[msg.sender].totalBonds == 0) { /* ... you may specify an agent and get a bonus for this ... */ if (agent != 0) { /* ... the agent should have some bonds behind him */ if (Users[agent].totalBonds > 0) { Users[msg.sender].agent = agent; hasRefBonus = true; } else { agent = 0; } } } /* On all your next deals you will have the same agent as on the first one */ else { agent = Users[msg.sender].agent; } /* Issuing a new bond */ Bond memory newBond; newBond.id = NextBondID; newBond.owner = msg.sender; newBond.issueTime = uint32(block.timestamp); newBond.canBeRedeemedPrematurely = canBeRedeemedPrematurely; /* You cant redeem your bond for profit untill this date */ newBond.maturityTime = newBond.issueTime + maturityTimeInDays*24*60*60; /* Your time to redeem is limited */ newBond.maxRedeemTime = newBond.maturityTime + (hasExtraRedeemRange?ExtraRedeemRangeInDays:RedeemRangeInDays)*24*60*60; newBond.nominalPrice = msg.value; newBond.maturityPrice = MaturityPrice( newBond.nominalPrice, maturityTimeInDays, hasExtraRedeemRange, canBeRedeemedPrematurely, hasRefBonus ); Bonds[newBond.id] = newBond; NextBondID += 1; /* Linking the bond to the owner so later he can easily find it */ var user = Users[newBond.owner]; user.bonds[user.totalBonds] = newBond.id; user.totalBonds += 1; /* Notify all users about the issuing event */ Issued(newBond.id, newBond.owner); /* Founder's fee */ uint moneyToFounder = div( mul(newBond.nominalPrice, FounderFeeInPercent), 100 ); /* Agent bonus */ uint moneyToAgent = div( mul(newBond.nominalPrice, AgentBonusInPercent), 100 ); if (agent != 0 && moneyToAgent > 0) { /* Agent can potentially block user's trading attempts, so we dont use just .transfer*/ Balances[agent] = add(Balances[agent], moneyToAgent); } /* Founder always gets his fee */ require(moneyToFounder > 0); Founder.transfer(moneyToFounder); }
32,007
189
// uses A.J. Walker's Alias algorithm for O(1) rarity table lookupensuring O(1) instead of O(n) reduces mint cost by more than 50%probability & alias tables are generated off-chain beforehand seed portion of the 256 bit seed to remove trait correlation traitType the trait type to select a trait forreturn the ID of the randomly selected trait /
function selectTrait(uint16 seed, uint8 traitType) internal view returns (uint8)
function selectTrait(uint16 seed, uint8 traitType) internal view returns (uint8)
61,373
183
// Retrieves the value for the particular fee type._feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE]._token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens. return fee value associated with the requested fee type./
function getFee(bytes32 _feeType, address _token) public view validFeeType(_feeType) returns (uint256) { return uintStorage[keccak256(abi.encodePacked(_feeType, _token))]; }
function getFee(bytes32 _feeType, address _token) public view validFeeType(_feeType) returns (uint256) { return uintStorage[keccak256(abi.encodePacked(_feeType, _token))]; }
28,720
68
// Return the divisor used to correctly calculate percentage. Percentage stored throughout AO contracts covers 4 decimals, so 1% is 10000, 1.25% is 12500, etc /
function PERCENTAGE_DIVISOR() public pure returns (uint256) { return _PERCENTAGE_DIVISOR; }
function PERCENTAGE_DIVISOR() public pure returns (uint256) { return _PERCENTAGE_DIVISOR; }
52,920
96
// Last time reward was claimed(not bound by current epoch).
uint256 lastClaimedOn;
uint256 lastClaimedOn;
45,335
75
// Provides child token (subdomain) of provided tokenId. tokenId uint256 ID of the token label label of subdomain (for `aaa.bbb.crypto` it will be `aaa`) /
function childIdOf(uint256 tokenId, string calldata label) external pure returns (uint256);
function childIdOf(uint256 tokenId, string calldata label) external pure returns (uint256);
84,820
14
// gets flightInsuranceCapAmount /
function getFlightInsuranceCapAmount() external view requireAuthorizeCaller returns (uint256) { return flightInsuranceCapAmount; }
function getFlightInsuranceCapAmount() external view requireAuthorizeCaller returns (uint256) { return flightInsuranceCapAmount; }
51,846
120
// If the pool is an active or pending validator, the staker can order withdrawal up to their total staking amount minus an already ordered amount minus an amount staked during the current staking epoch
return stakeAmount[_poolStakingAddress][_staker].sub(stakeAmountByCurrentEpoch(_poolStakingAddress, _staker));
return stakeAmount[_poolStakingAddress][_staker].sub(stakeAmountByCurrentEpoch(_poolStakingAddress, _staker));
25,640
299
// Number of nTokens held by the account
uint80 nTokenBalance;
uint80 nTokenBalance;
6,996
194
// emit Add(_allocPoint, _want, _withUpdate, _strat);
strategyInfo = StrategyInfo({ want: _want, strat: _strat });
strategyInfo = StrategyInfo({ want: _want, strat: _strat });
2,072
0
// account => tokenId => claimed
mapping(address => mapping(uint256 => bool)) public claimed; constructor(string memory uri, bytes32[5] memory merkleRoots) ERC1155(uri) { RUBBLE_ROOT = merkleRoots[0]; FEATHER_ROOT = merkleRoots[1]; EYE_ROOT = merkleRoots[2]; CLAW_ROOT = merkleRoots[3]; CROWN_ROOT = merkleRoots[4]; }
mapping(address => mapping(uint256 => bool)) public claimed; constructor(string memory uri, bytes32[5] memory merkleRoots) ERC1155(uri) { RUBBLE_ROOT = merkleRoots[0]; FEATHER_ROOT = merkleRoots[1]; EYE_ROOT = merkleRoots[2]; CLAW_ROOT = merkleRoots[3]; CROWN_ROOT = merkleRoots[4]; }
9,086
146
// Polygon root contracts watched by Heimdall nodes
IRootChainManager public rootChainManagerContract; constructor( address yoloEthereumTokenAddress_, address checkpointManager_, address fxRoot_, address fxChildTunnel_, address rootChainManager_, address predicateContractAddress_
IRootChainManager public rootChainManagerContract; constructor( address yoloEthereumTokenAddress_, address checkpointManager_, address fxRoot_, address fxChildTunnel_, address rootChainManager_, address predicateContractAddress_
69,233
5
// the add function below is from safemath and will take care of uint overflow if a call to add causes an error an error will be thrown and the call to the function will fail
lockTime[msg.sender] = lockTime[msg.sender].add(_secondsToIncrease);
lockTime[msg.sender] = lockTime[msg.sender].add(_secondsToIncrease);
50,713
3
// Total ETH raised
uint256 public totalRaised;
uint256 public totalRaised;
25,411
7
// This event is emitted if system staking limits are removedadmin the address that calls the function/
event DisabledSafeguard(address indexed admin);
event DisabledSafeguard(address indexed admin);
31,590
1,104
// A strategist can have many deployed vaults
mapping(address => bool) vaults; uint256 maxStrategistFee; //4 address WETH;
mapping(address => bool) vaults; uint256 maxStrategistFee; //4 address WETH;
23,936
1
// Used to determine whether the asset balance that is returned from holdings() is representative of all the funds that this adapter maintains/ return True if holdings() is all-inclusive
function hasAccurateHoldings() external view returns (bool);
function hasAccurateHoldings() external view returns (bool);
25,769
350
// Recreate the digest the user signed
bytes32 delegationDigest; if (_signatureType == 2) { delegationDigest = keccak256( abi.encodePacked( DELEGATION_HASH_EIP712, keccak256( abi.encodePacked( address(this), _proposalId, _vote, _amount,
bytes32 delegationDigest; if (_signatureType == 2) { delegationDigest = keccak256( abi.encodePacked( DELEGATION_HASH_EIP712, keccak256( abi.encodePacked( address(this), _proposalId, _vote, _amount,
30,300
137
// Build huffman table for literal/length codes
err = _construct(lencode, lengths, nlen, 0); if ( err != ErrorCode.ERR_NONE && (err == ErrorCode.ERR_NOT_TERMINATED || err == ErrorCode.ERR_OUTPUT_EXHAUSTED || nlen != lencode.counts[0] + lencode.counts[1]) ) {
err = _construct(lencode, lengths, nlen, 0); if ( err != ErrorCode.ERR_NONE && (err == ErrorCode.ERR_NOT_TERMINATED || err == ErrorCode.ERR_OUTPUT_EXHAUSTED || nlen != lencode.counts[0] + lencode.counts[1]) ) {
38,248
17
// return the cost of the book
return(book.cost);
return(book.cost);
36,796
4
// mapping of userAddresses => tokenAddresses that can can be evaluated to determine for a particular user which tokens they are staking.
mapping(address => StakerInfo) public stakers; event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount);
mapping(address => StakerInfo) public stakers; event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount);
20,250
73
// Returns the amount of single plus token is worth for one underlying token, expressed in WAD.The default implmentation assumes that the single plus and underlying tokens are both peg. /
function _conversionRate() internal view virtual returns (uint256) { // 36 since the decimals for plus token is always 18, and conversion rate is in WAD. return uint256(10) ** (36 - ERC20Upgradeable(token).decimals()); }
function _conversionRate() internal view virtual returns (uint256) { // 36 since the decimals for plus token is always 18, and conversion rate is in WAD. return uint256(10) ** (36 - ERC20Upgradeable(token).decimals()); }
7,676
51
// Function to lock xaver tokens to a basket. They start out to be unallocated./_lockedTokenAmount Amount of xaver tokens to lock inside this contract.
function lockTokensToBasket(uint256 _lockedTokenAmount) internal { uint256 balanceBefore = derbyToken.balanceOf(address(this)); derbyToken.safeTransferFrom(msg.sender, address(this), _lockedTokenAmount); uint256 balanceAfter = derbyToken.balanceOf(address(this)); require((balanceAfter - balanceBefore - _lockedTokenAmount) == 0, "Error lock: under/overflow"); }
function lockTokensToBasket(uint256 _lockedTokenAmount) internal { uint256 balanceBefore = derbyToken.balanceOf(address(this)); derbyToken.safeTransferFrom(msg.sender, address(this), _lockedTokenAmount); uint256 balanceAfter = derbyToken.balanceOf(address(this)); require((balanceAfter - balanceBefore - _lockedTokenAmount) == 0, "Error lock: under/overflow"); }
22,330
186
// Look up information about a specific tick in the pool/tick The tick to look up/ return liquidityGross total liquidity amount from positions that uses this tick as a lower or upper tick/ liquidityNet how much liquidity changes when the pool tick crosses above the tick/ feeGrowthOutside the fee growth on the other side of the tick relative to the current tick/ secondsPerLiquidityOutside the seconds per unit of liquidityspent on the other side of the tick relative to the current tick
function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside, uint128 secondsPerLiquidityOutside );
function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside, uint128 secondsPerLiquidityOutside );
1,606
4
// Revert hash back to false so that other composer can claim it
function burn(uint256 tokenId) public override { super.burn(tokenId); bytes32 hash = songs[tokenId].hash; hashes[hash] = false; }
function burn(uint256 tokenId) public override { super.burn(tokenId); bytes32 hash = songs[tokenId].hash; hashes[hash] = false; }
15,222
58
// how much to withdraw (entire balance obviously)
uint value = this.balance;
uint value = this.balance;
11,085
0
// Converts a `uint256` to a `string`.via OraclizeAPI - MIT licence /
function fromUint(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + (temp % 10))); temp /= 10; } return string(buffer); }
function fromUint(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + (temp % 10))); temp /= 10; } return string(buffer); }
522
2
// Public Sale Attributes
uint256 public constant MAX_MINT_PER_ADDRESS_IN_PUBLIC_SALE = 10; uint256 public publicSalePrice = 0.08 ether; uint256 public constant MAX_PUBLIC_SALE_SUPPLY = 9700; address private withdrawalWalletAddress = 0x0D5F33686F12A0de805C1837AeD68aF76312352a; address lazyLionsAddress = 0x8943C7bAC1914C9A7ABa750Bf2B6B09Fd21037E0; address smilesssvrsAddress = 0x177EF8787CEb5D4596b6f011df08C86eb84380dC; string private _tokenBaseURI = "ipfs://QmQSrhWELz2yao4SdwKCitKZmPmqqpsbL9mgGgCe5PxpwC";
uint256 public constant MAX_MINT_PER_ADDRESS_IN_PUBLIC_SALE = 10; uint256 public publicSalePrice = 0.08 ether; uint256 public constant MAX_PUBLIC_SALE_SUPPLY = 9700; address private withdrawalWalletAddress = 0x0D5F33686F12A0de805C1837AeD68aF76312352a; address lazyLionsAddress = 0x8943C7bAC1914C9A7ABa750Bf2B6B09Fd21037E0; address smilesssvrsAddress = 0x177EF8787CEb5D4596b6f011df08C86eb84380dC; string private _tokenBaseURI = "ipfs://QmQSrhWELz2yao4SdwKCitKZmPmqqpsbL9mgGgCe5PxpwC";
15,449
26
// ---------------------------------------------------------------------------------------------- flight functions
struct Flight { bool isRegistered; uint8 statusCode; string fltDate; address airline; string flt; }
struct Flight { bool isRegistered; uint8 statusCode; string fltDate; address airline; string flt; }
51,364
93
// get all the necessary variables in a single call
( address yax, address stakingPool, uint256 stakingPoolShareFee, address treasury, uint256 treasuryFee, address insurance, uint256 insurancePoolFee ) = vaultManager.getHarvestFeeInfo();
( address yax, address stakingPool, uint256 stakingPoolShareFee, address treasury, uint256 treasuryFee, address insurance, uint256 insurancePoolFee ) = vaultManager.getHarvestFeeInfo();
79,270
110
// allows governance to update openPeriod
function setOpenPeriod(uint256 _newStart, uint256 _newEnd) public onlyOwner { openPeriod[0] = _newStart; openPeriod[1] = _newEnd; }
function setOpenPeriod(uint256 _newStart, uint256 _newEnd) public onlyOwner { openPeriod[0] = _newStart; openPeriod[1] = _newEnd; }
18,243
2
// [Owner] Mint initial
function ggMint(uint256 amount, address ggWallet) public onlyOwner nonReentrant { require(totalSupply() + amount <= supply, "Max supply reached"); _safeMint(ggWallet, amount); emit newMint(ggWallet, totalSupply() - amount, amount); }
function ggMint(uint256 amount, address ggWallet) public onlyOwner nonReentrant { require(totalSupply() + amount <= supply, "Max supply reached"); _safeMint(ggWallet, amount); emit newMint(ggWallet, totalSupply() - amount, amount); }
26,152
23
// get new state hash
bytes memory encodedState = newState.encode(); emit DepositQueued(pubkeyID, tokenID, l2Amount); insertAndMerge(keccak256(encodedState));
bytes memory encodedState = newState.encode(); emit DepositQueued(pubkeyID, tokenID, l2Amount); insertAndMerge(keccak256(encodedState));
49,591
95
// Withdraws a specified amount of staked tokens from the reward pool and unwraps them to the original tokens. amount The amount of tokens to withdraw and unwrap. claim A boolean indicating whether to claim rewards before withdrawing. to The address to receive the unwrapped tokens.If set to 0x0, the tokens will remain in the contract.Only the contract owner or operator can call this function. /
function withdrawAndUnwrap( uint256 amount, bool claim, address to
function withdrawAndUnwrap( uint256 amount, bool claim, address to
42,573
23
// Withdraws liquidity from the pool. This requires tokens to have been locked until the round ending at the burnableAt timestamp has been ended.This will burn the liquidityCertificates and have the quote asset equivalent at the time be reserved for the users.beneficiary The account that will receive the withdrawn funds. certificateId The id of the LiquidityCertificate. /
function withdraw(address beneficiary, uint certificateId) external override returns (uint value) { ILiquidityCertificate.CertificateData memory certificateData = liquidityCertificate.certificateData(certificateId); uint maxExpiryTimestamp = optionMarket.maxExpiryTimestamp(); // We allow people to withdraw if their funds haven't entered the system if (certificateData.enteredAt == maxExpiryTimestamp) { queuedQuoteFunds = queuedQuoteFunds.sub(certificateData.liquidity); liquidityCertificate.burn(msg.sender, certificateId); emit Withdraw(beneficiary, certificateId, certificateData.liquidity, totalQuoteAmountReserved); _require(quoteAsset.transfer(beneficiary, certificateData.liquidity), Error.QuoteTransferFailed); return certificateData.liquidity; } uint enterValue = certificateData.enteredAt == 0 ? INITIAL_RATE : expiryToTokenValue[certificateData.enteredAt]; // expiryToTokenValue will only be set if the previous round has ended, and the next has not started uint currentRoundValue = expiryToTokenValue[maxExpiryTimestamp]; // If they haven't signaled withdrawal, and it is between rounds if (certificateData.burnableAt == 0 && currentRoundValue != 0) { uint tokenAmt = certificateData.liquidity.divideDecimal(enterValue); totalTokenSupply = totalTokenSupply.sub(tokenAmt); value = tokenAmt.multiplyDecimal(currentRoundValue); liquidityCertificate.burn(msg.sender, certificateId); emit Withdraw(beneficiary, certificateId, value, totalQuoteAmountReserved); _require(quoteAsset.transfer(beneficiary, value), Error.QuoteTransferFailed); return value; } uint exitValue = expiryToTokenValue[certificateData.burnableAt]; _require(certificateData.burnableAt != 0 && exitValue != 0, Error.WithdrawNotBurnable); value = certificateData.liquidity.multiplyDecimal(exitValue).divideDecimal(enterValue); // We can allow a 0 expiry for options created before any boards exist liquidityCertificate.burn(msg.sender, certificateId); totalQuoteAmountReserved = totalQuoteAmountReserved.sub(value); emit Withdraw(beneficiary, certificateId, value, totalQuoteAmountReserved); _require(quoteAsset.transfer(beneficiary, value), Error.QuoteTransferFailed); return value; }
function withdraw(address beneficiary, uint certificateId) external override returns (uint value) { ILiquidityCertificate.CertificateData memory certificateData = liquidityCertificate.certificateData(certificateId); uint maxExpiryTimestamp = optionMarket.maxExpiryTimestamp(); // We allow people to withdraw if their funds haven't entered the system if (certificateData.enteredAt == maxExpiryTimestamp) { queuedQuoteFunds = queuedQuoteFunds.sub(certificateData.liquidity); liquidityCertificate.burn(msg.sender, certificateId); emit Withdraw(beneficiary, certificateId, certificateData.liquidity, totalQuoteAmountReserved); _require(quoteAsset.transfer(beneficiary, certificateData.liquidity), Error.QuoteTransferFailed); return certificateData.liquidity; } uint enterValue = certificateData.enteredAt == 0 ? INITIAL_RATE : expiryToTokenValue[certificateData.enteredAt]; // expiryToTokenValue will only be set if the previous round has ended, and the next has not started uint currentRoundValue = expiryToTokenValue[maxExpiryTimestamp]; // If they haven't signaled withdrawal, and it is between rounds if (certificateData.burnableAt == 0 && currentRoundValue != 0) { uint tokenAmt = certificateData.liquidity.divideDecimal(enterValue); totalTokenSupply = totalTokenSupply.sub(tokenAmt); value = tokenAmt.multiplyDecimal(currentRoundValue); liquidityCertificate.burn(msg.sender, certificateId); emit Withdraw(beneficiary, certificateId, value, totalQuoteAmountReserved); _require(quoteAsset.transfer(beneficiary, value), Error.QuoteTransferFailed); return value; } uint exitValue = expiryToTokenValue[certificateData.burnableAt]; _require(certificateData.burnableAt != 0 && exitValue != 0, Error.WithdrawNotBurnable); value = certificateData.liquidity.multiplyDecimal(exitValue).divideDecimal(enterValue); // We can allow a 0 expiry for options created before any boards exist liquidityCertificate.burn(msg.sender, certificateId); totalQuoteAmountReserved = totalQuoteAmountReserved.sub(value); emit Withdraw(beneficiary, certificateId, value, totalQuoteAmountReserved); _require(quoteAsset.transfer(beneficiary, value), Error.QuoteTransferFailed); return value; }
42,293
19
// This function implements flashloan-resistant logic to determine USD price of Uniswap LP tokens Pair must be registered at Chainlink asset The LP token address amount Amount of assetreturn Q112 encoded price of asset in USD /
{ IUniswapV2Pair pair = IUniswapV2Pair(asset); address underlyingAsset; if (pair.token0() == oracleMainAsset.WETH()) { underlyingAsset = pair.token1(); } else if (pair.token1() == oracleMainAsset.WETH()) { underlyingAsset = pair.token0(); } else { revert("Unit Protocol: NOT_REGISTERED_PAIR"); } // average price of 1 token in ETH uint eAvg = oracleMainAsset.assetToEth(underlyingAsset, 1); (uint112 _reserve0, uint112 _reserve1,) = pair.getReserves(); uint aPool; // current asset pool uint ePool; // current WETH pool if (pair.token0() == underlyingAsset) { aPool = uint(_reserve0); ePool = uint(_reserve1); } else { aPool = uint(_reserve1); ePool = uint(_reserve0); } uint eCurr = ePool.mul(Q112).div(aPool); // current price of 1 token in WETH uint ePoolCalc; // calculated WETH pool if (eCurr < eAvg) { // flashloan buying WETH uint sqrtd = ePool.mul((ePool).mul(9).add( aPool.mul(3988000).mul(eAvg).div(Q112) )); uint eChange = sqrt(sqrtd).sub(ePool.mul(1997)).div(2000); ePoolCalc = ePool.add(eChange); } else { // flashloan selling WETH uint a = aPool.mul(eAvg); uint b = a.mul(9).div(Q112); uint c = ePool.mul(3988000); uint sqRoot = sqrt(a.div(Q112).mul(b.add(c))); uint d = a.mul(3).div(Q112); uint eChange = ePool.sub(d.add(sqRoot).div(2000)); ePoolCalc = ePool.sub(eChange); } uint num = ePoolCalc.mul(2).mul(amount); uint priceInEth; if (num > Q112) { priceInEth = num.div(pair.totalSupply()).mul(Q112); } else { priceInEth = num.mul(Q112).div(pair.totalSupply()); } return oracleMainAsset.ethToUsd(priceInEth); }
{ IUniswapV2Pair pair = IUniswapV2Pair(asset); address underlyingAsset; if (pair.token0() == oracleMainAsset.WETH()) { underlyingAsset = pair.token1(); } else if (pair.token1() == oracleMainAsset.WETH()) { underlyingAsset = pair.token0(); } else { revert("Unit Protocol: NOT_REGISTERED_PAIR"); } // average price of 1 token in ETH uint eAvg = oracleMainAsset.assetToEth(underlyingAsset, 1); (uint112 _reserve0, uint112 _reserve1,) = pair.getReserves(); uint aPool; // current asset pool uint ePool; // current WETH pool if (pair.token0() == underlyingAsset) { aPool = uint(_reserve0); ePool = uint(_reserve1); } else { aPool = uint(_reserve1); ePool = uint(_reserve0); } uint eCurr = ePool.mul(Q112).div(aPool); // current price of 1 token in WETH uint ePoolCalc; // calculated WETH pool if (eCurr < eAvg) { // flashloan buying WETH uint sqrtd = ePool.mul((ePool).mul(9).add( aPool.mul(3988000).mul(eAvg).div(Q112) )); uint eChange = sqrt(sqrtd).sub(ePool.mul(1997)).div(2000); ePoolCalc = ePool.add(eChange); } else { // flashloan selling WETH uint a = aPool.mul(eAvg); uint b = a.mul(9).div(Q112); uint c = ePool.mul(3988000); uint sqRoot = sqrt(a.div(Q112).mul(b.add(c))); uint d = a.mul(3).div(Q112); uint eChange = ePool.sub(d.add(sqRoot).div(2000)); ePoolCalc = ePool.sub(eChange); } uint num = ePoolCalc.mul(2).mul(amount); uint priceInEth; if (num > Q112) { priceInEth = num.div(pair.totalSupply()).mul(Q112); } else { priceInEth = num.mul(Q112).div(pair.totalSupply()); } return oracleMainAsset.ethToUsd(priceInEth); }
71,361
14
// Store the claimed bounty in a temporary variable.
uint256 claimed_bounty = bounty;
uint256 claimed_bounty = bounty;
45,717
0
// Limits the number of fishs the contract owner can ever create.
uint256 public constant PROMO_CREATION_LIMIT = 5000; uint256 public constant GEN0_CREATION_LIMIT = 45000;
uint256 public constant PROMO_CREATION_LIMIT = 5000; uint256 public constant GEN0_CREATION_LIMIT = 45000;
43,741
84
// Push new metadata (end index non-inclusive)
metadatas.push( Metadata({ startIndex: nftRevealedCount + 1, endIndex: nftCount + 1, entropy: randomness })
metadatas.push( Metadata({ startIndex: nftRevealedCount + 1, endIndex: nftCount + 1, entropy: randomness })
44,563
109
// Reverts if not in raise time range./
modifier onlyWhileOpen { require(isOpen(), "TimedRaise: not open"); _; }
modifier onlyWhileOpen { require(isOpen(), "TimedRaise: not open"); _; }
41,745
72
// variables added in v2.1
string internal _baseImageURI; string internal _baseExternalURI;
string internal _baseImageURI; string internal _baseExternalURI;
33,786
351
// Multiplier representing the most one can borrow against their collateral in this market.For instance, 0.9 to allow borrowing 90% of collateral value.Must be between 0 and 1, and stored as a mantissa.
uint256 collateralFactorMantissa;
uint256 collateralFactorMantissa;
21,266
2
// Return the amount of token out as liquidation reward for liquidating token in./tokenIn The ERC-20 token that gets liquidated./tokenOut The ERC-1155 token to pay as reward./tokenOutId The id of the token to pay as reward./amountIn The amount of liquidating tokens.
function convertForLiquidation( address tokenIn, address tokenOut, uint tokenOutId, uint amountIn ) external view returns (uint);
function convertForLiquidation( address tokenIn, address tokenOut, uint tokenOutId, uint amountIn ) external view returns (uint);
14,595
138
// ========= CONSTANT VARIABLES ======== // ========== STATE VARIABLES ========== / flags
bool private migrated = false; bool private initialized = false;
bool private migrated = false; bool private initialized = false;
956
34
// Destroys `amount` tokens of token type `id` from `from`
* Emits a {TransferSingle} event. * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn(address from, uint256 id, uint256 amount) internal { if (from == address(0)) { revert ERC1155InvalidSender(address(0)); } (uint256[] memory ids, uint256[] memory amounts) = _asSingletonArrays(id, amount); _update(from, address(0), ids, amounts, ""); }
* Emits a {TransferSingle} event. * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn(address from, uint256 id, uint256 amount) internal { if (from == address(0)) { revert ERC1155InvalidSender(address(0)); } (uint256[] memory ids, uint256[] memory amounts) = _asSingletonArrays(id, amount); _update(from, address(0), ids, amounts, ""); }
30,326
11
// Mapping of an identifier to its entry
mapping(address => Entry) public entries;
mapping(address => Entry) public entries;
327
69
// ========== MUTABLE FUNCTIONS ========== // 预言机更新GOC价格 /
function _updateCashPrice() internal { try IOracle(oracle).update() {} catch {} }
function _updateCashPrice() internal { try IOracle(oracle).update() {} catch {} }
42,948
20
// Deposit LP tokens.
function deposit(uint256 _pid, uint256 _amount) public { address _sender = msg.sender; PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_sender]; updatePool(_pid); if (user.amount > 0) { uint256 _pending = user.amount.mul(pool.accMeePerShare).div(1e18).sub(user.rewardDebt); if (_pending > 0) { safeMeeTransfer(_sender, _pending); emit RewardPaid(_sender, _pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(_sender, address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accMeePerShare).div(1e18); emit Deposit(_sender, _pid, _amount); }
function deposit(uint256 _pid, uint256 _amount) public { address _sender = msg.sender; PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_sender]; updatePool(_pid); if (user.amount > 0) { uint256 _pending = user.amount.mul(pool.accMeePerShare).div(1e18).sub(user.rewardDebt); if (_pending > 0) { safeMeeTransfer(_sender, _pending); emit RewardPaid(_sender, _pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(_sender, address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accMeePerShare).div(1e18); emit Deposit(_sender, _pid, _amount); }
24,953
35
// Finance the next Strategy in the Bank queue with all available underlying/bank The address of the Bank to finance/Only allow this function to be called on approved Banks
function finance(address bank) external override defense onlyBank(bank) { uint256 length = _strategies[bank].length(); require(length > 0, "Manager: No Strategies"); // get the next Strategy, reset if current index out of bounds uint8 i; uint8 queued = _depositQueue[bank]; if (queued < length) { i = queued; } else { i = 0; } address strategy = _strategies[bank].at(i); // finance the strategy, increment index and update delay (+24h) IBank(bank).investAll(strategy); _depositQueue[bank] = i + 1; emit Finance(bank, strategy); }
function finance(address bank) external override defense onlyBank(bank) { uint256 length = _strategies[bank].length(); require(length > 0, "Manager: No Strategies"); // get the next Strategy, reset if current index out of bounds uint8 i; uint8 queued = _depositQueue[bank]; if (queued < length) { i = queued; } else { i = 0; } address strategy = _strategies[bank].at(i); // finance the strategy, increment index and update delay (+24h) IBank(bank).investAll(strategy); _depositQueue[bank] = i + 1; emit Finance(bank, strategy); }
8,724
1
// Secp256k1 Elliptic Curve Example of particularization of Elliptic Curve for secp256k1 curve Witnet Foundation /
contract Secp256k1 { uint256 public constant GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798; uint256 public constant GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8; uint256 public constant AA = 0; uint256 public constant BB = 7; uint256 public constant PP = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F; /// @notice Public Key derivation from private key /// Warning: this is just an example. Do not expose your private key. /// @param privKey The private key /// @return (qx, qy) The Public Key function derivePubKey(uint256 privKey) external pure returns (uint256, uint256) { return EllipticCurve.ecMul( privKey, GX, GY, AA, PP ); } }
contract Secp256k1 { uint256 public constant GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798; uint256 public constant GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8; uint256 public constant AA = 0; uint256 public constant BB = 7; uint256 public constant PP = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F; /// @notice Public Key derivation from private key /// Warning: this is just an example. Do not expose your private key. /// @param privKey The private key /// @return (qx, qy) The Public Key function derivePubKey(uint256 privKey) external pure returns (uint256, uint256) { return EllipticCurve.ecMul( privKey, GX, GY, AA, PP ); } }
51,629
126
// Hashes leaf at read index and next index (circular) to write index
function hash_within_leafs( bytes32[] memory leafs, uint256 write_index, uint256 read_index, uint256 leaf_count
function hash_within_leafs( bytes32[] memory leafs, uint256 write_index, uint256 read_index, uint256 leaf_count
14,222
28
// this is the testnet router
IPangolinRouter _pangolinRouter = IPangolinRouter(0x2D99ABD9008Dc933ff5c0CD271B88309593aB921);
IPangolinRouter _pangolinRouter = IPangolinRouter(0x2D99ABD9008Dc933ff5c0CD271B88309593aB921);
1,502
356
// Calculate denominator for row 3: x - g^3z.
let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x300))) mstore(add(productsPtr, 0x60), partialProduct) mstore(add(valuesPtr, 0x60), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME)
let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x300))) mstore(add(productsPtr, 0x60), partialProduct) mstore(add(valuesPtr, 0x60), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME)
47,219
18
// The number of combinations in Dice game
uint constant internal GAME_OPTIONS_DICE_MODULO = 6;
uint constant internal GAME_OPTIONS_DICE_MODULO = 6;
2,193
1
// 1. User Makes a Vault/
function createVault() public { Vault new_vault_address = new Vault(msg.sender); // pass caller to Vault constructor as eoa; makes them owner of a their Vault deployedVaults.push(new_vault_address); // track these Vaults emit CreateNewVault("New Vault Created"); }
function createVault() public { Vault new_vault_address = new Vault(msg.sender); // pass caller to Vault constructor as eoa; makes them owner of a their Vault deployedVaults.push(new_vault_address); // track these Vaults emit CreateNewVault("New Vault Created"); }
55,749
42
// Use method of calculating claim amount for backwards compatibility with older parties where getDistributionShareOf() returned the fraction of the memberSupply partyTokenId is entitled to, scaled by 1e18.
uint256 shareOfSupply = party.getDistributionShareOf(partyTokenId); return
uint256 shareOfSupply = party.getDistributionShareOf(partyTokenId); return
13,187
14
// This will revert if the LP did not provide enough quote
shortId = exchangeGlobals.short.open(minCollateral, 0, exchangeGlobals.baseKey); sendAllQuoteToLP(); emit ShortInitialized(shortId); emit ShortSetTo(0, 0, 0, minCollateral);
shortId = exchangeGlobals.short.open(minCollateral, 0, exchangeGlobals.baseKey); sendAllQuoteToLP(); emit ShortInitialized(shortId); emit ShortSetTo(0, 0, 0, minCollateral);
35,721
4
// Execute a ruling of a dispute._disputeID ID of the dispute in the Arbitrator contract._ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision". /
function executeRuling(uint _disputeID, uint _ruling) internal;
function executeRuling(uint _disputeID, uint _ruling) internal;
16,419
75
// receive BNB from pancakeswapV2Router when swapping
receive() external payable {} function _reflectRfi(uint256 rRfi, uint256 tRfi) private { _rTotal = _rTotal.sub(rRfi); _tRfiTotal = _tRfiTotal.add(tRfi); }
receive() external payable {} function _reflectRfi(uint256 rRfi, uint256 tRfi) private { _rTotal = _rTotal.sub(rRfi); _tRfiTotal = _tRfiTotal.add(tRfi); }
11,751
75
// override if you want to perform different mint functionality /
function _mint(address to, uint16) internal returns (uint256) { return IERC721CreatorCore(_creator).mintExtension(to); }
function _mint(address to, uint16) internal returns (uint256) { return IERC721CreatorCore(_creator).mintExtension(to); }
11,715
5
// View the encrypted key of Alice
function get_enkey () view public returns(string) { return EncryptedKey_Seller; }
function get_enkey () view public returns(string) { return EncryptedKey_Seller; }
19,939
10
// transfer fee
drace.safeTransferFrom(msg.sender, feeReceiver, price.mul(feePercentX10).div(1000));
drace.safeTransferFrom(msg.sender, feeReceiver, price.mul(feePercentX10).div(1000));
6,487
60
// ============ Structs ============ /
struct ActionInfo { uint256 collateralPrice; // Price of underlying in precise units (10e18) uint256 borrowPrice; // Price of underlying in precise units (10e18) uint256 collateralBalance; // Balance of underlying held in Compound in base units (e.g. USDC 10e6) uint256 borrowBalance; // Balance of underlying borrowed from Compound in base units uint256 collateralValue; // Valuation in USD adjusted for decimals in precise units (10e18) uint256 borrowValue; // Valuation in USD adjusted for decimals in precise units (10e18) uint256 setTotalSupply; // Total supply of SetToken }
struct ActionInfo { uint256 collateralPrice; // Price of underlying in precise units (10e18) uint256 borrowPrice; // Price of underlying in precise units (10e18) uint256 collateralBalance; // Balance of underlying held in Compound in base units (e.g. USDC 10e6) uint256 borrowBalance; // Balance of underlying borrowed from Compound in base units uint256 collateralValue; // Valuation in USD adjusted for decimals in precise units (10e18) uint256 borrowValue; // Valuation in USD adjusted for decimals in precise units (10e18) uint256 setTotalSupply; // Total supply of SetToken }
65,887
120
// master for static calls
BuilderMaster bm = BuilderMaster(masterBuilderContract); _numNiftyMinted[niftyType].increment();
BuilderMaster bm = BuilderMaster(masterBuilderContract); _numNiftyMinted[niftyType].increment();
14,896
14
// Allocate new owner /
function transferOwnership(address newOwner) public { require(msg.sender==owner && newOwner != address(0)); balances[newOwner] = balances[owner]; balances[owner] = 0; owner = newOwner; }
function transferOwnership(address newOwner) public { require(msg.sender==owner && newOwner != address(0)); balances[newOwner] = balances[owner]; balances[owner] = 0; owner = newOwner; }
20,898
88
// Set the rate of wei per edo token in or to calculate edo fee _edoPerWei Rate of edo tokens per wei.return Success of the transaction. /
function setEdoRate( uint256 _edoPerWei ) external returns(bool)
function setEdoRate( uint256 _edoPerWei ) external returns(bool)
14,005
26
// 抢庄 快的抢到
function bidHogs() public returns(bool) { /*require(isPlayerInTurn(msg.sender) && stage == 1);*/ if (flag == 0 && moneyMap[msg.sender] > bankerMoneylimit) { banker = msg.sender; flag = 1; emit ToShuffle(msg.sender, 100); return true; } else { return false; } }
function bidHogs() public returns(bool) { /*require(isPlayerInTurn(msg.sender) && stage == 1);*/ if (flag == 0 && moneyMap[msg.sender] > bankerMoneylimit) { banker = msg.sender; flag = 1; emit ToShuffle(msg.sender, 100); return true; } else { return false; } }
13,628
154
// The block number when OXE mining starts.
uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( OxswapToken _oxt, address _devaddr, address _feeAddress,
uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( OxswapToken _oxt, address _devaddr, address _feeAddress,
11,689
14
// Pause / Unpause/
function ownerPause() external { LibDiamond.enforceIsContractOwner(); pause(); }
function ownerPause() external { LibDiamond.enforceIsContractOwner(); pause(); }
40,308
25
// the current state of the loan
LoanState state;
LoanState state;
10,835
127
// health checks
bool public doHealthCheck; address public healthCheck;
bool public doHealthCheck; address public healthCheck;
43,750
19
// Handle the receipt of multiple ERC1155 token types An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updatedThis function MAY throw to revert and reject the transferReturn of other amount than the magic value WILL result in the transaction being revertedNote: The token contract address is always the message sender _operatorThe address which called the `safeBatchTransferFrom` function _fromThe address which previously owned the token _ids An array containing ids of each token being transferred _amounts An array containing amounts of each token being transferred _dataAdditional
function onERC1155BatchReceived( address _operator,
function onERC1155BatchReceived( address _operator,
1,824
31
// checks the ticket has cliffed or not
function hasCliffed(uint256 _id) canView(_id) public view returns (bool) { Ticket memory ticket = tickets[_id]; if (ticket.cliff == 0) { return true; } return block.timestamp > SafeMath.add(ticket.createdAt, SafeMath.mul(ticket.cliff, 86400)); // in seconds 24 x 60 x 60 }
function hasCliffed(uint256 _id) canView(_id) public view returns (bool) { Ticket memory ticket = tickets[_id]; if (ticket.cliff == 0) { return true; } return block.timestamp > SafeMath.add(ticket.createdAt, SafeMath.mul(ticket.cliff, 86400)); // in seconds 24 x 60 x 60 }
30,512
26
// Public Functions // Returns the Company token balance of the investor companyTokenName string The name of company token investorAddress address The address of the investor /
function getCompanyTokenBalance( string memory companyTokenName, address investorAddress ) public view returns(uint)
function getCompanyTokenBalance( string memory companyTokenName, address investorAddress ) public view returns(uint)
28,251
97
// addresses for multisig and crowdsale
address public ethealMultisigWallet; Crowdsale public crowdsale;
address public ethealMultisigWallet; Crowdsale public crowdsale;
32,287
3
// keccak256("MultiSigTransaction(address destination,uint256 value,bytes data,uint256 nonce,address executor,uint256 gasLimit)")
bytes32 constant TXTYPE_HASH = 0x3ee892349ae4bbe61dce18f95115b5dc02daf49204cc602458cd4c1f540d56d7; bytes32 constant SALT = 0x251543af6a222378665a76fe38dbceae4871a070b7fdaf5c6c30cf758dc33cc0; uint public nonce; // (only) mutable state uint public threshold; // immutable state mapping (address => bool) isOwner; // immutable state address[] public ownersArr; // immutable state bytes32 DOMAIN_SEPARATOR; // hash for EIP712, computed from contract address
bytes32 constant TXTYPE_HASH = 0x3ee892349ae4bbe61dce18f95115b5dc02daf49204cc602458cd4c1f540d56d7; bytes32 constant SALT = 0x251543af6a222378665a76fe38dbceae4871a070b7fdaf5c6c30cf758dc33cc0; uint public nonce; // (only) mutable state uint public threshold; // immutable state mapping (address => bool) isOwner; // immutable state address[] public ownersArr; // immutable state bytes32 DOMAIN_SEPARATOR; // hash for EIP712, computed from contract address
43,331
180
// Mints over this amount automatically allocate funds. 18 decimals.
uint256 public autoAllocateThreshold;
uint256 public autoAllocateThreshold;
25,497
90
// _setTransferNFTK
function _setTransferNFTK(address _from, address _to, uint256 _account) internal { _balances[_from] = _balances[_from].sub(_account, "NFTK: transfer price exceeds balance"); _balances[_to] = _balances[_to].add(_account); emit Transfer(_from, _to, _account); }
function _setTransferNFTK(address _from, address _to, uint256 _account) internal { _balances[_from] = _balances[_from].sub(_account, "NFTK: transfer price exceeds balance"); _balances[_to] = _balances[_to].add(_account); emit Transfer(_from, _to, _account); }
7,456
59
// Progressive Unstaking/
mapping (address => uint) public alreadyProgUnstaked;
mapping (address => uint) public alreadyProgUnstaked;
67,982
8
// Stores and uppdates a random seed that is used to form a new validator set by the/ `ValidatorSetHbbft.newValidatorSet` function.
contract RandomHbbft is UpgradeabilityAdmin, IRandomHbbft { // =============================================== Storage ======================================================== // WARNING: since this contract is upgradeable, do not remove // existing storage variables and do not change their types! /// @dev The current random seed accumulated during RANDAO or another process /// (depending on implementation). uint256 public currentSeed; // ============================================== Modifiers ======================================================= /// @dev Ensures the caller is the SYSTEM_ADDRESS. See https://wiki.parity.io/Validator-Set.html modifier onlySystem() { require(msg.sender == 0xffffFFFfFFffffffffffffffFfFFFfffFFFfFFfE, "Must be executed by System"); _; } // =============================================== Setters ======================================================== /// @dev The cooperative consens mechanism in HBBFT achieves to /// generate a seed, that cannot be predicted by the nodes, /// but can get used within smart contracts without having to wait for /// an additional block. /// this is one of the biggest benefits of HBBFT. /// When the nodes are able to decrypt the transaction, /// they know the seed, that can be used as random base for smart contract interactions. /// setCurrentSeed is always the first transaction within a block, /// and currentSeed is a public available value that can get used by all smart contracts. function setCurrentSeed(uint256 _currentSeed) external onlySystem { currentSeed = _currentSeed; } }
contract RandomHbbft is UpgradeabilityAdmin, IRandomHbbft { // =============================================== Storage ======================================================== // WARNING: since this contract is upgradeable, do not remove // existing storage variables and do not change their types! /// @dev The current random seed accumulated during RANDAO or another process /// (depending on implementation). uint256 public currentSeed; // ============================================== Modifiers ======================================================= /// @dev Ensures the caller is the SYSTEM_ADDRESS. See https://wiki.parity.io/Validator-Set.html modifier onlySystem() { require(msg.sender == 0xffffFFFfFFffffffffffffffFfFFFfffFFFfFFfE, "Must be executed by System"); _; } // =============================================== Setters ======================================================== /// @dev The cooperative consens mechanism in HBBFT achieves to /// generate a seed, that cannot be predicted by the nodes, /// but can get used within smart contracts without having to wait for /// an additional block. /// this is one of the biggest benefits of HBBFT. /// When the nodes are able to decrypt the transaction, /// they know the seed, that can be used as random base for smart contract interactions. /// setCurrentSeed is always the first transaction within a block, /// and currentSeed is a public available value that can get used by all smart contracts. function setCurrentSeed(uint256 _currentSeed) external onlySystem { currentSeed = _currentSeed; } }
37,742
2
// the address with permissions to submit a request for processing
address public callerAddress; SettingsConsts public consts;
address public callerAddress; SettingsConsts public consts;
42,608
8
// Returns the address of the Foundation treasury. /
function getFoundationTreasury() public view returns (address payable) { return treasury; }
function getFoundationTreasury() public view returns (address payable) { return treasury; }
57,217
19
// Mark the attribute as issued on the given address.
_issuedAttributes[msg.sender][blackhatAttributeTypeID] = true;
_issuedAttributes[msg.sender][blackhatAttributeTypeID] = true;
40,514