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 |
|---|---|---|---|---|
207 | // Returns Minter / | function minter() internal view returns (IMinter) {
return IMinter(controller.getContract(keccak256("Minter")));
}
| function minter() internal view returns (IMinter) {
return IMinter(controller.getContract(keccak256("Minter")));
}
| 30,503 |
356 | // getHandAsSvg returns the SVG XML for a hand, which can be rendered as an img src in a UIhandId uint16 ID of the hand from 0 - 1325return string SVG XML of a hand of 2 cards / | function getHandAsSvg(uint16 handId) public validHandId(handId) view returns (string memory) {
(uint8 card1, uint8 card2) = getHandAsCardIds(handId);
string[4] memory parts;
parts[0] = "<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" viewBox=\"0 0 148 62\" width=\"5in\" height=\"2.147in\">";
parts[1] = playingCards.getCardBody(playingCards.getCardNumberAsUint(card1), playingCards.getCardSuitAsUint(card1), 7, 32, 2);
parts[2] = playingCards.getCardBody(playingCards.getCardNumberAsUint(card2), playingCards.getCardSuitAsUint(card2), 82, 107, 76);
parts[3] = "</svg>";
string memory output = string(
abi.encodePacked(parts[0], parts[1], parts[2], parts[3])
);
return output;
}
| function getHandAsSvg(uint16 handId) public validHandId(handId) view returns (string memory) {
(uint8 card1, uint8 card2) = getHandAsCardIds(handId);
string[4] memory parts;
parts[0] = "<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" viewBox=\"0 0 148 62\" width=\"5in\" height=\"2.147in\">";
parts[1] = playingCards.getCardBody(playingCards.getCardNumberAsUint(card1), playingCards.getCardSuitAsUint(card1), 7, 32, 2);
parts[2] = playingCards.getCardBody(playingCards.getCardNumberAsUint(card2), playingCards.getCardSuitAsUint(card2), 82, 107, 76);
parts[3] = "</svg>";
string memory output = string(
abi.encodePacked(parts[0], parts[1], parts[2], parts[3])
);
return output;
}
| 64,279 |
79 | // if (currentTC[transactionId] == 0){ transactions[transactionId] = Transaction({ destination: destination, value: value, data: data, executed: false }); transactionCount += 1; } else{ |
transactionBatch[transactionId][currentTC[transactionId]] = Transaction({
destination: destination,
value: value,
data: data,
executed: false
});
|
transactionBatch[transactionId][currentTC[transactionId]] = Transaction({
destination: destination,
value: value,
data: data,
executed: false
});
| 12,996 |
55 | // for which policy have we called? | uint policyId;
| uint policyId;
| 62,123 |
76 | // R(1 - P)6 /(1 + (T - 1)0.002) | function mediumRiskPremium(Decimal.D256 memory debtRatio, Decimal.D256 memory price, uint256 expirationPeriod) private pure returns (Decimal.D256 memory) {
return multiplier(debtRatio, price).mul(
Decimal.D256({ value: 6e18 }).div(
Decimal.one().add(Decimal.D256({ value: 2e15 }).mul(expirationPeriod - 1))
)
);
}
| function mediumRiskPremium(Decimal.D256 memory debtRatio, Decimal.D256 memory price, uint256 expirationPeriod) private pure returns (Decimal.D256 memory) {
return multiplier(debtRatio, price).mul(
Decimal.D256({ value: 6e18 }).div(
Decimal.one().add(Decimal.D256({ value: 2e15 }).mul(expirationPeriod - 1))
)
);
}
| 35,469 |
0 | // Executes once when a contract is created to initialize state variables_oracle - address of the specific Chainlink node that a contract makes an API call from _jobId - specific job for :_oracle: to run; each job is unique and returns different types of data _fee - node operator price per API call / data request _link - LINK token address on the corresponding network Network: GoerliOracle: 0xCC79157eb46F5624204f47AB42b3906cAA40eaB7Job ID: ca98366cc7314957b8c012c72f05aeebFee: 0.1 LINKLink: 0x326C977E6efc84E512bB9C30f76E30c160eD06FB / | constructor(
address _oracle,
bytes32 _jobId,
uint256 _fee,
address _link
| constructor(
address _oracle,
bytes32 _jobId,
uint256 _fee,
address _link
| 20,643 |
371 | // Update claimed interest fees and net deposits, mint RFT, emit events, and return no error | _interestFeesClaimed = _interestFeesClaimed.add(amountUsd);
_netDeposits = _netDeposits.add(int256(amountUsd));
require(rariFundToken.mint(_interestFeeMasterBeneficiary, rftAmount), "Failed to mint output tokens.");
emit Deposit("USD", _interestFeeMasterBeneficiary, _interestFeeMasterBeneficiary, amountUsd, amountUsd, rftAmount);
emit InterestFeeDeposit(_interestFeeMasterBeneficiary, amountUsd);
| _interestFeesClaimed = _interestFeesClaimed.add(amountUsd);
_netDeposits = _netDeposits.add(int256(amountUsd));
require(rariFundToken.mint(_interestFeeMasterBeneficiary, rftAmount), "Failed to mint output tokens.");
emit Deposit("USD", _interestFeeMasterBeneficiary, _interestFeeMasterBeneficiary, amountUsd, amountUsd, rftAmount);
emit InterestFeeDeposit(_interestFeeMasterBeneficiary, amountUsd);
| 10,975 |
254 | // adjust dai to art | (, uint rate,,,uint dust) = VatLike2(address(cdpManager.vat())).ilks(ilk);
uint daiDebt = art * rate / 1e27;
if(daiDebt < MIN_ORDER) return 0; // do nothing
uint orderSize = daiDebt / 10;
if(orderSize < MIN_ORDER) orderSize = MIN_ORDER;
| (, uint rate,,,uint dust) = VatLike2(address(cdpManager.vat())).ilks(ilk);
uint daiDebt = art * rate / 1e27;
if(daiDebt < MIN_ORDER) return 0; // do nothing
uint orderSize = daiDebt / 10;
if(orderSize < MIN_ORDER) orderSize = MIN_ORDER;
| 37,158 |
3 | // Marketer contractJunghoon Seo - <jh.seo@battleent.com> / | contract Marketer is IMarketer {
mapping (bytes32 => address) marketerInfo;
function generateMarketerKey() external returns(bytes32) {
bytes32 key = bytes32(keccak256(abi.encodePacked(msg.sender)));
return key;
}
function setMarketerKey(bytes32 _key) external {
marketerInfo[_key] = msg.sender;
}
function getMarketerAddress(bytes32 _key) external view returns(address) {
return marketerInfo[_key];
}
}
| contract Marketer is IMarketer {
mapping (bytes32 => address) marketerInfo;
function generateMarketerKey() external returns(bytes32) {
bytes32 key = bytes32(keccak256(abi.encodePacked(msg.sender)));
return key;
}
function setMarketerKey(bytes32 _key) external {
marketerInfo[_key] = msg.sender;
}
function getMarketerAddress(bytes32 _key) external view returns(address) {
return marketerInfo[_key];
}
}
| 21,825 |
74 | // merkle proof verifier, used only during first launch | function merkleVerify(bytes32[] memory proof, bytes32 root, bytes32 leaf) private pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
| function merkleVerify(bytes32[] memory proof, bytes32 root, bytes32 leaf) private pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
| 15,482 |
18 | // AVAX Mainnet | wrapped = 0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7; // WAVAX
factory = 0x9Ad6C38BE94206cA50bb0d90783181662f0Cfa10; // TraderJoe
router = 0x60aE616a2155Ee3d9A68541Ba4544862310933d4; // TraderJoe
| wrapped = 0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7; // WAVAX
factory = 0x9Ad6C38BE94206cA50bb0d90783181662f0Cfa10; // TraderJoe
router = 0x60aE616a2155Ee3d9A68541Ba4544862310933d4; // TraderJoe
| 22,339 |
529 | // storage // initializer //Initizalize Hypervisor/ access control: only proxy constructor/ state machine: can only be called once/ state scope: set initialization variables/ token transfer: none/ownerAddress address The admin address/rewardPoolFactory address The factory to use for deploying the RewardPool/powerSwitchFactory address The factory to use for deploying the PowerSwitch/stakingToken address The address of the staking token for this Hypervisor/rewardToken address The address of the reward token for this Hypervisor/rewardScaling RewardScaling The config for reward scaling floor, ceiling, and time | constructor(
address ownerAddress,
address rewardPoolFactory,
address powerSwitchFactory,
address stakingToken,
address rewardToken,
RewardScaling memory rewardScaling
) {
| constructor(
address ownerAddress,
address rewardPoolFactory,
address powerSwitchFactory,
address stakingToken,
address rewardToken,
RewardScaling memory rewardScaling
) {
| 33,660 |
6 | // 获取账户_spender可以从账户_owner中转出token的数量 | function allowance(address _owner, address _spender) constant returns
(uint256 remaining);
| function allowance(address _owner, address _spender) constant returns
(uint256 remaining);
| 12,840 |
119 | // useful addon to limit one call per block - to be used with multiple different excluding methods - e.g. mint and burn / |
mapping(address => uint) public lastblock;
constructor () internal {
|
mapping(address => uint) public lastblock;
constructor () internal {
| 35,295 |
445 | // Interface for securely interacting with Chainlink aggregators / | interface IOracleAdapter {
struct Value {
uint256 value;
uint256 periodEnd;
}
/// @notice Event fired when asset's pricing source (aggregator) is updated
event AssetSourceUpdated(address indexed asset, address indexed source);
/// @notice Event fired when the TVL aggregator address is updated
event TvlSourceUpdated(address indexed source);
/**
* @notice Set the TVL source (aggregator)
* @param source The new TVL source (aggregator)
*/
function emergencySetTvlSource(address source) external;
/**
* @notice Set an asset's price source (aggregator)
* @param asset The asset to change the source of
* @param source The new source (aggregator)
*/
function emergencySetAssetSource(address asset, address source) external;
/**
* @notice Set multiple assets' pricing sources
* @param assets An array of assets (tokens)
* @param sources An array of price sources (aggregators)
*/
function emergencySetAssetSources(
address[] memory assets,
address[] memory sources
) external;
/**
* @notice Retrieve the asset's price from its pricing source
* @param asset The asset address
* @return The price of the asset
*/
function getAssetPrice(address asset) external view returns (uint256);
/**
* @notice Retrieve the deployed TVL from the TVL aggregator
* @return The TVL
*/
function getTvl() external view returns (uint256);
}
| interface IOracleAdapter {
struct Value {
uint256 value;
uint256 periodEnd;
}
/// @notice Event fired when asset's pricing source (aggregator) is updated
event AssetSourceUpdated(address indexed asset, address indexed source);
/// @notice Event fired when the TVL aggregator address is updated
event TvlSourceUpdated(address indexed source);
/**
* @notice Set the TVL source (aggregator)
* @param source The new TVL source (aggregator)
*/
function emergencySetTvlSource(address source) external;
/**
* @notice Set an asset's price source (aggregator)
* @param asset The asset to change the source of
* @param source The new source (aggregator)
*/
function emergencySetAssetSource(address asset, address source) external;
/**
* @notice Set multiple assets' pricing sources
* @param assets An array of assets (tokens)
* @param sources An array of price sources (aggregators)
*/
function emergencySetAssetSources(
address[] memory assets,
address[] memory sources
) external;
/**
* @notice Retrieve the asset's price from its pricing source
* @param asset The asset address
* @return The price of the asset
*/
function getAssetPrice(address asset) external view returns (uint256);
/**
* @notice Retrieve the deployed TVL from the TVL aggregator
* @return The TVL
*/
function getTvl() external view returns (uint256);
}
| 69,233 |
80 | // CONFIG START |
uint256 private initialSupply;
uint256 private denominator = 100;
uint256 private swapThreshold = 0.0000005 ether; // The contract will only swap to ETH, once the fee tokens reach the specified threshold
uint256 private devTaxBuy;
uint256 private marketingTaxBuy;
uint256 private liquidityTaxBuy;
|
uint256 private initialSupply;
uint256 private denominator = 100;
uint256 private swapThreshold = 0.0000005 ether; // The contract will only swap to ETH, once the fee tokens reach the specified threshold
uint256 private devTaxBuy;
uint256 private marketingTaxBuy;
uint256 private liquidityTaxBuy;
| 44,126 |
5 | // TIME SETTINGS | uint256 moonRaffleLiveSecs = 518400; // 6 DAYS default
uint256 winnerCalcSecs = 345600; // 4 DAYS default
uint256 claimSecs = 15552000; // 180 DAYS default
uint256 latestMoonRaffleCompleteTime = 0;
bool latestMoonRaffleSeeded = true;
| uint256 moonRaffleLiveSecs = 518400; // 6 DAYS default
uint256 winnerCalcSecs = 345600; // 4 DAYS default
uint256 claimSecs = 15552000; // 180 DAYS default
uint256 latestMoonRaffleCompleteTime = 0;
bool latestMoonRaffleSeeded = true;
| 37,793 |
9 | // The specified block needs to be the first block not finalized (this way we always revert to a guaranteed valid block and don't revert multiple times) | require(blockIdx == S.numBlocksFinalized, "PREV_BLOCK_NOT_FINALIZED");
| require(blockIdx == S.numBlocksFinalized, "PREV_BLOCK_NOT_FINALIZED");
| 12,015 |
15 | // This creates a mapping with all data storage | mapping (address => uint256) private _balanceOf;
mapping (address => mapping (address => uint256)) private _allowance;
mapping (address => bool) public frozenAccount;
| mapping (address => uint256) private _balanceOf;
mapping (address => mapping (address => uint256)) private _allowance;
mapping (address => bool) public frozenAccount;
| 36,013 |
87 | // Change the base amount required as a deposit to challenge a submission. _submissionChallengeBaseDeposit The new base amount of wei required to challenge a submission. / | function changeSubmissionChallengeBaseDeposit(uint256 _submissionChallengeBaseDeposit) external onlyGovernor {
submissionChallengeBaseDeposit = _submissionChallengeBaseDeposit;
}
| function changeSubmissionChallengeBaseDeposit(uint256 _submissionChallengeBaseDeposit) external onlyGovernor {
submissionChallengeBaseDeposit = _submissionChallengeBaseDeposit;
}
| 42,253 |
100 | // If the entire position is being removed, delete it instead. | if (
tokensToRemove.isEqual(positionData.tokensOutstanding) &&
positionData.collateral.isEqual(collateralToRemove)
) {
_deleteSponsorPosition(sponsor);
return;
}
| if (
tokensToRemove.isEqual(positionData.tokensOutstanding) &&
positionData.collateral.isEqual(collateralToRemove)
) {
_deleteSponsorPosition(sponsor);
return;
}
| 30,041 |
575 | // Sets the timestamp of a given claim at which the Claim's details has been updated. _claimId Claim Id of claim which has been changed. _dateUpd timestamp at which claim is updated. / | function setClaimdateUpd(uint _claimId, uint _dateUpd) external onlyInternal {
allClaims[_claimId].dateUpd = _dateUpd;
}
| function setClaimdateUpd(uint _claimId, uint _dateUpd) external onlyInternal {
allClaims[_claimId].dateUpd = _dateUpd;
}
| 54,729 |
51 | // A wallet that is required to unlock reserve tokens | address public financeWallet;
| address public financeWallet;
| 48,025 |
60 | // Bad interface | if(!upgradeAgent.isUpgradeAgent()) throw;
| if(!upgradeAgent.isUpgradeAgent()) throw;
| 25,638 |
5 | // Events / | event AssetMinted(uint256 tokenId, address sender);
event SaleActivation(bool isActive);
| event AssetMinted(uint256 tokenId, address sender);
event SaleActivation(bool isActive);
| 50,451 |
2 | // 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-solidity/pull/522 | if (_a == 0)
return 0;
uint c = _a * _b;
return c / _a == _b ? c : UINT_MAX;
| if (_a == 0)
return 0;
uint c = _a * _b;
return c / _a == _b ? c : UINT_MAX;
| 9,815 |
1 | // map of nft and token id to Issuance metadata | mapping (address => mapping (uint => IssuanceData)) lookup;
| mapping (address => mapping (uint => IssuanceData)) lookup;
| 26,157 |
41 | // Minus 2y locked tokens | remainingTokens = remainingTokens.sub(totalSupplyLocked2Y);
| remainingTokens = remainingTokens.sub(totalSupplyLocked2Y);
| 23,716 |
2 | // This is payable because at some point we want to allow the LOCK to capture a fee on 2ndarymarket transactions... / | function transferFrom(
address _from,
address _recipient,
uint _tokenId
)
public
payable
| function transferFrom(
address _from,
address _recipient,
uint _tokenId
)
public
payable
| 24,567 |
2 | // events | event Deposit(uint256, address indexed);
event Withdraw(uint256, address indexed);
event NewReserves(uint256, uint256);
event LongXAUminted(uint256, address indexed);
event ShortXAUminted(uint256, address indexed);
event LongXAUredeemed(uint256, address indexed);
event ShortXAUredeemed(uint256, address indexed);
| event Deposit(uint256, address indexed);
event Withdraw(uint256, address indexed);
event NewReserves(uint256, uint256);
event LongXAUminted(uint256, address indexed);
event ShortXAUminted(uint256, address indexed);
event LongXAUredeemed(uint256, address indexed);
event ShortXAUredeemed(uint256, address indexed);
| 3,383 |
22 | // Allow user to buy someone else's NFT | function buyToken(uint id, uint amount, address nftOwner) payable public {
require(winner == 0, "We already have a winner, the market is closed");
require(
msg.value == transferPrice[id][nftOwner] * amount,
"The value sent must match the price");
require(amount <= balanceOf(nftOwner, id), "You can't buy that much");
uint earnings = transferPrice[id][nftOwner]*999/1000*amount;
payable(nftOwner).transfer(earnings);
payable(_owner).transfer(transferPrice[id][nftOwner]*1/1000*amount);
(bool success, ) = address(this).call(abi.encodeWithSignature(
"safeTransferFrom(address,address,uint256,uint256,bytes)",
nftOwner, msg.sender, id, amount, ""));
require(success, "Function call failed");
if (balanceOf(nftOwner, id) == 0) calculateAllPrices();
emit TokenBought(id, nftOwner, msg.sender, amount, earnings);
}
| function buyToken(uint id, uint amount, address nftOwner) payable public {
require(winner == 0, "We already have a winner, the market is closed");
require(
msg.value == transferPrice[id][nftOwner] * amount,
"The value sent must match the price");
require(amount <= balanceOf(nftOwner, id), "You can't buy that much");
uint earnings = transferPrice[id][nftOwner]*999/1000*amount;
payable(nftOwner).transfer(earnings);
payable(_owner).transfer(transferPrice[id][nftOwner]*1/1000*amount);
(bool success, ) = address(this).call(abi.encodeWithSignature(
"safeTransferFrom(address,address,uint256,uint256,bytes)",
nftOwner, msg.sender, id, amount, ""));
require(success, "Function call failed");
if (balanceOf(nftOwner, id) == 0) calculateAllPrices();
emit TokenBought(id, nftOwner, msg.sender, amount, earnings);
}
| 15,713 |
83 | // Transfer tokens from DeFi protocol to beneficiary amounts Array of amounts to withdraw, in order of supportedTokens()return new balances of each token / | function withdraw(address beneficiary, uint256[] calldata amounts) external;
| function withdraw(address beneficiary, uint256[] calldata amounts) external;
| 21,663 |
167 | // Get total supply minted | function totalSupply() public view returns (uint) {
return _tokenIds.current();
}
| function totalSupply() public view returns (uint) {
return _tokenIds.current();
}
| 58,061 |
7 | // adds a liquidity pool _liquidityPool liquidity pool/ | function addLiquidityPool(address _liquidityPool) external only(BANCOR_CONVERTER_REGISTRY) {
addItem(liquidityPools, _liquidityPool);
}
| function addLiquidityPool(address _liquidityPool) external only(BANCOR_CONVERTER_REGISTRY) {
addItem(liquidityPools, _liquidityPool);
}
| 44,494 |
148 | // Returns the message sender (defaults to `msg.sender`). If you are writing GSN compatible contracts, you need to override this function. / | function _msgSenderERC721A() internal view virtual returns (address) {
| function _msgSenderERC721A() internal view virtual returns (address) {
| 114 |
1 | // assert(b > 0);Solidity automatically throws when dividing by 0 | uint256 c = a / b;
| uint256 c = a / b;
| 6,927 |
4 | // Key: gameListId | struct GameList{
int256 questionId; // 2 items
int256 currencyId; // which currency // currencyQuantity items
uint revealTime; // gameParticipateStartTime
int256 lifeLengthId; // 3 items
string property; // 1 items
bool isActivity; //
bool isClose; //
}
| struct GameList{
int256 questionId; // 2 items
int256 currencyId; // which currency // currencyQuantity items
uint revealTime; // gameParticipateStartTime
int256 lifeLengthId; // 3 items
string property; // 1 items
bool isActivity; //
bool isClose; //
}
| 7,246 |
32 | // Returns the user account data across all the reserves user The address of the userreturn totalCollateralBase The total collateral of the user in the base currency used by the price feedreturn totalDebtBase The total debt of the user in the base currency used by the price feedreturn availableBorrowsBase The borrowing power left of the user in the base currency used by the price feedreturn currentLiquidationThreshold The liquidation threshold of the userreturn ltv The loan to value of The userreturn healthFactor The current health factor of the user / | function getUserAccountData(
| function getUserAccountData(
| 39,135 |
2 | // Returns address of oracle currency (0x0 for ETH)/ | function getCurrencyAddress() external view returns(address) {
return currencyAddress;
}
| function getCurrencyAddress() external view returns(address) {
return currencyAddress;
}
| 35,579 |
52 | // Validate whether same data is present for customer | bytes32 savedDataHash = viewCustomer(customerName, password);
require(
customers[customerName].dataHash != savedDataHash,
"This customer data is up to date"
);
| bytes32 savedDataHash = viewCustomer(customerName, password);
require(
customers[customerName].dataHash != savedDataHash,
"This customer data is up to date"
);
| 19,594 |
1 | // Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators). | mapping(address => bool) private _defaultOperators;
| mapping(address => bool) private _defaultOperators;
| 22,623 |
103 | // Make the swap | uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
ethAmount = address(this).balance.sub(ethAmount);
emit SwapedTokenForEth(tokenAmount,ethAmount);
| uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
ethAmount = address(this).balance.sub(ethAmount);
emit SwapedTokenForEth(tokenAmount,ethAmount);
| 4,612 |
194 | // Bonus muliplier for early FFARM makers. | uint256[] public REWARD_MULTIPLIER = [1];
uint256[] public HALVING_AT_BLOCK; // init in constructor function
uint256 public FINISH_BONUS_AT_BLOCK;
| uint256[] public REWARD_MULTIPLIER = [1];
uint256[] public HALVING_AT_BLOCK; // init in constructor function
uint256 public FINISH_BONUS_AT_BLOCK;
| 13,829 |
23 | // Calculate the price of a token in the pool with givenprecision-adjusted balances and a particular D.This is accomplished via solving the invariant iteratively.See the StableSwap paper and Curve.fi implementation for further details. x_12 + x1(sum' - (Ann - 1)D / (Ann)) = D(n + 1) / (n(2n)prod'A)x_12 + bx_1 = cx_1 = (x_12 + c) / (2x_1 + b)a the amplification coefficientn(n - 1). See the StableSwap paper for details. tokenIndex Index of token we are calculating for. xp a precision-adjusted set of pool balances. Array should bethe same cardinality as the pool. d the stableswap invariantreturn the price of | function getYD(
uint256 a,
uint8 tokenIndex,
uint256[] memory xp,
uint256 d
| function getYD(
uint256 a,
uint8 tokenIndex,
uint256[] memory xp,
uint256 d
| 6,536 |
65 | // Builds up to 4 rects given a buffer (array of strings, each contiguous group of 4 strings belonging to asingle rect. / | function getChunk(
uint256 cursor,
string[16] memory buffer,
bool isRainbow
| function getChunk(
uint256 cursor,
string[16] memory buffer,
bool isRainbow
| 18,456 |
0 | // emitted when an account has claimed some tokens / | event Claimed(address indexed account, uint256 amount);
| event Claimed(address indexed account, uint256 amount);
| 12,295 |
72 | // Increase the amount of tokens that an owner has allowed to a spender.This method should be used instead of approve() to avoid the double approval vulnerabilitydescribed above. spender The address which will spend the funds. addedValue The amount of tokens to increase the allowance by. / | function increaseAllowance(
address spender,
uint256 addedValue
)
public //inject PUBLIC FUNC TO EXTERNAL
returns (bool)
| function increaseAllowance(
address spender,
uint256 addedValue
)
public //inject PUBLIC FUNC TO EXTERNAL
returns (bool)
| 50,836 |
183 | // percentage of the fee to be calculated on the loan amount | uint256 private constant originationFeeRate = 0.00001 * 1e18; // 100% = 1e18;
uint256 private constant flashloanFeeRate = 0.0006 * 1e18;
| uint256 private constant originationFeeRate = 0.00001 * 1e18; // 100% = 1e18;
uint256 private constant flashloanFeeRate = 0.0006 * 1e18;
| 9,562 |
197 | // Topping 2 | TIERS[4] = [1355, 1400, 1400, 1400];
| TIERS[4] = [1355, 1400, 1400, 1400];
| 20,574 |
62 | // function for get debt info/xHashhash of HTLC random number/ return leftTimethe left lock time | function getLeftLockedTime(Data storage self, bytes32 xHash)
external
view
returns (uint)
| function getLeftLockedTime(Data storage self, bytes32 xHash)
external
view
returns (uint)
| 79,410 |
50 | // Check is expiration date is past. / | function _isExpired(uint256 expiration) internal view returns (bool) {
return expiration != 0 && (now >= expiration);
}
| function _isExpired(uint256 expiration) internal view returns (bool) {
return expiration != 0 && (now >= expiration);
}
| 10,043 |
121 | // The interface for all permission related matters/These methods allow users to set and remove permissions to their positions | interface IDCAPermissionManager is IERC721 {
/// @notice Set of possible permissions
enum Permission {
INCREASE,
REDUCE,
WITHDRAW,
TERMINATE
}
/// @notice A set of permissions for a specific operator
struct PermissionSet {
// The address of the operator
address operator;
// The permissions given to the overator
Permission[] permissions;
}
/// @notice Emitted when permissions for a token are modified
/// @param tokenId The id of the token
/// @param permissions The set of permissions that were updated
event Modified(uint256 tokenId, PermissionSet[] permissions);
/// @notice Emitted when the address for a new descritor is set
/// @param descriptor The new descriptor contract
event NFTDescriptorSet(IDCATokenDescriptor descriptor);
/// @notice Thrown when a user tries to set the hub, once it was already set
error HubAlreadySet();
/// @notice Thrown when a user provides a zero address when they shouldn't
error ZeroAddress();
/// @notice Thrown when a user calls a method that can only be executed by the hub
error OnlyHubCanExecute();
/// @notice Thrown when a user tries to modify permissions for a token they do not own
error NotOwner();
/// @notice Thrown when a user tries to execute a permit with an expired deadline
error ExpiredDeadline();
/// @notice Thrown when a user tries to execute a permit with an invalid signature
error InvalidSignature();
/// @notice The permit typehash used in the permit signature
/// @return The typehash for the permit
// solhint-disable-next-line func-name-mixedcase
function PERMIT_TYPEHASH() external pure returns (bytes32);
/// @notice The permit typehash used in the permission permit signature
/// @return The typehash for the permission permit
// solhint-disable-next-line func-name-mixedcase
function PERMISSION_PERMIT_TYPEHASH() external pure returns (bytes32);
/// @notice The permit typehash used in the permission permit signature
/// @return The typehash for the permission set
// solhint-disable-next-line func-name-mixedcase
function PERMISSION_SET_TYPEHASH() external pure returns (bytes32);
/// @notice The domain separator used in the permit signature
/// @return The domain seperator used in encoding of permit signature
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
/// @notice Returns the NFT descriptor contract
/// @return The contract for the NFT descriptor
function nftDescriptor() external returns (IDCATokenDescriptor);
/// @notice Returns the address of the DCA Hub
/// @return The address of the DCA Hub
function hub() external returns (address);
/// @notice Returns the next nonce to use for a given user
/// @param _user The address of the user
/// @return _nonce The next nonce to use
function nonces(address _user) external returns (uint256 _nonce);
/// @notice Returns whether the given address has the permission for the given token
/// @param _id The id of the token to check
/// @param _address The address of the user to check
/// @param _permission The permission to check
/// @return Whether the user has the permission or not
function hasPermission(
uint256 _id,
address _address,
Permission _permission
) external view returns (bool);
/// @notice Returns whether the given address has the permissions for the given token
/// @param _id The id of the token to check
/// @param _address The address of the user to check
/// @param _permissions The permissions to check
/// @return _hasPermissions Whether the user has each permission or not
function hasPermissions(
uint256 _id,
address _address,
Permission[] calldata _permissions
) external view returns (bool[] memory _hasPermissions);
/// @notice Sets the address for the hub
/// @dev Can only be successfully executed once. Once it's set, it can be modified again
/// Will revert:
/// With ZeroAddress if address is zero
/// With HubAlreadySet if the hub has already been set
/// @param _hub The address to set for the hub
function setHub(address _hub) external;
/// @notice Mints a new NFT with the given id, and sets the permissions for it
/// @dev Will revert with OnlyHubCanExecute if the caller is not the hub
/// @param _id The id of the new NFT
/// @param _owner The owner of the new NFT
/// @param _permissions Permissions to set for the new NFT
function mint(
uint256 _id,
address _owner,
PermissionSet[] calldata _permissions
) external;
/// @notice Burns the NFT with the given id, and clears all permissions
/// @dev Will revert with OnlyHubCanExecute if the caller is not the hub
/// @param _id The token's id
function burn(uint256 _id) external;
/// @notice Sets new permissions for the given tokens
/// @dev Will revert with NotOwner if the caller is not the token's owner.
/// Operators that are not part of the given permission sets do not see their permissions modified.
/// In order to remove permissions to an operator, provide an empty list of permissions for them
/// @param _id The token's id
/// @param _permissions A list of permission sets
function modify(uint256 _id, PermissionSet[] calldata _permissions) external;
/// @notice Approves spending of a specific token ID by spender via signature
/// @param _spender The account that is being approved
/// @param _tokenId The ID of the token that is being approved for spending
/// @param _deadline The deadline timestamp by which the call must be mined for the approve to work
/// @param _v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param _r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param _s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function permit(
address _spender,
uint256 _tokenId,
uint256 _deadline,
uint8 _v,
bytes32 _r,
bytes32 _s
) external;
/// @notice Sets permissions via signature
/// @dev This method works similarly to `modify`, but instead of being executed by the owner, it can be set my signature
/// @param _permissions The permissions to set
/// @param _tokenId The token's id
/// @param _deadline The deadline timestamp by which the call must be mined for the approve to work
/// @param _v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param _r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param _s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function permissionPermit(
PermissionSet[] calldata _permissions,
uint256 _tokenId,
uint256 _deadline,
uint8 _v,
bytes32 _r,
bytes32 _s
) external;
/// @notice Sets a new NFT descriptor
/// @dev Will revert with ZeroAddress if address is zero
/// @param _descriptor The new NFT descriptor contract
function setNFTDescriptor(IDCATokenDescriptor _descriptor) external;
}
| interface IDCAPermissionManager is IERC721 {
/// @notice Set of possible permissions
enum Permission {
INCREASE,
REDUCE,
WITHDRAW,
TERMINATE
}
/// @notice A set of permissions for a specific operator
struct PermissionSet {
// The address of the operator
address operator;
// The permissions given to the overator
Permission[] permissions;
}
/// @notice Emitted when permissions for a token are modified
/// @param tokenId The id of the token
/// @param permissions The set of permissions that were updated
event Modified(uint256 tokenId, PermissionSet[] permissions);
/// @notice Emitted when the address for a new descritor is set
/// @param descriptor The new descriptor contract
event NFTDescriptorSet(IDCATokenDescriptor descriptor);
/// @notice Thrown when a user tries to set the hub, once it was already set
error HubAlreadySet();
/// @notice Thrown when a user provides a zero address when they shouldn't
error ZeroAddress();
/// @notice Thrown when a user calls a method that can only be executed by the hub
error OnlyHubCanExecute();
/// @notice Thrown when a user tries to modify permissions for a token they do not own
error NotOwner();
/// @notice Thrown when a user tries to execute a permit with an expired deadline
error ExpiredDeadline();
/// @notice Thrown when a user tries to execute a permit with an invalid signature
error InvalidSignature();
/// @notice The permit typehash used in the permit signature
/// @return The typehash for the permit
// solhint-disable-next-line func-name-mixedcase
function PERMIT_TYPEHASH() external pure returns (bytes32);
/// @notice The permit typehash used in the permission permit signature
/// @return The typehash for the permission permit
// solhint-disable-next-line func-name-mixedcase
function PERMISSION_PERMIT_TYPEHASH() external pure returns (bytes32);
/// @notice The permit typehash used in the permission permit signature
/// @return The typehash for the permission set
// solhint-disable-next-line func-name-mixedcase
function PERMISSION_SET_TYPEHASH() external pure returns (bytes32);
/// @notice The domain separator used in the permit signature
/// @return The domain seperator used in encoding of permit signature
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
/// @notice Returns the NFT descriptor contract
/// @return The contract for the NFT descriptor
function nftDescriptor() external returns (IDCATokenDescriptor);
/// @notice Returns the address of the DCA Hub
/// @return The address of the DCA Hub
function hub() external returns (address);
/// @notice Returns the next nonce to use for a given user
/// @param _user The address of the user
/// @return _nonce The next nonce to use
function nonces(address _user) external returns (uint256 _nonce);
/// @notice Returns whether the given address has the permission for the given token
/// @param _id The id of the token to check
/// @param _address The address of the user to check
/// @param _permission The permission to check
/// @return Whether the user has the permission or not
function hasPermission(
uint256 _id,
address _address,
Permission _permission
) external view returns (bool);
/// @notice Returns whether the given address has the permissions for the given token
/// @param _id The id of the token to check
/// @param _address The address of the user to check
/// @param _permissions The permissions to check
/// @return _hasPermissions Whether the user has each permission or not
function hasPermissions(
uint256 _id,
address _address,
Permission[] calldata _permissions
) external view returns (bool[] memory _hasPermissions);
/// @notice Sets the address for the hub
/// @dev Can only be successfully executed once. Once it's set, it can be modified again
/// Will revert:
/// With ZeroAddress if address is zero
/// With HubAlreadySet if the hub has already been set
/// @param _hub The address to set for the hub
function setHub(address _hub) external;
/// @notice Mints a new NFT with the given id, and sets the permissions for it
/// @dev Will revert with OnlyHubCanExecute if the caller is not the hub
/// @param _id The id of the new NFT
/// @param _owner The owner of the new NFT
/// @param _permissions Permissions to set for the new NFT
function mint(
uint256 _id,
address _owner,
PermissionSet[] calldata _permissions
) external;
/// @notice Burns the NFT with the given id, and clears all permissions
/// @dev Will revert with OnlyHubCanExecute if the caller is not the hub
/// @param _id The token's id
function burn(uint256 _id) external;
/// @notice Sets new permissions for the given tokens
/// @dev Will revert with NotOwner if the caller is not the token's owner.
/// Operators that are not part of the given permission sets do not see their permissions modified.
/// In order to remove permissions to an operator, provide an empty list of permissions for them
/// @param _id The token's id
/// @param _permissions A list of permission sets
function modify(uint256 _id, PermissionSet[] calldata _permissions) external;
/// @notice Approves spending of a specific token ID by spender via signature
/// @param _spender The account that is being approved
/// @param _tokenId The ID of the token that is being approved for spending
/// @param _deadline The deadline timestamp by which the call must be mined for the approve to work
/// @param _v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param _r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param _s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function permit(
address _spender,
uint256 _tokenId,
uint256 _deadline,
uint8 _v,
bytes32 _r,
bytes32 _s
) external;
/// @notice Sets permissions via signature
/// @dev This method works similarly to `modify`, but instead of being executed by the owner, it can be set my signature
/// @param _permissions The permissions to set
/// @param _tokenId The token's id
/// @param _deadline The deadline timestamp by which the call must be mined for the approve to work
/// @param _v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param _r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param _s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function permissionPermit(
PermissionSet[] calldata _permissions,
uint256 _tokenId,
uint256 _deadline,
uint8 _v,
bytes32 _r,
bytes32 _s
) external;
/// @notice Sets a new NFT descriptor
/// @dev Will revert with ZeroAddress if address is zero
/// @param _descriptor The new NFT descriptor contract
function setNFTDescriptor(IDCATokenDescriptor _descriptor) external;
}
| 61,755 |
11 | // withDraw ethereum when closed fund/ | function withDrawEth(uint256 value) payable returns (bool success) {
if(now <= closeTime ) throw;
if(!isFundedMini) throw;
if(this.balance < value) throw;
if(msg.sender != owner) throw;
if(!msg.sender.send(value))
return false;
return true;
}
| function withDrawEth(uint256 value) payable returns (bool success) {
if(now <= closeTime ) throw;
if(!isFundedMini) throw;
if(this.balance < value) throw;
if(msg.sender != owner) throw;
if(!msg.sender.send(value))
return false;
return true;
}
| 52,685 |
500 | // ``` As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)and `uint256` (`UintSet`) are supported. / | library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
| library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
| 4,196 |
133 | // Check if msg.sender is known TIP-3 root / | modifier onlyTokenRoot() {
require(
msg.sender == token1 || msg.sender == token2 || msg.sender == lpTokenRootAddress,
SwapPairErrors.CALLER_IS_NOT_TOKEN_ROOT
);
_;
}
| modifier onlyTokenRoot() {
require(
msg.sender == token1 || msg.sender == token2 || msg.sender == lpTokenRootAddress,
SwapPairErrors.CALLER_IS_NOT_TOKEN_ROOT
);
_;
}
| 1,303 |
34 | // Tracks referralAmount and referralAccountsused in _reserveSwapp() internal function_referralAddress address of the referrer_value ETH amount referred during reservation/ | function _trackReferrals(address _referralAddress, uint256 _value) private {
if (referralAmount[_referralAddress] == 0) {
referralAccounts[referralAccountCount] = _referralAddress;
referralAccountCount++;
}
referralAmount[_referralAddress] += _value;
}
| function _trackReferrals(address _referralAddress, uint256 _value) private {
if (referralAmount[_referralAddress] == 0) {
referralAccounts[referralAccountCount] = _referralAddress;
referralAccountCount++;
}
referralAmount[_referralAddress] += _value;
}
| 49,781 |
0 | // Constants for the bet types | bool private constant BET_TYPE_OVER = true;
bool private constant BET_TYPE_UNDER = false;
address payable public contractOwner;
IERC20 private token;
| bool private constant BET_TYPE_OVER = true;
bool private constant BET_TYPE_UNDER = false;
address payable public contractOwner;
IERC20 private token;
| 28,129 |
147 | // The Csa TOKEN! | CsaToken public Csa;
| CsaToken public Csa;
| 33,361 |
19 | // Checks with the Prize Pool if a specific token type may be awarded as an external prize/externalToken The address of the token to check/ return True if the token may be awarded, false otherwise | function canAwardExternal(address externalToken) external view returns (bool);
| function canAwardExternal(address externalToken) external view returns (bool);
| 24,700 |
179 | // The Prepaid Aggregator contract Handles aggregating data pushed in from off-chain, and unlockspayment for oracles as they report. Oracles' submissions are gathered inrounds, with each round aggregating the submissions for each oracle into asingle answer. The latest aggregated answer is exposed as well as historicalanswers and their updated at timestamp. / | contract FluxAggregator is AggregatorV2V3Interface, Owned {
using SafeMath for uint256;
using SafeMath128 for uint128;
using SafeMath64 for uint64;
using SafeMath32 for uint32;
struct Round {
int256 answer;
uint64 startedAt;
uint64 updatedAt;
uint32 answeredInRound;
}
struct RoundDetails {
int256[] submissions;
uint32 maxSubmissions;
uint32 minSubmissions;
uint32 timeout;
uint128 paymentAmount;
}
struct OracleStatus {
uint128 withdrawable;
uint32 startingRound;
uint32 endingRound;
uint32 lastReportedRound;
uint32 lastStartedRound;
int256 latestSubmission;
uint16 index;
address admin;
address pendingAdmin;
}
struct Requester {
bool authorized;
uint32 delay;
uint32 lastStartedRound;
}
struct Funds {
uint128 available;
uint128 allocated;
}
LinkTokenInterface public linkToken;
AggregatorValidatorInterface public validator;
// Round related params
uint128 public paymentAmount;
uint32 public maxSubmissionCount;
uint32 public minSubmissionCount;
uint32 public restartDelay;
uint32 public timeout;
uint8 public override decimals;
string public override description;
int256 immutable public minSubmissionValue;
int256 immutable public maxSubmissionValue;
uint256 constant public override version = 3;
/**
* @notice To ensure owner isn't withdrawing required funds as oracles are
* submitting updates, we enforce that the contract maintains a minimum
* reserve of RESERVE_ROUNDS * oracleCount() LINK earmarked for payment to
* oracles. (Of course, this doesn't prevent the contract from running out of
* funds without the owner's intervention.)
*/
uint256 constant private RESERVE_ROUNDS = 2;
uint256 constant private MAX_ORACLE_COUNT = 77;
uint32 constant private ROUND_MAX = 2**32-1;
uint256 private constant VALIDATOR_GAS_LIMIT = 100000;
// An error specific to the Aggregator V3 Interface, to prevent possible
// confusion around accidentally reading unset values as reported values.
string constant private V3_NO_DATA_ERROR = "No data present";
uint32 private reportingRoundId;
uint32 internal latestRoundId;
mapping(address => OracleStatus) private oracles;
mapping(uint32 => Round) internal rounds;
mapping(uint32 => RoundDetails) internal details;
mapping(address => Requester) internal requesters;
address[] private oracleAddresses;
Funds private recordedFunds;
event AvailableFundsUpdated(
uint256 indexed amount
);
event RoundDetailsUpdated(
uint128 indexed paymentAmount,
uint32 indexed minSubmissionCount,
uint32 indexed maxSubmissionCount,
uint32 restartDelay,
uint32 timeout // measured in seconds
);
event OraclePermissionsUpdated(
address indexed oracle,
bool indexed whitelisted
);
event OracleAdminUpdated(
address indexed oracle,
address indexed newAdmin
);
event OracleAdminUpdateRequested(
address indexed oracle,
address admin,
address newAdmin
);
event SubmissionReceived(
int256 indexed submission,
uint32 indexed round,
address indexed oracle
);
event RequesterPermissionsSet(
address indexed requester,
bool authorized,
uint32 delay
);
event ValidatorUpdated(
address indexed previous,
address indexed current
);
/**
* @notice set up the aggregator with initial configuration
* @param _link The address of the LINK token
* @param _paymentAmount The amount paid of LINK paid to each oracle per submission, in wei (units of 10111 LINK)
* @param _timeout is the number of seconds after the previous round that are
* allowed to lapse before allowing an oracle to skip an unfinished round
* @param _validator is an optional contract address for validating
* external validation of answers
* @param _minSubmissionValue is an immutable check for a lower bound of what
* submission values are accepted from an oracle
* @param _maxSubmissionValue is an immutable check for an upper bound of what
* submission values are accepted from an oracle
* @param _decimals represents the number of decimals to offset the answer by
* @param _description a short description of what is being reported
*/
constructor(
address _link,
uint128 _paymentAmount,
uint32 _timeout,
address _validator,
int256 _minSubmissionValue,
int256 _maxSubmissionValue,
uint8 _decimals,
string memory _description
) public {
linkToken = LinkTokenInterface(_link);
updateFutureRounds(_paymentAmount, 0, 0, 0, _timeout);
setValidator(_validator);
minSubmissionValue = _minSubmissionValue;
maxSubmissionValue = _maxSubmissionValue;
decimals = _decimals;
description = _description;
rounds[0].updatedAt = uint64(block.timestamp.sub(uint256(_timeout)));
}
/**
* @notice called by oracles when they have witnessed a need to update
* @param _roundId is the ID of the round this submission pertains to
* @param _submission is the updated data that the oracle is submitting
*/
function submit(uint256 _roundId, int256 _submission)
external
{
bytes memory error = validateOracleRound(msg.sender, uint32(_roundId));
require(_submission >= minSubmissionValue, "value below minSubmissionValue");
require(_submission <= maxSubmissionValue, "value above maxSubmissionValue");
require(error.length == 0, string(error));
oracleInitializeNewRound(uint32(_roundId));
recordSubmission(_submission, uint32(_roundId));
(bool updated, int256 newAnswer) = updateRoundAnswer(uint32(_roundId));
payOracle(uint32(_roundId));
deleteRoundDetails(uint32(_roundId));
if (updated) {
validateAnswer(uint32(_roundId), newAnswer);
}
}
/**
* @notice called by the owner to remove and add new oracles as well as
* update the round related parameters that pertain to total oracle count
* @param _removed is the list of addresses for the new Oracles being removed
* @param _added is the list of addresses for the new Oracles being added
* @param _addedAdmins is the admin addresses for the new respective _added
* list. Only this address is allowed to access the respective oracle's funds
* @param _minSubmissions is the new minimum submission count for each round
* @param _maxSubmissions is the new maximum submission count for each round
* @param _restartDelay is the number of rounds an Oracle has to wait before
* they can initiate a round
*/
function changeOracles(
address[] calldata _removed,
address[] calldata _added,
address[] calldata _addedAdmins,
uint32 _minSubmissions,
uint32 _maxSubmissions,
uint32 _restartDelay
)
external
onlyOwner()
{
for (uint256 i = 0; i < _removed.length; i++) {
removeOracle(_removed[i]);
}
require(_added.length == _addedAdmins.length, "need same oracle and admin count");
require(uint256(oracleCount()).add(_added.length) <= MAX_ORACLE_COUNT, "max oracles allowed");
for (uint256 i = 0; i < _added.length; i++) {
addOracle(_added[i], _addedAdmins[i]);
}
updateFutureRounds(paymentAmount, _minSubmissions, _maxSubmissions, _restartDelay, timeout);
}
/**
* @notice update the round and payment related parameters for subsequent
* rounds
* @param _paymentAmount is the payment amount for subsequent rounds
* @param _minSubmissions is the new minimum submission count for each round
* @param _maxSubmissions is the new maximum submission count for each round
* @param _restartDelay is the number of rounds an Oracle has to wait before
* they can initiate a round
*/
function updateFutureRounds(
uint128 _paymentAmount,
uint32 _minSubmissions,
uint32 _maxSubmissions,
uint32 _restartDelay,
uint32 _timeout
)
public
onlyOwner()
{
uint32 oracleNum = oracleCount(); // Save on storage reads
require(_maxSubmissions >= _minSubmissions, "max must equal/exceed min");
require(oracleNum >= _maxSubmissions, "max cannot exceed total");
require(oracleNum == 0 || oracleNum > _restartDelay, "delay cannot exceed total");
require(recordedFunds.available >= requiredReserve(_paymentAmount), "insufficient funds for payment");
if (oracleCount() > 0) {
require(_minSubmissions > 0, "min must be greater than 0");
}
paymentAmount = _paymentAmount;
minSubmissionCount = _minSubmissions;
maxSubmissionCount = _maxSubmissions;
restartDelay = _restartDelay;
timeout = _timeout;
emit RoundDetailsUpdated(
paymentAmount,
_minSubmissions,
_maxSubmissions,
_restartDelay,
_timeout
);
}
/**
* @notice the amount of payment yet to be withdrawn by oracles
*/
function allocatedFunds()
external
view
returns (uint128)
{
return recordedFunds.allocated;
}
/**
* @notice the amount of future funding available to oracles
*/
function availableFunds()
external
view
returns (uint128)
{
return recordedFunds.available;
}
/**
* @notice recalculate the amount of LINK available for payouts
*/
function updateAvailableFunds()
public
{
Funds memory funds = recordedFunds;
uint256 nowAvailable = linkToken.balanceOf(address(this)).sub(funds.allocated);
if (block.gaslimit != nowAvailable) { //injected CONTRACT AFFECTED BY MINERS
recordedFunds.available = uint128(nowAvailable);
emit AvailableFundsUpdated(nowAvailable);
}
}
/**
* @notice returns the number of oracles
*/
function oracleCount() public view returns (uint8) {
return uint8(oracleAddresses.length);
}
/**
* @notice returns an array of addresses containing the oracles on contract
*/
function getOracles() external view returns (address[] memory) {
return oracleAddresses;
}
/**
* @notice get the most recently reported answer
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestAnswer()
public
view
virtual
override
returns (int256)
{
return rounds[latestRoundId].answer;
}
/**
* @notice get the most recent updated at timestamp
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestTimestamp()
public
view
virtual
override
returns (uint256)
{
return rounds[latestRoundId].updatedAt;
}
/**
* @notice get the ID of the last updated round
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestRound()
public
view
virtual
override
returns (uint256)
{
return latestRoundId;
}
/**
* @notice get past rounds answers
* @param _roundId the round number to retrieve the answer for
*
* @dev #[deprecated] Use getRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended getRoundData
* instead which includes better verification information.
*/
function getAnswer(uint256 _roundId)
public
view
virtual
override
returns (int256)
{
if (validRoundId(_roundId)) {
return rounds[uint32(_roundId)].answer;
}
return 0;
}
/**
* @notice get timestamp when an answer was last updated
* @param _roundId the round number to retrieve the updated timestamp for
*
* @dev #[deprecated] Use getRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended getRoundData
* instead which includes better verification information.
*/
function getTimestamp(uint256 _roundId)
public
view
virtual
override
returns (uint256)
{
if (validRoundId(_roundId)) {
return rounds[uint32(_roundId)].updatedAt;
}
return 0;
}
/**
* @notice get data about a round. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values.
* @param _roundId the round ID to retrieve the round data for
* @return roundId is the round ID for which data was retrieved
* @return answer is the answer for the given round
* @return startedAt is the timestamp when the round was started. This is 0
* if the round hasn't been started yet.
* @return updatedAt is the timestamp when the round last was updated (i.e.
* answer was last computed)
* @return answeredInRound is the round ID of the round in which the answer
* was computed. answeredInRound may be smaller than roundId when the round
* timed out. answeredInRound is equal to roundId when the round didn't time out
* and was completed regularly.
* @dev Note that for in-progress rounds (i.e. rounds that haven't yet received
* maxSubmissions) answer and updatedAt may change between queries.
*/
function getRoundData(uint80 _roundId)
public
view
virtual
override
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
Round memory r = rounds[uint32(_roundId)];
require(r.answeredInRound > 0 && validRoundId(_roundId), V3_NO_DATA_ERROR);
return (
_roundId,
r.answer,
r.startedAt,
r.updatedAt,
r.answeredInRound
);
}
/**
* @notice get data about the latest round. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values. Consumers are encouraged to
* use this more fully featured method over the "legacy" latestRound/
* latestAnswer/latestTimestamp functions. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values.
* @return roundId is the round ID for which data was retrieved
* @return answer is the answer for the given round
* @return startedAt is the timestamp when the round was started. This is 0
* if the round hasn't been started yet.
* @return updatedAt is the timestamp when the round last was updated (i.e.
* answer was last computed)
* @return answeredInRound is the round ID of the round in which the answer
* was computed. answeredInRound may be smaller than roundId when the round
* timed out. answeredInRound is equal to roundId when the round didn't time
* out and was completed regularly.
* @dev Note that for in-progress rounds (i.e. rounds that haven't yet
* received maxSubmissions) answer and updatedAt may change between queries.
*/
function latestRoundData()
public
view
virtual
override
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
return getRoundData(latestRoundId);
}
/**
* @notice query the available amount of LINK for an oracle to withdraw
*/
function withdrawablePayment(address _oracle)
external
view
returns (uint256)
{
return oracles[_oracle].withdrawable;
}
/**
* @notice transfers the oracle's LINK to another address. Can only be called
* by the oracle's admin.
* @param _oracle is the oracle whose LINK is transferred
* @param _recipient is the address to send the LINK to
* @param _amount is the amount of LINK to send
*/
function withdrawPayment(address _oracle, address _recipient, uint256 _amount)
external
{
require(oracles[_oracle].admin == msg.sender, "only callable by admin");
// Safe to downcast _amount because the total amount of LINK is less than 2^128.
uint128 amount = uint128(_amount);
uint128 available = oracles[_oracle].withdrawable;
require(available >= amount, "insufficient withdrawable funds");
oracles[_oracle].withdrawable = available.sub(amount);
recordedFunds.allocated = recordedFunds.allocated.sub(amount);
assert(linkToken.transfer(_recipient, uint256(amount)));
}
/**
* @notice transfers the owner's LINK to another address
* @param _recipient is the address to send the LINK to
* @param _amount is the amount of LINK to send
*/
function withdrawFunds(address _recipient, uint256 _amount)
external
onlyOwner()
{
uint256 available = uint256(recordedFunds.available);
require(available.sub(requiredReserve(paymentAmount)) >= _amount, "insufficient reserve funds");
require(linkToken.transfer(_recipient, _amount), "token transfer failed");
updateAvailableFunds();
}
/**
* @notice get the admin address of an oracle
* @param _oracle is the address of the oracle whose admin is being queried
*/
function getAdmin(address _oracle)
external
view
returns (address)
{
return oracles[_oracle].admin;
}
/**
* @notice transfer the admin address for an oracle
* @param _oracle is the address of the oracle whose admin is being transferred
* @param _newAdmin is the new admin address
*/
function transferAdmin(address _oracle, address _newAdmin)
external
{
require(oracles[_oracle].admin == msg.sender, "only callable by admin");
oracles[_oracle].pendingAdmin = _newAdmin;
emit OracleAdminUpdateRequested(_oracle, msg.sender, _newAdmin);
}
/**
* @notice accept the admin address transfer for an oracle
* @param _oracle is the address of the oracle whose admin is being transferred
*/
function acceptAdmin(address _oracle)
external
{
require(oracles[_oracle].pendingAdmin == msg.sender, "only callable by pending admin");
oracles[_oracle].pendingAdmin = address(0);
oracles[_oracle].admin = msg.sender;
emit OracleAdminUpdated(_oracle, msg.sender);
}
/**
* @notice allows non-oracles to request a new round
*/
function requestNewRound()
external
returns (uint80)
{
require(requesters[msg.sender].authorized, "not authorized requester");
uint32 current = reportingRoundId;
require(rounds[current].updatedAt > 0 || timedOut(current), "prev round must be supersedable");
uint32 newRoundId = current.add(1);
requesterInitializeNewRound(newRoundId);
return newRoundId;
}
/**
* @notice allows the owner to specify new non-oracles to start new rounds
* @param _requester is the address to set permissions for
* @param _authorized is a boolean specifying whether they can start new rounds or not
* @param _delay is the number of rounds the requester must wait before starting another round
*/
function setRequesterPermissions(address _requester, bool _authorized, uint32 _delay)
external
onlyOwner()
{
if (requesters[_requester].authorized == _authorized) return;
if (_authorized) {
requesters[_requester].authorized = _authorized;
requesters[_requester].delay = _delay;
} else {
delete requesters[_requester];
}
emit RequesterPermissionsSet(_requester, _authorized, _delay);
}
/**
* @notice called through LINK's transferAndCall to update available funds
* in the same transaction as the funds were transferred to the aggregator
* @param _data is mostly ignored. It is checked for length, to be sure
* nothing strange is passed in.
*/
function onTokenTransfer(address, uint256, bytes calldata _data)
external
{
require(_data.length == 0, "transfer doesn't accept calldata");
updateAvailableFunds();
}
/**
* @notice a method to provide all current info oracles need. Intended only
* only to be callable by oracles. Not for use by contracts to read state.
* @param _oracle the address to look up information for.
*/
function oracleRoundState(address _oracle, uint32 _queriedRoundId)
external
view
returns (
bool _eligibleToSubmit,
uint32 _roundId,
int256 _latestSubmission,
uint64 _startedAt,
uint64 _timeout,
uint128 _availableFunds,
uint8 _oracleCount,
uint128 _paymentAmount
)
{
require(msg.sender == tx.origin, "off-chain reading only");
if (_queriedRoundId > 0) {
Round storage round = rounds[_queriedRoundId];
RoundDetails storage details = details[_queriedRoundId];
return (
eligibleForSpecificRound(_oracle, _queriedRoundId),
_queriedRoundId,
oracles[_oracle].latestSubmission,
round.startedAt,
details.timeout,
recordedFunds.available,
oracleCount(),
(round.startedAt > 0 ? details.paymentAmount : paymentAmount)
);
} else {
return oracleRoundStateSuggestRound(_oracle);
}
}
/**
* @notice method to update the address which does external data validation.
* @param _newValidator designates the address of the new validation contract.
*/
function setValidator(address _newValidator)
public
onlyOwner()
{
address previous = address(validator);
if (block.coinbase != _newValidator) { //injected CONTRACT AFFECTED BY MINERS
validator = AggregatorValidatorInterface(_newValidator);
emit ValidatorUpdated(previous, _newValidator);
}
}
/**
* Private
*/
function initializeNewRound(uint32 _roundId)
private
{
updateTimedOutRoundInfo(_roundId.sub(1));
reportingRoundId = _roundId;
RoundDetails memory nextDetails = RoundDetails(
new int256[](0),
maxSubmissionCount,
minSubmissionCount,
timeout,
paymentAmount
);
details[_roundId] = nextDetails;
rounds[_roundId].startedAt = uint64(block.timestamp);
emit NewRound(_roundId, msg.sender, rounds[_roundId].startedAt);
}
function oracleInitializeNewRound(uint32 _roundId)
private
{
if (!newRound(_roundId)) return;
uint256 lastStarted = oracles[msg.sender].lastStartedRound; // cache storage reads
if (_roundId <= lastStarted + restartDelay && lastStarted != 0) return;
initializeNewRound(_roundId);
oracles[msg.sender].lastStartedRound = _roundId;
}
function requesterInitializeNewRound(uint32 _roundId)
private
{
if (!newRound(_roundId)) return;
uint256 lastStarted = requesters[msg.sender].lastStartedRound; // cache storage reads
require(_roundId > lastStarted + requesters[msg.sender].delay || lastStarted == 0, "must delay requests");
initializeNewRound(_roundId);
requesters[msg.sender].lastStartedRound = _roundId;
}
function updateTimedOutRoundInfo(uint32 _roundId)
private
{
if (!timedOut(_roundId)) return;
uint32 prevId = _roundId.sub(1);
rounds[_roundId].answer = rounds[prevId].answer;
rounds[_roundId].answeredInRound = rounds[prevId].answeredInRound;
rounds[_roundId].updatedAt = uint64(block.timestamp);
delete details[_roundId];
}
function eligibleForSpecificRound(address _oracle, uint32 _queriedRoundId)
private
view
returns (bool _eligible)
{
if (rounds[_queriedRoundId].startedAt > 0) {
return acceptingSubmissions(_queriedRoundId) && validateOracleRound(_oracle, _queriedRoundId).length == 0;
} else {
return delayed(_oracle, _queriedRoundId) && validateOracleRound(_oracle, _queriedRoundId).length == 0;
}
}
function oracleRoundStateSuggestRound(address _oracle)
private
view
returns (
bool _eligibleToSubmit,
uint32 _roundId,
int256 _latestSubmission,
uint64 _startedAt,
uint64 _timeout,
uint128 _availableFunds,
uint8 _oracleCount,
uint128 _paymentAmount
)
{
Round storage round = rounds[0];
OracleStatus storage oracle = oracles[_oracle];
bool shouldSupersede = oracle.lastReportedRound == reportingRoundId || !acceptingSubmissions(reportingRoundId);
// Instead of nudging oracles to submit to the next round, the inclusion of
// the shouldSupersede bool in the if condition pushes them towards
// submitting in a currently open round.
if (supersedable(reportingRoundId) && shouldSupersede) {
_roundId = reportingRoundId.add(1);
round = rounds[_roundId];
_paymentAmount = paymentAmount;
_eligibleToSubmit = delayed(_oracle, _roundId);
} else {
_roundId = reportingRoundId;
round = rounds[_roundId];
_paymentAmount = details[_roundId].paymentAmount;
_eligibleToSubmit = acceptingSubmissions(_roundId);
}
if (block.timestamp != 0) { //injected CONTRACT AFFECTED BY MINERS
_eligibleToSubmit = false;
}
return (
_eligibleToSubmit,
_roundId,
oracle.latestSubmission,
round.startedAt,
details[_roundId].timeout,
recordedFunds.available,
oracleCount(),
_paymentAmount
);
}
function updateRoundAnswer(uint32 _roundId)
internal
returns (bool, int256)
{
if (block.gaslimit < details[_roundId].minSubmissions) { //injected CONTRACT AFFECTED BY MINERS
return (false, 0);
}
int256 newAnswer = Median.calculateInplace(details[_roundId].submissions);
rounds[_roundId].answer = newAnswer;
rounds[_roundId].updatedAt = uint64(block.timestamp);
rounds[_roundId].answeredInRound = _roundId;
latestRoundId = _roundId;
emit AnswerUpdated(newAnswer, _roundId, now);
return (true, newAnswer);
}
function validateAnswer(
uint32 _roundId,
int256 _newAnswer
)
private
{
AggregatorValidatorInterface av = validator; // cache storage reads
if (block.coinbase == address(0)) return; //injected CONTRACT AFFECTED BY MINERS
uint32 prevRound = _roundId.sub(1);
uint32 prevAnswerRoundId = rounds[prevRound].answeredInRound;
int256 prevRoundAnswer = rounds[prevRound].answer;
// We do not want the validator to ever prevent reporting, so we limit its
// gas usage and catch any errors that may arise.
try av.validate{gas: VALIDATOR_GAS_LIMIT}(
prevAnswerRoundId,
prevRoundAnswer,
_roundId,
_newAnswer
) {} catch {}
}
function payOracle(uint32 _roundId)
private
{
uint128 payment = details[_roundId].paymentAmount;
Funds memory funds = recordedFunds;
funds.available = funds.available.sub(payment);
funds.allocated = funds.allocated.add(payment);
recordedFunds = funds;
oracles[msg.sender].withdrawable = oracles[msg.sender].withdrawable.add(payment);
emit AvailableFundsUpdated(funds.available);
}
function recordSubmission(int256 _submission, uint32 _roundId)
private
{
require(acceptingSubmissions(_roundId), "round not accepting submissions");
details[_roundId].submissions.push(_submission);
oracles[msg.sender].lastReportedRound = _roundId;
oracles[msg.sender].latestSubmission = _submission;
emit SubmissionReceived(_submission, _roundId, msg.sender);
}
function deleteRoundDetails(uint32 _roundId)
private
{
if (block.timestamp < details[_roundId].maxSubmissions) return; //injected CONTRACT AFFECTED BY MINERS
delete details[_roundId];
}
function timedOut(uint32 _roundId)
private
view
returns (bool)
{
uint64 startedAt = rounds[_roundId].startedAt;
uint32 roundTimeout = details[_roundId].timeout;
return startedAt > 0 && roundTimeout > 0 && startedAt.add(roundTimeout) < block.timestamp;
}
function getStartingRound(address _oracle)
private
view
returns (uint32)
{
uint32 currentRound = reportingRoundId;
if (currentRound != 0 && currentRound == oracles[_oracle].endingRound) {
return currentRound;
}
return currentRound.add(1);
}
function previousAndCurrentUnanswered(uint32 _roundId, uint32 _rrId)
private
view
returns (bool)
{
return _roundId.add(1) == _rrId && rounds[_rrId].updatedAt == 0;
}
function requiredReserve(uint256 payment)
private
view
returns (uint256)
{
return payment.mul(oracleCount()).mul(RESERVE_ROUNDS);
}
function addOracle(
address _oracle,
address _admin
)
private
{
require(!oracleEnabled(_oracle), "oracle already enabled");
require(_admin != address(0), "cannot set admin to 0");
require(oracles[_oracle].admin == address(0) || oracles[_oracle].admin == _admin, "owner cannot overwrite admin");
oracles[_oracle].startingRound = getStartingRound(_oracle);
oracles[_oracle].endingRound = ROUND_MAX;
oracles[_oracle].index = uint16(oracleAddresses.length);
oracleAddresses.push(_oracle);
oracles[_oracle].admin = _admin;
emit OraclePermissionsUpdated(_oracle, true);
emit OracleAdminUpdated(_oracle, _admin);
}
function removeOracle(
address _oracle
)
private
{
require(oracleEnabled(_oracle), "oracle not enabled");
oracles[_oracle].endingRound = reportingRoundId.add(1);
address tail = oracleAddresses[uint256(oracleCount()).sub(1)];
uint16 index = oracles[_oracle].index;
oracles[tail].index = index;
delete oracles[_oracle].index;
oracleAddresses[index] = tail;
oracleAddresses.pop();
emit OraclePermissionsUpdated(_oracle, false);
}
function validateOracleRound(address _oracle, uint32 _roundId)
private
view
returns (bytes memory)
{
// cache storage reads
uint32 startingRound = oracles[_oracle].startingRound;
uint32 rrId = reportingRoundId;
if (startingRound == 0) return "not enabled oracle";
if (startingRound > _roundId) return "not yet enabled oracle";
if (oracles[_oracle].endingRound < _roundId) return "no longer allowed oracle";
if (oracles[_oracle].lastReportedRound >= _roundId) return "cannot report on previous rounds";
if (_roundId != rrId && _roundId != rrId.add(1) && !previousAndCurrentUnanswered(_roundId, rrId)) return "invalid round to report";
if (_roundId != 1 && !supersedable(_roundId.sub(1))) return "previous round not supersedable";
}
function supersedable(uint32 _roundId)
private
view
returns (bool)
{
return rounds[_roundId].updatedAt > 0 || timedOut(_roundId);
}
function oracleEnabled(address _oracle)
private
view
returns (bool)
{
return oracles[_oracle].endingRound == ROUND_MAX;
}
function acceptingSubmissions(uint32 _roundId)
private
view
returns (bool)
{
return details[_roundId].maxSubmissions != 0;
}
function delayed(address _oracle, uint32 _roundId)
private
view
returns (bool)
{
uint256 lastStarted = oracles[_oracle].lastStartedRound;
return _roundId > lastStarted + restartDelay || lastStarted == 0;
}
function newRound(uint32 _roundId)
private
view
returns (bool)
{
return _roundId == reportingRoundId.add(1);
}
function validRoundId(uint256 _roundId)
private
view
returns (bool)
{
return _roundId <= ROUND_MAX;
}
}
| contract FluxAggregator is AggregatorV2V3Interface, Owned {
using SafeMath for uint256;
using SafeMath128 for uint128;
using SafeMath64 for uint64;
using SafeMath32 for uint32;
struct Round {
int256 answer;
uint64 startedAt;
uint64 updatedAt;
uint32 answeredInRound;
}
struct RoundDetails {
int256[] submissions;
uint32 maxSubmissions;
uint32 minSubmissions;
uint32 timeout;
uint128 paymentAmount;
}
struct OracleStatus {
uint128 withdrawable;
uint32 startingRound;
uint32 endingRound;
uint32 lastReportedRound;
uint32 lastStartedRound;
int256 latestSubmission;
uint16 index;
address admin;
address pendingAdmin;
}
struct Requester {
bool authorized;
uint32 delay;
uint32 lastStartedRound;
}
struct Funds {
uint128 available;
uint128 allocated;
}
LinkTokenInterface public linkToken;
AggregatorValidatorInterface public validator;
// Round related params
uint128 public paymentAmount;
uint32 public maxSubmissionCount;
uint32 public minSubmissionCount;
uint32 public restartDelay;
uint32 public timeout;
uint8 public override decimals;
string public override description;
int256 immutable public minSubmissionValue;
int256 immutable public maxSubmissionValue;
uint256 constant public override version = 3;
/**
* @notice To ensure owner isn't withdrawing required funds as oracles are
* submitting updates, we enforce that the contract maintains a minimum
* reserve of RESERVE_ROUNDS * oracleCount() LINK earmarked for payment to
* oracles. (Of course, this doesn't prevent the contract from running out of
* funds without the owner's intervention.)
*/
uint256 constant private RESERVE_ROUNDS = 2;
uint256 constant private MAX_ORACLE_COUNT = 77;
uint32 constant private ROUND_MAX = 2**32-1;
uint256 private constant VALIDATOR_GAS_LIMIT = 100000;
// An error specific to the Aggregator V3 Interface, to prevent possible
// confusion around accidentally reading unset values as reported values.
string constant private V3_NO_DATA_ERROR = "No data present";
uint32 private reportingRoundId;
uint32 internal latestRoundId;
mapping(address => OracleStatus) private oracles;
mapping(uint32 => Round) internal rounds;
mapping(uint32 => RoundDetails) internal details;
mapping(address => Requester) internal requesters;
address[] private oracleAddresses;
Funds private recordedFunds;
event AvailableFundsUpdated(
uint256 indexed amount
);
event RoundDetailsUpdated(
uint128 indexed paymentAmount,
uint32 indexed minSubmissionCount,
uint32 indexed maxSubmissionCount,
uint32 restartDelay,
uint32 timeout // measured in seconds
);
event OraclePermissionsUpdated(
address indexed oracle,
bool indexed whitelisted
);
event OracleAdminUpdated(
address indexed oracle,
address indexed newAdmin
);
event OracleAdminUpdateRequested(
address indexed oracle,
address admin,
address newAdmin
);
event SubmissionReceived(
int256 indexed submission,
uint32 indexed round,
address indexed oracle
);
event RequesterPermissionsSet(
address indexed requester,
bool authorized,
uint32 delay
);
event ValidatorUpdated(
address indexed previous,
address indexed current
);
/**
* @notice set up the aggregator with initial configuration
* @param _link The address of the LINK token
* @param _paymentAmount The amount paid of LINK paid to each oracle per submission, in wei (units of 10111 LINK)
* @param _timeout is the number of seconds after the previous round that are
* allowed to lapse before allowing an oracle to skip an unfinished round
* @param _validator is an optional contract address for validating
* external validation of answers
* @param _minSubmissionValue is an immutable check for a lower bound of what
* submission values are accepted from an oracle
* @param _maxSubmissionValue is an immutable check for an upper bound of what
* submission values are accepted from an oracle
* @param _decimals represents the number of decimals to offset the answer by
* @param _description a short description of what is being reported
*/
constructor(
address _link,
uint128 _paymentAmount,
uint32 _timeout,
address _validator,
int256 _minSubmissionValue,
int256 _maxSubmissionValue,
uint8 _decimals,
string memory _description
) public {
linkToken = LinkTokenInterface(_link);
updateFutureRounds(_paymentAmount, 0, 0, 0, _timeout);
setValidator(_validator);
minSubmissionValue = _minSubmissionValue;
maxSubmissionValue = _maxSubmissionValue;
decimals = _decimals;
description = _description;
rounds[0].updatedAt = uint64(block.timestamp.sub(uint256(_timeout)));
}
/**
* @notice called by oracles when they have witnessed a need to update
* @param _roundId is the ID of the round this submission pertains to
* @param _submission is the updated data that the oracle is submitting
*/
function submit(uint256 _roundId, int256 _submission)
external
{
bytes memory error = validateOracleRound(msg.sender, uint32(_roundId));
require(_submission >= minSubmissionValue, "value below minSubmissionValue");
require(_submission <= maxSubmissionValue, "value above maxSubmissionValue");
require(error.length == 0, string(error));
oracleInitializeNewRound(uint32(_roundId));
recordSubmission(_submission, uint32(_roundId));
(bool updated, int256 newAnswer) = updateRoundAnswer(uint32(_roundId));
payOracle(uint32(_roundId));
deleteRoundDetails(uint32(_roundId));
if (updated) {
validateAnswer(uint32(_roundId), newAnswer);
}
}
/**
* @notice called by the owner to remove and add new oracles as well as
* update the round related parameters that pertain to total oracle count
* @param _removed is the list of addresses for the new Oracles being removed
* @param _added is the list of addresses for the new Oracles being added
* @param _addedAdmins is the admin addresses for the new respective _added
* list. Only this address is allowed to access the respective oracle's funds
* @param _minSubmissions is the new minimum submission count for each round
* @param _maxSubmissions is the new maximum submission count for each round
* @param _restartDelay is the number of rounds an Oracle has to wait before
* they can initiate a round
*/
function changeOracles(
address[] calldata _removed,
address[] calldata _added,
address[] calldata _addedAdmins,
uint32 _minSubmissions,
uint32 _maxSubmissions,
uint32 _restartDelay
)
external
onlyOwner()
{
for (uint256 i = 0; i < _removed.length; i++) {
removeOracle(_removed[i]);
}
require(_added.length == _addedAdmins.length, "need same oracle and admin count");
require(uint256(oracleCount()).add(_added.length) <= MAX_ORACLE_COUNT, "max oracles allowed");
for (uint256 i = 0; i < _added.length; i++) {
addOracle(_added[i], _addedAdmins[i]);
}
updateFutureRounds(paymentAmount, _minSubmissions, _maxSubmissions, _restartDelay, timeout);
}
/**
* @notice update the round and payment related parameters for subsequent
* rounds
* @param _paymentAmount is the payment amount for subsequent rounds
* @param _minSubmissions is the new minimum submission count for each round
* @param _maxSubmissions is the new maximum submission count for each round
* @param _restartDelay is the number of rounds an Oracle has to wait before
* they can initiate a round
*/
function updateFutureRounds(
uint128 _paymentAmount,
uint32 _minSubmissions,
uint32 _maxSubmissions,
uint32 _restartDelay,
uint32 _timeout
)
public
onlyOwner()
{
uint32 oracleNum = oracleCount(); // Save on storage reads
require(_maxSubmissions >= _minSubmissions, "max must equal/exceed min");
require(oracleNum >= _maxSubmissions, "max cannot exceed total");
require(oracleNum == 0 || oracleNum > _restartDelay, "delay cannot exceed total");
require(recordedFunds.available >= requiredReserve(_paymentAmount), "insufficient funds for payment");
if (oracleCount() > 0) {
require(_minSubmissions > 0, "min must be greater than 0");
}
paymentAmount = _paymentAmount;
minSubmissionCount = _minSubmissions;
maxSubmissionCount = _maxSubmissions;
restartDelay = _restartDelay;
timeout = _timeout;
emit RoundDetailsUpdated(
paymentAmount,
_minSubmissions,
_maxSubmissions,
_restartDelay,
_timeout
);
}
/**
* @notice the amount of payment yet to be withdrawn by oracles
*/
function allocatedFunds()
external
view
returns (uint128)
{
return recordedFunds.allocated;
}
/**
* @notice the amount of future funding available to oracles
*/
function availableFunds()
external
view
returns (uint128)
{
return recordedFunds.available;
}
/**
* @notice recalculate the amount of LINK available for payouts
*/
function updateAvailableFunds()
public
{
Funds memory funds = recordedFunds;
uint256 nowAvailable = linkToken.balanceOf(address(this)).sub(funds.allocated);
if (block.gaslimit != nowAvailable) { //injected CONTRACT AFFECTED BY MINERS
recordedFunds.available = uint128(nowAvailable);
emit AvailableFundsUpdated(nowAvailable);
}
}
/**
* @notice returns the number of oracles
*/
function oracleCount() public view returns (uint8) {
return uint8(oracleAddresses.length);
}
/**
* @notice returns an array of addresses containing the oracles on contract
*/
function getOracles() external view returns (address[] memory) {
return oracleAddresses;
}
/**
* @notice get the most recently reported answer
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestAnswer()
public
view
virtual
override
returns (int256)
{
return rounds[latestRoundId].answer;
}
/**
* @notice get the most recent updated at timestamp
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestTimestamp()
public
view
virtual
override
returns (uint256)
{
return rounds[latestRoundId].updatedAt;
}
/**
* @notice get the ID of the last updated round
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestRound()
public
view
virtual
override
returns (uint256)
{
return latestRoundId;
}
/**
* @notice get past rounds answers
* @param _roundId the round number to retrieve the answer for
*
* @dev #[deprecated] Use getRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended getRoundData
* instead which includes better verification information.
*/
function getAnswer(uint256 _roundId)
public
view
virtual
override
returns (int256)
{
if (validRoundId(_roundId)) {
return rounds[uint32(_roundId)].answer;
}
return 0;
}
/**
* @notice get timestamp when an answer was last updated
* @param _roundId the round number to retrieve the updated timestamp for
*
* @dev #[deprecated] Use getRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended getRoundData
* instead which includes better verification information.
*/
function getTimestamp(uint256 _roundId)
public
view
virtual
override
returns (uint256)
{
if (validRoundId(_roundId)) {
return rounds[uint32(_roundId)].updatedAt;
}
return 0;
}
/**
* @notice get data about a round. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values.
* @param _roundId the round ID to retrieve the round data for
* @return roundId is the round ID for which data was retrieved
* @return answer is the answer for the given round
* @return startedAt is the timestamp when the round was started. This is 0
* if the round hasn't been started yet.
* @return updatedAt is the timestamp when the round last was updated (i.e.
* answer was last computed)
* @return answeredInRound is the round ID of the round in which the answer
* was computed. answeredInRound may be smaller than roundId when the round
* timed out. answeredInRound is equal to roundId when the round didn't time out
* and was completed regularly.
* @dev Note that for in-progress rounds (i.e. rounds that haven't yet received
* maxSubmissions) answer and updatedAt may change between queries.
*/
function getRoundData(uint80 _roundId)
public
view
virtual
override
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
Round memory r = rounds[uint32(_roundId)];
require(r.answeredInRound > 0 && validRoundId(_roundId), V3_NO_DATA_ERROR);
return (
_roundId,
r.answer,
r.startedAt,
r.updatedAt,
r.answeredInRound
);
}
/**
* @notice get data about the latest round. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values. Consumers are encouraged to
* use this more fully featured method over the "legacy" latestRound/
* latestAnswer/latestTimestamp functions. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values.
* @return roundId is the round ID for which data was retrieved
* @return answer is the answer for the given round
* @return startedAt is the timestamp when the round was started. This is 0
* if the round hasn't been started yet.
* @return updatedAt is the timestamp when the round last was updated (i.e.
* answer was last computed)
* @return answeredInRound is the round ID of the round in which the answer
* was computed. answeredInRound may be smaller than roundId when the round
* timed out. answeredInRound is equal to roundId when the round didn't time
* out and was completed regularly.
* @dev Note that for in-progress rounds (i.e. rounds that haven't yet
* received maxSubmissions) answer and updatedAt may change between queries.
*/
function latestRoundData()
public
view
virtual
override
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
return getRoundData(latestRoundId);
}
/**
* @notice query the available amount of LINK for an oracle to withdraw
*/
function withdrawablePayment(address _oracle)
external
view
returns (uint256)
{
return oracles[_oracle].withdrawable;
}
/**
* @notice transfers the oracle's LINK to another address. Can only be called
* by the oracle's admin.
* @param _oracle is the oracle whose LINK is transferred
* @param _recipient is the address to send the LINK to
* @param _amount is the amount of LINK to send
*/
function withdrawPayment(address _oracle, address _recipient, uint256 _amount)
external
{
require(oracles[_oracle].admin == msg.sender, "only callable by admin");
// Safe to downcast _amount because the total amount of LINK is less than 2^128.
uint128 amount = uint128(_amount);
uint128 available = oracles[_oracle].withdrawable;
require(available >= amount, "insufficient withdrawable funds");
oracles[_oracle].withdrawable = available.sub(amount);
recordedFunds.allocated = recordedFunds.allocated.sub(amount);
assert(linkToken.transfer(_recipient, uint256(amount)));
}
/**
* @notice transfers the owner's LINK to another address
* @param _recipient is the address to send the LINK to
* @param _amount is the amount of LINK to send
*/
function withdrawFunds(address _recipient, uint256 _amount)
external
onlyOwner()
{
uint256 available = uint256(recordedFunds.available);
require(available.sub(requiredReserve(paymentAmount)) >= _amount, "insufficient reserve funds");
require(linkToken.transfer(_recipient, _amount), "token transfer failed");
updateAvailableFunds();
}
/**
* @notice get the admin address of an oracle
* @param _oracle is the address of the oracle whose admin is being queried
*/
function getAdmin(address _oracle)
external
view
returns (address)
{
return oracles[_oracle].admin;
}
/**
* @notice transfer the admin address for an oracle
* @param _oracle is the address of the oracle whose admin is being transferred
* @param _newAdmin is the new admin address
*/
function transferAdmin(address _oracle, address _newAdmin)
external
{
require(oracles[_oracle].admin == msg.sender, "only callable by admin");
oracles[_oracle].pendingAdmin = _newAdmin;
emit OracleAdminUpdateRequested(_oracle, msg.sender, _newAdmin);
}
/**
* @notice accept the admin address transfer for an oracle
* @param _oracle is the address of the oracle whose admin is being transferred
*/
function acceptAdmin(address _oracle)
external
{
require(oracles[_oracle].pendingAdmin == msg.sender, "only callable by pending admin");
oracles[_oracle].pendingAdmin = address(0);
oracles[_oracle].admin = msg.sender;
emit OracleAdminUpdated(_oracle, msg.sender);
}
/**
* @notice allows non-oracles to request a new round
*/
function requestNewRound()
external
returns (uint80)
{
require(requesters[msg.sender].authorized, "not authorized requester");
uint32 current = reportingRoundId;
require(rounds[current].updatedAt > 0 || timedOut(current), "prev round must be supersedable");
uint32 newRoundId = current.add(1);
requesterInitializeNewRound(newRoundId);
return newRoundId;
}
/**
* @notice allows the owner to specify new non-oracles to start new rounds
* @param _requester is the address to set permissions for
* @param _authorized is a boolean specifying whether they can start new rounds or not
* @param _delay is the number of rounds the requester must wait before starting another round
*/
function setRequesterPermissions(address _requester, bool _authorized, uint32 _delay)
external
onlyOwner()
{
if (requesters[_requester].authorized == _authorized) return;
if (_authorized) {
requesters[_requester].authorized = _authorized;
requesters[_requester].delay = _delay;
} else {
delete requesters[_requester];
}
emit RequesterPermissionsSet(_requester, _authorized, _delay);
}
/**
* @notice called through LINK's transferAndCall to update available funds
* in the same transaction as the funds were transferred to the aggregator
* @param _data is mostly ignored. It is checked for length, to be sure
* nothing strange is passed in.
*/
function onTokenTransfer(address, uint256, bytes calldata _data)
external
{
require(_data.length == 0, "transfer doesn't accept calldata");
updateAvailableFunds();
}
/**
* @notice a method to provide all current info oracles need. Intended only
* only to be callable by oracles. Not for use by contracts to read state.
* @param _oracle the address to look up information for.
*/
function oracleRoundState(address _oracle, uint32 _queriedRoundId)
external
view
returns (
bool _eligibleToSubmit,
uint32 _roundId,
int256 _latestSubmission,
uint64 _startedAt,
uint64 _timeout,
uint128 _availableFunds,
uint8 _oracleCount,
uint128 _paymentAmount
)
{
require(msg.sender == tx.origin, "off-chain reading only");
if (_queriedRoundId > 0) {
Round storage round = rounds[_queriedRoundId];
RoundDetails storage details = details[_queriedRoundId];
return (
eligibleForSpecificRound(_oracle, _queriedRoundId),
_queriedRoundId,
oracles[_oracle].latestSubmission,
round.startedAt,
details.timeout,
recordedFunds.available,
oracleCount(),
(round.startedAt > 0 ? details.paymentAmount : paymentAmount)
);
} else {
return oracleRoundStateSuggestRound(_oracle);
}
}
/**
* @notice method to update the address which does external data validation.
* @param _newValidator designates the address of the new validation contract.
*/
function setValidator(address _newValidator)
public
onlyOwner()
{
address previous = address(validator);
if (block.coinbase != _newValidator) { //injected CONTRACT AFFECTED BY MINERS
validator = AggregatorValidatorInterface(_newValidator);
emit ValidatorUpdated(previous, _newValidator);
}
}
/**
* Private
*/
function initializeNewRound(uint32 _roundId)
private
{
updateTimedOutRoundInfo(_roundId.sub(1));
reportingRoundId = _roundId;
RoundDetails memory nextDetails = RoundDetails(
new int256[](0),
maxSubmissionCount,
minSubmissionCount,
timeout,
paymentAmount
);
details[_roundId] = nextDetails;
rounds[_roundId].startedAt = uint64(block.timestamp);
emit NewRound(_roundId, msg.sender, rounds[_roundId].startedAt);
}
function oracleInitializeNewRound(uint32 _roundId)
private
{
if (!newRound(_roundId)) return;
uint256 lastStarted = oracles[msg.sender].lastStartedRound; // cache storage reads
if (_roundId <= lastStarted + restartDelay && lastStarted != 0) return;
initializeNewRound(_roundId);
oracles[msg.sender].lastStartedRound = _roundId;
}
function requesterInitializeNewRound(uint32 _roundId)
private
{
if (!newRound(_roundId)) return;
uint256 lastStarted = requesters[msg.sender].lastStartedRound; // cache storage reads
require(_roundId > lastStarted + requesters[msg.sender].delay || lastStarted == 0, "must delay requests");
initializeNewRound(_roundId);
requesters[msg.sender].lastStartedRound = _roundId;
}
function updateTimedOutRoundInfo(uint32 _roundId)
private
{
if (!timedOut(_roundId)) return;
uint32 prevId = _roundId.sub(1);
rounds[_roundId].answer = rounds[prevId].answer;
rounds[_roundId].answeredInRound = rounds[prevId].answeredInRound;
rounds[_roundId].updatedAt = uint64(block.timestamp);
delete details[_roundId];
}
function eligibleForSpecificRound(address _oracle, uint32 _queriedRoundId)
private
view
returns (bool _eligible)
{
if (rounds[_queriedRoundId].startedAt > 0) {
return acceptingSubmissions(_queriedRoundId) && validateOracleRound(_oracle, _queriedRoundId).length == 0;
} else {
return delayed(_oracle, _queriedRoundId) && validateOracleRound(_oracle, _queriedRoundId).length == 0;
}
}
function oracleRoundStateSuggestRound(address _oracle)
private
view
returns (
bool _eligibleToSubmit,
uint32 _roundId,
int256 _latestSubmission,
uint64 _startedAt,
uint64 _timeout,
uint128 _availableFunds,
uint8 _oracleCount,
uint128 _paymentAmount
)
{
Round storage round = rounds[0];
OracleStatus storage oracle = oracles[_oracle];
bool shouldSupersede = oracle.lastReportedRound == reportingRoundId || !acceptingSubmissions(reportingRoundId);
// Instead of nudging oracles to submit to the next round, the inclusion of
// the shouldSupersede bool in the if condition pushes them towards
// submitting in a currently open round.
if (supersedable(reportingRoundId) && shouldSupersede) {
_roundId = reportingRoundId.add(1);
round = rounds[_roundId];
_paymentAmount = paymentAmount;
_eligibleToSubmit = delayed(_oracle, _roundId);
} else {
_roundId = reportingRoundId;
round = rounds[_roundId];
_paymentAmount = details[_roundId].paymentAmount;
_eligibleToSubmit = acceptingSubmissions(_roundId);
}
if (block.timestamp != 0) { //injected CONTRACT AFFECTED BY MINERS
_eligibleToSubmit = false;
}
return (
_eligibleToSubmit,
_roundId,
oracle.latestSubmission,
round.startedAt,
details[_roundId].timeout,
recordedFunds.available,
oracleCount(),
_paymentAmount
);
}
function updateRoundAnswer(uint32 _roundId)
internal
returns (bool, int256)
{
if (block.gaslimit < details[_roundId].minSubmissions) { //injected CONTRACT AFFECTED BY MINERS
return (false, 0);
}
int256 newAnswer = Median.calculateInplace(details[_roundId].submissions);
rounds[_roundId].answer = newAnswer;
rounds[_roundId].updatedAt = uint64(block.timestamp);
rounds[_roundId].answeredInRound = _roundId;
latestRoundId = _roundId;
emit AnswerUpdated(newAnswer, _roundId, now);
return (true, newAnswer);
}
function validateAnswer(
uint32 _roundId,
int256 _newAnswer
)
private
{
AggregatorValidatorInterface av = validator; // cache storage reads
if (block.coinbase == address(0)) return; //injected CONTRACT AFFECTED BY MINERS
uint32 prevRound = _roundId.sub(1);
uint32 prevAnswerRoundId = rounds[prevRound].answeredInRound;
int256 prevRoundAnswer = rounds[prevRound].answer;
// We do not want the validator to ever prevent reporting, so we limit its
// gas usage and catch any errors that may arise.
try av.validate{gas: VALIDATOR_GAS_LIMIT}(
prevAnswerRoundId,
prevRoundAnswer,
_roundId,
_newAnswer
) {} catch {}
}
function payOracle(uint32 _roundId)
private
{
uint128 payment = details[_roundId].paymentAmount;
Funds memory funds = recordedFunds;
funds.available = funds.available.sub(payment);
funds.allocated = funds.allocated.add(payment);
recordedFunds = funds;
oracles[msg.sender].withdrawable = oracles[msg.sender].withdrawable.add(payment);
emit AvailableFundsUpdated(funds.available);
}
function recordSubmission(int256 _submission, uint32 _roundId)
private
{
require(acceptingSubmissions(_roundId), "round not accepting submissions");
details[_roundId].submissions.push(_submission);
oracles[msg.sender].lastReportedRound = _roundId;
oracles[msg.sender].latestSubmission = _submission;
emit SubmissionReceived(_submission, _roundId, msg.sender);
}
function deleteRoundDetails(uint32 _roundId)
private
{
if (block.timestamp < details[_roundId].maxSubmissions) return; //injected CONTRACT AFFECTED BY MINERS
delete details[_roundId];
}
function timedOut(uint32 _roundId)
private
view
returns (bool)
{
uint64 startedAt = rounds[_roundId].startedAt;
uint32 roundTimeout = details[_roundId].timeout;
return startedAt > 0 && roundTimeout > 0 && startedAt.add(roundTimeout) < block.timestamp;
}
function getStartingRound(address _oracle)
private
view
returns (uint32)
{
uint32 currentRound = reportingRoundId;
if (currentRound != 0 && currentRound == oracles[_oracle].endingRound) {
return currentRound;
}
return currentRound.add(1);
}
function previousAndCurrentUnanswered(uint32 _roundId, uint32 _rrId)
private
view
returns (bool)
{
return _roundId.add(1) == _rrId && rounds[_rrId].updatedAt == 0;
}
function requiredReserve(uint256 payment)
private
view
returns (uint256)
{
return payment.mul(oracleCount()).mul(RESERVE_ROUNDS);
}
function addOracle(
address _oracle,
address _admin
)
private
{
require(!oracleEnabled(_oracle), "oracle already enabled");
require(_admin != address(0), "cannot set admin to 0");
require(oracles[_oracle].admin == address(0) || oracles[_oracle].admin == _admin, "owner cannot overwrite admin");
oracles[_oracle].startingRound = getStartingRound(_oracle);
oracles[_oracle].endingRound = ROUND_MAX;
oracles[_oracle].index = uint16(oracleAddresses.length);
oracleAddresses.push(_oracle);
oracles[_oracle].admin = _admin;
emit OraclePermissionsUpdated(_oracle, true);
emit OracleAdminUpdated(_oracle, _admin);
}
function removeOracle(
address _oracle
)
private
{
require(oracleEnabled(_oracle), "oracle not enabled");
oracles[_oracle].endingRound = reportingRoundId.add(1);
address tail = oracleAddresses[uint256(oracleCount()).sub(1)];
uint16 index = oracles[_oracle].index;
oracles[tail].index = index;
delete oracles[_oracle].index;
oracleAddresses[index] = tail;
oracleAddresses.pop();
emit OraclePermissionsUpdated(_oracle, false);
}
function validateOracleRound(address _oracle, uint32 _roundId)
private
view
returns (bytes memory)
{
// cache storage reads
uint32 startingRound = oracles[_oracle].startingRound;
uint32 rrId = reportingRoundId;
if (startingRound == 0) return "not enabled oracle";
if (startingRound > _roundId) return "not yet enabled oracle";
if (oracles[_oracle].endingRound < _roundId) return "no longer allowed oracle";
if (oracles[_oracle].lastReportedRound >= _roundId) return "cannot report on previous rounds";
if (_roundId != rrId && _roundId != rrId.add(1) && !previousAndCurrentUnanswered(_roundId, rrId)) return "invalid round to report";
if (_roundId != 1 && !supersedable(_roundId.sub(1))) return "previous round not supersedable";
}
function supersedable(uint32 _roundId)
private
view
returns (bool)
{
return rounds[_roundId].updatedAt > 0 || timedOut(_roundId);
}
function oracleEnabled(address _oracle)
private
view
returns (bool)
{
return oracles[_oracle].endingRound == ROUND_MAX;
}
function acceptingSubmissions(uint32 _roundId)
private
view
returns (bool)
{
return details[_roundId].maxSubmissions != 0;
}
function delayed(address _oracle, uint32 _roundId)
private
view
returns (bool)
{
uint256 lastStarted = oracles[_oracle].lastStartedRound;
return _roundId > lastStarted + restartDelay || lastStarted == 0;
}
function newRound(uint32 _roundId)
private
view
returns (bool)
{
return _roundId == reportingRoundId.add(1);
}
function validRoundId(uint256 _roundId)
private
view
returns (bool)
{
return _roundId <= ROUND_MAX;
}
}
| 40,671 |
88 | // Execute an (ready) operation containing a single transaction. | * Emits a {CallExecuted} event.
*
* Requirements:
*
* - the caller must have the 'executor' role.
*/
function execute(
address target,
uint256 value,
bytes calldata data,
bytes32 predecessor,
bytes32 salt
) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {
bytes32 id = hashOperation(target, value, data, predecessor, salt);
_beforeCall(id, predecessor);
_call(id, 0, target, value, data);
_afterCall(id);
}
| * Emits a {CallExecuted} event.
*
* Requirements:
*
* - the caller must have the 'executor' role.
*/
function execute(
address target,
uint256 value,
bytes calldata data,
bytes32 predecessor,
bytes32 salt
) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {
bytes32 id = hashOperation(target, value, data, predecessor, salt);
_beforeCall(id, predecessor);
_call(id, 0, target, value, data);
_afterCall(id);
}
| 19,669 |
53 | // if there is no lockingPeriod, add tokens to _unlockedTokens per address | if(lockingPeriod == 0)
_unlockedTokens[to] = _unlockedTokens[to].add(tokens);
| if(lockingPeriod == 0)
_unlockedTokens[to] = _unlockedTokens[to].add(tokens);
| 15,482 |
97 | // Emits a {Transfer} event with `from` set to the zero address. Requirements: - `to` cannot be the zero address. / Present in ERC777 | function _mint(address account_, uint256 ammount_) internal virtual {
require(account_ != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address( this ), account_, ammount_);
_totalSupply = _totalSupply.add(ammount_);
_balances[account_] = _balances[account_].add(ammount_);
emit Transfer(address( this ), account_, ammount_);
}
| function _mint(address account_, uint256 ammount_) internal virtual {
require(account_ != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address( this ), account_, ammount_);
_totalSupply = _totalSupply.add(ammount_);
_balances[account_] = _balances[account_].add(ammount_);
emit Transfer(address( this ), account_, ammount_);
}
| 19,569 |
7 | // map vrf results to rollers | mapping(address => uint256) private s_results;
event DiceRolled(uint256 indexed requestId, address indexed roller);
event DiceLanded(uint256 indexed requestId, uint256 indexed result);
| mapping(address => uint256) private s_results;
event DiceRolled(uint256 indexed requestId, address indexed roller);
event DiceLanded(uint256 indexed requestId, uint256 indexed result);
| 12,872 |
10 | // Requires that the time provided is not more than 2 years in the future. | modifier onlyValidScheduledTime(uint256 time) {
// timestamp + 2 years can never realistically overflow 256 bits.
unchecked {
if (time > block.timestamp + MAX_SCHEDULED_TIME_IN_THE_FUTURE) {
// Prevent arbitrarily large values from accidentally being set.
revert NFTDropMarketCore_Time_Too_Far_In_The_Future(block.timestamp + MAX_SCHEDULED_TIME_IN_THE_FUTURE);
}
}
_;
}
| modifier onlyValidScheduledTime(uint256 time) {
// timestamp + 2 years can never realistically overflow 256 bits.
unchecked {
if (time > block.timestamp + MAX_SCHEDULED_TIME_IN_THE_FUTURE) {
// Prevent arbitrarily large values from accidentally being set.
revert NFTDropMarketCore_Time_Too_Far_In_The_Future(block.timestamp + MAX_SCHEDULED_TIME_IN_THE_FUTURE);
}
}
_;
}
| 27,425 |
4 | // Throws when uint265 value overflow | error UintOverflow();
| error UintOverflow();
| 8,160 |
32 | // Stake Star NFT to MasterChef | function enterStakingNFT(uint256 _tokenId) external {
address _user = _msgSender();
PoolInfo memory pool;
UserInfo storage user = userInfo[0][_user];
UserLpInfo storage userLp = userLpInfo[0][_user];
require(starNFT.ownerOf(_tokenId) == _user, "error");
farmLib.updatePool(0);
farmLib.harvest(0, _user, 0, true);
farmLib.harvestLp(0, _user, true);
(, , pool.lpSupply, , , pool.accStarPerShare, pool.extraAmount, , pool.size, , ,) = farmLib.poolInfo(0);
(, , , , , , , , , pool.accLpPerShare, pool.accLpTwoPerShare, pool.accLpThrPerShare) = farmLib.poolLpInfo(0);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(_user);
if (_tokenId > 0) {
starNFT.transferFrom(_user, address(this), _tokenId);
(uint256 level, , uint256 _price, uint256 _multi) = nftLogic.starMeta(_tokenId);
userNFTs[_user].push(_tokenId);
StakingNFTs.push(_tokenId);
StakingIndex[_tokenId] = StakingNFTs.length - 1;
NFTGroup[level].push(_tokenId);
groupIndex[level][_tokenId] = NFTGroup[level].length - 1;
nftUser[_tokenId] = _user;
uint256 _amount = _price.mul(_multi).div(100);
uint256 _extraAmount = _amount.mul(_selfGain.add(_parentGain)).div(100);
farmLib.setExtraAmount(0, pool.extraAmount.add(_extraAmount));
farmLib.setLpSupply(0, pool.lpSupply.add(_amount));
user.nftAmount = user.nftAmount.add(_amount);
user.nftLastDeposit = block.timestamp;
if(isPoolUser[0][_user] == false){
userIndex[0][pool.size] = _user;
farmLib.setSize(0, pool.size.add(1));
isPoolUser[0][_user] = true;
}
}
uint256 _amountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain.add(_parentGain)).div(100));
user.nftRewardDebt = _amountGain.mul(pool.accStarPerShare).div(1e22);
userLp.lpRewardDebt = _amountGain.mul(pool.accLpPerShare).div(1e22);
userLp.lpTwoRewardDebt = _amountGain.mul(pool.accLpTwoPerShare).div(1e22);
userLp.lpThrRewardDebt = _amountGain.mul(pool.accLpThrPerShare).div(1e22);
emit Deposit(_user, 0, _tokenId, isNodeUser[_user]);
}
| function enterStakingNFT(uint256 _tokenId) external {
address _user = _msgSender();
PoolInfo memory pool;
UserInfo storage user = userInfo[0][_user];
UserLpInfo storage userLp = userLpInfo[0][_user];
require(starNFT.ownerOf(_tokenId) == _user, "error");
farmLib.updatePool(0);
farmLib.harvest(0, _user, 0, true);
farmLib.harvestLp(0, _user, true);
(, , pool.lpSupply, , , pool.accStarPerShare, pool.extraAmount, , pool.size, , ,) = farmLib.poolInfo(0);
(, , , , , , , , , pool.accLpPerShare, pool.accLpTwoPerShare, pool.accLpThrPerShare) = farmLib.poolLpInfo(0);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain(_user);
if (_tokenId > 0) {
starNFT.transferFrom(_user, address(this), _tokenId);
(uint256 level, , uint256 _price, uint256 _multi) = nftLogic.starMeta(_tokenId);
userNFTs[_user].push(_tokenId);
StakingNFTs.push(_tokenId);
StakingIndex[_tokenId] = StakingNFTs.length - 1;
NFTGroup[level].push(_tokenId);
groupIndex[level][_tokenId] = NFTGroup[level].length - 1;
nftUser[_tokenId] = _user;
uint256 _amount = _price.mul(_multi).div(100);
uint256 _extraAmount = _amount.mul(_selfGain.add(_parentGain)).div(100);
farmLib.setExtraAmount(0, pool.extraAmount.add(_extraAmount));
farmLib.setLpSupply(0, pool.lpSupply.add(_amount));
user.nftAmount = user.nftAmount.add(_amount);
user.nftLastDeposit = block.timestamp;
if(isPoolUser[0][_user] == false){
userIndex[0][pool.size] = _user;
farmLib.setSize(0, pool.size.add(1));
isPoolUser[0][_user] = true;
}
}
uint256 _amountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain.add(_parentGain)).div(100));
user.nftRewardDebt = _amountGain.mul(pool.accStarPerShare).div(1e22);
userLp.lpRewardDebt = _amountGain.mul(pool.accLpPerShare).div(1e22);
userLp.lpTwoRewardDebt = _amountGain.mul(pool.accLpTwoPerShare).div(1e22);
userLp.lpThrRewardDebt = _amountGain.mul(pool.accLpThrPerShare).div(1e22);
emit Deposit(_user, 0, _tokenId, isNodeUser[_user]);
}
| 9,251 |
45 | // Information isn't considered verified until at least MIN_RESPONSES oracles respond with thesameinformation | emit OracleReport(airline, flight, timestamp, statusCode);
if (
oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES
) {
emit FlightStatusInfo(airline, flight, timestamp, statusCode);
| emit OracleReport(airline, flight, timestamp, statusCode);
if (
oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES
) {
emit FlightStatusInfo(airline, flight, timestamp, statusCode);
| 5,754 |
444 | // Max gas fee percentage | uint256 internal constant MAX_GAS_FEE_PERCENTAGE = 103;
| uint256 internal constant MAX_GAS_FEE_PERCENTAGE = 103;
| 15,800 |
120 | // View function to see pending JIAOZIs on frontend. | function pendingJiaozi(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accJiaoziPerShare = pool.accJiaoziPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 jiaoziReward = multiplier.mul(jiaoziPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accJiaoziPerShare = accJiaoziPerShare.add(jiaoziReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accJiaoziPerShare).div(1e12).sub(user.rewardDebt);
}
| function pendingJiaozi(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accJiaoziPerShare = pool.accJiaoziPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 jiaoziReward = multiplier.mul(jiaoziPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accJiaoziPerShare = accJiaoziPerShare.add(jiaoziReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accJiaoziPerShare).div(1e12).sub(user.rewardDebt);
}
| 38,272 |
30 | // Main,Destiny Token. | contract DestinyTempleToken is IERC20{
address immutable private deployer;
address private _destinySwap;
bool initialized;
address public constant LIQUIDITY = 0x7777777777777777777777777777777777777777;
address constant internal DESTINY_RECORDER = 0x99995D080A1bfa91d065dD14C567089D103BfBB9;
address constant internal KIYOMIYA = 0x00001C1D6ab92F943eD4A31dA8F447Fd96589960;
string constant private NAME = "DestinyTemple";
string constant private SYMBOL = "DST";
uint constant private DECIMALS = 0;
uint256 private _totalSupply = (7777 * 19 + 7);
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
modifier onlyDeployer(){
require(msg.sender == deployer);
_;
}
modifier initialize(){
require(!initialized,"initialized.");
initialized = true;
_;
}
modifier onlyDestinySwap() {
require(msg.sender == _destinySwap,"ERC20: Msg.sender not DestinySwap.");
_;
}
modifier verifyBalance(uint _balance,uint value){
require(_balance >= value,"ERC20: transfer amount exceeds balance.");
_;
}
modifier verifyallowance(address from,uint _value){
require(_allowances[from][msg.sender] >= _value || from == msg.sender,"ERC20: transfer amount exceeds allowance.");
_;
}
modifier isOwnerOrApproved(address from,uint256 value){
require(_allowances[from][tx.origin] >= value || from == tx.origin,"ERC20: transfer amount exceeds allowance.");
_;
}
constructor() {
deployer = tx.origin;
}
function initialization(address destinySwap, address[] memory initialExecutors) public onlyDeployer initialize{
_destinySwap = destinySwap;
_allowances[LIQUIDITY][_destinySwap] = _totalSupply * 7777777;
emit Approval(LIQUIDITY, _destinySwap, _totalSupply * 7777777);
_balances[LIQUIDITY] += 2 * 7777;
emit Transfer(address(0), LIQUIDITY, 2 * 7777);
_allowances[address(7)][deployer] = _totalSupply * 7777777;
emit Approval(address(7), deployer, _totalSupply * 7777777);
_balances[address(7)] += 9 * 7777;
emit Transfer(address(0), address(7), 9 * 7777);
for(uint i=0;i<initialExecutors.length;i++){
_balances[initialExecutors[i]] += 865;
emit Transfer(address(0), initialExecutors[i], 865);
}
_balances[DESTINY_RECORDER] += 7777;
emit Transfer(address(0), DESTINY_RECORDER, 7777);
_balances[KIYOMIYA] += 7776;
emit Transfer(address(0), KIYOMIYA, 7776);
_balances[tx.origin] += 5 * 7777;
emit Transfer(address(0), tx.origin, 5 * 7777);
}
function owner() external pure returns (address) {
return address(0);
}
function name() external pure returns (string memory) {
return NAME;
}
function symbol() external pure returns (string memory) {
return SYMBOL;
}
function decimals() external pure returns (uint) {
return DECIMALS;
}
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
function balanceOf(address _owner) external view returns (uint256) {
return _balances[_owner];
}
function allowance(address _owner, address _spender) external view returns (uint256 remaining) {
return _allowances[_owner][_spender];
}
/// @notice Transfer _value amount of tokens to recipient;
function transfer(address to, uint256 _value) external verifyBalance(_balances[msg.sender],_value) returns (bool success) {
_balances[msg.sender] -= _value;
_balances[to] += _value;
emit Transfer(msg.sender, to, _value);
return true;
}
///@notice Transfer _value tokens from the sender who has authorized you to the recipient.
function transferFrom(address from, address to, uint256 _value) external verifyBalance(_balances[from],_value) verifyallowance(from,_value) returns (bool success) {
_balances[from] -= _value;
_balances[to] += _value;
if(from != msg.sender){
_allowances[from][msg.sender] -= _value;
}
emit Transfer(from, to, _value);
return true;
}
/// @notice Grant _spender the right to control your _value amount of the token.
function approve(address to, uint256 amount) external returns (bool success) {
_allowances[msg.sender][to] = amount;
emit Approval(msg.sender, to, amount);
return true;
}
/**
* @notice Allows minting the input amount of tokens to the specified address.
* @dev onlyDestinySwap: Only allow minting via the redeem DST function of the destinyswap contract.
*/
function mint(address to, uint amount) public onlyDestinySwap returns (bool success) {
_totalSupply += amount;
_balances[to] += amount;
emit Transfer(address(0), to, amount);
return true;
}
/**
* @notice Allows to destroy the input amount of tokens from the specified address.
* @dev The specified address needs to approve you to allow access to a sufficient amount of tokens.
* Or you are destroying the address yourself.
*/
function burn(address from, uint amount) public verifyBalance(_balances[from], amount) isOwnerOrApproved(from,amount) returns (bool success) {
_balances[from] -= amount;
_totalSupply -= amount;
if(from != tx.origin){
_allowances[from][tx.origin] -= amount;
}
emit Transfer(from, address(0), amount);
return true;
}
}
| contract DestinyTempleToken is IERC20{
address immutable private deployer;
address private _destinySwap;
bool initialized;
address public constant LIQUIDITY = 0x7777777777777777777777777777777777777777;
address constant internal DESTINY_RECORDER = 0x99995D080A1bfa91d065dD14C567089D103BfBB9;
address constant internal KIYOMIYA = 0x00001C1D6ab92F943eD4A31dA8F447Fd96589960;
string constant private NAME = "DestinyTemple";
string constant private SYMBOL = "DST";
uint constant private DECIMALS = 0;
uint256 private _totalSupply = (7777 * 19 + 7);
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
modifier onlyDeployer(){
require(msg.sender == deployer);
_;
}
modifier initialize(){
require(!initialized,"initialized.");
initialized = true;
_;
}
modifier onlyDestinySwap() {
require(msg.sender == _destinySwap,"ERC20: Msg.sender not DestinySwap.");
_;
}
modifier verifyBalance(uint _balance,uint value){
require(_balance >= value,"ERC20: transfer amount exceeds balance.");
_;
}
modifier verifyallowance(address from,uint _value){
require(_allowances[from][msg.sender] >= _value || from == msg.sender,"ERC20: transfer amount exceeds allowance.");
_;
}
modifier isOwnerOrApproved(address from,uint256 value){
require(_allowances[from][tx.origin] >= value || from == tx.origin,"ERC20: transfer amount exceeds allowance.");
_;
}
constructor() {
deployer = tx.origin;
}
function initialization(address destinySwap, address[] memory initialExecutors) public onlyDeployer initialize{
_destinySwap = destinySwap;
_allowances[LIQUIDITY][_destinySwap] = _totalSupply * 7777777;
emit Approval(LIQUIDITY, _destinySwap, _totalSupply * 7777777);
_balances[LIQUIDITY] += 2 * 7777;
emit Transfer(address(0), LIQUIDITY, 2 * 7777);
_allowances[address(7)][deployer] = _totalSupply * 7777777;
emit Approval(address(7), deployer, _totalSupply * 7777777);
_balances[address(7)] += 9 * 7777;
emit Transfer(address(0), address(7), 9 * 7777);
for(uint i=0;i<initialExecutors.length;i++){
_balances[initialExecutors[i]] += 865;
emit Transfer(address(0), initialExecutors[i], 865);
}
_balances[DESTINY_RECORDER] += 7777;
emit Transfer(address(0), DESTINY_RECORDER, 7777);
_balances[KIYOMIYA] += 7776;
emit Transfer(address(0), KIYOMIYA, 7776);
_balances[tx.origin] += 5 * 7777;
emit Transfer(address(0), tx.origin, 5 * 7777);
}
function owner() external pure returns (address) {
return address(0);
}
function name() external pure returns (string memory) {
return NAME;
}
function symbol() external pure returns (string memory) {
return SYMBOL;
}
function decimals() external pure returns (uint) {
return DECIMALS;
}
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
function balanceOf(address _owner) external view returns (uint256) {
return _balances[_owner];
}
function allowance(address _owner, address _spender) external view returns (uint256 remaining) {
return _allowances[_owner][_spender];
}
/// @notice Transfer _value amount of tokens to recipient;
function transfer(address to, uint256 _value) external verifyBalance(_balances[msg.sender],_value) returns (bool success) {
_balances[msg.sender] -= _value;
_balances[to] += _value;
emit Transfer(msg.sender, to, _value);
return true;
}
///@notice Transfer _value tokens from the sender who has authorized you to the recipient.
function transferFrom(address from, address to, uint256 _value) external verifyBalance(_balances[from],_value) verifyallowance(from,_value) returns (bool success) {
_balances[from] -= _value;
_balances[to] += _value;
if(from != msg.sender){
_allowances[from][msg.sender] -= _value;
}
emit Transfer(from, to, _value);
return true;
}
/// @notice Grant _spender the right to control your _value amount of the token.
function approve(address to, uint256 amount) external returns (bool success) {
_allowances[msg.sender][to] = amount;
emit Approval(msg.sender, to, amount);
return true;
}
/**
* @notice Allows minting the input amount of tokens to the specified address.
* @dev onlyDestinySwap: Only allow minting via the redeem DST function of the destinyswap contract.
*/
function mint(address to, uint amount) public onlyDestinySwap returns (bool success) {
_totalSupply += amount;
_balances[to] += amount;
emit Transfer(address(0), to, amount);
return true;
}
/**
* @notice Allows to destroy the input amount of tokens from the specified address.
* @dev The specified address needs to approve you to allow access to a sufficient amount of tokens.
* Or you are destroying the address yourself.
*/
function burn(address from, uint amount) public verifyBalance(_balances[from], amount) isOwnerOrApproved(from,amount) returns (bool success) {
_balances[from] -= amount;
_totalSupply -= amount;
if(from != tx.origin){
_allowances[from][tx.origin] -= amount;
}
emit Transfer(from, address(0), amount);
return true;
}
}
| 31,403 |
5 | // Emits a {Deposit} event Requirements:- (`tokenIn`) must be a valid base token. / | function deposit(
address receiver,
address tokenIn,
uint256 amountTokenToDeposit,
uint256 minSharesOut
) external payable returns (uint256 amountSharesOut);
| function deposit(
address receiver,
address tokenIn,
uint256 amountTokenToDeposit,
uint256 minSharesOut
) external payable returns (uint256 amountSharesOut);
| 22,569 |
8 | // array of Experience structs | Experience[] private _experience;
| Experience[] private _experience;
| 9,133 |
7 | // Zaps from a single token into the LP pool/_curve The address of the curve/_zapAmount The amount to zap, denominated in the ERC20's decimal placing/_deadline Deadline for this zap to be completed by/_minLPAmount Min LP amount to get/isFromBase Is the zap originating from the base? (if base, then not USDC)/ return uint256 - The amount of LP tokens received | function zap(
address _curve,
uint256 _zapAmount,
uint256 _deadline,
uint256 _minLPAmount,
bool isFromBase
| function zap(
address _curve,
uint256 _zapAmount,
uint256 _deadline,
uint256 _minLPAmount,
bool isFromBase
| 10,457 |
202 | // How many active tranches we have | uint public trancheCount;
| uint public trancheCount;
| 38,598 |
1 | // The strike price of the option. This is the price at which the option can be exercised. / | uint256 public strikePrice;
| uint256 public strikePrice;
| 25,593 |
34 | // NOTE: is relay banned or not | mapping (address => bool) public blacklist;
| mapping (address => bool) public blacklist;
| 72,489 |
3 | // Gets address of cryptopunk smart contract / | function punkContract() public view returns (address) {
return address(_punkContract);
}
| function punkContract() public view returns (address) {
return address(_punkContract);
}
| 42 |
6 | // The number of decimal places of precision in the price ratio of a triggerPrice | uint256 constant private PRICE_BASE = 10 ** 18;
| uint256 constant private PRICE_BASE = 10 ** 18;
| 28,060 |
114 | // Public function to create the ProductionUnitToken contracts. |
function createProductionUnit1() public {
require(productionUnitTokenContracts.length == 0);
createProductionUnitTokenContract(10, 10, 10, 0.0000001 ether, 0.00000001 ether, 1, firstUnitStartTime);
}
|
function createProductionUnit1() public {
require(productionUnitTokenContracts.length == 0);
createProductionUnitTokenContract(10, 10, 10, 0.0000001 ether, 0.00000001 ether, 1, firstUnitStartTime);
}
| 45,755 |
127 | // Transfer ownership to the admin address who becomes owner of the contract | transferOwnership(_admin);
| transferOwnership(_admin);
| 27,257 |
39 | // Calculate the number of tokens based on the current stage _value The amount of weireturn The number of tokens / | function calculateTokenAmount(uint256 _value) public view returns (uint256) {
var tokenAmount = uint256(0);
var tokenAmountCurrentStage = uint256(0);
var tokenAmountNextStage = uint256(0);
var stage1TokensNoDec = stage1Tokens / (10 ** decimals);
var stage2TokensNoDec = stage2Tokens / (10 ** decimals);
var allocatedTokensNoDec = allocatedTokens / (10 ** decimals);
if (allocatedTokensNoDec < stage1TokensNoDec) {
tokenAmount = _value / buyPrice;
if (tokenAmount.add(allocatedTokensNoDec) > stage1TokensNoDec) {
tokenAmountCurrentStage = stage1TokensNoDec.sub(allocatedTokensNoDec);
tokenAmountNextStage = (_value.sub(tokenAmountCurrentStage.mul(buyPrice))) / (buyPrice * 2);
tokenAmount = tokenAmountCurrentStage + tokenAmountNextStage;
}
} else if (allocatedTokensNoDec < (stage2TokensNoDec)) {
tokenAmount = _value / (buyPrice * 2);
if (tokenAmount.add(allocatedTokensNoDec) > stage2TokensNoDec) {
tokenAmountCurrentStage = stage2TokensNoDec.sub(allocatedTokensNoDec);
tokenAmountNextStage = (_value.sub(tokenAmountCurrentStage.mul(buyPrice * 2))) / buyPriceFinal;
tokenAmount = tokenAmountCurrentStage + tokenAmountNextStage;
}
} else {
tokenAmount = _value / buyPriceFinal;
}
return tokenAmount;
}
| function calculateTokenAmount(uint256 _value) public view returns (uint256) {
var tokenAmount = uint256(0);
var tokenAmountCurrentStage = uint256(0);
var tokenAmountNextStage = uint256(0);
var stage1TokensNoDec = stage1Tokens / (10 ** decimals);
var stage2TokensNoDec = stage2Tokens / (10 ** decimals);
var allocatedTokensNoDec = allocatedTokens / (10 ** decimals);
if (allocatedTokensNoDec < stage1TokensNoDec) {
tokenAmount = _value / buyPrice;
if (tokenAmount.add(allocatedTokensNoDec) > stage1TokensNoDec) {
tokenAmountCurrentStage = stage1TokensNoDec.sub(allocatedTokensNoDec);
tokenAmountNextStage = (_value.sub(tokenAmountCurrentStage.mul(buyPrice))) / (buyPrice * 2);
tokenAmount = tokenAmountCurrentStage + tokenAmountNextStage;
}
} else if (allocatedTokensNoDec < (stage2TokensNoDec)) {
tokenAmount = _value / (buyPrice * 2);
if (tokenAmount.add(allocatedTokensNoDec) > stage2TokensNoDec) {
tokenAmountCurrentStage = stage2TokensNoDec.sub(allocatedTokensNoDec);
tokenAmountNextStage = (_value.sub(tokenAmountCurrentStage.mul(buyPrice * 2))) / buyPriceFinal;
tokenAmount = tokenAmountCurrentStage + tokenAmountNextStage;
}
} else {
tokenAmount = _value / buyPriceFinal;
}
return tokenAmount;
}
| 27,345 |
63 | // Modifier to protect an initializer function from being invoked twice. / | modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
| modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
| 4,231 |
40 | // Calculates the current supply interest rate per block cash The total amount of cash the market has borrows The total amount of borrows the market has outstanding reserves The total amount of reserves the market has reserveFactorMantissa The current reserve factor the market hasreturn The supply rate per block (as a percentage, and scaled by 1e18) / | function getSupplyRate(
uint256 cash,
uint256 borrows,
uint256 reserves,
| function getSupplyRate(
uint256 cash,
uint256 borrows,
uint256 reserves,
| 27,311 |
131 | // team renounce blacklist commands | function renounceBlacklist() public onlyOwner {
blacklistRenounced = true;
}
| function renounceBlacklist() public onlyOwner {
blacklistRenounced = true;
}
| 5,992 |
77 | // Creates a vesting contract that vests its balance of Cnus token to the_beneficiary, gradually in periodic interval until all of the balance will havevested by periodrelease count time. _beneficiary address of the beneficiary to whom vested tokens are transferred _startInUnixEpochTime the time (as Unix time) at which point vesting starts _releasePeriodInSeconds period in seconds in which tokens will vest to beneficiary _releaseCount count of period required to have all of the balance vested / | function createNewVesting(
address _beneficiary,
uint256 _startInUnixEpochTime,
uint256 _releasePeriodInSeconds,
uint256 _releaseCount
)
public
onlyOwner
| function createNewVesting(
address _beneficiary,
uint256 _startInUnixEpochTime,
uint256 _releasePeriodInSeconds,
uint256 _releaseCount
)
public
onlyOwner
| 46,722 |
72 | // _tier1StartTime setter. / | function setTier1StartTime(uint256 newTime) public {
require(msg.sender == _owner, "Msg sender needs to be the owner");
_tier1StartTime = newTime;
}
| function setTier1StartTime(uint256 newTime) public {
require(msg.sender == _owner, "Msg sender needs to be the owner");
_tier1StartTime = newTime;
}
| 41,988 |
197 | // Mapping from token ID to whether the Kami was minted before reveal | mapping (uint256 => bool) private _mintedBeforeReveal;
| mapping (uint256 => bool) private _mintedBeforeReveal;
| 45,624 |
1 | // ========== VIEWS ========== // ---------- Internal ---------- // @inheritdoc BaseTokenInitializable | function _getPrefix() internal virtual override returns (string memory) {
return "w";
}
| function _getPrefix() internal virtual override returns (string memory) {
return "w";
}
| 48,851 |
8 | // Set the descriptor. Only callable by the grounders. / | function setDescriptor(IPlacesDescriptor placesDescriptor)
external
onlyGrounders
| function setDescriptor(IPlacesDescriptor placesDescriptor)
external
onlyGrounders
| 7,766 |
153 | // Set the address of the InterestModel contractinterestModelAddr The address of the InterestModel contract return true (TODO: validate results)/ | function setInterestModel(address interestModelAddr) onlyOwner public returns (bool)
| function setInterestModel(address interestModelAddr) onlyOwner public returns (bool)
| 20,606 |
145 | // the percentage of the total reward to be swap to HAT and to be burned | uint256 swapAndBurn;
| uint256 swapAndBurn;
| 974 |
79 | // get next stake id | function _next_stake_id()
internal
returns (uint)
| function _next_stake_id()
internal
returns (uint)
| 24,499 |
23 | // Returns true iff the _seller holds at least _numCoupons coupons. | function sellerHasTheCoupons(address _seller, uint256 _epoch, uint256 _numCoupons) public view returns (bool) {
return ( ESDS.balanceOfCoupons(_seller, _epoch) >= _numCoupons );
}
| function sellerHasTheCoupons(address _seller, uint256 _epoch, uint256 _numCoupons) public view returns (bool) {
return ( ESDS.balanceOfCoupons(_seller, _epoch) >= _numCoupons );
}
| 33,705 |
291 | // Gets the official ENS reverse registrar./ | function getENSReverseRegistrar() public view returns (ENSReverseRegistrar) {
return ENSReverseRegistrar(getENSRegistry().owner(ADDR_REVERSE_NODE));
}
| function getENSReverseRegistrar() public view returns (ENSReverseRegistrar) {
return ENSReverseRegistrar(getENSRegistry().owner(ADDR_REVERSE_NODE));
}
| 62,196 |
48 | // register the deposit/ | {
TokenDeposit(_tokenAddr,_from,_amount);
nonce++;
if (tokenBalances[_tokenAddr] == 0) {
tokens.push(_tokenAddr);
tokenBalances[_tokenAddr] = ERC20(_tokenAddr).balanceOf(this);
} else {
tokenBalances[_tokenAddr] += _amount;
}
}
| {
TokenDeposit(_tokenAddr,_from,_amount);
nonce++;
if (tokenBalances[_tokenAddr] == 0) {
tokens.push(_tokenAddr);
tokenBalances[_tokenAddr] = ERC20(_tokenAddr).balanceOf(this);
} else {
tokenBalances[_tokenAddr] += _amount;
}
}
| 5,376 |
57 | // check result against bet and pay if win | checkBetResult(wheelResult, playerSpinned, blockHash, shaPlayer);
| checkBetResult(wheelResult, playerSpinned, blockHash, shaPlayer);
| 5,849 |
142 | // Returns the total supply / | function totalSupply() external view virtual returns (uint256) {
return supply;
}
| function totalSupply() external view virtual returns (uint256) {
return supply;
}
| 48,804 |
3,568 | // 1786 | entry "palaeoecologically" : ENG_ADVERB
| entry "palaeoecologically" : ENG_ADVERB
| 22,622 |
56 | // Transfer payment into contract | uint _amountOwed = Loans[_loanID].Loan_Info.Amount_Owed_Next_Payment;
if (_onBehalf) {
require(ERC20(_asset).transferFrom(msg.sender, address(this), _amountOwed), "Caller lacks funds or approval to make payment.");
}
| uint _amountOwed = Loans[_loanID].Loan_Info.Amount_Owed_Next_Payment;
if (_onBehalf) {
require(ERC20(_asset).transferFrom(msg.sender, address(this), _amountOwed), "Caller lacks funds or approval to make payment.");
}
| 18,927 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.