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
49
// to change autoLP threshold, GAS savings
function setLiquityAddThreshold(uint256 threshold) external onlyOwner { addLiquityThresholdETH = threshold; }
function setLiquityAddThreshold(uint256 threshold) external onlyOwner { addLiquityThresholdETH = threshold; }
42,401
28
// random number generation
uint256 public randomNumber; // for debugging bytes32 public lastRequestId; uint256 public lastRequestAt; event SwapETHForTokens( uint256 amountIn, address[] path );
uint256 public randomNumber; // for debugging bytes32 public lastRequestId; uint256 public lastRequestAt; event SwapETHForTokens( uint256 amountIn, address[] path );
76,871
11
// Data about the future reward rates. emissionSchedule stored in reverse chronological order, whenever the number of blocks since the start block exceeds the next block offset a new reward rate is applied.
EmissionPoint[] public emissionSchedule;
EmissionPoint[] public emissionSchedule;
12,624
51
// Method for setting royalty/_nftAddress NFT contract address/_royalty Royalty
function registerCollectionRoyalty( address _nftAddress, address _creator, uint16 _royalty, address _feeRecipient
function registerCollectionRoyalty( address _nftAddress, address _creator, uint16 _royalty, address _feeRecipient
16,519
3
// this is not a payable function so we cannot use msg.value or msg.sender
function withdrawFunds(uint amount) ifClient { if (client.send(amount)) { UpdateStatus("User withdraw some money", amount); _switch = true; } else { _switch = false; } }
function withdrawFunds(uint amount) ifClient { if (client.send(amount)) { UpdateStatus("User withdraw some money", amount); _switch = true; } else { _switch = false; } }
20,699
26
// ---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers ----------------------------------------------------------------------------
contract ADZbuzzCommunityToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function ADZbuzzCommunityToken() public { symbol = "ACT125845"; name = "ADZbuzz Medicalnewstoday.com Community Token"; decimals = 8; _totalSupply = 200000000000000; balances[0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187] = _totalSupply; emit Transfer(address(0), 0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
contract ADZbuzzCommunityToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function ADZbuzzCommunityToken() public { symbol = "ACT125845"; name = "ADZbuzz Medicalnewstoday.com Community Token"; decimals = 8; _totalSupply = 200000000000000; balances[0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187] = _totalSupply; emit Transfer(address(0), 0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
1,399
23
// Change royalty address
function setRoyaltyAddress(address addr) external onlyOwner { royaltyAddress = addr; emit RoyaltyAddressUpdated(addr); }
function setRoyaltyAddress(address addr) external onlyOwner { royaltyAddress = addr; emit RoyaltyAddressUpdated(addr); }
25,417
140
// Assigns rewards and sets a new monthly rate for the geenral commitee bootstrap.
function setGeneralCommitteeAnnualBootstrap(uint256 annual_amount) external /* onlyFunctionalOwner */;
function setGeneralCommitteeAnnualBootstrap(uint256 annual_amount) external /* onlyFunctionalOwner */;
43,050
36
// withdraw tokens from boardroom _amount amount of staked tokens /
function withdraw(uint256 _amount) public override(IBoardroomV2, TokenStoreWrapper) directorExists updateReward(_msgSender())
function withdraw(uint256 _amount) public override(IBoardroomV2, TokenStoreWrapper) directorExists updateReward(_msgSender())
19,315
59
// Creates a checkpoint that can be used to query historical balances / totalSuppy /
function createCheckpoint() public returns(uint256);
function createCheckpoint() public returns(uint256);
46,483
35
// --- EIP712 niceties ---
bytes32 public DOMAIN_SEPARATOR;
bytes32 public DOMAIN_SEPARATOR;
6,036
5
// g2 elements
vk.g2_elements[0] = PairingsBn254.new_g2( [ 0x198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2, 0x1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed ], [ 0x090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b, 0x12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa ] );
vk.g2_elements[0] = PairingsBn254.new_g2( [ 0x198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2, 0x1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed ], [ 0x090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b, 0x12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa ] );
27,736
168
// Events/emitted upon dispute tally
event DisputeVoteTallied( uint256 indexed _disputeID, int256 _result, address indexed _reportedMiner, address _reportingParty, bool _passed ); event StakeWithdrawn(address indexed _sender); //Emits when a staker is block.timestamp no longer staked event StakeWithdrawRequested(address indexed _sender); //Emits when a staker begins the 7 day withdraw period event NewStake(address indexed _sender); //Emits upon new staker
event DisputeVoteTallied( uint256 indexed _disputeID, int256 _result, address indexed _reportedMiner, address _reportingParty, bool _passed ); event StakeWithdrawn(address indexed _sender); //Emits when a staker is block.timestamp no longer staked event StakeWithdrawRequested(address indexed _sender); //Emits when a staker begins the 7 day withdraw period event NewStake(address indexed _sender); //Emits upon new staker
7,344
20
// Proof of oracle iterator contract/Verifies that contract is a oracle iterator contract/ return true if contract is a oracle iterator contract
function isOracleIterator() external pure returns(bool);
function isOracleIterator() external pure returns(bool);
10,428
23
// bonus cap in wei
uint256 private _bonusCap;
uint256 private _bonusCap;
33,526
26
// Oracle types enabled for this asset
uint16 oracleType; CDP cdp;
uint16 oracleType; CDP cdp;
39,761
140
// buy
if(swapV2Pairs[sender]){ _fee = amount * buyFee / 100; }else{
if(swapV2Pairs[sender]){ _fee = amount * buyFee / 100; }else{
22,128
225
// 0. 加载配置
Config memory config = _config;
Config memory config = _config;
30,510
120
// Ensure that the from and to positions are valid positions for a slice within the byte array that is being used.
if (from > to) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired, from, to )); }
if (from > to) { LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError( LibBytesRichErrors.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired, from, to )); }
32,530
39
// Tokens balance /_owner holder address / return balance amount
function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; }
function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; }
10,297
43
// return {uint} number of blocks to mine/validate until this license is considered expired
function blocksRemaining( LicenseStorage storage self )internal view returns( uint ){
function blocksRemaining( LicenseStorage storage self )internal view returns( uint ){
6,446
86
// exclude from paying fees or having max transaction amount, max wallet amount
excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); excludeFromMaxWallet(owner(), true); excludeFromMaxWallet(address(this), true);
excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); excludeFromMaxWallet(owner(), true); excludeFromMaxWallet(address(this), true);
17,383
0
// aToken interface Aegis /
contract ATokenInterface is AegisTokenCommon { bool public constant aToken = true; /** * @notice Emitted when interest is accrued */ event AccrueInterest(uint _cashPrior, uint _interestAccumulated, uint _borrowIndex, uint _totalBorrows); /** * @notice Emitted when tokens are minted */ event Mint(address _minter, uint _mintAmount, uint _mintTokens); /** * @notice Emitted when tokens are redeemed */ event Redeem(address _redeemer, uint _redeemAmount, uint _redeemTokens); /** * @notice Emitted when underlying is borrowed */ event Borrow(address _borrower, uint _borrowAmount, uint _accountBorrows, uint _totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow(address _payer, address _borrower, uint _repayAmount, uint _accountBorrows, uint _totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow(address _liquidator, address _borrower, uint _repayAmount, address _aTokenCollateral, uint _seizeTokens); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address _old, address _new); /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when comptroller is changed */ event NewComptroller(AegisComptrollerInterface _oldComptroller, AegisComptrollerInterface _newComptroller); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketInterestRateModel(InterestRateModel _oldInterestRateModel, InterestRateModel _newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint _oldReserveFactorMantissa, uint _newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address _benefactor, uint _addAmount, uint _newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address _admin, uint _reduceAmount, uint _newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed _from, address indexed _to, uint _amount); /** * @notice EIP20 Approval event */ event Approval(address indexed _owner, address indexed _spender, uint _amount); /** * @notice Failure event */ event Failure(uint _error, uint _info, uint _detail); function transfer(address _dst, uint _amount) external returns (bool); function transferFrom(address _src, address _dst, uint _amount) external returns (bool); function approve(address _spender, uint _amount) external returns (bool); function allowance(address _owner, address _spender) external view returns (uint); function balanceOf(address _owner) external view returns (uint); function balanceOfUnderlying(address _owner) external returns (uint); function getAccountSnapshot(address _account) external view returns (uint, uint, uint, uint); function borrowRatePerBlock() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function totalBorrowsCurrent() external returns (uint); function borrowBalanceCurrent(address _account) external returns (uint); function borrowBalanceStored(address _account) public view returns (uint); function exchangeRateCurrent() public returns (uint); function exchangeRateStored() public view returns (uint); function getCash() external view returns (uint); function accrueInterest() public returns (uint); function seize(address _liquidator, address _borrower, uint _seizeTokens) external returns (uint); function _acceptAdmin() external returns (uint); function _setComptroller(AegisComptrollerInterface _newComptroller) public returns (uint); function _setReserveFactor(uint _newReserveFactorMantissa) external returns (uint); function _reduceReserves(uint _reduceAmount, address payable _account) external returns (uint); function _setInterestRateModel(InterestRateModel _newInterestRateModel) public returns (uint); }
contract ATokenInterface is AegisTokenCommon { bool public constant aToken = true; /** * @notice Emitted when interest is accrued */ event AccrueInterest(uint _cashPrior, uint _interestAccumulated, uint _borrowIndex, uint _totalBorrows); /** * @notice Emitted when tokens are minted */ event Mint(address _minter, uint _mintAmount, uint _mintTokens); /** * @notice Emitted when tokens are redeemed */ event Redeem(address _redeemer, uint _redeemAmount, uint _redeemTokens); /** * @notice Emitted when underlying is borrowed */ event Borrow(address _borrower, uint _borrowAmount, uint _accountBorrows, uint _totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow(address _payer, address _borrower, uint _repayAmount, uint _accountBorrows, uint _totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow(address _liquidator, address _borrower, uint _repayAmount, address _aTokenCollateral, uint _seizeTokens); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address _old, address _new); /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when comptroller is changed */ event NewComptroller(AegisComptrollerInterface _oldComptroller, AegisComptrollerInterface _newComptroller); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketInterestRateModel(InterestRateModel _oldInterestRateModel, InterestRateModel _newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint _oldReserveFactorMantissa, uint _newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address _benefactor, uint _addAmount, uint _newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address _admin, uint _reduceAmount, uint _newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed _from, address indexed _to, uint _amount); /** * @notice EIP20 Approval event */ event Approval(address indexed _owner, address indexed _spender, uint _amount); /** * @notice Failure event */ event Failure(uint _error, uint _info, uint _detail); function transfer(address _dst, uint _amount) external returns (bool); function transferFrom(address _src, address _dst, uint _amount) external returns (bool); function approve(address _spender, uint _amount) external returns (bool); function allowance(address _owner, address _spender) external view returns (uint); function balanceOf(address _owner) external view returns (uint); function balanceOfUnderlying(address _owner) external returns (uint); function getAccountSnapshot(address _account) external view returns (uint, uint, uint, uint); function borrowRatePerBlock() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function totalBorrowsCurrent() external returns (uint); function borrowBalanceCurrent(address _account) external returns (uint); function borrowBalanceStored(address _account) public view returns (uint); function exchangeRateCurrent() public returns (uint); function exchangeRateStored() public view returns (uint); function getCash() external view returns (uint); function accrueInterest() public returns (uint); function seize(address _liquidator, address _borrower, uint _seizeTokens) external returns (uint); function _acceptAdmin() external returns (uint); function _setComptroller(AegisComptrollerInterface _newComptroller) public returns (uint); function _setReserveFactor(uint _newReserveFactorMantissa) external returns (uint); function _reduceReserves(uint _reduceAmount, address payable _account) external returns (uint); function _setInterestRateModel(InterestRateModel _newInterestRateModel) public returns (uint); }
20,990
16
// Apply the Dampening factor.
supplyDelta = supplyDelta.div(rebaseLag.toInt256Safe()); if ( supplyDelta > 0 && uFrags.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY ) { supplyDelta = (MAX_SUPPLY.sub(uFrags.totalSupply())).toInt256Safe(); }
supplyDelta = supplyDelta.div(rebaseLag.toInt256Safe()); if ( supplyDelta > 0 && uFrags.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY ) { supplyDelta = (MAX_SUPPLY.sub(uFrags.totalSupply())).toInt256Safe(); }
38,986
14
// Check for number of increases to start price
uint256 timeDiff = _currentTime.sub(_startTime).div(timeDelta);
uint256 timeDiff = _currentTime.sub(_startTime).div(timeDelta);
44,679
109
// Gets the current day indexreturn day index /
function getDayIndex() internal view returns (uint)
function getDayIndex() internal view returns (uint)
6,435
43
// ^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ _Available since v4.1._ /
modifier onlyRole(bytes32 role) { _checkRole(role); _; }
modifier onlyRole(bytes32 role) { _checkRole(role); _; }
10,094
595
// Amount in SDVD. After hard cap reached, stake ETH will function as normal staking.
uint256 public LGE_HARD_CAP = 200 ether;
uint256 public LGE_HARD_CAP = 200 ether;
45,007
23
// Function to increment the value of a slot in a blob by some amount _slot Slot value. Up to 7 _amount Amout to increment a slot _tokenId Token ID from which to update the blob data /
function incSlot( uint8 _slot, uint256 _amount, uint256 _tokenId
function incSlot( uint8 _slot, uint256 _amount, uint256 _tokenId
9,955
45
// Populate the store owner's storefront record with the details/ Both storefronts (mapping to storefront struct) and/ storefrontIndexes (array of hashes) would be updated accordingly
storefronts[uniqueId].storeOwner = msg.sender; storefronts[uniqueId].index = (storefrontIndexes.push(uniqueId)).sub(1); storefronts[uniqueId].storefrontName = newStorefrontName; storefronts[uniqueId].balance = 0; emit LogCreateStorefront(uniqueId); return (storefrontIndexes.length).sub(1);
storefronts[uniqueId].storeOwner = msg.sender; storefronts[uniqueId].index = (storefrontIndexes.push(uniqueId)).sub(1); storefronts[uniqueId].storefrontName = newStorefrontName; storefronts[uniqueId].balance = 0; emit LogCreateStorefront(uniqueId); return (storefrontIndexes.length).sub(1);
51,726
7
// Override supportsInterface function to resolve conflict
function supportsInterface( bytes4 interfaceId ) public view override( ERC721Upgradeable, ERC721URIStorageUpgradeable, ERC721EnumerableUpgradeable )
function supportsInterface( bytes4 interfaceId ) public view override( ERC721Upgradeable, ERC721URIStorageUpgradeable, ERC721EnumerableUpgradeable )
27,923
47
// Can Set %
function setFeeBurnUnstake(uint256 _percentage) external virtual { if (!_canSetStakeConditions()) { revert("Not authorized"); } require(_percentage <= 100, "Invalid percentage"); feePercentage = _percentage; }
function setFeeBurnUnstake(uint256 _percentage) external virtual { if (!_canSetStakeConditions()) { revert("Not authorized"); } require(_percentage <= 100, "Invalid percentage"); feePercentage = _percentage; }
9,479
8
// if there were previous tax objects then they must have been revoked
if (licenceTaxObjects[_licence_Id].length > 0) { require( taxObjects[licenceTaxObjects[_licence_Id][licenceTaxObjects[_licence_Id].length - 1]].status == TaxObjectStatus.Revoked, "Can only create tax object if previous revoked" ); }
if (licenceTaxObjects[_licence_Id].length > 0) { require( taxObjects[licenceTaxObjects[_licence_Id][licenceTaxObjects[_licence_Id].length - 1]].status == TaxObjectStatus.Revoked, "Can only create tax object if previous revoked" ); }
44,950
45
// Second
second = getSecond(timestamp);
second = getSecond(timestamp);
30,265
50
// KeeperRewardDistributor
error INCORRECT_PART_IN_REWARD();
error INCORRECT_PART_IN_REWARD();
29,190
15
// See {AccessControl-renounceRole}. For the `DEFAULT_ADMIN_ROLE`, it only allows renouncing in two steps by first calling{beginDefaultAdminTransfer} to the `address(0)`, so it's required that the {pendingDefaultAdmin} schedulehas also passed when calling this function. After its execution, it will not be possible to call `onlyRole(DEFAULT_ADMIN_ROLE)` functions. NOTE: Renouncing `DEFAULT_ADMIN_ROLE` will leave the contract without a {defaultAdmin},thereby disabling any functionality that is only available for it, and the possibility of reassigning anon-administrated role. /
function renounceRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) { if (role == DEFAULT_ADMIN_ROLE && account == defaultAdmin()) { (address newDefaultAdmin, uint48 schedule) = pendingDefaultAdmin(); if (newDefaultAdmin != address(0) || !_isScheduleSet(schedule) || !_hasSchedulePassed(schedule)) { revert AccessControlEnforcedDefaultAdminDelay(schedule); }
function renounceRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) { if (role == DEFAULT_ADMIN_ROLE && account == defaultAdmin()) { (address newDefaultAdmin, uint48 schedule) = pendingDefaultAdmin(); if (newDefaultAdmin != address(0) || !_isScheduleSet(schedule) || !_hasSchedulePassed(schedule)) { revert AccessControlEnforcedDefaultAdminDelay(schedule); }
767
5
// Utils Anton /
library StaticCall { function isContract(address what) internal view returns (bool) { uint256 size; assembly { size := extcodesize(what) } return size > 0; } /** * @dev Execute a STATICCALL (introduced with Ethereum Metropolis, non-state-modifying external call) * @param target Contract to call * @param data Calldata (appended to extradata) * @param extradata Base data for STATICCALL (probably function selector and argument encoding) * @return result of the call (success or failure) */ function staticCall( address target, bytes memory data, bytes memory extradata ) internal view returns (bool result) { bytes memory combined = new bytes(data.length + extradata.length); uint256 index; assembly { index := add(combined, 0x20) } index = ArrayUtils.unsafeWriteBytes(index, extradata); ArrayUtils.unsafeWriteBytes(index, data); return staticCall(target, combined); } /** * @dev Execute a STATICCALL (introduced with Ethereum Metropolis, non-state-modifying external call) * @param target Contract to call * @param data Calldata (appended to extradata) * @return result of the call (success or failure) */ function staticCall( address target, bytes memory data ) internal view returns (bool result) { assembly { result := staticcall(gas(), target, add(data, 0x20), mload(data), mload(0x40), 0) } return result; } }
library StaticCall { function isContract(address what) internal view returns (bool) { uint256 size; assembly { size := extcodesize(what) } return size > 0; } /** * @dev Execute a STATICCALL (introduced with Ethereum Metropolis, non-state-modifying external call) * @param target Contract to call * @param data Calldata (appended to extradata) * @param extradata Base data for STATICCALL (probably function selector and argument encoding) * @return result of the call (success or failure) */ function staticCall( address target, bytes memory data, bytes memory extradata ) internal view returns (bool result) { bytes memory combined = new bytes(data.length + extradata.length); uint256 index; assembly { index := add(combined, 0x20) } index = ArrayUtils.unsafeWriteBytes(index, extradata); ArrayUtils.unsafeWriteBytes(index, data); return staticCall(target, combined); } /** * @dev Execute a STATICCALL (introduced with Ethereum Metropolis, non-state-modifying external call) * @param target Contract to call * @param data Calldata (appended to extradata) * @return result of the call (success or failure) */ function staticCall( address target, bytes memory data ) internal view returns (bool result) { assembly { result := staticcall(gas(), target, add(data, 0x20), mload(data), mload(0x40), 0) } return result; } }
13,839
3
// Set number of seconds used for the time window of the UniV3 price oracle
function setTimeWindowLengthSeconds(uint32 _timeWindowLengthSeconds) external onlyOwner { timeWindowLengthSeconds = _timeWindowLengthSeconds; }
function setTimeWindowLengthSeconds(uint32 _timeWindowLengthSeconds) external onlyOwner { timeWindowLengthSeconds = _timeWindowLengthSeconds; }
17,706
118
// Decode an array of fixed16 values from a Witnet.Result as an `int128[]` value./_result An instance of Witnet.Result./ return The `int128[]` decoded from the Witnet.Result.
function asFixed16Array(Witnet.Result memory _result) external pure returns (int32[] memory);
function asFixed16Array(Witnet.Result memory _result) external pure returns (int32[] memory);
54,153
18
// ========== INTERNAL FUNCTIONS ========== /
function _deposit(address asset, uint256 amount) internal { (address pool, address aToken) = _getLendingPoolAndAToken(asset); _tokenApprove(asset, pool, amount); try ILendingPoolV2(pool).deposit( asset, amount, address(this), REFERRAL_CODE ) {} catch Error(string memory reason) { _revertMsg("deposit", reason); } catch { _revertMsg("deposit"); }
function _deposit(address asset, uint256 amount) internal { (address pool, address aToken) = _getLendingPoolAndAToken(asset); _tokenApprove(asset, pool, amount); try ILendingPoolV2(pool).deposit( asset, amount, address(this), REFERRAL_CODE ) {} catch Error(string memory reason) { _revertMsg("deposit", reason); } catch { _revertMsg("deposit"); }
4,004
20
// set pausable methods to unpaused
function unpause() public override onlyGuardianOrGovernor { _unpause(); }
function unpause() public override onlyGuardianOrGovernor { _unpause(); }
23,015
350
// this is the case in which we are starting with two amounts of the same LP asset. we update the first harvestAmount in place to contain the total amount of this asset
tokenAmountsArray[0] = tokenAmountsArray[0] + tokenAmountsArray[1];
tokenAmountsArray[0] = tokenAmountsArray[0] + tokenAmountsArray[1];
15,331
59
// call to stake more KNC for msg.sender amount amount of KNC to stake /
function deposit(uint256 amount) external override { require(amount > 0, "deposit: amount is 0"); uint256 curEpoch = getCurrentEpochNumber(); address staker = msg.sender; // collect KNC token from staker require( kncToken.transferFrom(staker, address(this), amount), "deposit: can not get token" ); initDataIfNeeded(staker, curEpoch); stakerPerEpochData[curEpoch + 1][staker].stake = stakerPerEpochData[curEpoch + 1][staker].stake.add(amount); //injected INTEGER OVERFLOW OR UNDERFLOW stakerLatestData[staker].stake = stakerLatestData[staker].stake.add(amount); //injected INTEGER OVERFLOW OR UNDERFLOW // increase delegated stake for address that staker has delegated to (if it is not staker) address representative = stakerPerEpochData[curEpoch + 1][staker].representative; if (representative != staker) { initDataIfNeeded(representative, curEpoch); stakerPerEpochData[curEpoch + 1][representative].delegatedStake = stakerPerEpochData[curEpoch + 1][representative].delegatedStake.add(amount); //injected INTEGER OVERFLOW OR UNDERFLOW stakerLatestData[representative].delegatedStake = stakerLatestData[representative].delegatedStake.add(amount); //injected INTEGER OVERFLOW OR UNDERFLOW } emit Deposited(curEpoch, staker, amount); }
function deposit(uint256 amount) external override { require(amount > 0, "deposit: amount is 0"); uint256 curEpoch = getCurrentEpochNumber(); address staker = msg.sender; // collect KNC token from staker require( kncToken.transferFrom(staker, address(this), amount), "deposit: can not get token" ); initDataIfNeeded(staker, curEpoch); stakerPerEpochData[curEpoch + 1][staker].stake = stakerPerEpochData[curEpoch + 1][staker].stake.add(amount); //injected INTEGER OVERFLOW OR UNDERFLOW stakerLatestData[staker].stake = stakerLatestData[staker].stake.add(amount); //injected INTEGER OVERFLOW OR UNDERFLOW // increase delegated stake for address that staker has delegated to (if it is not staker) address representative = stakerPerEpochData[curEpoch + 1][staker].representative; if (representative != staker) { initDataIfNeeded(representative, curEpoch); stakerPerEpochData[curEpoch + 1][representative].delegatedStake = stakerPerEpochData[curEpoch + 1][representative].delegatedStake.add(amount); //injected INTEGER OVERFLOW OR UNDERFLOW stakerLatestData[representative].delegatedStake = stakerLatestData[representative].delegatedStake.add(amount); //injected INTEGER OVERFLOW OR UNDERFLOW } emit Deposited(curEpoch, staker, amount); }
13,788
15
// rlp(child) was at least 32 bytes. node[1] contains Keccak256(rlp(child)).
nodeHashHash = node[1].payloadKeccak256();
nodeHashHash = node[1].payloadKeccak256();
39,546
308
// : Change fees amounts for each token : Must pass an array with complete fee structure with all 5 fees
function setFeesAmounts(uint256[] calldata _feesAmounts) external onlyOwner() { feesAmounts = _feesAmounts; }
function setFeesAmounts(uint256[] calldata _feesAmounts) external onlyOwner() { feesAmounts = _feesAmounts; }
20,139
274
// keccak256(abi.encodePacked("ERC1820_ACCEPT_MAGIC"));
bytes32 public constant ACCEPT_MAGIC = 0xa2ef4600d742022d532d4747cb3547474667d6f13804902513b2ec01c848f4b4; bytes4 public constant ERC165_INTERFACE_ID_ERC165 = 0x01ffc9a7; bytes4 public constant ERC165_INTERFACE_ID_ERC721 = 0x80ac58cd;
bytes32 public constant ACCEPT_MAGIC = 0xa2ef4600d742022d532d4747cb3547474667d6f13804902513b2ec01c848f4b4; bytes4 public constant ERC165_INTERFACE_ID_ERC165 = 0x01ffc9a7; bytes4 public constant ERC165_INTERFACE_ID_ERC721 = 0x80ac58cd;
23,674
78
// Fallback function
function () payable { throw; }
function () payable { throw; }
4,624
14
// Right now, the contract owner can just arbitrarily rule on any outstanding challenge. Decentralizing this is a high priority.
function ruleOnChallenge( uint40 challengee, uint256 challengeIndex, bool challengerWon
function ruleOnChallenge( uint40 challengee, uint256 challengeIndex, bool challengerWon
12,202
10
// updates the votes amount of the given user /
function updateVote( address user, uint256 originAmount, // original amount before change uint256 currentAmount // current amount after change
function updateVote( address user, uint256 originAmount, // original amount before change uint256 currentAmount // current amount after change
47,437
10
// Calc amounts of token0 and token1 including fees
(amount0, amount1) = amountsForLiquidity(pool, liquidity, _tickLower, _tickUpper); amount0 = amount0.add(uint256(tokensOwed0)); amount1 = amount1.add(uint256(tokensOwed1));
(amount0, amount1) = amountsForLiquidity(pool, liquidity, _tickLower, _tickUpper); amount0 = amount0.add(uint256(tokensOwed0)); amount1 = amount1.add(uint256(tokensOwed1));
33,250
276
// Constant values used in ramping A calculations
uint256 public constant A_PRECISION = 100; uint256 public constant MAX_A = 10**6; uint256 private constant MAX_A_CHANGE = 2; uint256 private constant MIN_RAMP_TIME = 14 days;
uint256 public constant A_PRECISION = 100; uint256 public constant MAX_A = 10**6; uint256 private constant MAX_A_CHANGE = 2; uint256 private constant MIN_RAMP_TIME = 14 days;
8,790
47
// Withdraw collateral
function investorWithdraw(uint256 amount) external onlyInvestor { require(collateral_invested.add(amount) <= availableForInvestment(), 'Investment cap reached'); collateral_invested = collateral_invested.add(amount); collateral_token.transfer(investor_contract_address, amount); }
function investorWithdraw(uint256 amount) external onlyInvestor { require(collateral_invested.add(amount) <= availableForInvestment(), 'Investment cap reached'); collateral_invested = collateral_invested.add(amount); collateral_token.transfer(investor_contract_address, amount); }
51,650
136
// Calculates maker amount/ return Floored maker amount
function getMakerAmount(uint256 orderMakerAmount, uint256 orderTakerAmount, uint256 swapTakerAmount) external pure returns(uint256) { return swapTakerAmount * orderMakerAmount / orderTakerAmount; }
function getMakerAmount(uint256 orderMakerAmount, uint256 orderTakerAmount, uint256 swapTakerAmount) external pure returns(uint256) { return swapTakerAmount * orderMakerAmount / orderTakerAmount; }
12,583
24
// Get a reference to the tokenUriResolver.
IJB721TokenUriResolver _resolver = store.tokenUriResolverOf(address(this));
IJB721TokenUriResolver _resolver = store.tokenUriResolverOf(address(this));
30,522
14
// setup next round
currentRoundID += 1; rounds[currentRoundID].initTime = block.timestamp; rounds[currentRoundID].initPrice = rate(); rounds[currentRoundID].status = 1; return true;
currentRoundID += 1; rounds[currentRoundID].initTime = block.timestamp; rounds[currentRoundID].initPrice = rate(); rounds[currentRoundID].status = 1; return true;
19,945
106
// Copyright (c) The Force Protocol Development Team /
interface ICoreUtils { function d(uint256 id) external view returns (address); function bondData(uint256 id) external view returns (IBondData); //principal + interest = principal * (1 + couponRate); function calcPrincipalAndInterest(uint256 principal, uint256 couponRate) external pure returns (uint256); //可转出金额,募集到的总资金减去给所有投票人的手续费 function transferableAmount(uint256 id) external view returns (uint256); //总的募集资金量 function debt(uint256 id) external view returns (uint256); //总的募集资金量 function totalInterest(uint256 id) external view returns (uint256); function debtPlusTotalInterest(uint256 id) external view returns (uint256); //可投资的剩余份数 function remainInvestAmount(uint256 id) external view returns (uint256); function calcMinCollateralTokenAmount(uint256 id) external view returns (uint256); function pawnBalanceInUsd(uint256 id) external view returns (uint256); function disCountPawnBalanceInUsd(uint256 id) external view returns (uint256); function crowdBalanceInUsd(uint256 id) external view returns (uint256); //资不抵债判断,资不抵债时,为true,否则为false function isInsolvency(uint256 id) external view returns (bool); //获取质押的代币价格 function pawnPrice(uint256 id) external view returns (uint256); //获取募资的代币价格 function crowdPrice(uint256 id) external view returns (uint256); //要清算的质押物数量 //X = (AC*price - PCR*PD)/(price*(1-PCR*Discount)) //X = (PCR*PD - AC*price)/(price*(PCR*Discount-1)) function X(uint256 id) external view returns (uint256 res); //清算额,减少的债务 //X*price(collater)*Discount/price(crowd) function Y(uint256 id) external view returns (uint256 res); //到期后,由系统债务算出需要清算的抵押物数量 function calcLiquidatePawnAmount(uint256 id) external view returns (uint256); function calcLiquidatePawnAmount(uint256 id, uint256 liability) external view returns (uint256); function investPrincipalWithInterest(uint256 id, address who) external view returns (uint256); //bond: function convert2BondAmount(address b, address t, uint256 amount) external view returns (uint256); //bond: function convert2GiveAmount(uint256 id, uint256 bondAmount) external view returns (uint256); function isUnsafe(uint256 id) external view returns (bool unsafe); function isDepositMultipleUnsafe(uint256 id) external view returns (bool unsafe); function getLiquidateAmount(uint id, uint y1) external view returns (uint256, uint256); function precision(uint256 id) external view returns (uint256); function isDebtOpen(uint256 id) external view returns (bool); function isMinIssuanceCheckOK(uint256 id) external view returns (bool ok); }
interface ICoreUtils { function d(uint256 id) external view returns (address); function bondData(uint256 id) external view returns (IBondData); //principal + interest = principal * (1 + couponRate); function calcPrincipalAndInterest(uint256 principal, uint256 couponRate) external pure returns (uint256); //可转出金额,募集到的总资金减去给所有投票人的手续费 function transferableAmount(uint256 id) external view returns (uint256); //总的募集资金量 function debt(uint256 id) external view returns (uint256); //总的募集资金量 function totalInterest(uint256 id) external view returns (uint256); function debtPlusTotalInterest(uint256 id) external view returns (uint256); //可投资的剩余份数 function remainInvestAmount(uint256 id) external view returns (uint256); function calcMinCollateralTokenAmount(uint256 id) external view returns (uint256); function pawnBalanceInUsd(uint256 id) external view returns (uint256); function disCountPawnBalanceInUsd(uint256 id) external view returns (uint256); function crowdBalanceInUsd(uint256 id) external view returns (uint256); //资不抵债判断,资不抵债时,为true,否则为false function isInsolvency(uint256 id) external view returns (bool); //获取质押的代币价格 function pawnPrice(uint256 id) external view returns (uint256); //获取募资的代币价格 function crowdPrice(uint256 id) external view returns (uint256); //要清算的质押物数量 //X = (AC*price - PCR*PD)/(price*(1-PCR*Discount)) //X = (PCR*PD - AC*price)/(price*(PCR*Discount-1)) function X(uint256 id) external view returns (uint256 res); //清算额,减少的债务 //X*price(collater)*Discount/price(crowd) function Y(uint256 id) external view returns (uint256 res); //到期后,由系统债务算出需要清算的抵押物数量 function calcLiquidatePawnAmount(uint256 id) external view returns (uint256); function calcLiquidatePawnAmount(uint256 id, uint256 liability) external view returns (uint256); function investPrincipalWithInterest(uint256 id, address who) external view returns (uint256); //bond: function convert2BondAmount(address b, address t, uint256 amount) external view returns (uint256); //bond: function convert2GiveAmount(uint256 id, uint256 bondAmount) external view returns (uint256); function isUnsafe(uint256 id) external view returns (bool unsafe); function isDepositMultipleUnsafe(uint256 id) external view returns (bool unsafe); function getLiquidateAmount(uint id, uint y1) external view returns (uint256, uint256); function precision(uint256 id) external view returns (uint256); function isDebtOpen(uint256 id) external view returns (bool); function isMinIssuanceCheckOK(uint256 id) external view returns (bool ok); }
36,058
6
// 25% dividends for token selling
uint8 constant internal exitFee_ = 25;
uint8 constant internal exitFee_ = 25;
13,123
252
// Emitted when `minter` is removed from `minters`. /
event MinterRemoved(address minter);
event MinterRemoved(address minter);
52,189
44
// My Cayman Condos token smart contract. /
contract MKYCToken is AbstractToken { /** * Maximum allowed number of tokens in circulation. * tokenSupply = tokensIActuallyWant * (10 ^ decimals) */ uint256 constant MAX_TOKEN_COUNT = 200000000 * (10**18); /** * Address of the owner of this smart contract. */ address private owner; /** * Frozen account list holder */ mapping (address => bool) private frozenAccount; /** * Current number of tokens in circulation. */ uint256 tokenCount = 0; /** * True if tokens transfers are currently frozen, false otherwise. */ bool frozen = false; /** * Create new token smart contract and make msg.sender the * owner of this smart contract. */ function MKYCToken () { owner = msg.sender; } /** * Get total number of tokens in circulation. * * @return total number of tokens in circulation */ function totalSupply() constant returns (uint256 supply) { return tokenCount; } string constant public name = "My Cayman Condos"; string constant public symbol = "MKYC"; uint8 constant public decimals = 18; /** * Transfer given number of tokens from message sender to given recipient. * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer to the owner of given address * @return true if tokens were transferred successfully, false otherwise */ function transfer(address _to, uint256 _value) returns (bool success) { require(!frozenAccount[msg.sender]); if (frozen) return false; else return AbstractToken.transfer (_to, _value); } /** * Transfer given number of tokens from given owner to given recipient. * * @param _from address to transfer tokens from the owner of * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer from given owner to given * recipient * @return true if tokens were transferred successfully, false otherwise */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require(!frozenAccount[_from]); if (frozen) return false; else return AbstractToken.transferFrom (_from, _to, _value); } /** * Change how many tokens given spender is allowed to transfer from message * spender. In order to prevent double spending of allowance, * To change the approve amount you first have to reduce the addresses` * allowance to zero by calling `approve(_spender, 0)` if it is not * already 0 to mitigate the race condition described here: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender address to allow the owner of to transfer tokens from * message sender * @param _value number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ function approve (address _spender, uint256 _value) returns (bool success) { require(allowance (msg.sender, _spender) == 0 || _value == 0); return AbstractToken.approve (_spender, _value); } /** * Create _value new tokens and give new created tokens to msg.sender. * May only be called by smart contract owner. * * @param _value number of tokens to create * @return true if tokens were created successfully, false otherwise */ function createTokens(uint256 _value) returns (bool success) { require (msg.sender == owner); if (_value > 0) { if (_value > safeSub (MAX_TOKEN_COUNT, tokenCount)) return false; accounts [msg.sender] = safeAdd (accounts [msg.sender], _value); tokenCount = safeAdd (tokenCount, _value); // adding transfer event and _from address as null address Transfer(0x0, msg.sender, _value); return true; } return false; } /** * Set new owner for the smart contract. * May only be called by smart contract owner. * * @param _newOwner address of new owner of the smart contract */ function setOwner(address _newOwner) { require (msg.sender == owner); owner = _newOwner; } /** * Freeze ALL token transfers. * May only be called by smart contract owner. */ function freezeTransfers () { require (msg.sender == owner); if (!frozen) { frozen = true; Freeze (); } } /** * Unfreeze ALL token transfers. * May only be called by smart contract owner. */ function unfreezeTransfers () { require (msg.sender == owner); if (frozen) { frozen = false; Unfreeze (); } } /*A user is able to unintentionally send tokens to a contract * and if the contract is not prepared to refund them they will get stuck in the contract. * The same issue used to happen for Ether too but new Solidity versions added the payable modifier to * prevent unintended Ether transfers. However, there’s no such mechanism for token transfers. * so the below function is created */ function refundTokens(address _token, address _refund, uint256 _value) { require (msg.sender == owner); require(_token != address(this)); AbstractToken token = AbstractToken(_token); token.transfer(_refund, _value); RefundTokens(_token, _refund, _value); } /** * Freeze specific account * May only be called by smart contract owner. */ function freezeAccount(address _target, bool freeze) { require (msg.sender == owner); require (msg.sender != _target); frozenAccount[_target] = freeze; FrozenFunds(_target, freeze); } /** * Logged when token transfers were frozen. */ event Freeze (); /** * Logged when token transfers were unfrozen. */ event Unfreeze (); /** * Logged when a particular account is frozen. */ event FrozenFunds(address target, bool frozen); /** * when accidentally send other tokens are refunded */ event RefundTokens(address _token, address _refund, uint256 _value); }
contract MKYCToken is AbstractToken { /** * Maximum allowed number of tokens in circulation. * tokenSupply = tokensIActuallyWant * (10 ^ decimals) */ uint256 constant MAX_TOKEN_COUNT = 200000000 * (10**18); /** * Address of the owner of this smart contract. */ address private owner; /** * Frozen account list holder */ mapping (address => bool) private frozenAccount; /** * Current number of tokens in circulation. */ uint256 tokenCount = 0; /** * True if tokens transfers are currently frozen, false otherwise. */ bool frozen = false; /** * Create new token smart contract and make msg.sender the * owner of this smart contract. */ function MKYCToken () { owner = msg.sender; } /** * Get total number of tokens in circulation. * * @return total number of tokens in circulation */ function totalSupply() constant returns (uint256 supply) { return tokenCount; } string constant public name = "My Cayman Condos"; string constant public symbol = "MKYC"; uint8 constant public decimals = 18; /** * Transfer given number of tokens from message sender to given recipient. * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer to the owner of given address * @return true if tokens were transferred successfully, false otherwise */ function transfer(address _to, uint256 _value) returns (bool success) { require(!frozenAccount[msg.sender]); if (frozen) return false; else return AbstractToken.transfer (_to, _value); } /** * Transfer given number of tokens from given owner to given recipient. * * @param _from address to transfer tokens from the owner of * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer from given owner to given * recipient * @return true if tokens were transferred successfully, false otherwise */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require(!frozenAccount[_from]); if (frozen) return false; else return AbstractToken.transferFrom (_from, _to, _value); } /** * Change how many tokens given spender is allowed to transfer from message * spender. In order to prevent double spending of allowance, * To change the approve amount you first have to reduce the addresses` * allowance to zero by calling `approve(_spender, 0)` if it is not * already 0 to mitigate the race condition described here: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender address to allow the owner of to transfer tokens from * message sender * @param _value number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ function approve (address _spender, uint256 _value) returns (bool success) { require(allowance (msg.sender, _spender) == 0 || _value == 0); return AbstractToken.approve (_spender, _value); } /** * Create _value new tokens and give new created tokens to msg.sender. * May only be called by smart contract owner. * * @param _value number of tokens to create * @return true if tokens were created successfully, false otherwise */ function createTokens(uint256 _value) returns (bool success) { require (msg.sender == owner); if (_value > 0) { if (_value > safeSub (MAX_TOKEN_COUNT, tokenCount)) return false; accounts [msg.sender] = safeAdd (accounts [msg.sender], _value); tokenCount = safeAdd (tokenCount, _value); // adding transfer event and _from address as null address Transfer(0x0, msg.sender, _value); return true; } return false; } /** * Set new owner for the smart contract. * May only be called by smart contract owner. * * @param _newOwner address of new owner of the smart contract */ function setOwner(address _newOwner) { require (msg.sender == owner); owner = _newOwner; } /** * Freeze ALL token transfers. * May only be called by smart contract owner. */ function freezeTransfers () { require (msg.sender == owner); if (!frozen) { frozen = true; Freeze (); } } /** * Unfreeze ALL token transfers. * May only be called by smart contract owner. */ function unfreezeTransfers () { require (msg.sender == owner); if (frozen) { frozen = false; Unfreeze (); } } /*A user is able to unintentionally send tokens to a contract * and if the contract is not prepared to refund them they will get stuck in the contract. * The same issue used to happen for Ether too but new Solidity versions added the payable modifier to * prevent unintended Ether transfers. However, there’s no such mechanism for token transfers. * so the below function is created */ function refundTokens(address _token, address _refund, uint256 _value) { require (msg.sender == owner); require(_token != address(this)); AbstractToken token = AbstractToken(_token); token.transfer(_refund, _value); RefundTokens(_token, _refund, _value); } /** * Freeze specific account * May only be called by smart contract owner. */ function freezeAccount(address _target, bool freeze) { require (msg.sender == owner); require (msg.sender != _target); frozenAccount[_target] = freeze; FrozenFunds(_target, freeze); } /** * Logged when token transfers were frozen. */ event Freeze (); /** * Logged when token transfers were unfrozen. */ event Unfreeze (); /** * Logged when a particular account is frozen. */ event FrozenFunds(address target, bool frozen); /** * when accidentally send other tokens are refunded */ event RefundTokens(address _token, address _refund, uint256 _value); }
58,841
44
// mapping of checkpoint header numbers to block details These checkpoints are submited by plasma contracts /
mapping(uint256 => HeaderBlock) public headerBlocks;
mapping(uint256 => HeaderBlock) public headerBlocks;
12,723
56
// A trusted proxy for updating where current answers are read from This contract provides a consistent address for theCurrentAnwerInterface but delegates where it reads from to the owner, who istrusted to update it. /
contract AggregatorProxy is AggregatorV2V3Interface, Owned { struct Phase { uint16 id; AggregatorV2V3Interface aggregator; } Phase private currentPhase; AggregatorV2V3Interface public proposedAggregator; mapping(uint16 => AggregatorV2V3Interface) public phaseAggregators; uint256 constant private PHASE_OFFSET = 64; uint256 constant private PHASE_SIZE = 16; uint256 constant private MAX_ID = 2**(PHASE_OFFSET+PHASE_SIZE) - 1; constructor(address _aggregator) public Owned() { setAggregator(_aggregator); } /** * @notice Reads the current answer from aggregator delegated to. * * @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 answer) { return currentPhase.aggregator.latestAnswer(); } /** * @notice Reads the last updated height from aggregator delegated to. * * @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 updatedAt) { return currentPhase.aggregator.latestTimestamp(); } /** * @notice get past rounds answers * @param _roundId the answer 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 answer) { if (_roundId > MAX_ID) return 0; (uint16 phaseId, uint64 aggregatorRoundId) = parseIds(_roundId); AggregatorV2V3Interface aggregator = phaseAggregators[phaseId]; if (address(aggregator) == address(0)) return 0; return aggregator.getAnswer(aggregatorRoundId); } /** * @notice get block timestamp when an answer was last updated * @param _roundId the answer 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 updatedAt) { if (_roundId > MAX_ID) return 0; (uint16 phaseId, uint64 aggregatorRoundId) = parseIds(_roundId); AggregatorV2V3Interface aggregator = phaseAggregators[phaseId]; if (address(aggregator) == address(0)) return 0; return aggregator.getTimestamp(aggregatorRoundId); } /** * @notice get the latest completed round where the answer was updated. This * ID includes the proxy's phase, to make sure round IDs increase even when * switching to a newly deployed aggregator. * * @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 roundId) { Phase memory phase = currentPhase; // cache storage reads return addPhase(phase.id, uint64(phase.aggregator.latestRound())); } /** * @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. * Note that different underlying implementations of AggregatorV3Interface * have slightly different semantics for some of the return values. Consumers * should determine what implementations they expect to receive * data from and validate that they can properly handle return data from all * of them. * @param _roundId the requested round ID as presented through the proxy, this * is made up of the aggregator's round ID with the phase ID encoded in the * two highest order bytes * @return roundId is the round ID from the aggregator for which the data was * retrieved combined with an phase to ensure that round IDs get larger as * time moves forward. * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @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. * (Only some AggregatorV3Interface implementations return meaningful values) * @dev Note that 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 ) { (uint16 phaseId, uint64 aggregatorRoundId) = parseIds(_roundId); ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 ansIn ) = phaseAggregators[phaseId].getRoundData(aggregatorRoundId); return addPhaseIds(roundId, answer, startedAt, updatedAt, ansIn, phaseId); } /** * @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. * Note that different underlying implementations of AggregatorV3Interface * have slightly different semantics for some of the return values. Consumers * should determine what implementations they expect to receive * data from and validate that they can properly handle return data from all * of them. * @return roundId is the round ID from the aggregator for which the data was * retrieved combined with an phase to ensure that round IDs get larger as * time moves forward. * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @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. * (Only some AggregatorV3Interface implementations return meaningful values) * @dev Note that answer and updatedAt may change between queries. */ function latestRoundData() public view virtual override returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { Phase memory current = currentPhase; // cache storage reads ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 ansIn ) = current.aggregator.latestRoundData(); return addPhaseIds(roundId, answer, startedAt, updatedAt, ansIn, current.id); } /** * @notice Used if an aggregator contract has been proposed. * @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. * (Only some AggregatorV3Interface implementations return meaningful values) * @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. */ function proposedGetRoundData(uint80 _roundId) public view virtual hasProposal() returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { return proposedAggregator.getRoundData(_roundId); } /** * @notice Used if an aggregator contract has been proposed. * @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. * (Only some AggregatorV3Interface implementations return meaningful values) * @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. */ function proposedLatestRoundData() public view virtual hasProposal() returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { return proposedAggregator.latestRoundData(); } /** * @notice returns the current phase's aggregator address. */ function aggregator() external view returns (address) { return address(currentPhase.aggregator); } /** * @notice returns the current phase's ID. */ function phaseId() external view returns (uint16) { return currentPhase.id; } /** * @notice represents the number of decimals the aggregator responses represent. */ function decimals() external view override returns (uint8) { return currentPhase.aggregator.decimals(); } /** * @notice the version number representing the type of aggregator the proxy * points to. */ function version() external view override returns (uint256) { return currentPhase.aggregator.version(); } /** * @notice returns the description of the aggregator the proxy points to. */ function description() external view override returns (string memory) { return currentPhase.aggregator.description(); } /** * @notice Allows the owner to propose a new address for the aggregator * @param _aggregator The new address for the aggregator contract */ function proposeAggregator(address _aggregator) external onlyOwner() { proposedAggregator = AggregatorV2V3Interface(_aggregator); } /** * @notice Allows the owner to confirm and change the address * to the proposed aggregator * @dev Reverts if the given address doesn't match what was previously * proposed * @param _aggregator The new address for the aggregator contract */ function confirmAggregator(address _aggregator) external onlyOwner() { require(_aggregator == address(proposedAggregator), "Invalid proposed aggregator"); delete proposedAggregator; setAggregator(_aggregator); } /* * Internal */ function setAggregator(address _aggregator) internal { uint16 id = currentPhase.id + 1; currentPhase = Phase(id, AggregatorV2V3Interface(_aggregator)); phaseAggregators[id] = AggregatorV2V3Interface(_aggregator); } function addPhase( uint16 _phase, uint64 _originalId ) internal view returns (uint80) { return uint80(uint256(_phase) << PHASE_OFFSET | _originalId); } function parseIds( uint256 _roundId ) internal view returns (uint16, uint64) { uint16 phaseId = uint16(_roundId >> PHASE_OFFSET); uint64 aggregatorRoundId = uint64(_roundId); return (phaseId, aggregatorRoundId); } function addPhaseIds( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound, uint16 phaseId ) internal view returns (uint80, int256, uint256, uint256, uint80) { return ( addPhase(phaseId, uint64(roundId)), answer, startedAt, updatedAt, addPhase(phaseId, uint64(answeredInRound)) ); } /* * Modifiers */ modifier hasProposal() { require(address(proposedAggregator) != address(0), "No proposed aggregator present"); _; } }
contract AggregatorProxy is AggregatorV2V3Interface, Owned { struct Phase { uint16 id; AggregatorV2V3Interface aggregator; } Phase private currentPhase; AggregatorV2V3Interface public proposedAggregator; mapping(uint16 => AggregatorV2V3Interface) public phaseAggregators; uint256 constant private PHASE_OFFSET = 64; uint256 constant private PHASE_SIZE = 16; uint256 constant private MAX_ID = 2**(PHASE_OFFSET+PHASE_SIZE) - 1; constructor(address _aggregator) public Owned() { setAggregator(_aggregator); } /** * @notice Reads the current answer from aggregator delegated to. * * @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 answer) { return currentPhase.aggregator.latestAnswer(); } /** * @notice Reads the last updated height from aggregator delegated to. * * @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 updatedAt) { return currentPhase.aggregator.latestTimestamp(); } /** * @notice get past rounds answers * @param _roundId the answer 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 answer) { if (_roundId > MAX_ID) return 0; (uint16 phaseId, uint64 aggregatorRoundId) = parseIds(_roundId); AggregatorV2V3Interface aggregator = phaseAggregators[phaseId]; if (address(aggregator) == address(0)) return 0; return aggregator.getAnswer(aggregatorRoundId); } /** * @notice get block timestamp when an answer was last updated * @param _roundId the answer 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 updatedAt) { if (_roundId > MAX_ID) return 0; (uint16 phaseId, uint64 aggregatorRoundId) = parseIds(_roundId); AggregatorV2V3Interface aggregator = phaseAggregators[phaseId]; if (address(aggregator) == address(0)) return 0; return aggregator.getTimestamp(aggregatorRoundId); } /** * @notice get the latest completed round where the answer was updated. This * ID includes the proxy's phase, to make sure round IDs increase even when * switching to a newly deployed aggregator. * * @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 roundId) { Phase memory phase = currentPhase; // cache storage reads return addPhase(phase.id, uint64(phase.aggregator.latestRound())); } /** * @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. * Note that different underlying implementations of AggregatorV3Interface * have slightly different semantics for some of the return values. Consumers * should determine what implementations they expect to receive * data from and validate that they can properly handle return data from all * of them. * @param _roundId the requested round ID as presented through the proxy, this * is made up of the aggregator's round ID with the phase ID encoded in the * two highest order bytes * @return roundId is the round ID from the aggregator for which the data was * retrieved combined with an phase to ensure that round IDs get larger as * time moves forward. * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @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. * (Only some AggregatorV3Interface implementations return meaningful values) * @dev Note that 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 ) { (uint16 phaseId, uint64 aggregatorRoundId) = parseIds(_roundId); ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 ansIn ) = phaseAggregators[phaseId].getRoundData(aggregatorRoundId); return addPhaseIds(roundId, answer, startedAt, updatedAt, ansIn, phaseId); } /** * @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. * Note that different underlying implementations of AggregatorV3Interface * have slightly different semantics for some of the return values. Consumers * should determine what implementations they expect to receive * data from and validate that they can properly handle return data from all * of them. * @return roundId is the round ID from the aggregator for which the data was * retrieved combined with an phase to ensure that round IDs get larger as * time moves forward. * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @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. * (Only some AggregatorV3Interface implementations return meaningful values) * @dev Note that answer and updatedAt may change between queries. */ function latestRoundData() public view virtual override returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { Phase memory current = currentPhase; // cache storage reads ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 ansIn ) = current.aggregator.latestRoundData(); return addPhaseIds(roundId, answer, startedAt, updatedAt, ansIn, current.id); } /** * @notice Used if an aggregator contract has been proposed. * @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. * (Only some AggregatorV3Interface implementations return meaningful values) * @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. */ function proposedGetRoundData(uint80 _roundId) public view virtual hasProposal() returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { return proposedAggregator.getRoundData(_roundId); } /** * @notice Used if an aggregator contract has been proposed. * @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. * (Only some AggregatorV3Interface implementations return meaningful values) * @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. */ function proposedLatestRoundData() public view virtual hasProposal() returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { return proposedAggregator.latestRoundData(); } /** * @notice returns the current phase's aggregator address. */ function aggregator() external view returns (address) { return address(currentPhase.aggregator); } /** * @notice returns the current phase's ID. */ function phaseId() external view returns (uint16) { return currentPhase.id; } /** * @notice represents the number of decimals the aggregator responses represent. */ function decimals() external view override returns (uint8) { return currentPhase.aggregator.decimals(); } /** * @notice the version number representing the type of aggregator the proxy * points to. */ function version() external view override returns (uint256) { return currentPhase.aggregator.version(); } /** * @notice returns the description of the aggregator the proxy points to. */ function description() external view override returns (string memory) { return currentPhase.aggregator.description(); } /** * @notice Allows the owner to propose a new address for the aggregator * @param _aggregator The new address for the aggregator contract */ function proposeAggregator(address _aggregator) external onlyOwner() { proposedAggregator = AggregatorV2V3Interface(_aggregator); } /** * @notice Allows the owner to confirm and change the address * to the proposed aggregator * @dev Reverts if the given address doesn't match what was previously * proposed * @param _aggregator The new address for the aggregator contract */ function confirmAggregator(address _aggregator) external onlyOwner() { require(_aggregator == address(proposedAggregator), "Invalid proposed aggregator"); delete proposedAggregator; setAggregator(_aggregator); } /* * Internal */ function setAggregator(address _aggregator) internal { uint16 id = currentPhase.id + 1; currentPhase = Phase(id, AggregatorV2V3Interface(_aggregator)); phaseAggregators[id] = AggregatorV2V3Interface(_aggregator); } function addPhase( uint16 _phase, uint64 _originalId ) internal view returns (uint80) { return uint80(uint256(_phase) << PHASE_OFFSET | _originalId); } function parseIds( uint256 _roundId ) internal view returns (uint16, uint64) { uint16 phaseId = uint16(_roundId >> PHASE_OFFSET); uint64 aggregatorRoundId = uint64(_roundId); return (phaseId, aggregatorRoundId); } function addPhaseIds( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound, uint16 phaseId ) internal view returns (uint80, int256, uint256, uint256, uint80) { return ( addPhase(phaseId, uint64(roundId)), answer, startedAt, updatedAt, addPhase(phaseId, uint64(answeredInRound)) ); } /* * Modifiers */ modifier hasProposal() { require(address(proposedAggregator) != address(0), "No proposed aggregator present"); _; } }
66,096
24
// Checks if group with the given index is terminated. /
function isGroupTerminated( Storage storage self, uint256 groupIndex
function isGroupTerminated( Storage storage self, uint256 groupIndex
2,029
45
// Sender redeems saving assets in exchange for a specified amount of underlying asset Interst shall be accrued redeemAmount The amount of underlying to redeemreturn uint256 Amount of saving assets burned /
function redeemUnderlying(uint256 redeemAmount) external returns (uint256);
function redeemUnderlying(uint256 redeemAmount) external returns (uint256);
10,403
23
// WRITE METHOD Private/
function setZeroLevelOfLandI(uint256 lLand, uint8 lLevel) private { require(msg.sender == ownerOf(lLand)); zeroLevelOfLand_[lLand] = lLevel; }
function setZeroLevelOfLandI(uint256 lLand, uint8 lLevel) private { require(msg.sender == ownerOf(lLand)); zeroLevelOfLand_[lLand] = lLevel; }
24,022
13
// Internal function to set the sources for each asset/_assets The addresses of the assets/_sources The address of the source of each asset
function internalSetAssetsSources(address[] memory _assets, address[] memory _sources) internal { require(_assets.length == _sources.length, "INCONSISTENT_PARAMS_LENGTH"); for (uint256 i = 0; i < _assets.length; i++) { assetsSources[_assets[i]] = IChainlinkAggregator(_sources[i]); emit AssetSourceUpdated(_assets[i], _sources[i]); } }
function internalSetAssetsSources(address[] memory _assets, address[] memory _sources) internal { require(_assets.length == _sources.length, "INCONSISTENT_PARAMS_LENGTH"); for (uint256 i = 0; i < _assets.length; i++) { assetsSources[_assets[i]] = IChainlinkAggregator(_sources[i]); emit AssetSourceUpdated(_assets[i], _sources[i]); } }
15,991
97
// Verifies that the hash is valid Snapshot Hub will call this function when a vote is submitted using snapshot.js on behalf of this contract. Snapshot Hub will call this function with the hash and the signature of the vote that was cast. _hash Hash of the message that was sent to Snapshot Hub to cast a votereturn EIP1271 magic value if the signature is value/
function isValidSignature(bytes32 _hash, bytes memory) public view returns (bytes4) { if(votes[_hash]) { return EIP1271_MAGIC_VALUE; } else { return 0xffffffff; } }
function isValidSignature(bytes32 _hash, bytes memory) public view returns (bytes4) { if(votes[_hash]) { return EIP1271_MAGIC_VALUE; } else { return 0xffffffff; } }
39,714
199
// 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 SafeMathChainlink 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 10⁻¹⁸ 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 (funds.available != nowAvailable) { 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 (previous != _newValidator) { 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 (validateOracleRound(_oracle, _roundId).length != 0) { _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 (details[_roundId].submissions.length < details[_roundId].minSubmissions) { 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 (address(av) == address(0)) return; 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 (details[_roundId].submissions.length < details[_roundId].maxSubmissions) return; 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 SafeMathChainlink 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 10⁻¹⁸ 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 (funds.available != nowAvailable) { 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 (previous != _newValidator) { 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 (validateOracleRound(_oracle, _roundId).length != 0) { _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 (details[_roundId].submissions.length < details[_roundId].minSubmissions) { 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 (address(av) == address(0)) return; 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 (details[_roundId].submissions.length < details[_roundId].maxSubmissions) return; 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; } }
8,232
15
// Closes the escrow, and increments the fork id. Once the escrow is closed, all the escrowed tokenscan no longer be unescrowed by the owner, but can be withdrawn by the DAO. Can only be called by the DAO contractreturn closedForkId The fork id which was closed /
function closeEscrow() external onlyDAO returns (uint32 closedForkId) { numTokensInEscrow = 0; closedForkId = forkId; forkId++; }
function closeEscrow() external onlyDAO returns (uint32 closedForkId) { numTokensInEscrow = 0; closedForkId = forkId; forkId++; }
32,597
536
// Grab the sUSD Synth
ISynth sUSDSynth = issuer().synths(sUSD);
ISynth sUSDSynth = issuer().synths(sUSD);
34,260
51
// Write the selector first, since it overlaps the digest
mstore(selectorPtr, 0x44)
mstore(selectorPtr, 0x44)
38,591
9
// Events ------------------------------------------------------------------------
event BaseTokenURIChanged(string baseTokenURI); event Received(address, uint256);
event BaseTokenURIChanged(string baseTokenURI); event Received(address, uint256);
71,169
332
// Get the current allowance from `owner` for `spender`owner The address of the account which owns the tokens to be spentspender The address of the account which may transfer tokens return remaining The number of tokens allowed to be spent (-1 means infinite)/
function allowance(address owner, address spender) external view returns (uint256 remaining);
function allowance(address owner, address spender) external view returns (uint256 remaining);
3,885
25
// If last point was in this block, the slope change has been applied already But in such case we have 0 slope(s)
last_point.slope += (u_new.slope - u_old.slope); last_point.bias += (u_new.bias - u_old.bias); if (last_point.slope < 0) { last_point.slope = 0; }
last_point.slope += (u_new.slope - u_old.slope); last_point.bias += (u_new.bias - u_old.bias); if (last_point.slope < 0) { last_point.slope = 0; }
18,664
303
// to get the status of recently holded coverIDuserAdd is the user address in concernreturn the status of the concerned coverId /
function getRecentHoldedCoverIdStatus(address userAdd) public view returns(int) { uint holdedCoverLen = qd.getUserHoldedCoverLength(userAdd); if (holdedCoverLen == 0) { return -1; } else { uint holdedCoverID = qd.getUserHoldedCoverByIndex(userAdd, holdedCoverLen.sub(1)); return int(qd.holdedCoverIDStatus(holdedCoverID)); } }
function getRecentHoldedCoverIdStatus(address userAdd) public view returns(int) { uint holdedCoverLen = qd.getUserHoldedCoverLength(userAdd); if (holdedCoverLen == 0) { return -1; } else { uint holdedCoverID = qd.getUserHoldedCoverByIndex(userAdd, holdedCoverLen.sub(1)); return int(qd.holdedCoverIDStatus(holdedCoverID)); } }
12,891
44
// This function makes it easy to read the `allowed[]` map/_owner The address of the account that owns the token/_spender The address of the account able to transfer the tokens/ return Amount of remaining tokens of _owner that _spender is allowed/to spend
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; }
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; }
47,072
63
// Checks that a nonce has the correct format and is valid.
* It must be constructed as nonce = {block number}{timestamp} where each component is 16 bytes. * @param _wallet The target wallet. * @param _nonce The nonce */ function checkAndUpdateNonce(BaseWallet _wallet, uint256 _nonce) internal returns (bool) { if(_nonce <= relayer[address(_wallet)].nonce) { return false; } uint256 nonceBlock = (_nonce & 0xffffffffffffffffffffffffffffffff00000000000000000000000000000000) >> 128; if(nonceBlock > block.number + BLOCKBOUND) { return false; } relayer[address(_wallet)].nonce = _nonce; return true; }
* It must be constructed as nonce = {block number}{timestamp} where each component is 16 bytes. * @param _wallet The target wallet. * @param _nonce The nonce */ function checkAndUpdateNonce(BaseWallet _wallet, uint256 _nonce) internal returns (bool) { if(_nonce <= relayer[address(_wallet)].nonce) { return false; } uint256 nonceBlock = (_nonce & 0xffffffffffffffffffffffffffffffff00000000000000000000000000000000) >> 128; if(nonceBlock > block.number + BLOCKBOUND) { return false; } relayer[address(_wallet)].nonce = _nonce; return true; }
1,923
57
// Add an address to operator list of token /
function addOperator(address minter) external returns (bool);
function addOperator(address minter) external returns (bool);
19,530
77
// We copy the first 4 bytes to check if it matches with the expected signature, otherwise there was another revert reason and we should forward it.
returndatacopy(0, 0, 0x04) let error := and(mload(0), 0xffffffff00000000000000000000000000000000000000000000000000000000)
returndatacopy(0, 0, 0x04) let error := and(mload(0), 0xffffffff00000000000000000000000000000000000000000000000000000000)
4,338
159
// reset request URL for balance /
function setBalanceRequestUrl(string memory _balanceRequestUrl) public onlyOwner { balanceRequestUrl = _balanceRequestUrl; }
function setBalanceRequestUrl(string memory _balanceRequestUrl) public onlyOwner { balanceRequestUrl = _balanceRequestUrl; }
16,636
79
// produces the cumulative price using counterfactuals to save gas and avoid a call to sync. only gets the first price
function currentCumulativePrice0(address pair) internal view returns (uint256 price0Cumulative, uint32 blockTimestamp)
function currentCumulativePrice0(address pair) internal view returns (uint256 price0Cumulative, uint32 blockTimestamp)
8,239
10
// Creates a new escrow contract
function newEscrow(uint256 _id, address payable _seller, address payable _buyer) external { // Check a contract doesnt already exist with that ID require(!this.exists(_id), 'Sorry a contract with that ID already exist.'); // Check _seller, _buyer are not empty inputs require(_seller != address(0) && _buyer != address(0), 'Ensure buyer and seller address are valid.'); // Create new contract Escrow e = new Escrow(_seller,_buyer,address(this)); // Store contract in mapping escrows[_id] = e; }
function newEscrow(uint256 _id, address payable _seller, address payable _buyer) external { // Check a contract doesnt already exist with that ID require(!this.exists(_id), 'Sorry a contract with that ID already exist.'); // Check _seller, _buyer are not empty inputs require(_seller != address(0) && _buyer != address(0), 'Ensure buyer and seller address are valid.'); // Create new contract Escrow e = new Escrow(_seller,_buyer,address(this)); // Store contract in mapping escrows[_id] = e; }
42,648
111
// disables an address from minting / burningcontroller the address to disbale/
function removeController(address controller) external returns(bool);
function removeController(address controller) external returns(bool);
5,386
3
// Add function to set the power levelThis function is only callable by admin members
function setPowerLevel(uint256 tokenId, uint256 _powerLevel) public onlyRole(DEFAULT_ADMIN_ROLE)
function setPowerLevel(uint256 tokenId, uint256 _powerLevel) public onlyRole(DEFAULT_ADMIN_ROLE)
9,658
161
// update token withdraw balance
tokenWithdrawBalances[address(pool.rewardToken)] += penaltyFee + unstakingFee;
tokenWithdrawBalances[address(pool.rewardToken)] += penaltyFee + unstakingFee;
17,190
2
// Revert with an error if the mint quantity is zero. /
error MintQuantityCannotBeZero();
error MintQuantityCannotBeZero();
6,839
40
// Batch token transfer. Used by contract creator to distribute initial tokens to holders /
function batchTransfer(address[] _recipients, uint[] _values) onlyOwner returns (bool) { require( _recipients.length > 0 && _recipients.length == _values.length); uint total = 0; for(uint i = 0; i < _values.length; i++){ total = total.add(_values[i]); } require(total <= balances[msg.sender]); uint64 _now = uint64(now); for(uint j = 0; j < _recipients.length; j++){ balances[_recipients[j]] = balances[_recipients[j]].add(_values[j]); transferIns[_recipients[j]].push(transferInStruct(uint128(_values[j]),_now)); Transfer(msg.sender, _recipients[j], _values[j]); } balances[msg.sender] = balances[msg.sender].sub(total); if(transferIns[msg.sender].length > 0) delete transferIns[msg.sender]; if(balances[msg.sender] > 0) transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]),_now)); return true; }
function batchTransfer(address[] _recipients, uint[] _values) onlyOwner returns (bool) { require( _recipients.length > 0 && _recipients.length == _values.length); uint total = 0; for(uint i = 0; i < _values.length; i++){ total = total.add(_values[i]); } require(total <= balances[msg.sender]); uint64 _now = uint64(now); for(uint j = 0; j < _recipients.length; j++){ balances[_recipients[j]] = balances[_recipients[j]].add(_values[j]); transferIns[_recipients[j]].push(transferInStruct(uint128(_values[j]),_now)); Transfer(msg.sender, _recipients[j], _values[j]); } balances[msg.sender] = balances[msg.sender].sub(total); if(transferIns[msg.sender].length > 0) delete transferIns[msg.sender]; if(balances[msg.sender] > 0) transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]),_now)); return true; }
13,096
173
// share x 1000
uint16 share;
uint16 share;
24,826
202
// Safe remit transfer function, just in case if rounding error causes pool to not have enough REMITs.
function safeRemitTransfer(address _to, uint256 _amount) internal { uint256 remitBal = remit.balanceOf(address(this)); if (_amount > remitBal) { remit.transfer(_to, remitBal); } else { remit.transfer(_to, _amount); } }
function safeRemitTransfer(address _to, uint256 _amount) internal { uint256 remitBal = remit.balanceOf(address(this)); if (_amount > remitBal) { remit.transfer(_to, remitBal); } else { remit.transfer(_to, _amount); } }
35,912
23
// Burn existing tokens for the account Modifiers:- onlySelf/
function selfBurn(
function selfBurn(
21,811
72
// We don't really care if the burn fails for someweird reason./
bool ret = burnAddress.send(value);
bool ret = burnAddress.send(value);
4,789
54
// If no vote is underway, then there is nothing to action.
VoteType action = blockchains[_blockchainId].votes[_voteTarget].voteType; require(action != VoteType.VOTE_NONE);
VoteType action = blockchains[_blockchainId].votes[_voteTarget].voteType; require(action != VoteType.VOTE_NONE);
9,154
90
// Account dYdX Library of structs and functions that represent an account /
library Account { // ============ Enums ============ /* * Most-recently-cached account status. * * Normal: Can only be liquidated if the account values are violating the global margin-ratio. * Liquid: Can be liquidated no matter the account values. * Can be vaporized if there are no more positive account values. * Vapor: Has only negative (or zeroed) account values. Can be vaporized. * */ enum Status { Normal, Liquid, Vapor } // ============ Structs ============ // Represents the unique key that specifies an account struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } // The complete storage for any account struct Storage { mapping (uint256 => Types.Par) balances; // Mapping from marketId to principal Status status; } // ============ Library Functions ============ function equals( Info memory a, Info memory b ) internal pure returns (bool) { return a.owner == b.owner && a.number == b.number; } }
library Account { // ============ Enums ============ /* * Most-recently-cached account status. * * Normal: Can only be liquidated if the account values are violating the global margin-ratio. * Liquid: Can be liquidated no matter the account values. * Can be vaporized if there are no more positive account values. * Vapor: Has only negative (or zeroed) account values. Can be vaporized. * */ enum Status { Normal, Liquid, Vapor } // ============ Structs ============ // Represents the unique key that specifies an account struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } // The complete storage for any account struct Storage { mapping (uint256 => Types.Par) balances; // Mapping from marketId to principal Status status; } // ============ Library Functions ============ function equals( Info memory a, Info memory b ) internal pure returns (bool) { return a.owner == b.owner && a.number == b.number; } }
59,113
18
// 验证金额 1000000000000000000 => 1100000000000000000 500000000000000000=> 550000000000000000 100000000000000000=> 110000000000000000
if (value != eth && value != eth.div(2) && value != eth.div(10)) { require(eth < 1, "Wrong amount of first investment"); }
if (value != eth && value != eth.div(2) && value != eth.div(10)) { require(eth < 1, "Wrong amount of first investment"); }
5,774
164
// EVENTS// MODIFIERS /
modifier onlyManager() { require(isManager[msg.sender], "not manager"); _; }
modifier onlyManager() { require(isManager[msg.sender], "not manager"); _; }
48,497
273
// write ILV address
ilv = _ilv;
ilv = _ilv;
68,014
22
// player_submitted
if(eventName == 4){ emit playerSubmitted(talentId, ti.scoutId, data); }
if(eventName == 4){ emit playerSubmitted(talentId, ti.scoutId, data); }
30,363
4
// set committer & deadline
committer = msg.sender; deadline = block.timestamp + 1 hours;
committer = msg.sender; deadline = block.timestamp + 1 hours;
28,436
18
// set the cat price
catPrice[newCatId] = calculateMinCatPrice(newCatId);
catPrice[newCatId] = calculateMinCatPrice(newCatId);
23,566
1
// Function to calculate the interest accumulated using a linear interest rate formula rate The interest rate, in ray lastUpdateTimestamp The timestamp of the last update of the interestreturn The interest rate linearly accumulated during the timeDelta, in ray /solium-disable-next-line
uint256 result = rate * (block.timestamp - uint256(lastUpdateTimestamp)); unchecked { result = result / SECONDS_PER_YEAR; }
uint256 result = rate * (block.timestamp - uint256(lastUpdateTimestamp)); unchecked { result = result / SECONDS_PER_YEAR; }
4,457
304
// Calculate RFT to mint
uint256 rftTotalSupply = rariFundToken.totalSupply(); uint256 fundBalanceUsd = rftTotalSupply > 0 ? getFundBalance() : 0; // Only set if used uint256 rftAmount = 0; if (rftTotalSupply > 0 && fundBalanceUsd > 0) rftAmount = amountUsd.mul(rftTotalSupply).div(fundBalanceUsd); else rftAmount = amountUsd; require(rftAmount > 0, "Deposit amount is so small that no RFT would be minted.");
uint256 rftTotalSupply = rariFundToken.totalSupply(); uint256 fundBalanceUsd = rftTotalSupply > 0 ? getFundBalance() : 0; // Only set if used uint256 rftAmount = 0; if (rftTotalSupply > 0 && fundBalanceUsd > 0) rftAmount = amountUsd.mul(rftTotalSupply).div(fundBalanceUsd); else rftAmount = amountUsd; require(rftAmount > 0, "Deposit amount is so small that no RFT would be minted.");
2,347