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
293
// point = g^2.
point := mulmod(point, /*traceGenerator^2*/ mload(expmodsAndPoints), PRIME)
point := mulmod(point, /*traceGenerator^2*/ mload(expmodsAndPoints), PRIME)
28,993
174
// assert there is message to retry
FailedMessages storage failedMsg = failedMessages[_srcChainId][_srcAddress][_nonce]; require(failedMsg.payloadHash != bytes32(0), "NonblockingReceiver: no stored message"); require(_payload.length == failedMsg.payloadLength && keccak256(_payload) == failedMsg.payloadHash, "LayerZero: invalid payload");
FailedMessages storage failedMsg = failedMessages[_srcChainId][_srcAddress][_nonce]; require(failedMsg.payloadHash != bytes32(0), "NonblockingReceiver: no stored message"); require(_payload.length == failedMsg.payloadLength && keccak256(_payload) == failedMsg.payloadHash, "LayerZero: invalid payload");
2,924
7
// emit Event
emit PhotoNFTCreated(msg.sender, currentPhotoId); currentPhotoId++;
emit PhotoNFTCreated(msg.sender, currentPhotoId); currentPhotoId++;
31,186
104
// Total staked cards by user /
function balanceOf(uint256 tokenId, address account) external view returns (uint256) { return nftTokenMap[tokenId].balances[account]; }
function balanceOf(uint256 tokenId, address account) external view returns (uint256) { return nftTokenMap[tokenId].balances[account]; }
39,131
19
// Initialize the core with an initial node initialNode Initial node to start the chain with /
function initializeCore(INode initialNode) internal { _nodes[0] = initialNode; _firstUnresolvedNode = 1; }
function initializeCore(INode initialNode) internal { _nodes[0] = initialNode; _firstUnresolvedNode = 1; }
19,646
79
// Update the current timestamp.
self.limitTimestamp = now;
self.limitTimestamp = now;
16,923
14
// Deri Protocol migratable pool implementation /
abstract contract MigratablePool is IMigratablePool { // Controller address address _controller; // Migration timestamp of this pool, zero means not set // Migration timestamp can only be set with a grace period at least 3 days, and the // `migrationDestination` pool address must be also set when setting migration timestamp, // users can use this grace period to verify the `migrationDestination` pool code uint256 _migrationTimestamp; // The new pool this pool will migrate to after grace period, zero address means not set address _migrationDestination; modifier _controller_() { require(msg.sender == _controller, "can only be called by current controller"); _; } /** * @dev See {IMigratablePool}.{setController} */ function setController(address newController) public override { require(newController != address(0), "MigratablePool: setController to 0 address"); require( _controller == address(0) || msg.sender == _controller, "MigratablePool: setController can only be called by current controller or not set" ); _controller = newController; } /** * @dev See {IMigratablePool}.{controller} */ function controller() public view override returns (address) { return _controller; } /** * @dev See {IMigratablePool}.{migrationTimestamp} */ function migrationTimestamp() public view override returns (uint256) { return _migrationTimestamp; } /** * @dev See {IMigratablePool}.{migrationDestination} */ function migrationDestination() public view override returns (address) { return _migrationDestination; } /** * @dev See {IMigratablePool}.{prepareMigration} */ function prepareMigration(address newPool, uint256 graceDays) public override _controller_ { require(newPool != address(0), "MigratablePool: prepareMigration to 0 address"); require(graceDays >= 3 && graceDays <= 365, "MigratablePool: graceDays must be 3-365 days"); _migrationTimestamp = block.timestamp + graceDays * 1 days; _migrationDestination = newPool; emit PrepareMigration(_migrationTimestamp, address(this), _migrationDestination); } /** * @dev See {IMigratablePool}.{approveMigration} * * This function will be implemented in inheriting contract * This function will change if there is an upgrade to existent pool */ // function approveMigration() public virtual override _controller_ {} /** * @dev See {IMigratablePool}.{executeMigration} * * This function will be implemented in inheriting contract * This function will change if there is an upgrade to existent pool */ // function executeMigration(address source) public virtual override _controller_ {} }
abstract contract MigratablePool is IMigratablePool { // Controller address address _controller; // Migration timestamp of this pool, zero means not set // Migration timestamp can only be set with a grace period at least 3 days, and the // `migrationDestination` pool address must be also set when setting migration timestamp, // users can use this grace period to verify the `migrationDestination` pool code uint256 _migrationTimestamp; // The new pool this pool will migrate to after grace period, zero address means not set address _migrationDestination; modifier _controller_() { require(msg.sender == _controller, "can only be called by current controller"); _; } /** * @dev See {IMigratablePool}.{setController} */ function setController(address newController) public override { require(newController != address(0), "MigratablePool: setController to 0 address"); require( _controller == address(0) || msg.sender == _controller, "MigratablePool: setController can only be called by current controller or not set" ); _controller = newController; } /** * @dev See {IMigratablePool}.{controller} */ function controller() public view override returns (address) { return _controller; } /** * @dev See {IMigratablePool}.{migrationTimestamp} */ function migrationTimestamp() public view override returns (uint256) { return _migrationTimestamp; } /** * @dev See {IMigratablePool}.{migrationDestination} */ function migrationDestination() public view override returns (address) { return _migrationDestination; } /** * @dev See {IMigratablePool}.{prepareMigration} */ function prepareMigration(address newPool, uint256 graceDays) public override _controller_ { require(newPool != address(0), "MigratablePool: prepareMigration to 0 address"); require(graceDays >= 3 && graceDays <= 365, "MigratablePool: graceDays must be 3-365 days"); _migrationTimestamp = block.timestamp + graceDays * 1 days; _migrationDestination = newPool; emit PrepareMigration(_migrationTimestamp, address(this), _migrationDestination); } /** * @dev See {IMigratablePool}.{approveMigration} * * This function will be implemented in inheriting contract * This function will change if there is an upgrade to existent pool */ // function approveMigration() public virtual override _controller_ {} /** * @dev See {IMigratablePool}.{executeMigration} * * This function will be implemented in inheriting contract * This function will change if there is an upgrade to existent pool */ // function executeMigration(address source) public virtual override _controller_ {} }
51,685
90
// Function to recover any ERC20 Tokens sent to Contract by Mistake./
function recoverAnyERC20TokensFromContract(address _tokenAddr, address _to, uint _amount) public onlyOwner { IERC20(_tokenAddr).transfer(_to, _amount); }
function recoverAnyERC20TokensFromContract(address _tokenAddr, address _to, uint _amount) public onlyOwner { IERC20(_tokenAddr).transfer(_to, _amount); }
18,090
26
// 0 => withdraw1 => predefinedCall2 => uniswap//Gets the detail of a specific locked amount created for a pool._callData (optional) Contains customized instructions such as "external call to uniswap smart contract"._lockAddress The address that created the lock._predefinedCall Some predefined instructions available._callContractAddress (optional) If callData exists, specify the external contract to be called._indexStr index of the lock === index of the address paid to in a lock._index The number format of the index of the lock. return success/
function fulfillLock( bytes memory _callData, //deposit,addresses address _lockAddress, uint256 _predefinedCall, address _callContractAddress, string memory _indexStr, // to be reviewed uint256 _index // to be reviewed ) public onlyLoker(_lockAddress, _index) // is this necessary?
function fulfillLock( bytes memory _callData, //deposit,addresses address _lockAddress, uint256 _predefinedCall, address _callContractAddress, string memory _indexStr, // to be reviewed uint256 _index // to be reviewed ) public onlyLoker(_lockAddress, _index) // is this necessary?
7,823
23
// Tells whether the msg.sender is approved for the given token ID or not _asker address of asking for approval _tokenId uint256 ID of the token to query the approval ofreturn bool whether the msg.sender is approved for the given token ID or not /
function isSpecificallyApprovedFor(address _asker, uint256 _tokenId) internal view returns (bool) { return getApproved(_tokenId) == _asker; }
function isSpecificallyApprovedFor(address _asker, uint256 _tokenId) internal view returns (bool) { return getApproved(_tokenId) == _asker; }
35,198
35
// Return the total amount of tokens that are being escrowed for a specific accountwho The address for which we calculate the amount of tokens that are still waiting to be unlocked/
function getTokensBeingEscrowed(address who) public view returns (uint256) { if (oldestEscrowSlot[who] >= currentEscrowSlot[who]) return 0; EscrowSlot memory escrowReward; uint256 totalEscrowed; uint256 endDate; for (uint i = oldestEscrowSlot[who]; i <= currentEscrowSlot[who]; i++) { escrowReward = escrows[who][i]; endDate = addition(escrowReward.startDate, escrowReward.duration); if (escrowReward.amountClaimed >= escrowReward.total) { continue; } if (both(escrowReward.claimedUntil < endDate, now >= endDate)) { continue; } totalEscrowed = addition(totalEscrowed, subtract(escrowReward.total, escrowReward.amountClaimed)); } return totalEscrowed; }
function getTokensBeingEscrowed(address who) public view returns (uint256) { if (oldestEscrowSlot[who] >= currentEscrowSlot[who]) return 0; EscrowSlot memory escrowReward; uint256 totalEscrowed; uint256 endDate; for (uint i = oldestEscrowSlot[who]; i <= currentEscrowSlot[who]; i++) { escrowReward = escrows[who][i]; endDate = addition(escrowReward.startDate, escrowReward.duration); if (escrowReward.amountClaimed >= escrowReward.total) { continue; } if (both(escrowReward.claimedUntil < endDate, now >= endDate)) { continue; } totalEscrowed = addition(totalEscrowed, subtract(escrowReward.total, escrowReward.amountClaimed)); } return totalEscrowed; }
34,611
596
// Returns the normalized weight of `token`. Weights are fixed point numbers that sum to FixedPoint.ONE. /
function _getNormalizedWeight(IERC20 token) internal view virtual returns (uint256);
function _getNormalizedWeight(IERC20 token) internal view virtual returns (uint256);
7,375
22
// Contract address that can override globalFixedNativeFee
address public feeContractUpdater;
address public feeContractUpdater;
71,799
26
// make sure m_numOwners is equal to the number of owners and always points to the last owner
reorganizeOwners(); assertOwnersAreConsistent(); emit OwnerRemoved(_owner);
reorganizeOwners(); assertOwnersAreConsistent(); emit OwnerRemoved(_owner);
40,794
37
// Returns the current block number.Using a function rather than `block.number` allows us to easily mock the block number intests./
function getBlockNumber() internal view returns (uint256) { return block.number; }
function getBlockNumber() internal view returns (uint256) { return block.number; }
13,046
1
// the oracle can transfer tokens to any address sender is the address in the child chain for which the tokens were burned recipient is the address which will get the tokens on the parent chain/
function transfer(address from, address to, uint256 amount, address token, uint256 nonce, uint8 v, bytes32 r, bytes32 s)
function transfer(address from, address to, uint256 amount, address token, uint256 nonce, uint8 v, bytes32 r, bytes32 s)
31,374
19
// tax is 0.225% above 60,000 trades
taxNumerator = 225;
taxNumerator = 225;
37,781
41
// Generic proxy
function execute( address _to, uint256 _value, bytes calldata _data
function execute( address _to, uint256 _value, bytes calldata _data
35,023
7
// Changes the multiplier for challengers' deposit._challengeMultiplier A new value of the multiplier for calculating challenger's deposit. In basis points. /
function changeChallengeMultiplier(uint256 _challengeMultiplier) public onlyOwner { challengeMultiplier = _challengeMultiplier; }
function changeChallengeMultiplier(uint256 _challengeMultiplier) public onlyOwner { challengeMultiplier = _challengeMultiplier; }
45,478
319
// Allow users to sign a message authorizing a sell
function permitSell( address _from, address payable _to, uint _quantityToSell, uint _minCurrencyReturned, uint _deadline, uint8 _v, bytes32 _r, bytes32 _s ) external
function permitSell( address _from, address payable _to, uint _quantityToSell, uint _minCurrencyReturned, uint _deadline, uint8 _v, bytes32 _r, bytes32 _s ) external
29,741
11
// wizards earn 12000 $GP per day
uint256 public constant DAILY_GP_RATE = 12000 ether;
uint256 public constant DAILY_GP_RATE = 12000 ether;
13,293
42
// Determines how many Patrons are issues per donation
uint256 public donationMultiplier;
uint256 public donationMultiplier;
34,492
140
// we are paying out the stake
exitStake.paid = true; totalWithdraw = totalWithdraw.add(_totalExpected(exitStake));
exitStake.paid = true; totalWithdraw = totalWithdraw.add(_totalExpected(exitStake));
9,929
103
// place creation code and constructor args of contract to spawn in memory.
initCode = abi.encodePacked( type(Spawn).creationCode, abi.encode(logicContract, initializationCalldata) );
initCode = abi.encodePacked( type(Spawn).creationCode, abi.encode(logicContract, initializationCalldata) );
39,183
25
// Auto-generated via 'PrintMaxExpArray.py'
uint256[128] private maxExpArray;
uint256[128] private maxExpArray;
14,292
87
// Name and symbol were updated. // Minimum ammount of tokens every buyer can buy. //Construct the token. This token must be created through a team multisig wallet, so that it is owned by that wallet._name Token name _symbol Token symbol - should be all caps _initialSupply How many tokens we start with _decimals Number of decimal places _mintable Are new tokens created over the crowdsale or do we distribute only the initial supply? Note that when the token becomes transferable the minting always ends. /
function CrowdsaleTokenExt(string _name, string _symbol, uint _initialSupply, uint _decimals, bool _mintable, uint _globalMinCap)
function CrowdsaleTokenExt(string _name, string _symbol, uint _initialSupply, uint _decimals, bool _mintable, uint _globalMinCap)
5,026
144
// require(addresses[i].isContract(), "Role address need contract only");
if (setTo[i]) { grantRole(roleType, addresses[i]); } else {
if (setTo[i]) { grantRole(roleType, addresses[i]); } else {
41,390
179
// The Prepaid Aggregator contract Handles aggregating data pushed in from off-chain, and unlockspayment for oracles as they report. Oracles' submissions are gathered inrounds, with each round aggregating the submissions for each oracle into asingle answer. The latest aggregated answer is exposed as well as historicalanswers and their updated at timestamp. /
contract FluxAggregator is AggregatorV2V3Interface, Owned { using SafeMath for uint256; using SafeMath128 for uint128; using SafeMath64 for uint64; using SafeMath32 for uint32; struct Round { int256 answer; uint64 startedAt; uint64 updatedAt; uint32 answeredInRound; } struct RoundDetails { int256[] submissions; uint32 maxSubmissions; uint32 minSubmissions; uint32 timeout; uint128 paymentAmount; } struct OracleStatus { uint128 withdrawable; uint32 startingRound; uint32 endingRound; uint32 lastReportedRound; uint32 lastStartedRound; int256 latestSubmission; uint16 index; address admin; address pendingAdmin; } struct Requester { bool authorized; uint32 delay; uint32 lastStartedRound; } struct Funds { uint128 available; uint128 allocated; } LinkTokenInterface public linkToken; AggregatorValidatorInterface public validator; // Round related params uint128 public paymentAmount; uint32 public maxSubmissionCount; uint32 public minSubmissionCount; uint32 public restartDelay; uint32 public timeout; uint8 public override decimals; string public override description; int256 immutable public minSubmissionValue; int256 immutable public maxSubmissionValue; uint256 constant public override version = 3; /** * @notice To ensure owner isn't withdrawing required funds as oracles are * submitting updates, we enforce that the contract maintains a minimum * reserve of RESERVE_ROUNDS * oracleCount() LINK earmarked for payment to * oracles. (Of course, this doesn't prevent the contract from running out of * funds without the owner's intervention.) */ uint256 constant private RESERVE_ROUNDS = 2; uint256 constant private MAX_ORACLE_COUNT = 77; uint32 constant private ROUND_MAX = 2**32-1; uint256 private constant VALIDATOR_GAS_LIMIT = 100000; // An error specific to the Aggregator V3 Interface, to prevent possible // confusion around accidentally reading unset values as reported values. string constant private V3_NO_DATA_ERROR = "No data present"; uint32 private reportingRoundId; uint32 internal latestRoundId; mapping(address => OracleStatus) private oracles; mapping(uint32 => Round) internal rounds; mapping(uint32 => RoundDetails) internal details; mapping(address => Requester) internal requesters; address[] private oracleAddresses; Funds private recordedFunds; event AvailableFundsUpdated( uint256 indexed amount ); event RoundDetailsUpdated( uint128 indexed paymentAmount, uint32 indexed minSubmissionCount, uint32 indexed maxSubmissionCount, uint32 restartDelay, uint32 timeout // measured in seconds ); event OraclePermissionsUpdated( address indexed oracle, bool indexed whitelisted ); event OracleAdminUpdated( address indexed oracle, address indexed newAdmin ); event OracleAdminUpdateRequested( address indexed oracle, address admin, address newAdmin ); event SubmissionReceived( int256 indexed submission, uint32 indexed round, address indexed oracle ); event RequesterPermissionsSet( address indexed requester, bool authorized, uint32 delay ); event ValidatorUpdated( address indexed previous, address indexed current ); /** * @notice set up the aggregator with initial configuration * @param _link The address of the LINK token * @param _paymentAmount The amount paid of LINK paid to each oracle per submission, in wei (units of 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 SafeMath for uint256; using SafeMath128 for uint128; using SafeMath64 for uint64; using SafeMath32 for uint32; struct Round { int256 answer; uint64 startedAt; uint64 updatedAt; uint32 answeredInRound; } struct RoundDetails { int256[] submissions; uint32 maxSubmissions; uint32 minSubmissions; uint32 timeout; uint128 paymentAmount; } struct OracleStatus { uint128 withdrawable; uint32 startingRound; uint32 endingRound; uint32 lastReportedRound; uint32 lastStartedRound; int256 latestSubmission; uint16 index; address admin; address pendingAdmin; } struct Requester { bool authorized; uint32 delay; uint32 lastStartedRound; } struct Funds { uint128 available; uint128 allocated; } LinkTokenInterface public linkToken; AggregatorValidatorInterface public validator; // Round related params uint128 public paymentAmount; uint32 public maxSubmissionCount; uint32 public minSubmissionCount; uint32 public restartDelay; uint32 public timeout; uint8 public override decimals; string public override description; int256 immutable public minSubmissionValue; int256 immutable public maxSubmissionValue; uint256 constant public override version = 3; /** * @notice To ensure owner isn't withdrawing required funds as oracles are * submitting updates, we enforce that the contract maintains a minimum * reserve of RESERVE_ROUNDS * oracleCount() LINK earmarked for payment to * oracles. (Of course, this doesn't prevent the contract from running out of * funds without the owner's intervention.) */ uint256 constant private RESERVE_ROUNDS = 2; uint256 constant private MAX_ORACLE_COUNT = 77; uint32 constant private ROUND_MAX = 2**32-1; uint256 private constant VALIDATOR_GAS_LIMIT = 100000; // An error specific to the Aggregator V3 Interface, to prevent possible // confusion around accidentally reading unset values as reported values. string constant private V3_NO_DATA_ERROR = "No data present"; uint32 private reportingRoundId; uint32 internal latestRoundId; mapping(address => OracleStatus) private oracles; mapping(uint32 => Round) internal rounds; mapping(uint32 => RoundDetails) internal details; mapping(address => Requester) internal requesters; address[] private oracleAddresses; Funds private recordedFunds; event AvailableFundsUpdated( uint256 indexed amount ); event RoundDetailsUpdated( uint128 indexed paymentAmount, uint32 indexed minSubmissionCount, uint32 indexed maxSubmissionCount, uint32 restartDelay, uint32 timeout // measured in seconds ); event OraclePermissionsUpdated( address indexed oracle, bool indexed whitelisted ); event OracleAdminUpdated( address indexed oracle, address indexed newAdmin ); event OracleAdminUpdateRequested( address indexed oracle, address admin, address newAdmin ); event SubmissionReceived( int256 indexed submission, uint32 indexed round, address indexed oracle ); event RequesterPermissionsSet( address indexed requester, bool authorized, uint32 delay ); event ValidatorUpdated( address indexed previous, address indexed current ); /** * @notice set up the aggregator with initial configuration * @param _link The address of the LINK token * @param _paymentAmount The amount paid of LINK paid to each oracle per submission, in wei (units of 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; } }
14,405
168
// OVERRIDEadd account to whitelist & create a snapshot of current balanceaccount address/
function addWhitelisted(address account) public { super.addWhitelisted(account); uint256 balance = balanceOf(account); _createAccountSnapshot(account, balance); uint256 newSupplyValue = totalSupplyAt(now).add(balance); _createTotalSupplySnapshot(account, newSupplyValue); }
function addWhitelisted(address account) public { super.addWhitelisted(account); uint256 balance = balanceOf(account); _createAccountSnapshot(account, balance); uint256 newSupplyValue = totalSupplyAt(now).add(balance); _createTotalSupplySnapshot(account, newSupplyValue); }
4,125
26
// Calculates the price of a VRF request with the given callbackGasLimit at the current block.This function relies on the transaction gas price which is not automatically set during simulation. To estimate the price at a specific gas price, use the estimatePrice function._callbackGasLimit is the gas limit used to estimate the price. /
function calculateRequestPrice(uint32 _callbackGasLimit) external view returns (uint256);
function calculateRequestPrice(uint32 _callbackGasLimit) external view returns (uint256);
3,156
0
// ISafeGnosis interface.
ISafeGnosis public safeGnosis;
ISafeGnosis public safeGnosis;
42,111
35
// Internal function that mints an amount of the token and assigns it to an account. This encapsulates the modification of balances such that the proper events are emitted._account The account that will receive the created tokens._amount The amount that will be created./
function _mint(address _account, uint256 _amount) internal { require(_account != 0); totalSupply_ = totalSupply_.add(_amount); balances[_account] = balances[_account].add(_amount); emit Transfer(address(0), _account, _amount); }
function _mint(address _account, uint256 _amount) internal { require(_account != 0); totalSupply_ = totalSupply_.add(_amount); balances[_account] = balances[_account].add(_amount); emit Transfer(address(0), _account, _amount); }
30,113
4
// store accounts that have voted
mapping(address => Voter) private voters;
mapping(address => Voter) private voters;
13,637
16
// transfer token from reward contract to lock contract
token.safeTransferFrom(msg.sender, address(this), quantity);
token.safeTransferFrom(msg.sender, address(this), quantity);
13,648
177
// Update Public Sale Cost
function setPublicPrice(uint256 _newPublicPrice) public onlyOwner { PublicPrice = _newPublicPrice; }
function setPublicPrice(uint256 _newPublicPrice) public onlyOwner { PublicPrice = _newPublicPrice; }
30,512
10
// Event emitted upon a withdrawal with timelock
event TimelockedWithdrawal( address indexed operator, address indexed from, address indexed token, uint256 amount, uint256 unlockTimestamp ); event ReserveWithdrawal( address indexed to,
event TimelockedWithdrawal( address indexed operator, address indexed from, address indexed token, uint256 amount, uint256 unlockTimestamp ); event ReserveWithdrawal( address indexed to,
14,328
11
// Broadcast deposit event
emit DepositMade(msg.sender, msg.value); // fire event return balances[msg.sender];
emit DepositMade(msg.sender, msg.value); // fire event return balances[msg.sender];
33,193
194
// Emit batch mint event
emit TransferBatch(operator, origin, _to, _ids, _amounts);
emit TransferBatch(operator, origin, _to, _ids, _amounts);
27,327
63
// add addresses to the whitelist _operators addressesreturn true if at least one address was added to the whitelist,false if all addresses were already in the whitelist /
function addAddressesToWhitelist(address[] _operators) public onlyOwner { for (uint256 i = 0; i < _operators.length; i++) { addAddressToWhitelist(_operators[i]); } }
function addAddressesToWhitelist(address[] _operators) public onlyOwner { for (uint256 i = 0; i < _operators.length; i++) { addAddressToWhitelist(_operators[i]); } }
32,848
3
// ---------------------- MODIFIERS ----------------------
modifier onlyExistsTicket(uint256 tier, uint256 amount) { require(amount > 0, "Amount of tickets must be higher than 0"); Ticket memory _ticket = _tierToTicket[tier]; require(_ticket.tier != 0, "Ticket is not exist"); _; }
modifier onlyExistsTicket(uint256 tier, uint256 amount) { require(amount > 0, "Amount of tickets must be higher than 0"); Ticket memory _ticket = _tierToTicket[tier]; require(_ticket.tier != 0, "Ticket is not exist"); _; }
5,393
12
// ------------------------------------------------------------------------ Get the token balance for account tokenOwner ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; }
function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; }
2,008
21
// _link is the address of LinkToken _vrfV2Wrapper is the address of the VRFV2Wrapper contract /
constructor(address _link, address _vrfV2Wrapper) { LINK = LinkTokenInterface(_link); VRF_V2_WRAPPER = VRFV2WrapperInterface(_vrfV2Wrapper); }
constructor(address _link, address _vrfV2Wrapper) { LINK = LinkTokenInterface(_link); VRF_V2_WRAPPER = VRFV2WrapperInterface(_vrfV2Wrapper); }
23,477
45
// Internal function to add a token ID to the list of a given address_to address representing the new owner of the given token ID_tokenId uint256 ID of the token to be added to the tokens list of the given address/
function addToken(address _to, uint256 _tokenId) private { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; uint256 length = balanceOf(_to); ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; totalTokens = totalTokens.add(1); }
function addToken(address _to, uint256 _tokenId) private { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; uint256 length = balanceOf(_to); ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; totalTokens = totalTokens.add(1); }
82,252
130
// When block number more than endReleaseBlock, all locked ALPACAs can be unlocked
else if (block.number >= endReleaseBlock) { return _locks[_account]; }
else if (block.number >= endReleaseBlock) { return _locks[_account]; }
11,197
54
// Sets the protocol management fee percentage/_managementFee The new management fee/Only Governance; base 1000, 1% = 10
function setManagementFee(uint256 _managementFee) external onlyGovernance { require(_managementFee > MIN_MANAGEMENT_FEE, "Registry: Invalid Mgmt"); require(_managementFee < MAX_MANAGEMENT_FEE, "Registry: Mgmt Too High"); managementFee = _managementFee; }
function setManagementFee(uint256 _managementFee) external onlyGovernance { require(_managementFee > MIN_MANAGEMENT_FEE, "Registry: Invalid Mgmt"); require(_managementFee < MAX_MANAGEMENT_FEE, "Registry: Mgmt Too High"); managementFee = _managementFee; }
8,741
96
// list of payees
address[] public payees; address private constant ETHER_ASSET = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address[] public payees; address private constant ETHER_ASSET = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
19,269
17
// for from, withdraw the revenue on the amount of token transferd
from.transfer(fromBonus); emit Transfer(from, to, amount); emit Withdraw(from, fromBonus);
from.transfer(fromBonus); emit Transfer(from, to, amount); emit Withdraw(from, fromBonus);
6,228
60
// distribute the Tokens
C4FToken C4F = C4FToken(owner);
C4FToken C4F = C4FToken(owner);
39,079
105
// Contains the functionality to transition the token to the open market using the market transtition contract.Requires that the market has reached the transition state. Transfers collateral into the market transition contract which then creates the uniswap market./
function _transition() internal { require( transitionConditionsMet, "Token has not met requirements for free market transition" ); address router = marketTransfterInstance.getRouterAddress(); uint256 tokensToMint = marketTransfterInstance.getTokensToMint(); _mint(address(marketTransfterInstance), tokensToMint); // Approves require( collateralInstance.transfer( address(marketTransfterInstance), collateralInstance.balanceOf(address(this)) ), "Transfer of collateral failed" ); marketTransfterInstance.transition(); }
function _transition() internal { require( transitionConditionsMet, "Token has not met requirements for free market transition" ); address router = marketTransfterInstance.getRouterAddress(); uint256 tokensToMint = marketTransfterInstance.getTokensToMint(); _mint(address(marketTransfterInstance), tokensToMint); // Approves require( collateralInstance.transfer( address(marketTransfterInstance), collateralInstance.balanceOf(address(this)) ), "Transfer of collateral failed" ); marketTransfterInstance.transition(); }
2,132
7
// A boolean for use in other contracts to halt execution if the oraclebecomes at of sync by (delay + 120) seconds. Throwing based on this function should be safe as the 120 second bufferaccounts for network congestion so it should always be true unless theoracle is unfunded. /
function priceNeedsUpdate() public constant returns (bool) { return block.timestamp > lastUpdated + delay + 120; }
function priceNeedsUpdate() public constant returns (bool) { return block.timestamp > lastUpdated + delay + 120; }
246
303
// Admin owned tokens can be rolled while paused for testing purposes, but no chance of jackpot
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()) || tokens[tid].level < paused_level,"Rolling paused"); require(num> 0 && num <= 10,"Number of rolls must be in range 1 - 10"); require(msg.value >= roll_price*num, "Must send minimum value to purchase!"); require(LINK.balanceOf(address(this)) >= fee*num, "Not enough LINK - fill contract"); for (uint i=0;i<num;i++) { bytes32 requestId = requestRandomness(keyHash, fee); request2token[requestId] = tid; }
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()) || tokens[tid].level < paused_level,"Rolling paused"); require(num> 0 && num <= 10,"Number of rolls must be in range 1 - 10"); require(msg.value >= roll_price*num, "Must send minimum value to purchase!"); require(LINK.balanceOf(address(this)) >= fee*num, "Not enough LINK - fill contract"); for (uint i=0;i<num;i++) { bytes32 requestId = requestRandomness(keyHash, fee); request2token[requestId] = tid; }
75,114
31
// address of additional reward token accured from investing via different strategies like wmatic.
IERC20[] public rewardTokens;
IERC20[] public rewardTokens;
24,776
201
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function requestPrice(bytes32 identifier, uint256 time) public override { requestPrice(identifier, time, ""); }
function requestPrice(bytes32 identifier, uint256 time) public override { requestPrice(identifier, time, ""); }
21,302
1
// The address that is authorized to manage a validator or validator group and sign consensus messages on behalf of the account. The account can manage the validator, whether or not a validator signing key has been specified. However, if a validator signing key has been specified, only that key may actually participate in consensus.
address validator;
address validator;
15,168
16
// Returns index of non-fungible token
function getNonFungibleIndex(uint256 id) public pure returns (uint256) { return id & NF_INDEX; }
function getNonFungibleIndex(uint256 id) public pure returns (uint256) { return id & NF_INDEX; }
44,867
27
// END RESTRICTIONS//This function withdrawals assets to the target Ethereum address/asset_source Contract address for given ERC20 token/amount Amount of ERC20 tokens to withdraw/target Target Ethereum address to receive withdrawn ERC20 tokens/creation Timestamp of when requestion was created RESTRICTION FEATURE/nonce Vega-assigned single-use number that provides replay attack protection/signatures Vega-supplied signature bundle of a validator-signed order/See MultisigControl for more about signatures/Emits Asset_Withdrawn if successful
function withdraw_asset(address asset_source, uint256 amount, address target, uint256 creation, uint256 nonce, bytes memory signatures) public override{ require(!is_stopped, "bridge stopped"); require(withdraw_thresholds[asset_source] > amount || creation + default_withdraw_delay <= block.timestamp, "large withdraw is not old enough"); bytes memory message = abi.encode(asset_source, amount, target, creation, nonce, 'withdraw_asset'); require(IMultisigControl(multisig_control_address()).verify_signatures(signatures, message, nonce), "bad signatures"); ERC20_Asset_Pool(erc20_asset_pool_address).withdraw(asset_source, target, amount); emit Asset_Withdrawn(target, asset_source, amount, nonce); }
function withdraw_asset(address asset_source, uint256 amount, address target, uint256 creation, uint256 nonce, bytes memory signatures) public override{ require(!is_stopped, "bridge stopped"); require(withdraw_thresholds[asset_source] > amount || creation + default_withdraw_delay <= block.timestamp, "large withdraw is not old enough"); bytes memory message = abi.encode(asset_source, amount, target, creation, nonce, 'withdraw_asset'); require(IMultisigControl(multisig_control_address()).verify_signatures(signatures, message, nonce), "bad signatures"); ERC20_Asset_Pool(erc20_asset_pool_address).withdraw(asset_source, target, amount); emit Asset_Withdrawn(target, asset_source, amount, nonce); }
31,478
14
// Defining addresses that have custom lockups periods
mapping(address => uint256) public lockupExpirations;
mapping(address => uint256) public lockupExpirations;
42,125
14
// get the send() LayerZero messaging library version_userApplication - the contract address of the user application
function getSendVersion( address _userApplication ) external view returns (uint16);
function getSendVersion( address _userApplication ) external view returns (uint16);
18,460
350
// if the current round does not exist create it
if(currentRound >= roundsPerCK.length) { roundsPerCK.push(); }
if(currentRound >= roundsPerCK.length) { roundsPerCK.push(); }
49,357
64
// --- Views ---
function isMaster(bytes32 network) public view returns (bool) { if (networks.length() == 0) return false; return network == networks.at((block.number / window) % networks.length()); }
function isMaster(bytes32 network) public view returns (bool) { if (networks.length() == 0) return false; return network == networks.at((block.number / window) % networks.length()); }
76,055
108
// Used to change `profitFactor`. `profitFactor` is used to determine if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` for more details.)This may only be called by governance or the strategist. _profitFactor A ratio to multiply anticipated`harvest()` gas cost against. /
function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); }
function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); }
9,192
41
// Functions based on Q64.96 sqrt price and liquidity/Aperture Finance/Modified from Uniswap (https:github.com/uniswap/v3-core/blob/main/contracts/libraries/SqrtPriceMath.sol)/Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas
library SqrtPriceMath { using UnsafeMath for *; using SafeCast for uint256; /// @notice Gets the next sqrt price given a delta of token0 /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the /// price less in order to not send too much output. /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96), /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount). /// @param sqrtPX96 The starting price, i.e. before accounting for the token0 delta /// @param liquidity The amount of usable liquidity /// @param amount How much of token0 to add or remove from virtual reserves /// @param add Whether to add or remove the amount of token0 /// @return The price after adding or removing amount, depending on add function getNextSqrtPriceFromAmount0RoundingUp( uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add ) internal pure returns (uint160) { // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price if (amount == 0) return sqrtPX96; uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION; if (add) { unchecked { uint256 product = amount * sqrtPX96; // checks for overflow if (product.div(amount) == sqrtPX96) { // denominator = liquidity + amount * sqrtPX96 uint256 denominator = numerator1 + product; // checks for overflow if (denominator >= numerator1) // always fits in 160 bits return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator)); } } // liquidity / (liquidity / sqrtPX96 + amount) return uint160(numerator1.divRoundingUp(numerator1.div(sqrtPX96) + amount)); } else { uint256 denominator; assembly ("memory-safe") { // if the product overflows, we know the denominator underflows // in addition, we must check that the denominator does not underflow let product := mul(amount, sqrtPX96) if iszero(and(eq(div(product, amount), sqrtPX96), gt(numerator1, product))) { revert(0, 0) } denominator := sub(numerator1, product) } return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160(); } } /// @notice Gets the next sqrt price given a delta of token1 /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the /// price less in order to not send too much output. /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity /// @param sqrtPX96 The starting price, i.e., before accounting for the token1 delta /// @param liquidity The amount of usable liquidity /// @param amount How much of token1 to add, or remove, from virtual reserves /// @param add Whether to add, or remove, the amount of token1 /// @return nextSqrtPrice The price after adding or removing `amount` function getNextSqrtPriceFromAmount1RoundingDown( uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add ) internal pure returns (uint160 nextSqrtPrice) { // if we're adding (subtracting), rounding down requires rounding the quotient down (up) // in both cases, avoid a mulDiv for most inputs if (add) { uint256 quotient = ( amount <= type(uint160).max ? (amount << FixedPoint96.RESOLUTION).div(liquidity) : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity) ); nextSqrtPrice = (sqrtPX96 + quotient).toUint160(); } else { uint256 quotient = ( amount <= type(uint160).max ? (amount << FixedPoint96.RESOLUTION).divRoundingUp(liquidity) : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity) ); assembly ("memory-safe") { if iszero(gt(sqrtPX96, quotient)) { revert(0, 0) } // always fits 160 bits nextSqrtPrice := sub(sqrtPX96, quotient) } } } /// @notice Gets the next sqrt price given an input amount of token0 or token1 /// @dev Throws if price or liquidity are 0, or if the next price is out of bounds /// @param sqrtPX96 The starting price, i.e., before accounting for the input amount /// @param liquidity The amount of usable liquidity /// @param amountIn How much of token0, or token1, is being swapped in /// @param zeroForOne Whether the amount in is token0 or token1 /// @return sqrtQX96 The price after adding the input amount to token0 or token1 function getNextSqrtPriceFromInput( uint160 sqrtPX96, uint128 liquidity, uint256 amountIn, bool zeroForOne ) internal pure returns (uint160 sqrtQX96) { assembly ("memory-safe") { if or(iszero(sqrtPX96), iszero(liquidity)) { revert(0, 0) } } // round to make sure that we don't pass the target price return zeroForOne ? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true) : getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true); } /// @notice Gets the next sqrt price given an output amount of token0 or token1 /// @dev Throws if price or liquidity are 0 or the next price is out of bounds /// @param sqrtPX96 The starting price before accounting for the output amount /// @param liquidity The amount of usable liquidity /// @param amountOut How much of token0, or token1, is being swapped out /// @param zeroForOne Whether the amount out is token0 or token1 /// @return sqrtQX96 The price after removing the output amount of token0 or token1 function getNextSqrtPriceFromOutput( uint160 sqrtPX96, uint128 liquidity, uint256 amountOut, bool zeroForOne ) internal pure returns (uint160 sqrtQX96) { assembly ("memory-safe") { if or(iszero(sqrtPX96), iszero(liquidity)) { revert(0, 0) } } // round to make sure that we pass the target price return zeroForOne ? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false) : getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false); } /// @notice Gets the amount0 delta between two prices /// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper), /// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price assumed to be lower otherwise swapped /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The amount of usable liquidity /// @param roundUp Whether to round the amount up or down /// @return amount0 Amount of token0 required to cover a position of size liquidity between the two passed prices function getAmount0Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity, bool roundUp ) internal pure returns (uint256 amount0) { (sqrtRatioAX96, sqrtRatioBX96) = TernaryLib.sort2(sqrtRatioAX96, sqrtRatioBX96); assembly ("memory-safe") { if iszero(sqrtRatioAX96) { revert(0, 0) } } uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION; uint256 numerator2 = sqrtRatioBX96.sub(sqrtRatioAX96); /** * Equivalent to: * roundUp * ? FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96).divRoundingUp(sqrtRatioAX96) * : FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96; * If `md = mulDiv(n1, n2, srb) == mulDivRoundingUp(n1, n2, srb)`, then `mulmod(n1, n2, srb) == 0`. * Add `roundUp && md % sra > 0` to `div(md, sra)`. * If `md = mulDiv(n1, n2, srb)` and `mulDivRoundingUp(n1, n2, srb)` differs by 1 and `sra > 0`, * then `(md + 1).divRoundingUp(sra) == md.div(sra) + 1` whether `sra` fully divides `md` or not. */ uint256 mulDivResult = FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96); assembly { amount0 := add( div(mulDivResult, sqrtRatioAX96), and(gt(or(mod(mulDivResult, sqrtRatioAX96), mulmod(numerator1, numerator2, sqrtRatioBX96)), 0), roundUp) ) } } /// @notice Gets the amount1 delta between two prices /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price assumed to be lower otherwise swapped /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The amount of usable liquidity /// @param roundUp Whether to round the amount up, or down /// @return amount1 Amount of token1 required to cover a position of size liquidity between the two passed prices function getAmount1Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity, bool roundUp ) internal pure returns (uint256 amount1) { (sqrtRatioAX96, sqrtRatioBX96) = TernaryLib.sort2(sqrtRatioAX96, sqrtRatioBX96); uint256 numerator = sqrtRatioBX96.sub(sqrtRatioAX96); uint256 denominator = FixedPoint96.Q96; /** * Equivalent to: * amount1 = roundUp * ? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96) * : FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); * Cannot overflow because `type(uint128).max * type(uint160).max >> 96 < (1 << 192)`. */ amount1 = FullMath.mulDiv96(liquidity, numerator); assembly { amount1 := add(amount1, and(gt(mulmod(liquidity, numerator, denominator), 0), roundUp)) } } /// @notice Helper that gets signed token0 delta /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The change in liquidity for which to compute the amount0 delta /// @return amount0 Amount of token0 corresponding to the passed liquidityDelta between the two prices function getAmount0Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, int128 liquidity ) internal pure returns (int256 amount0) { /** * Equivalent to: * amount0 = liquidity < 0 * ? -getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256() * : getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256(); */ bool sign; uint256 mask; uint128 liquidityAbs; assembly { // In case the upper bits are not clean. liquidity := signextend(15, liquidity) // sign = 1 if liquidity >= 0 else 0 sign := iszero(slt(liquidity, 0)) // mask = 0 if liquidity >= 0 else -1 mask := sub(sign, 1) liquidityAbs := xor(mask, add(mask, liquidity)) } // amount0Abs = liquidity / sqrt(lower) - liquidity / sqrt(upper) < type(uint224).max // always fits in 224 bits, no need for toInt256() uint256 amount0Abs = getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, liquidityAbs, sign); assembly { // If liquidity >= 0, amount0 = |amount0| = 0 ^ |amount0| // If liquidity < 0, amount0 = -|amount0| = ~|amount0| + 1 = (-1) ^ |amount0| - (-1) amount0 := sub(xor(amount0Abs, mask), mask) } } /// @notice Helper that gets signed token1 delta /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The change in liquidity for which to compute the amount1 delta /// @return amount1 Amount of token1 corresponding to the passed liquidityDelta between the two prices function getAmount1Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, int128 liquidity ) internal pure returns (int256 amount1) { /** * Equivalent to: * amount1 = liquidity < 0 * ? -getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256() * : getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256(); */ bool sign; uint256 mask; uint128 liquidityAbs; assembly { // In case the upper bits are not clean. liquidity := signextend(15, liquidity) // sign = 1 if liquidity >= 0 else 0 sign := iszero(slt(liquidity, 0)) // mask = 0 if liquidity >= 0 else -1 mask := sub(sign, 1) liquidityAbs := xor(mask, add(mask, liquidity)) } // amount1Abs = liquidity * (sqrt(upper) - sqrt(lower)) < type(uint192).max // always fits in 192 bits, no need for toInt256() uint256 amount1Abs = getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, liquidityAbs, sign); assembly { // If liquidity >= 0, amount1 = |amount1| = 0 ^ |amount1| // If liquidity < 0, amount1 = -|amount1| = ~|amount1| + 1 = (-1) ^ |amount1| - (-1) amount1 := sub(xor(amount1Abs, mask), mask) } } }
library SqrtPriceMath { using UnsafeMath for *; using SafeCast for uint256; /// @notice Gets the next sqrt price given a delta of token0 /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the /// price less in order to not send too much output. /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96), /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount). /// @param sqrtPX96 The starting price, i.e. before accounting for the token0 delta /// @param liquidity The amount of usable liquidity /// @param amount How much of token0 to add or remove from virtual reserves /// @param add Whether to add or remove the amount of token0 /// @return The price after adding or removing amount, depending on add function getNextSqrtPriceFromAmount0RoundingUp( uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add ) internal pure returns (uint160) { // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price if (amount == 0) return sqrtPX96; uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION; if (add) { unchecked { uint256 product = amount * sqrtPX96; // checks for overflow if (product.div(amount) == sqrtPX96) { // denominator = liquidity + amount * sqrtPX96 uint256 denominator = numerator1 + product; // checks for overflow if (denominator >= numerator1) // always fits in 160 bits return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator)); } } // liquidity / (liquidity / sqrtPX96 + amount) return uint160(numerator1.divRoundingUp(numerator1.div(sqrtPX96) + amount)); } else { uint256 denominator; assembly ("memory-safe") { // if the product overflows, we know the denominator underflows // in addition, we must check that the denominator does not underflow let product := mul(amount, sqrtPX96) if iszero(and(eq(div(product, amount), sqrtPX96), gt(numerator1, product))) { revert(0, 0) } denominator := sub(numerator1, product) } return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160(); } } /// @notice Gets the next sqrt price given a delta of token1 /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the /// price less in order to not send too much output. /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity /// @param sqrtPX96 The starting price, i.e., before accounting for the token1 delta /// @param liquidity The amount of usable liquidity /// @param amount How much of token1 to add, or remove, from virtual reserves /// @param add Whether to add, or remove, the amount of token1 /// @return nextSqrtPrice The price after adding or removing `amount` function getNextSqrtPriceFromAmount1RoundingDown( uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add ) internal pure returns (uint160 nextSqrtPrice) { // if we're adding (subtracting), rounding down requires rounding the quotient down (up) // in both cases, avoid a mulDiv for most inputs if (add) { uint256 quotient = ( amount <= type(uint160).max ? (amount << FixedPoint96.RESOLUTION).div(liquidity) : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity) ); nextSqrtPrice = (sqrtPX96 + quotient).toUint160(); } else { uint256 quotient = ( amount <= type(uint160).max ? (amount << FixedPoint96.RESOLUTION).divRoundingUp(liquidity) : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity) ); assembly ("memory-safe") { if iszero(gt(sqrtPX96, quotient)) { revert(0, 0) } // always fits 160 bits nextSqrtPrice := sub(sqrtPX96, quotient) } } } /// @notice Gets the next sqrt price given an input amount of token0 or token1 /// @dev Throws if price or liquidity are 0, or if the next price is out of bounds /// @param sqrtPX96 The starting price, i.e., before accounting for the input amount /// @param liquidity The amount of usable liquidity /// @param amountIn How much of token0, or token1, is being swapped in /// @param zeroForOne Whether the amount in is token0 or token1 /// @return sqrtQX96 The price after adding the input amount to token0 or token1 function getNextSqrtPriceFromInput( uint160 sqrtPX96, uint128 liquidity, uint256 amountIn, bool zeroForOne ) internal pure returns (uint160 sqrtQX96) { assembly ("memory-safe") { if or(iszero(sqrtPX96), iszero(liquidity)) { revert(0, 0) } } // round to make sure that we don't pass the target price return zeroForOne ? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true) : getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true); } /// @notice Gets the next sqrt price given an output amount of token0 or token1 /// @dev Throws if price or liquidity are 0 or the next price is out of bounds /// @param sqrtPX96 The starting price before accounting for the output amount /// @param liquidity The amount of usable liquidity /// @param amountOut How much of token0, or token1, is being swapped out /// @param zeroForOne Whether the amount out is token0 or token1 /// @return sqrtQX96 The price after removing the output amount of token0 or token1 function getNextSqrtPriceFromOutput( uint160 sqrtPX96, uint128 liquidity, uint256 amountOut, bool zeroForOne ) internal pure returns (uint160 sqrtQX96) { assembly ("memory-safe") { if or(iszero(sqrtPX96), iszero(liquidity)) { revert(0, 0) } } // round to make sure that we pass the target price return zeroForOne ? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false) : getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false); } /// @notice Gets the amount0 delta between two prices /// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper), /// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price assumed to be lower otherwise swapped /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The amount of usable liquidity /// @param roundUp Whether to round the amount up or down /// @return amount0 Amount of token0 required to cover a position of size liquidity between the two passed prices function getAmount0Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity, bool roundUp ) internal pure returns (uint256 amount0) { (sqrtRatioAX96, sqrtRatioBX96) = TernaryLib.sort2(sqrtRatioAX96, sqrtRatioBX96); assembly ("memory-safe") { if iszero(sqrtRatioAX96) { revert(0, 0) } } uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION; uint256 numerator2 = sqrtRatioBX96.sub(sqrtRatioAX96); /** * Equivalent to: * roundUp * ? FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96).divRoundingUp(sqrtRatioAX96) * : FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96; * If `md = mulDiv(n1, n2, srb) == mulDivRoundingUp(n1, n2, srb)`, then `mulmod(n1, n2, srb) == 0`. * Add `roundUp && md % sra > 0` to `div(md, sra)`. * If `md = mulDiv(n1, n2, srb)` and `mulDivRoundingUp(n1, n2, srb)` differs by 1 and `sra > 0`, * then `(md + 1).divRoundingUp(sra) == md.div(sra) + 1` whether `sra` fully divides `md` or not. */ uint256 mulDivResult = FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96); assembly { amount0 := add( div(mulDivResult, sqrtRatioAX96), and(gt(or(mod(mulDivResult, sqrtRatioAX96), mulmod(numerator1, numerator2, sqrtRatioBX96)), 0), roundUp) ) } } /// @notice Gets the amount1 delta between two prices /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price assumed to be lower otherwise swapped /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The amount of usable liquidity /// @param roundUp Whether to round the amount up, or down /// @return amount1 Amount of token1 required to cover a position of size liquidity between the two passed prices function getAmount1Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity, bool roundUp ) internal pure returns (uint256 amount1) { (sqrtRatioAX96, sqrtRatioBX96) = TernaryLib.sort2(sqrtRatioAX96, sqrtRatioBX96); uint256 numerator = sqrtRatioBX96.sub(sqrtRatioAX96); uint256 denominator = FixedPoint96.Q96; /** * Equivalent to: * amount1 = roundUp * ? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96) * : FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); * Cannot overflow because `type(uint128).max * type(uint160).max >> 96 < (1 << 192)`. */ amount1 = FullMath.mulDiv96(liquidity, numerator); assembly { amount1 := add(amount1, and(gt(mulmod(liquidity, numerator, denominator), 0), roundUp)) } } /// @notice Helper that gets signed token0 delta /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The change in liquidity for which to compute the amount0 delta /// @return amount0 Amount of token0 corresponding to the passed liquidityDelta between the two prices function getAmount0Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, int128 liquidity ) internal pure returns (int256 amount0) { /** * Equivalent to: * amount0 = liquidity < 0 * ? -getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256() * : getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256(); */ bool sign; uint256 mask; uint128 liquidityAbs; assembly { // In case the upper bits are not clean. liquidity := signextend(15, liquidity) // sign = 1 if liquidity >= 0 else 0 sign := iszero(slt(liquidity, 0)) // mask = 0 if liquidity >= 0 else -1 mask := sub(sign, 1) liquidityAbs := xor(mask, add(mask, liquidity)) } // amount0Abs = liquidity / sqrt(lower) - liquidity / sqrt(upper) < type(uint224).max // always fits in 224 bits, no need for toInt256() uint256 amount0Abs = getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, liquidityAbs, sign); assembly { // If liquidity >= 0, amount0 = |amount0| = 0 ^ |amount0| // If liquidity < 0, amount0 = -|amount0| = ~|amount0| + 1 = (-1) ^ |amount0| - (-1) amount0 := sub(xor(amount0Abs, mask), mask) } } /// @notice Helper that gets signed token1 delta /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The change in liquidity for which to compute the amount1 delta /// @return amount1 Amount of token1 corresponding to the passed liquidityDelta between the two prices function getAmount1Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, int128 liquidity ) internal pure returns (int256 amount1) { /** * Equivalent to: * amount1 = liquidity < 0 * ? -getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256() * : getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256(); */ bool sign; uint256 mask; uint128 liquidityAbs; assembly { // In case the upper bits are not clean. liquidity := signextend(15, liquidity) // sign = 1 if liquidity >= 0 else 0 sign := iszero(slt(liquidity, 0)) // mask = 0 if liquidity >= 0 else -1 mask := sub(sign, 1) liquidityAbs := xor(mask, add(mask, liquidity)) } // amount1Abs = liquidity * (sqrt(upper) - sqrt(lower)) < type(uint192).max // always fits in 192 bits, no need for toInt256() uint256 amount1Abs = getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, liquidityAbs, sign); assembly { // If liquidity >= 0, amount1 = |amount1| = 0 ^ |amount1| // If liquidity < 0, amount1 = -|amount1| = ~|amount1| + 1 = (-1) ^ |amount1| - (-1) amount1 := sub(xor(amount1Abs, mask), mask) } } }
23,850
19
// public variables for DAPP
uint public counterDeposits; uint public counterPercents; uint public counterBeneficiaries; uint public timeLastayment;
uint public counterDeposits; uint public counterPercents; uint public counterBeneficiaries; uint public timeLastayment;
53,669
156
// If there's no funding cycle, track this payment as having been made before a configuration.
if (_fundingCycle.number == 0) {
if (_fundingCycle.number == 0) {
16,952
148
// Variables changing during day to day interaction.
uint public session = 1; // Current session of the court. uint public lastPeriodChange; // The last time we changed of period (seconds). uint public segmentSize; // Size of the segment of activated tokens. uint public rnBlock; // The block linked with the RN which is requested. uint public randomNumber; // Random number of the session.
uint public session = 1; // Current session of the court. uint public lastPeriodChange; // The last time we changed of period (seconds). uint public segmentSize; // Size of the segment of activated tokens. uint public rnBlock; // The block linked with the RN which is requested. uint public randomNumber; // Random number of the session.
76,081
9
// Structure that defines the return data for a given call
struct ReturnData { // Whether the call should be successful bool success; // The data to return // If the call is unsuccessful, this is the reason for failure bytes data; }
struct ReturnData { // Whether the call should be successful bool success; // The data to return // If the call is unsuccessful, this is the reason for failure bytes data; }
46,787
54
// Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution ```solidity uint256 count = 5; console.log('count: %d', count); console.log('count:', count); ``` See `util.format()` for more information./
function log(string memory value1, address value2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", value1, value2)); }
function log(string memory value1, address value2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", value1, value2)); }
22,169
7
// sanity check to ensure we don't overflow arithmetic (this big number is 2^128-1).
require(avePrice < 340282366920938463463374607431768211455); uint256 nextPrice = avePrice + (avePrice / 2);
require(avePrice < 340282366920938463463374607431768211455); uint256 nextPrice = avePrice + (avePrice / 2);
48,837
84
// Delegate votes from `msg.sender` to `delegatee` delegatee The address to delegate votes to /
function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); }
function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); }
672
110
// Reverts if the sender is not the auction's curator.
modifier onlyCurator(uint256 tokenId) { require( auctions[tokenId].curator == msg.sender, "Can only be called by auction curator" ); _; }
modifier onlyCurator(uint256 tokenId) { require( auctions[tokenId].curator == msg.sender, "Can only be called by auction curator" ); _; }
24,457
71
// AttendanceTokenControllerTEST Test various way to validate signatures in order to optimize gas consumption /
contract ParticipationTokenControllerTEST is Ownable { using SafeMath for uint256; //Variables mapping (address => bool) admin; // Who can sign messages mapping (address => mapping (uint256 => bool)) redeemedTokens; // Whether tokens where redeemed for an ID FrozenMintBurnToken public token; // Token contract //Struct mapping (address => bool) sigUsed; //placeholder to prevent reusing same signature uint8 sigRequired = 2; //Number of signatures required to redeem tokens //Variables for BITMASK mapping(uint256 => address) IDadmin; mapping(address => uint256) adminID; //Events event TokensRedeemed(address indexed _address, uint256 _amount, uint256 _nonce); event AdminStatusChanged(address _admin, uint256 _adminStatus); event SigRequiredChanged(uint256 _sigRequired); /* @dev Create new ParticipationToken and token controller contract @param _name Name of the new participation token. @param _symbol Symbol of the new participation token. @param _decimals Number of decimals for the new participation token. */ function ParticipationTokenControllerTEST( string _name, string _symbol, uint8 _decimals) public { // Create new token token = new FrozenMintBurnToken(_name, _symbol, _decimals); } /* @dev Change the authorization status of a given address @param _add Address to change authorization status @param _adminStatus Authorization status to give to address */ function setAdminStatus(address _add, bool _adminStatus) public onlyOwner returns(bool) { admin[_add] = _adminStatus; //AdminStatusChanged(_add, _adminStatus); return true; } /* @dev Set number of signatures required to redeem tokens. @param _sigRequired New number of signature required. */ function setSigRequired(uint8 _sigRequired) onlyOwner public returns (bool) { require(_sigRequired > 0); sigRequired = _sigRequired; SigRequiredChanged(_sigRequired); return true; } /* @dev Allows to redeem tokens to _benificiary if possessing enough valid signed messages @param _beneficiary Address that is allowed to redeem tokens @param _amount Amounts of tokens they can claim @param _nonce Nonce of the event for which this message was generated @param _sigs Array of signatures. */ function redeemTokensARRAY( address _beneficiary, uint256 _amount, uint256 _nonce, bytes _sigs) public returns (bool) { //Number of signatures uint256 nSigs = _sigs.length.div(65); require(nSigs >= sigRequired); //Make sure tokens were not redeemed already for given nonce //require(!redeemedTokens[_beneficiary][_nonce]); address[] memory signer = new address[](sigRequired); bytes32 r; bytes32 s; uint8 v; // Verifying if msg.senders provides enough valid signatures for(uint8 i = 0; i < sigRequired; i++) { // Extract ECDSA signature variables from current signature assembly { r := mload(add(_sigs, add(mul(i, 65), 32))) s := mload(add(_sigs, add(mul(i, 65), 64))) v := byte(0, mload(add(_sigs, add(mul(i, 65), 96)))) } // Check validity of current signature signer[i] = recoverRedeemMessageSignerRSV(_beneficiary, _amount, _nonce, r, s, v); // If signer is an admin and if their signature wasn't already used require(admin[signer[i]]); //Making sure signer wasn't used already for (uint8 ii = 0; ii < i; ii++){ require(signer[ii] != signer[i]); } } //Tokens for given nonce were claimed //redeemedTokens[_beneficiary][_nonce] = true; //Minting tokens to _benificiary token.mint(_beneficiary, _amount); TokensRedeemed(_beneficiary, _amount, _nonce); return true; } //ARRAY APPROACH function redeemTokensMAPPING( address _beneficiary, uint256 _amount, uint256 _nonce, bytes _sigs) public returns (bool) { //Number of signatures uint256 nSigs = _sigs.length.div(65); require(nSigs >= sigRequired); //Make sure tokens were not redeemed already for given nonce //require(!redeemedTokens[_beneficiary][_nonce]); address[] memory signer = new address[](sigRequired); bytes32 r; bytes32 s; uint8 v; // Verifying if msg.senders provides enough valid signatures for(uint8 i = 0; i < sigRequired; i++) { // Extract ECDSA signature variables from current signature assembly { r := mload(add(_sigs, add(mul(i, 65), 32))) s := mload(add(_sigs, add(mul(i, 65), 64))) v := byte(0, mload(add(_sigs, add(mul(i, 65), 96)))) } // Check validity of current signature signer[i] = recoverRedeemMessageSignerRSV(_beneficiary, _amount, _nonce, r, s, v); // If signer is an admin and if their signature wasn't already used require(admin[signer[i]]); // Signature from signer has been used sigUsed[signer[i]] = true; } //Tokens for given nonce were claimed //redeemedTokens[_beneficiary][_nonce] = true; //Minting tokens to _benificiary token.mint(_beneficiary, _amount); //Clearing sigUsed for (i = 0; i < sigRequired; i++){ sigUsed[signer[i]] = false; } TokensRedeemed(_beneficiary, _amount, _nonce); return true; } // BITMASK APPROACH function setIDadmin(address _admin, uint256 _ID) public { require(IDadmin[_ID] == 0x0); IDadmin[_ID] = _admin; adminID[_admin] = _ID; } /* @dev Change the authorization status of a given address @param _admin Address to give admin status to */ function setAsAdmin(address _admin) public onlyOwner returns(bool) { //Will find the first free admin spot from 0 to 256 for (uint256 i = 0; i<256; i++){ if (IDadmin[2**i] == 0x0) { IDadmin[2**i] = _admin; adminID[_admin] = 2**i; //AdminStatusChanged(_admin, 2**i); return true; } } return false; } /* @dev Remove admin status from an address @param _admin Address to remove admin status */ function removeAsAdmin(address _admin) public onlyOwner returns(bool) { IDadmin[adminID[_admin]] = 0x0; adminID[_admin] = 0; //AdminStatusChanged(_admin, 0); return true; } function redeemTokensBITMASK( address _beneficiary, uint256 _amount, uint256 _nonce, bytes _sigs) public returns (bool) { uint256 nSigs = _sigs.length.div(65); // Number of signatures require(nSigs >= sigRequired); // Enough signatures provided //require(!redeemedTokens[_beneficiary][_nonce]); // Nonce's tokens not redeemed yet uint256 bitsigners; // Keeps track of who signed address signer; // Address of currently recovered signer bytes32 r; // ECDSA signature r variable bytes32 s; // ECDSA signature s variable uint8 v; // ECDSA signature v variable // Verifying if msg.senders provides enough valid signatures for(uint8 i = 0; i < sigRequired; i++) { // Extract ECDSA signature variables from current signature assembly { r := mload(add(_sigs, add(mul(i, 65), 32))) s := mload(add(_sigs, add(mul(i, 65), 64))) v := byte(0, mload(add(_sigs, add(mul(i, 65), 96)))) } // Check validity of current signature signer = recoverRedeemMessageSignerRSV(_beneficiary, _amount, _nonce, r, s, v); // If signer is an admin, count bitsigners = bitsigners | adminID[signer]; } //Tokens for given nonce were claimed //redeemedTokens[_beneficiary][_nonce] = true; //Counting number of valid signatures uint8 counter = 0; //Count number of unique, valid signatures for (uint256 ii = 0; ii<256; ii++){ if (2**ii & bitsigners == 2**ii) { counter++; if (counter == sigRequired){ //Minting tokens to _benificiary token.mint(_beneficiary, _amount); TokensRedeemed(_beneficiary, _amount, _nonce); return true; } } } return false; } // SEOCND VERSION /* @dev Verifies if message was signed by an admin to give access to _add for this contract. Assumes Geth signature prefix. @param _add Address of agent with access. @param _amount Amount of tokens that can be claimed @param _nonce Nonce of the event @param _sig Valid signature from owner */ function recoverRedeemMessageSigner( address _add, uint256 _amount, uint256 _nonce, bytes _sig) view public returns (address) { bytes32 r; bytes32 s; uint8 v; //Extract ECDSA signature variables from `sig` assembly { r := mload(add(_sig, 32)) s := mload(add(_sig, 64)) v := byte(0, mload(add(_sig, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // Verifying if recovered signer is contract admin bytes32 hash = keccak256(this, _add, _amount, _nonce); //Return recovered signer address return ecrecover( keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s ); } /* @dev Verifies if message was signed by an admin to give access to _add for this contract. Assumes Geth signature prefix. @param _add Address of agent with access. @param _amount Amount of tokens that can be claimed @param _nonce Nonce of the event @param _r r variable from ECDSA signature. @param _s s variable from ECDSA signature. @param _v v variable from ECDSA signature. @return Validity of access message for a given address. */ function recoverRedeemMessageSignerRSV( address _add, uint256 _amount, uint256 _nonce, bytes32 _r, bytes32 _s, uint8 _v) view public returns (address) { // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (_v < 27) { _v += 27; } // Hash of the message that had to be signed bytes32 hash = keccak256(this, _add, _amount, _nonce); //Return recovered signer address return ecrecover( keccak256("\x19Ethereum Signed Message:\n32", hash), _v, _r, _s ); } /* @dev Checks whether the current message is valid. @param _add Address of agent with access. @param _amount Amount of tokens that can be claimed @param _nonce Nonce of the event @param _sig Valid signature from owner */ function isValidRedeemMessage( address _add, uint256 _amount, uint256 _nonce, bytes _sig) view public returns (bool){ return ( adminID[recoverRedeemMessageSigner(_add, _amount, _nonce, _sig)] > 0 ); } /* @dev Returns whether the address is an admin or not. @param _add Address to query admin status. */ function getAdminStatus(address _add) public view returns (bool) { return admin[_add]; } /* @dev Returns admin's ID. @param _add Address to query admin ID. */ function getAdminID(address _add) public view returns (uint256) { return adminID[_add]; } /* @dev Returns the admin's address associated with an ID. @param _add ID (2^i) to query admin's address associated with it . */ function getAdminAddress(uint256 _ID) public view returns (address) { return IDadmin[_ID]; } }
contract ParticipationTokenControllerTEST is Ownable { using SafeMath for uint256; //Variables mapping (address => bool) admin; // Who can sign messages mapping (address => mapping (uint256 => bool)) redeemedTokens; // Whether tokens where redeemed for an ID FrozenMintBurnToken public token; // Token contract //Struct mapping (address => bool) sigUsed; //placeholder to prevent reusing same signature uint8 sigRequired = 2; //Number of signatures required to redeem tokens //Variables for BITMASK mapping(uint256 => address) IDadmin; mapping(address => uint256) adminID; //Events event TokensRedeemed(address indexed _address, uint256 _amount, uint256 _nonce); event AdminStatusChanged(address _admin, uint256 _adminStatus); event SigRequiredChanged(uint256 _sigRequired); /* @dev Create new ParticipationToken and token controller contract @param _name Name of the new participation token. @param _symbol Symbol of the new participation token. @param _decimals Number of decimals for the new participation token. */ function ParticipationTokenControllerTEST( string _name, string _symbol, uint8 _decimals) public { // Create new token token = new FrozenMintBurnToken(_name, _symbol, _decimals); } /* @dev Change the authorization status of a given address @param _add Address to change authorization status @param _adminStatus Authorization status to give to address */ function setAdminStatus(address _add, bool _adminStatus) public onlyOwner returns(bool) { admin[_add] = _adminStatus; //AdminStatusChanged(_add, _adminStatus); return true; } /* @dev Set number of signatures required to redeem tokens. @param _sigRequired New number of signature required. */ function setSigRequired(uint8 _sigRequired) onlyOwner public returns (bool) { require(_sigRequired > 0); sigRequired = _sigRequired; SigRequiredChanged(_sigRequired); return true; } /* @dev Allows to redeem tokens to _benificiary if possessing enough valid signed messages @param _beneficiary Address that is allowed to redeem tokens @param _amount Amounts of tokens they can claim @param _nonce Nonce of the event for which this message was generated @param _sigs Array of signatures. */ function redeemTokensARRAY( address _beneficiary, uint256 _amount, uint256 _nonce, bytes _sigs) public returns (bool) { //Number of signatures uint256 nSigs = _sigs.length.div(65); require(nSigs >= sigRequired); //Make sure tokens were not redeemed already for given nonce //require(!redeemedTokens[_beneficiary][_nonce]); address[] memory signer = new address[](sigRequired); bytes32 r; bytes32 s; uint8 v; // Verifying if msg.senders provides enough valid signatures for(uint8 i = 0; i < sigRequired; i++) { // Extract ECDSA signature variables from current signature assembly { r := mload(add(_sigs, add(mul(i, 65), 32))) s := mload(add(_sigs, add(mul(i, 65), 64))) v := byte(0, mload(add(_sigs, add(mul(i, 65), 96)))) } // Check validity of current signature signer[i] = recoverRedeemMessageSignerRSV(_beneficiary, _amount, _nonce, r, s, v); // If signer is an admin and if their signature wasn't already used require(admin[signer[i]]); //Making sure signer wasn't used already for (uint8 ii = 0; ii < i; ii++){ require(signer[ii] != signer[i]); } } //Tokens for given nonce were claimed //redeemedTokens[_beneficiary][_nonce] = true; //Minting tokens to _benificiary token.mint(_beneficiary, _amount); TokensRedeemed(_beneficiary, _amount, _nonce); return true; } //ARRAY APPROACH function redeemTokensMAPPING( address _beneficiary, uint256 _amount, uint256 _nonce, bytes _sigs) public returns (bool) { //Number of signatures uint256 nSigs = _sigs.length.div(65); require(nSigs >= sigRequired); //Make sure tokens were not redeemed already for given nonce //require(!redeemedTokens[_beneficiary][_nonce]); address[] memory signer = new address[](sigRequired); bytes32 r; bytes32 s; uint8 v; // Verifying if msg.senders provides enough valid signatures for(uint8 i = 0; i < sigRequired; i++) { // Extract ECDSA signature variables from current signature assembly { r := mload(add(_sigs, add(mul(i, 65), 32))) s := mload(add(_sigs, add(mul(i, 65), 64))) v := byte(0, mload(add(_sigs, add(mul(i, 65), 96)))) } // Check validity of current signature signer[i] = recoverRedeemMessageSignerRSV(_beneficiary, _amount, _nonce, r, s, v); // If signer is an admin and if their signature wasn't already used require(admin[signer[i]]); // Signature from signer has been used sigUsed[signer[i]] = true; } //Tokens for given nonce were claimed //redeemedTokens[_beneficiary][_nonce] = true; //Minting tokens to _benificiary token.mint(_beneficiary, _amount); //Clearing sigUsed for (i = 0; i < sigRequired; i++){ sigUsed[signer[i]] = false; } TokensRedeemed(_beneficiary, _amount, _nonce); return true; } // BITMASK APPROACH function setIDadmin(address _admin, uint256 _ID) public { require(IDadmin[_ID] == 0x0); IDadmin[_ID] = _admin; adminID[_admin] = _ID; } /* @dev Change the authorization status of a given address @param _admin Address to give admin status to */ function setAsAdmin(address _admin) public onlyOwner returns(bool) { //Will find the first free admin spot from 0 to 256 for (uint256 i = 0; i<256; i++){ if (IDadmin[2**i] == 0x0) { IDadmin[2**i] = _admin; adminID[_admin] = 2**i; //AdminStatusChanged(_admin, 2**i); return true; } } return false; } /* @dev Remove admin status from an address @param _admin Address to remove admin status */ function removeAsAdmin(address _admin) public onlyOwner returns(bool) { IDadmin[adminID[_admin]] = 0x0; adminID[_admin] = 0; //AdminStatusChanged(_admin, 0); return true; } function redeemTokensBITMASK( address _beneficiary, uint256 _amount, uint256 _nonce, bytes _sigs) public returns (bool) { uint256 nSigs = _sigs.length.div(65); // Number of signatures require(nSigs >= sigRequired); // Enough signatures provided //require(!redeemedTokens[_beneficiary][_nonce]); // Nonce's tokens not redeemed yet uint256 bitsigners; // Keeps track of who signed address signer; // Address of currently recovered signer bytes32 r; // ECDSA signature r variable bytes32 s; // ECDSA signature s variable uint8 v; // ECDSA signature v variable // Verifying if msg.senders provides enough valid signatures for(uint8 i = 0; i < sigRequired; i++) { // Extract ECDSA signature variables from current signature assembly { r := mload(add(_sigs, add(mul(i, 65), 32))) s := mload(add(_sigs, add(mul(i, 65), 64))) v := byte(0, mload(add(_sigs, add(mul(i, 65), 96)))) } // Check validity of current signature signer = recoverRedeemMessageSignerRSV(_beneficiary, _amount, _nonce, r, s, v); // If signer is an admin, count bitsigners = bitsigners | adminID[signer]; } //Tokens for given nonce were claimed //redeemedTokens[_beneficiary][_nonce] = true; //Counting number of valid signatures uint8 counter = 0; //Count number of unique, valid signatures for (uint256 ii = 0; ii<256; ii++){ if (2**ii & bitsigners == 2**ii) { counter++; if (counter == sigRequired){ //Minting tokens to _benificiary token.mint(_beneficiary, _amount); TokensRedeemed(_beneficiary, _amount, _nonce); return true; } } } return false; } // SEOCND VERSION /* @dev Verifies if message was signed by an admin to give access to _add for this contract. Assumes Geth signature prefix. @param _add Address of agent with access. @param _amount Amount of tokens that can be claimed @param _nonce Nonce of the event @param _sig Valid signature from owner */ function recoverRedeemMessageSigner( address _add, uint256 _amount, uint256 _nonce, bytes _sig) view public returns (address) { bytes32 r; bytes32 s; uint8 v; //Extract ECDSA signature variables from `sig` assembly { r := mload(add(_sig, 32)) s := mload(add(_sig, 64)) v := byte(0, mload(add(_sig, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // Verifying if recovered signer is contract admin bytes32 hash = keccak256(this, _add, _amount, _nonce); //Return recovered signer address return ecrecover( keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s ); } /* @dev Verifies if message was signed by an admin to give access to _add for this contract. Assumes Geth signature prefix. @param _add Address of agent with access. @param _amount Amount of tokens that can be claimed @param _nonce Nonce of the event @param _r r variable from ECDSA signature. @param _s s variable from ECDSA signature. @param _v v variable from ECDSA signature. @return Validity of access message for a given address. */ function recoverRedeemMessageSignerRSV( address _add, uint256 _amount, uint256 _nonce, bytes32 _r, bytes32 _s, uint8 _v) view public returns (address) { // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (_v < 27) { _v += 27; } // Hash of the message that had to be signed bytes32 hash = keccak256(this, _add, _amount, _nonce); //Return recovered signer address return ecrecover( keccak256("\x19Ethereum Signed Message:\n32", hash), _v, _r, _s ); } /* @dev Checks whether the current message is valid. @param _add Address of agent with access. @param _amount Amount of tokens that can be claimed @param _nonce Nonce of the event @param _sig Valid signature from owner */ function isValidRedeemMessage( address _add, uint256 _amount, uint256 _nonce, bytes _sig) view public returns (bool){ return ( adminID[recoverRedeemMessageSigner(_add, _amount, _nonce, _sig)] > 0 ); } /* @dev Returns whether the address is an admin or not. @param _add Address to query admin status. */ function getAdminStatus(address _add) public view returns (bool) { return admin[_add]; } /* @dev Returns admin's ID. @param _add Address to query admin ID. */ function getAdminID(address _add) public view returns (uint256) { return adminID[_add]; } /* @dev Returns the admin's address associated with an ID. @param _add ID (2^i) to query admin's address associated with it . */ function getAdminAddress(uint256 _ID) public view returns (address) { return IDadmin[_ID]; } }
49,079
4
// this contract has an internal balance which can only be withdrawn by the owner of the contract.if you manage to pull all the value out of this contract you can trigger the winnerAnnounced event anddeclare yourself a winner! /
contract Honeypot is OwnablePausable { constructor() public payable { require(msg.value != 0); balance = msg.value; } uint public balance; event winnerAnnounced(address winner, string yourName); /** * @dev The transferBalance function sends the current balance of this contract to the owner, * but will revert if the owner is a new owner (less than 15 minutes) */ function transferBalance() public onlyOwner { require(ownershipTransferTime <= now + 15 minutes); uint memory transferBalance = balance; balance = 0; owner.transfer(transferBalance); } /** * @dev only the current owner of the contract can call this function * and the winner will be announced if the balance is 0 */ function announceWinner(string yourName) public onlyOwner { require(balance == 0); emit winnerAnnounced(msg.sender, yourName); } /** * @dev non-payable fallback function that has no functionality */ function () { } }
contract Honeypot is OwnablePausable { constructor() public payable { require(msg.value != 0); balance = msg.value; } uint public balance; event winnerAnnounced(address winner, string yourName); /** * @dev The transferBalance function sends the current balance of this contract to the owner, * but will revert if the owner is a new owner (less than 15 minutes) */ function transferBalance() public onlyOwner { require(ownershipTransferTime <= now + 15 minutes); uint memory transferBalance = balance; balance = 0; owner.transfer(transferBalance); } /** * @dev only the current owner of the contract can call this function * and the winner will be announced if the balance is 0 */ function announceWinner(string yourName) public onlyOwner { require(balance == 0); emit winnerAnnounced(msg.sender, yourName); } /** * @dev non-payable fallback function that has no functionality */ function () { } }
13,438
2
// : function to intiate a new auction Warning: In case the auction is expected to raise more than 2^96 units of the biddingToken, don't start the auction, as it will not be settlable. This corresponds to about 79 billion DAI. Prices between biddingToken and auctioningToken are expressed by a fraction whose components are stored as uint96.
function initiateAuction( address _auctioningToken, address _biddingToken, uint256 orderCancellationEndDate, uint256 auctionEndDate, uint96 _auctionedSellAmount, uint96 _minBuyAmount, uint256 minimumBiddingAmountPerOrder, uint256 minFundingThreshold, bool isAtomicClosureAllowed,
function initiateAuction( address _auctioningToken, address _biddingToken, uint256 orderCancellationEndDate, uint256 auctionEndDate, uint96 _auctionedSellAmount, uint96 _minBuyAmount, uint256 minimumBiddingAmountPerOrder, uint256 minFundingThreshold, bool isAtomicClosureAllowed,
10,430
118
// Update brrAndEpochData
updateBRRData(rewardBps, rebateBps, expiryTimestamp, epoch);
updateBRRData(rewardBps, rebateBps, expiryTimestamp, epoch);
11,913
6
// Token in which a reward is paid out with
address tokenAddress;
address tokenAddress;
48,395
19
// Returns true if the index has been marked claimed.
function isClaimed(uint256 index) external view returns (bool);
function isClaimed(uint256 index) external view returns (bool);
20,534
103
// Calculate final MILK tokens amount to transfer to the holder
undistributed = (undistributedCow.add(undistributedCowLP).add(undistributedMilkLP)).sub(devTeamFee);
undistributed = (undistributedCow.add(undistributedCowLP).add(undistributedMilkLP)).sub(devTeamFee);
48,077
103
// Allowes access to the uint variables saved in the apiUintVars under the requestDetails structfor the requestId specified _requestId to look up _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is the variables/strings used to save the data in the mapping. The variables names arecommented out under the apiUintVars under the requestDetails structreturn uint value of the apiUintVars specified in _data for the requestId specified /
// function getRequestUintVars(uint _requestId,bytes32 _data) external view returns(uint){ // return tellor.getRequestUintVars(_requestId,_data); // }
// function getRequestUintVars(uint _requestId,bytes32 _data) external view returns(uint){ // return tellor.getRequestUintVars(_requestId,_data); // }
2,321
76
// given genes of current floor and dungeon seed, return a genetic combination - may have a random factor. _floorGenes Genes of floor. _seedGenes Seed genes of dungeon.return The resulting genes. /
function calculateResult(uint _floorGenes, uint _seedGenes) external returns (uint);
function calculateResult(uint _floorGenes, uint _seedGenes) external returns (uint);
42,777
7
// see{Accesscontrol}. emits {OwnershipTransferred} event.
function transferOwnership(address newOwner) external onlyRole("ADMIN_ROLE") returns (bool) { require( newOwner != address(0), "Ownable: new owner is the zero address" );
function transferOwnership(address newOwner) external onlyRole("ADMIN_ROLE") returns (bool) { require( newOwner != address(0), "Ownable: new owner is the zero address" );
26,785
40
// Fix the unlock time of each stage
uint256[] public unlockStage = [ 1624982400, // 2021-06-30 1632931200, // 2021-09-30 1640880000, // 2021-12-31 1648569600, // 2022-03-30 1656518400, // 2022-06-30 1664467200, // 2022-09-30 1672416000, // 2022-12-31 1680105600 // 2023-03-30 ];
uint256[] public unlockStage = [ 1624982400, // 2021-06-30 1632931200, // 2021-09-30 1640880000, // 2021-12-31 1648569600, // 2022-03-30 1656518400, // 2022-06-30 1664467200, // 2022-09-30 1672416000, // 2022-12-31 1680105600 // 2023-03-30 ];
49,140
36
// Get airline status from Adress
function getAirlineStatus(address airlineAddress ) external view isCallerAuthorized returns (bool status)
function getAirlineStatus(address airlineAddress ) external view isCallerAuthorized returns (bool status)
44,623
47
// owner can drain tokens that are sent here by mistake
function emergencyERC20Drain(IERC20 tokenDrained, uint amount) external onlyOwner { tokenDrained.transfer(owner, amount); }
function emergencyERC20Drain(IERC20 tokenDrained, uint amount) external onlyOwner { tokenDrained.transfer(owner, amount); }
33,530
30
// Perform the elliptic curve recover operation
bytes32 check = keccak256(header, message); return ecrecover(check, v, r, s);
bytes32 check = keccak256(header, message); return ecrecover(check, v, r, s);
8,235
7
// Emit when `ifQualified` is called to decide if the given `address`is `qualified` according to the preset rule by the contract creator and the current block `number` and the current block `timestamp`. /
event Qualification(address account, bool qualified, uint256 blockNumber, uint256 timestamp);
event Qualification(address account, bool qualified, uint256 blockNumber, uint256 timestamp);
6,583
0
// Directly deposits a certain amount of surplus collateral to a user'saccount. This call can be used both for token and native Ether collateral. Fortokens, each call initiates a token transfer call to the ERC20 contract,and it's safe to call repeatedly in the same transaction even for the sametoken. For native Ether deposits, the call consumes the value in msg.value using thepopMsgVal() function. If called more than once in a single transctionpopMsgVal() will revert. Therefore if calling depositSurplus() on native ETHbe aware than calling more than once in a single transaction result in the top-level CrocSwapDex contract call failing and reverting.recv
function depositSurplus (address recv, uint128 value, address token) internal { debitTransfer(lockHolder_, value, token, popMsgVal()); bytes32 key = tokenKey(recv, token); userBals_[key].surplusCollateral_ += value; }
function depositSurplus (address recv, uint128 value, address token) internal { debitTransfer(lockHolder_, value, token, popMsgVal()); bytes32 key = tokenKey(recv, token); userBals_[key].surplusCollateral_ += value; }
13,289
40
// States the total number of authorized payments in this contract/ return The number of payments ever authorized even if they were canceled
function numberOfAuthorizedPayments() public view returns (uint) { return authorizedPayments.length; }
function numberOfAuthorizedPayments() public view returns (uint) { return authorizedPayments.length; }
83,365
5
// Relay entry callback gas limit. This is the gas limit with which/ callback function provided in the relay request transaction is/ executed. The callback is executed with a new relay entry value/ in the same transaction the relay entry is submitted.
uint256 public callbackGasLimit;
uint256 public callbackGasLimit;
35,377
44
// Create `mintedAmount` tokens and send it to `target`/target Address to receive the tokens/mintedAmount the amount of tokens it will receive
function mintToken(address target, uint256 mintedAmount) onlyOwner public returns(bool) { balanceOf[target] += mintedAmount; totalSupply += mintedAmount; emit Transfer(address(0x0), address(this), mintedAmount); emit Transfer(address(this), target, mintedAmount); emit mylog(0); return true; }
function mintToken(address target, uint256 mintedAmount) onlyOwner public returns(bool) { balanceOf[target] += mintedAmount; totalSupply += mintedAmount; emit Transfer(address(0x0), address(this), mintedAmount); emit Transfer(address(this), target, mintedAmount); emit mylog(0); return true; }
37,475
65
// Sets the values for `name`, `symbol`, and `decimals`. All three ofthese values are immutable: they can only be set once duringconstruction. /
constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; }
constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; }
576
275
// Getter Functions ///
function BPTVal( address _bPool, address _liquidityAsset, address _staker, address _stakeLocker
function BPTVal( address _bPool, address _liquidityAsset, address _staker, address _stakeLocker
60,232
13
// listener when a video is updated./_oldViewCount old view count./_newViewCount new view count./_tokenId whose the video is associated to.
function onVideoUpdated( uint256 _oldViewCount, uint256 _newViewCount, uint256 _tokenId)
function onVideoUpdated( uint256 _oldViewCount, uint256 _newViewCount, uint256 _tokenId)
9,589
325
// Get the borrower's pending accumulated ETH reward, earned by their stake
function getPendingETHReward(address _borrower) public view override returns (uint) { uint snapshotETH = rewardSnapshots[_borrower].ETH; uint rewardPerUnitStaked = L_ETH.sub(snapshotETH); if ( rewardPerUnitStaked == 0 || Troves[_borrower].status != Status.active) { return 0; } uint stake = Troves[_borrower].stake; uint pendingETHReward = stake.mul(rewardPerUnitStaked).div(DECIMAL_PRECISION); return pendingETHReward; }
function getPendingETHReward(address _borrower) public view override returns (uint) { uint snapshotETH = rewardSnapshots[_borrower].ETH; uint rewardPerUnitStaked = L_ETH.sub(snapshotETH); if ( rewardPerUnitStaked == 0 || Troves[_borrower].status != Status.active) { return 0; } uint stake = Troves[_borrower].stake; uint pendingETHReward = stake.mul(rewardPerUnitStaked).div(DECIMAL_PRECISION); return pendingETHReward; }
28,121
97
// Prevent overflow when dividing INT256_MIN by -1 https:github.com/RequestNetwork/requestNetwork/issues/43
require(!(a == - 2**255 && b == -1) && (b > 0)); return a / b;
require(!(a == - 2**255 && b == -1) && (b > 0)); return a / b;
16,900
23
// address -> permission -> flag
mapping (address=>mapping(bytes32=>bool)) byAddress;
mapping (address=>mapping(bytes32=>bool)) byAddress;
12,008
130
// Get a reference to the tier.
JB721Tier memory _tier = store.tierOfTokenId(address(this), _tokenId);
JB721Tier memory _tier = store.tierOfTokenId(address(this), _tokenId);
25,358
15
// TODO - existing investment? 3, 1 to change
investments.push(Investment(msg.sender, msg.value, 0, 3, 1, sectorList)); for(uint x = 0; x < sectorList.length; x++) { blackList[sectorList[x]] = sectorList[x]; }
investments.push(Investment(msg.sender, msg.value, 0, 3, 1, sectorList)); for(uint x = 0; x < sectorList.length; x++) { blackList[sectorList[x]] = sectorList[x]; }
33,654
20
// TOKEN DATA /
IRule[] memory rules) { TokenData storage tokenData = tokens[_token]; mintingFinished = tokenData.mintingFinished; allTimeMinted = tokenData.allTimeMinted; allTimeBurned = tokenData.allTimeBurned; allTimeSeized = tokenData.allTimeSeized; lock = [ tokenData.lock.startAt, tokenData.lock.endAt ]; lockExceptions = tokenData.lock.exceptionsList; frozenUntil = tokenData.frozenUntils[_token]; rules = tokenData.rules; }
IRule[] memory rules) { TokenData storage tokenData = tokens[_token]; mintingFinished = tokenData.mintingFinished; allTimeMinted = tokenData.allTimeMinted; allTimeBurned = tokenData.allTimeBurned; allTimeSeized = tokenData.allTimeSeized; lock = [ tokenData.lock.startAt, tokenData.lock.endAt ]; lockExceptions = tokenData.lock.exceptionsList; frozenUntil = tokenData.frozenUntils[_token]; rules = tokenData.rules; }
10,235
48
// Contracts that should be able to recover tokens SylTi This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner.This will prevent any accidental loss of tokens. /
contract CanReclaimToken is Ownable { using SafeERC20 for ERC20Basic; /** * @dev Reclaim all ERC20Basic compatible tokens * @param _token ERC20Basic The address of the token contract */ function reclaimToken(ERC20Basic _token) external onlyOwner { uint256 balance = _token.balanceOf(this); _token.safeTransfer(owner, balance); } }
contract CanReclaimToken is Ownable { using SafeERC20 for ERC20Basic; /** * @dev Reclaim all ERC20Basic compatible tokens * @param _token ERC20Basic The address of the token contract */ function reclaimToken(ERC20Basic _token) external onlyOwner { uint256 balance = _token.balanceOf(this); _token.safeTransfer(owner, balance); } }
10,915
21
// how much is being swapped out
uint256 amountOut;
uint256 amountOut;
50,469