// Flattened with jO-Osko's flattener // SPDX-License-Identifier: MIT pragma abicoder v2; // Inlining: @openzeppelin/contracts/token/ERC20/IERC20.sol // INLINED-SPDX-INLINED-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // End of inlining: @openzeppelin/contracts/token/ERC20/IERC20.sol // Inlining: ../../../userInterfaces/IVoterWhitelister.sol // INLINED-SPDX-INLINED-License-Identifier: MIT pragma solidity 0.7.6; interface IVoterWhitelister { /** * Raised when an account is removed from the voter whitelist. */ event VoterWhitelisted(address voter, uint256 ftsoIndex); /** * Raised when an account is removed from the voter whitelist. */ event VoterRemovedFromWhitelist(address voter, uint256 ftsoIndex); /** * Request to whitelist `_voter` account to ftso at `_ftsoIndex`. Will revert if vote power too low. * May be called by any address. */ function requestWhitelistingVoter(address _voter, uint256 _ftsoIndex) external; /** * Request to whitelist `_voter` account to all active ftsos. * May be called by any address. * It returns an array of supported ftso indices and success flag per index. */ function requestFullVoterWhitelisting( address _voter ) external returns ( uint256[] memory _supportedIndices, bool[] memory _success ); /** * Maximum number of voters in the whitelist for a new FTSO. */ function defaultMaxVotersForFtso() external view returns (uint256); /** * Maximum number of voters in the whitelist for FTSO at index `_ftsoIndex`. */ function maxVotersForFtso(uint256 _ftsoIndex) external view returns (uint256); /** * Get whitelisted price providers for ftso with `_symbol` */ function getFtsoWhitelistedPriceProvidersBySymbol(string memory _symbol) external view returns (address[] memory); /** * Get whitelisted price providers for ftso at `_ftsoIndex` */ function getFtsoWhitelistedPriceProviders(uint256 _ftsoIndex) external view returns (address[] memory); } // End of inlining: ../../../userInterfaces/IVoterWhitelister.sol // Inlining: ../../../userInterfaces/IVPToken.sol // INLINED-SPDX-INLINED-License-Identifier: MIT pragma solidity 0.7.6; // import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import {IGovernanceVotePower} from "./IGovernanceVotePower.sol"; // import {IVPContractEvents} from "./IVPContractEvents.sol"; interface IVPToken is IERC20 { /** * @notice Delegate by percentage `_bips` of voting power to `_to` from `msg.sender`. * @param _to The address of the recipient * @param _bips The percentage of voting power to be delegated expressed in basis points (1/100 of one percent). * Not cummulative - every call resets the delegation value (and value of 0 undelegates `to`). **/ function delegate(address _to, uint256 _bips) external; /** * @notice Explicitly delegate `_amount` of voting power to `_to` from `msg.sender`. * @param _to The address of the recipient * @param _amount An explicit vote power amount to be delegated. * Not cummulative - every call resets the delegation value (and value of 0 undelegates `to`). **/ function delegateExplicit(address _to, uint _amount) external; /** * @notice Revoke all delegation from sender to `_who` at given block. * Only affects the reads via `votePowerOfAtCached()` in the block `_blockNumber`. * Block `_blockNumber` must be in the past. * This method should be used only to prevent rogue delegate voting in the current voting block. * To stop delegating use delegate/delegateExplicit with value of 0 or undelegateAll/undelegateAllExplicit. * @param _who Address of the delegatee * @param _blockNumber The block number at which to revoke delegation. */ function revokeDelegationAt(address _who, uint _blockNumber) external; /** * @notice Undelegate all voting power for delegates of `msg.sender` * Can only be used with percentage delegation. * Does not reset delegation mode back to NOTSET. **/ function undelegateAll() external; /** * @notice Undelegate all explicit vote power by amount delegates for `msg.sender`. * Can only be used with explicit delegation. * Does not reset delegation mode back to NOTSET. * @param _delegateAddresses Explicit delegation does not store delegatees' addresses, * so the caller must supply them. * @return The amount still delegated (in case the list of delegates was incomplete). */ function undelegateAllExplicit(address[] memory _delegateAddresses) external returns (uint256); /** * @dev Should be compatible with ERC20 method */ function name() external view returns (string memory); /** * @dev Should be compatible with ERC20 method */ function symbol() external view returns (string memory); /** * @dev Should be compatible with ERC20 method */ function decimals() external view returns (uint8); /** * @notice Total amount of tokens at a specific `_blockNumber`. * @param _blockNumber The block number when the totalSupply is queried * @return The total amount of tokens at `_blockNumber` **/ function totalSupplyAt(uint _blockNumber) external view returns(uint256); /** * @dev Queries the token balance of `_owner` at a specific `_blockNumber`. * @param _owner The address from which the balance will be retrieved. * @param _blockNumber The block number when the balance is queried. * @return The balance at `_blockNumber`. **/ function balanceOfAt(address _owner, uint _blockNumber) external view returns (uint256); /** * @notice Get the current total vote power. * @return The current total vote power (sum of all accounts' vote powers). */ function totalVotePower() external view returns(uint256); /** * @notice Get the total vote power at block `_blockNumber` * @param _blockNumber The block number at which to fetch. * @return The total vote power at the block (sum of all accounts' vote powers). */ function totalVotePowerAt(uint _blockNumber) external view returns(uint256); /** * @notice Get the current vote power of `_owner`. * @param _owner The address to get voting power. * @return Current vote power of `_owner`. */ function votePowerOf(address _owner) external view returns(uint256); /** * @notice Get the vote power of `_owner` at block `_blockNumber` * @param _owner The address to get voting power. * @param _blockNumber The block number at which to fetch. * @return Vote power of `_owner` at `_blockNumber`. */ function votePowerOfAt(address _owner, uint256 _blockNumber) external view returns(uint256); /** * @notice Get the delegation mode for '_who'. This mode determines whether vote power is * allocated by percentage or by explicit value. Once the delegation mode is set, * it never changes, even if all delegations are removed. * @param _who The address to get delegation mode. * @return delegation mode: 0 = NOTSET, 1 = PERCENTAGE, 2 = AMOUNT (i.e. explicit) */ function delegationModeOf(address _who) external view returns(uint256); /** * @notice Get current delegated vote power `_from` delegator delegated `_to` delegatee. * @param _from Address of delegator * @param _to Address of delegatee * @return The delegated vote power. */ function votePowerFromTo(address _from, address _to) external view returns(uint256); /** * @notice Get delegated the vote power `_from` delegator delegated `_to` delegatee at `_blockNumber`. * @param _from Address of delegator * @param _to Address of delegatee * @param _blockNumber The block number at which to fetch. * @return The delegated vote power. */ function votePowerFromToAt(address _from, address _to, uint _blockNumber) external view returns(uint256); /** * @notice Compute the current undelegated vote power of `_owner` * @param _owner The address to get undelegated voting power. * @return The unallocated vote power of `_owner` */ function undelegatedVotePowerOf(address _owner) external view returns(uint256); /** * @notice Get the undelegated vote power of `_owner` at given block. * @param _owner The address to get undelegated voting power. * @param _blockNumber The block number at which to fetch. * @return The undelegated vote power of `_owner` (= owner's own balance minus all delegations from owner) */ function undelegatedVotePowerOfAt(address _owner, uint256 _blockNumber) external view returns(uint256); /** * @notice Get the vote power delegation `delegationAddresses` * and `_bips` of `_who`. Returned in two separate positional arrays. * @param _who The address to get delegations. * @return _delegateAddresses Positional array of delegation addresses. * @return _bips Positional array of delegation percents specified in basis points (1/100 or 1 percent) * @return _count The number of delegates. * @return _delegationMode The mode of the delegation (NOTSET=0, PERCENTAGE=1, AMOUNT=2). */ function delegatesOf(address _who) external view returns ( address[] memory _delegateAddresses, uint256[] memory _bips, uint256 _count, uint256 _delegationMode ); /** * @notice Get the vote power delegation `delegationAddresses` * and `pcts` of `_who`. Returned in two separate positional arrays. * @param _who The address to get delegations. * @param _blockNumber The block for which we want to know the delegations. * @return _delegateAddresses Positional array of delegation addresses. * @return _bips Positional array of delegation percents specified in basis points (1/100 or 1 percent) * @return _count The number of delegates. * @return _delegationMode The mode of the delegation (NOTSET=0, PERCENTAGE=1, AMOUNT=2). */ function delegatesOfAt(address _who, uint256 _blockNumber) external view returns ( address[] memory _delegateAddresses, uint256[] memory _bips, uint256 _count, uint256 _delegationMode ); /** * Returns VPContract used for readonly operations (view methods). * The only non-view method that might be called on it is `revokeDelegationAt`. * * @notice `readVotePowerContract` is almost always equal to `writeVotePowerContract` * except during upgrade from one VPContract to a new version (which should happen * rarely or never and will be anounced before). * * @notice You shouldn't call any methods on VPContract directly, all are exposed * via VPToken (and state changing methods are forbidden from direct calls). * This is the reason why this method returns `IVPContractEvents` - it should only be used * for listening to events (`Revoke` only). */ function readVotePowerContract() external view returns (IVPContractEvents); /** * Returns VPContract used for state changing operations (non-view methods). * The only non-view method that might be called on it is `revokeDelegationAt`. * * @notice `writeVotePowerContract` is almost always equal to `readVotePowerContract` * except during upgrade from one VPContract to a new version (which should happen * rarely or never and will be anounced before). In the case of upgrade, * `writeVotePowerContract` will be replaced first to establish delegations, and * after some perio (e.g. after a reward epoch ends) `readVotePowerContract` will be set equal to it. * * @notice You shouldn't call any methods on VPContract directly, all are exposed * via VPToken (and state changing methods are forbidden from direct calls). * This is the reason why this method returns `IVPContractEvents` - it should only be used * for listening to events (`Delegate` and `Revoke` only). */ function writeVotePowerContract() external view returns (IVPContractEvents); /** * When set, allows token owners to participate in governance voting * and delegate governance vote power. */ function governanceVotePower() external view returns (IGovernanceVotePower); } // End of inlining: ../../../userInterfaces/IVPToken.sol // Inlining: ../../../userInterfaces/IVPContractEvents.sol // INLINED-SPDX-INLINED-License-Identifier: MIT pragma solidity 0.7.6; interface IVPContractEvents { /** * Event triggered when an account delegates or undelegates another account. * Definition: `votePowerFromTo(from, to)` is `changed` from `priorVotePower` to `newVotePower`. * For undelegation, `newVotePower` is 0. * * Note: the event is always emitted from VPToken's `writeVotePowerContract`. */ event Delegate(address indexed from, address indexed to, uint256 priorVotePower, uint256 newVotePower); /** * Event triggered only when account `delegator` revokes delegation to `delegatee` * for a single block in the past (typically the current vote block). * * Note: the event is always emitted from VPToken's `writeVotePowerContract` and/or `readVotePowerContract`. */ event Revoke(address indexed delegator, address indexed delegatee, uint256 votePower, uint256 blockNumber); } // End of inlining: ../../../userInterfaces/IVPContractEvents.sol // Inlining: ../../../userInterfaces/IPriceSubmitter.sol // INLINED-SPDX-INLINED-License-Identifier: MIT pragma solidity 0.7.6; // import "../genesis/interface/IFtsoGenesis.sol"; // import "../genesis/interface/IFtsoRegistryGenesis.sol"; interface IPriceSubmitter { /** * Event emitted when price hashes were submitted through PriceSubmitter. * @param submitter the address of the sender * @param epochId current price epoch id * @param ftsos array of ftsos that correspond to the indexes in call * @param hashes the submitted hashes * @param timestamp current block timestamp */ event PriceHashesSubmitted( address indexed submitter, uint256 indexed epochId, IFtsoGenesis[] ftsos, bytes32[] hashes, uint256 timestamp ); /** * Event emitted when prices were revealed through PriceSubmitter. * @param voter the address of the sender * @param epochId id of the epoch in which the price hash was submitted * @param ftsos array of ftsos that correspond to the indexes in the call * @param prices the submitted prices * @param timestamp current block timestamp */ event PricesRevealed( address indexed voter, uint256 indexed epochId, IFtsoGenesis[] ftsos, uint256[] prices, uint256[] randoms, uint256 timestamp ); /** * @notice Submits price hashes for current epoch * @param _epochId Target epoch id to which hashes are submitted * @param _ftsoIndices List of ftso indices * @param _hashes List of hashed price and random number * @notice Emits PriceHashesSubmitted event */ function submitPriceHashes( uint256 _epochId, uint256[] memory _ftsoIndices, bytes32[] memory _hashes ) external; /** * @notice Reveals submitted prices during epoch reveal period * @param _epochId Id of the epoch in which the price hashes was submitted * @param _ftsoIndices List of ftso indices * @param _prices List of submitted prices in USD * @param _randoms List of submitted random numbers * @notice The hash of _price and _random must be equal to the submitted hash * @notice Emits PricesRevealed event */ function revealPrices( uint256 _epochId, uint256[] memory _ftsoIndices, uint256[] memory _prices, uint256[] memory _randoms ) external; /** * Returns bitmap of all ftso's for which `_voter` is allowed to submit prices/hashes. * If voter is allowed to vote for ftso at index (see *_FTSO_INDEX), the corrsponding * bit in the result will be 1. */ function voterWhitelistBitmap(address _voter) external view returns (uint256); function getVoterWhitelister() external view returns (address); function getFtsoRegistry() external view returns (IFtsoRegistryGenesis); function getFtsoManager() external view returns (address); } // End of inlining: ../../../userInterfaces/IPriceSubmitter.sol // Inlining: ../../../userInterfaces/IGovernanceVotePower.sol // INLINED-SPDX-INLINED-License-Identifier: MIT pragma solidity 0.7.6; interface IGovernanceVotePower { /** * @notice Delegate all governance vote power of `msg.sender` to `_to`. * @param _to The address of the recipient **/ function delegate(address _to) external; /** * @notice Undelegate all governance vote power that `msg.sender` has delegated. **/ function undelegate() external; /** * @notice Get the governance vote power of `_who` at block `_blockNumber` * @param _who The address to get voting power. * @param _blockNumber The block number at which to fetch. * @return Governance vote power of `_who` at `_blockNumber`. */ function votePowerOfAt(address _who, uint256 _blockNumber) external view returns(uint256); } // End of inlining: ../../../userInterfaces/IGovernanceVotePower.sol // Inlining: ../../../userInterfaces/IFtso.sol // INLINED-SPDX-INLINED-License-Identifier: MIT pragma solidity 0.7.6; interface IFtso { enum PriceFinalizationType { // initial state NOT_FINALIZED, // median calculation used to find price WEIGHTED_MEDIAN, // low turnout - price calculated from median of trusted addresses TRUSTED_ADDRESSES, // low turnout + no votes from trusted addresses - price copied from previous epoch PREVIOUS_PRICE_COPIED, // price calculated from median of trusted addresses - triggered due to an exception TRUSTED_ADDRESSES_EXCEPTION, // previous price copied - triggered due to an exception PREVIOUS_PRICE_COPIED_EXCEPTION } // events event PriceHashSubmitted( address indexed submitter, uint256 indexed epochId, bytes32 hash, uint256 timestamp ); event PriceRevealed( address indexed voter, uint256 indexed epochId, uint256 price, uint256 random, uint256 timestamp, uint256 votePowerNat, uint256 votePowerAsset ); event PriceFinalized( uint256 indexed epochId, uint256 price, bool rewardedFtso, uint256 lowRewardPrice, uint256 highRewardPrice, PriceFinalizationType finalizationType, uint256 timestamp ); event PriceEpochInitializedOnFtso( uint256 indexed epochId, uint256 endTime, uint256 timestamp ); event LowTurnout( uint256 indexed epochId, uint256 natTurnout, uint256 lowNatTurnoutThresholdBIPS, uint256 timestamp ); /** * @notice Returns if FTSO is active */ function active() external view returns (bool); /** * @notice Returns the FTSO symbol */ function symbol() external view returns (string memory); /** * @notice Returns current epoch id */ function getCurrentEpochId() external view returns (uint256); /** * @notice Returns id of the epoch which was opened for price submission at the specified timestamp * @param _timestamp Timestamp as seconds from unix epoch */ function getEpochId(uint256 _timestamp) external view returns (uint256); /** * @notice Returns random number of the specified epoch * @param _epochId Id of the epoch */ function getRandom(uint256 _epochId) external view returns (uint256); /** * @notice Returns asset price consented in specific epoch * @param _epochId Id of the epoch * @return Price in USD multiplied by ASSET_PRICE_USD_DECIMALS */ function getEpochPrice(uint256 _epochId) external view returns (uint256); /** * @notice Returns current epoch data * @return _epochId Current epoch id * @return _epochSubmitEndTime End time of the current epoch price submission as seconds from unix epoch * @return _epochRevealEndTime End time of the current epoch price reveal as seconds from unix epoch * @return _votePowerBlock Vote power block for the current epoch * @return _fallbackMode Current epoch in fallback mode - only votes from trusted addresses will be used * @dev half-closed intervals - end time not included */ function getPriceEpochData() external view returns ( uint256 _epochId, uint256 _epochSubmitEndTime, uint256 _epochRevealEndTime, uint256 _votePowerBlock, bool _fallbackMode ); /** * @notice Returns current epoch data * @return _firstEpochStartTs First epoch start timestamp * @return _submitPeriodSeconds Submit period in seconds * @return _revealPeriodSeconds Reveal period in seconds */ function getPriceEpochConfiguration() external view returns ( uint256 _firstEpochStartTs, uint256 _submitPeriodSeconds, uint256 _revealPeriodSeconds ); /** * @notice Returns asset price submitted by voter in specific epoch * @param _epochId Id of the epoch * @param _voter Address of the voter * @return Price in USD multiplied by ASSET_PRICE_USD_DECIMALS */ function getEpochPriceForVoter(uint256 _epochId, address _voter) external view returns (uint256); /** * @notice Returns current asset price * @return _price Price in USD multiplied by ASSET_PRICE_USD_DECIMALS * @return _timestamp Time when price was updated for the last time */ function getCurrentPrice() external view returns (uint256 _price, uint256 _timestamp); /** * @notice Returns current random number */ function getCurrentRandom() external view returns (uint256); } // End of inlining: ../../../userInterfaces/IFtso.sol // Inlining: ../../../token/interface/IIGovernanceVotePower.sol // INLINED-SPDX-INLINED-License-Identifier: MIT pragma solidity 0.7.6; // import "../../userInterfaces/IVPToken.sol"; // import "../../userInterfaces/IGovernanceVotePower.sol"; interface IIGovernanceVotePower is IGovernanceVotePower { /** * Update vote powers when tokens are transfered. **/ function updateAtTokenTransfer( address _from, address _to, uint256 _fromBalance, uint256 _toBalance, uint256 _amount ) external; /** * Set the cleanup block number. * Historic data for the blocks before `cleanupBlockNumber` can be erased, * history before that block should never be used since it can be inconsistent. * In particular, cleanup block number must be before current vote power block. * @param _blockNumber The new cleanup block number. */ function setCleanupBlockNumber(uint256 _blockNumber) external; /** * Set the contract that is allowed to call history cleaning methods. */ function setCleanerContract(address _cleanerContract) external; /** * @notice Get the token that this governance vote power contract belongs to. */ function ownerToken() external view returns(IVPToken); } // End of inlining: ../../../token/interface/IIGovernanceVotePower.sol // Inlining: ../../../token/interface/IICleanable.sol // INLINED-SPDX-INLINED-License-Identifier: MIT pragma solidity 0.7.6; interface IICleanable { /** * Set the contract that is allowed to call history cleaning methods. */ function setCleanerContract(address _cleanerContract) external; /** * Set the cleanup block number. * Historic data for the blocks before `cleanupBlockNumber` can be erased, * history before that block should never be used since it can be inconsistent. * In particular, cleanup block number must be before current vote power block. * @param _blockNumber The new cleanup block number. */ function setCleanupBlockNumber(uint256 _blockNumber) external; /** * Set the contract that is allowed to set cleanupBlockNumber. * Usually this will be an instance of CleanupBlockNumberManager. */ function setCleanupBlockNumberManager(address _cleanupBlockNumberManager) external; /** * Get the current cleanup block number. */ function cleanupBlockNumber() external view returns (uint256); } // End of inlining: ../../../token/interface/IICleanable.sol // Inlining: ../../../token/interface/IIVPToken.sol // INLINED-SPDX-INLINED-License-Identifier: MIT pragma solidity 0.7.6; // import "../../userInterfaces/IVPToken.sol"; // import "../../userInterfaces/IGovernanceVotePower.sol"; // import "./IIVPContract.sol"; // import "./IIGovernanceVotePower.sol"; // import "./IICleanable.sol"; interface IIVPToken is IVPToken, IICleanable { /** * Sets new governance vote power contract that allows token owners to participate in governance voting * and delegate governance vote power. */ function setGovernanceVotePower(IIGovernanceVotePower _governanceVotePower) external; /** * @notice Get the total vote power at block `_blockNumber` using cache. * It tries to read the cached value and if not found, reads the actual value and stores it in cache. * Can only be used if `_blockNumber` is in the past, otherwise reverts. * @param _blockNumber The block number at which to fetch. * @return The total vote power at the block (sum of all accounts' vote powers). */ function totalVotePowerAtCached(uint256 _blockNumber) external returns(uint256); /** * @notice Get the vote power of `_owner` at block `_blockNumber` using cache. * It tries to read the cached value and if not found, reads the actual value and stores it in cache. * Can only be used if _blockNumber is in the past, otherwise reverts. * @param _owner The address to get voting power. * @param _blockNumber The block number at which to fetch. * @return Vote power of `_owner` at `_blockNumber`. */ function votePowerOfAtCached(address _owner, uint256 _blockNumber) external returns(uint256); /** * Return vote powers for several addresses in a batch. * @param _owners The list of addresses to fetch vote power of. * @param _blockNumber The block number at which to fetch. * @return A list of vote powers. */ function batchVotePowerOfAt( address[] memory _owners, uint256 _blockNumber ) external view returns(uint256[] memory); } // End of inlining: ../../../token/interface/IIVPToken.sol // Inlining: ../../../token/interface/IIVPContract.sol // INLINED-SPDX-INLINED-License-Identifier: MIT pragma solidity 0.7.6; // import "../../userInterfaces/IVPToken.sol"; // import "../../userInterfaces/IVPContractEvents.sol"; // import "./IICleanable.sol"; interface IIVPContract is IICleanable, IVPContractEvents { /** * Update vote powers when tokens are transfered. * Also update delegated vote powers for percentage delegation * and check for enough funds for explicit delegations. **/ function updateAtTokenTransfer( address _from, address _to, uint256 _fromBalance, uint256 _toBalance, uint256 _amount ) external; /** * @notice Delegate `_bips` percentage of voting power to `_to` from `_from` * @param _from The address of the delegator * @param _to The address of the recipient * @param _balance The delegator's current balance * @param _bips The percentage of voting power to be delegated expressed in basis points (1/100 of one percent). * Not cummulative - every call resets the delegation value (and value of 0 revokes delegation). **/ function delegate( address _from, address _to, uint256 _balance, uint256 _bips ) external; /** * @notice Explicitly delegate `_amount` of voting power to `_to` from `msg.sender`. * @param _from The address of the delegator * @param _to The address of the recipient * @param _balance The delegator's current balance * @param _amount An explicit vote power amount to be delegated. * Not cummulative - every call resets the delegation value (and value of 0 undelegates `to`). **/ function delegateExplicit( address _from, address _to, uint256 _balance, uint _amount ) external; /** * @notice Revoke all delegation from sender to `_who` at given block. * Only affects the reads via `votePowerOfAtCached()` in the block `_blockNumber`. * Block `_blockNumber` must be in the past. * This method should be used only to prevent rogue delegate voting in the current voting block. * To stop delegating use delegate/delegateExplicit with value of 0 or undelegateAll/undelegateAllExplicit. * @param _from The address of the delegator * @param _who Address of the delegatee * @param _balance The delegator's current balance * @param _blockNumber The block number at which to revoke delegation. **/ function revokeDelegationAt( address _from, address _who, uint256 _balance, uint _blockNumber ) external; /** * @notice Undelegate all voting power for delegates of `msg.sender` * Can only be used with percentage delegation. * Does not reset delegation mode back to NOTSET. * @param _from The address of the delegator **/ function undelegateAll( address _from, uint256 _balance ) external; /** * @notice Undelegate all explicit vote power by amount delegates for `msg.sender`. * Can only be used with explicit delegation. * Does not reset delegation mode back to NOTSET. * @param _from The address of the delegator * @param _delegateAddresses Explicit delegation does not store delegatees' addresses, * so the caller must supply them. * @return The amount still delegated (in case the list of delegates was incomplete). */ function undelegateAllExplicit( address _from, address[] memory _delegateAddresses ) external returns (uint256); /** * @notice Get the vote power of `_who` at block `_blockNumber` * Reads/updates cache and upholds revocations. * @param _who The address to get voting power. * @param _blockNumber The block number at which to fetch. * @return Vote power of `_who` at `_blockNumber`. */ function votePowerOfAtCached(address _who, uint256 _blockNumber) external returns(uint256); /** * @notice Get the current vote power of `_who`. * @param _who The address to get voting power. * @return Current vote power of `_who`. */ function votePowerOf(address _who) external view returns(uint256); /** * @notice Get the vote power of `_who` at block `_blockNumber` * @param _who The address to get voting power. * @param _blockNumber The block number at which to fetch. * @return Vote power of `_who` at `_blockNumber`. */ function votePowerOfAt(address _who, uint256 _blockNumber) external view returns(uint256); /** * Return vote powers for several addresses in a batch. * @param _owners The list of addresses to fetch vote power of. * @param _blockNumber The block number at which to fetch. * @return A list of vote powers. */ function batchVotePowerOfAt( address[] memory _owners, uint256 _blockNumber ) external view returns(uint256[] memory); /** * @notice Get current delegated vote power `_from` delegator delegated `_to` delegatee. * @param _from Address of delegator * @param _to Address of delegatee * @param _balance The delegator's current balance * @return The delegated vote power. */ function votePowerFromTo( address _from, address _to, uint256 _balance ) external view returns(uint256); /** * @notice Get delegated the vote power `_from` delegator delegated `_to` delegatee at `_blockNumber`. * @param _from Address of delegator * @param _to Address of delegatee * @param _balance The delegator's current balance * @param _blockNumber The block number at which to fetch. * @return The delegated vote power. */ function votePowerFromToAt( address _from, address _to, uint256 _balance, uint _blockNumber ) external view returns(uint256); /** * @notice Compute the current undelegated vote power of `_owner` * @param _owner The address to get undelegated voting power. * @param _balance Owner's current balance * @return The unallocated vote power of `_owner` */ function undelegatedVotePowerOf( address _owner, uint256 _balance ) external view returns(uint256); /** * @notice Get the undelegated vote power of `_owner` at given block. * @param _owner The address to get undelegated voting power. * @param _blockNumber The block number at which to fetch. * @return The undelegated vote power of `_owner` (= owner's own balance minus all delegations from owner) */ function undelegatedVotePowerOfAt( address _owner, uint256 _balance, uint256 _blockNumber ) external view returns(uint256); /** * @notice Get the delegation mode for '_who'. This mode determines whether vote power is * allocated by percentage or by explicit value. * @param _who The address to get delegation mode. * @return Delegation mode (NOTSET=0, PERCENTAGE=1, AMOUNT=2)) */ function delegationModeOf(address _who) external view returns (uint256); /** * @notice Get the vote power delegation `_delegateAddresses` * and `pcts` of an `_owner`. Returned in two separate positional arrays. * @param _owner The address to get delegations. * @return _delegateAddresses Positional array of delegation addresses. * @return _bips Positional array of delegation percents specified in basis points (1/100 or 1 percent) * @return _count The number of delegates. * @return _delegationMode The mode of the delegation (NOTSET=0, PERCENTAGE=1, AMOUNT=2). */ function delegatesOf( address _owner ) external view returns ( address[] memory _delegateAddresses, uint256[] memory _bips, uint256 _count, uint256 _delegationMode ); /** * @notice Get the vote power delegation `delegationAddresses` * and `pcts` of an `_owner`. Returned in two separate positional arrays. * @param _owner The address to get delegations. * @param _blockNumber The block for which we want to know the delegations. * @return _delegateAddresses Positional array of delegation addresses. * @return _bips Positional array of delegation percents specified in basis points (1/100 or 1 percent) * @return _count The number of delegates. * @return _delegationMode The mode of the delegation (NOTSET=0, PERCENTAGE=1, AMOUNT=2). */ function delegatesOfAt( address _owner, uint256 _blockNumber ) external view returns ( address[] memory _delegateAddresses, uint256[] memory _bips, uint256 _count, uint256 _delegationMode ); /** * The VPToken (or some other contract) that owns this VPContract. * All state changing methods may be called only from this address. * This is because original msg.sender is sent in `_from` parameter * and we must be sure that it cannot be faked by directly calling VPContract. * Owner token is also used in case of replacement to recover vote powers from balances. */ function ownerToken() external view returns (IVPToken); /** * Return true if this IIVPContract is configured to be used as a replacement for other contract. * It means that vote powers are not necessarily correct at the initialization, therefore * every method that reads vote power must check whether it is initialized for that address and block. */ function isReplacement() external view returns (bool); } // End of inlining: ../../../token/interface/IIVPContract.sol // Inlining: ../../../governance/implementation/GovernedBase.sol // INLINED-SPDX-INLINED-License-Identifier: MIT pragma solidity 0.7.6; /** * @title Governed Base * @notice This abstract base class defines behaviors for a governed contract. * @dev This class is abstract so that specific behaviors can be defined for the constructor. * Contracts should not be left ungoverned, but not all contract will have a constructor * (for example those pre-defined in genesis). **/ abstract contract GovernedBase { address public governance; address public proposedGovernance; bool private initialised; event GovernanceProposed(address proposedGovernance); event GovernanceUpdated (address oldGovernance, address newGoveranance); modifier onlyGovernance () { _checkOnlyGovernance(); _; } constructor(address _governance) { if (_governance != address(0)) { initialise(_governance); } } /** * @notice First of a two step process for turning over governance to another address. * @param _governance The address to propose to receive governance role. * @dev Must hold governance to propose another address. */ function proposeGovernance(address _governance) external onlyGovernance { proposedGovernance = _governance; emit GovernanceProposed(_governance); } /** * @notice Once proposed, claimant can claim the governance role as the second of a two-step process. */ function claimGovernance() external { require(msg.sender == proposedGovernance, "not claimaint"); emit GovernanceUpdated(governance, proposedGovernance); governance = proposedGovernance; proposedGovernance = address(0); } /** * @notice In a one-step process, turn over governance to another address. * @dev Must hold governance to transfer. */ function transferGovernance(address _governance) external onlyGovernance { emit GovernanceUpdated(governance, _governance); governance = _governance; proposedGovernance = address(0); } /** * @notice Initialize the governance address if not first initialized. */ function initialise(address _governance) public virtual { require(initialised == false, "initialised != false"); initialised = true; emit GovernanceUpdated(governance, _governance); governance = _governance; proposedGovernance = address(0); } function _checkOnlyGovernance() internal view { require(msg.sender == governance, "only governance"); } } // End of inlining: ../../../governance/implementation/GovernedBase.sol // Inlining: ../../../governance/implementation/Governed.sol // INLINED-SPDX-INLINED-License-Identifier: MIT pragma solidity 0.7.6; // import { GovernedBase } from "./GovernedBase.sol"; /** * @title Governed * @dev For deployed, governed contracts, enforce a non-zero address at create time. **/ contract Governed is GovernedBase { constructor(address _governance) GovernedBase(_governance) { require(_governance != address(0), "_governance zero"); } } // End of inlining: ../../../governance/implementation/Governed.sol // Inlining: ../../../genesis/interface/IFtsoRegistryGenesis.sol // INLINED-SPDX-INLINED-License-Identifier: MIT pragma solidity 0.7.6; // import "./IFtsoGenesis.sol"; interface IFtsoRegistryGenesis { function getFtsos(uint256[] memory _indices) external view returns(IFtsoGenesis[] memory _ftsos); } // End of inlining: ../../../genesis/interface/IFtsoRegistryGenesis.sol // Inlining: ../../../userInterfaces/IFtsoRegistry.sol // INLINED-SPDX-INLINED-License-Identifier: MIT pragma solidity 0.7.6; // pragma abicoder v2; // import "../ftso/interface/IIFtso.sol"; // import "../genesis/interface/IFtsoRegistryGenesis.sol"; interface IFtsoRegistry is IFtsoRegistryGenesis { function getFtso(uint256 _ftsoIndex) external view returns(IIFtso _activeFtsoAddress); function getFtsoBySymbol(string memory _symbol) external view returns(IIFtso _activeFtsoAddress); function getSupportedIndices() external view returns(uint256[] memory _supportedIndices); function getSupportedSymbols() external view returns(string[] memory _supportedSymbols); function getSupportedFtsos() external view returns(IIFtso[] memory _ftsos); function getFtsoIndex(string memory _symbol) external view returns (uint256 _assetIndex); function getFtsoSymbol(uint256 _ftsoIndex) external view returns (string memory _symbol); function getCurrentPrice(uint256 _ftsoIndex) external view returns(uint256 _price, uint256 _timestamp); function getCurrentPrice(string memory _symbol) external view returns(uint256 _price, uint256 _timestamp); function getSupportedIndicesAndFtsos() external view returns(uint256[] memory _supportedIndices, IIFtso[] memory _ftsos); function getSupportedSymbolsAndFtsos() external view returns(string[] memory _supportedSymbols, IIFtso[] memory _ftsos); function getSupportedIndicesAndSymbols() external view returns(uint256[] memory _supportedIndices, string[] memory _supportedSymbols); function getSupportedIndicesSymbolsAndFtsos() external view returns(uint256[] memory _supportedIndices, string[] memory _supportedSymbols, IIFtso[] memory _ftsos); } // End of inlining: ../../../userInterfaces/IFtsoRegistry.sol // Inlining: ../../../genesis/interface/IFtsoGenesis.sol // INLINED-SPDX-INLINED-License-Identifier: MIT pragma solidity 0.7.6; interface IFtsoGenesis { /** * @notice Submits price hash for current epoch - only price submitter * @param _sender Sender address * @param _epochId Target epoch id to which hashes are submitted * @param _hash Hashed price and random number * @notice Emits PriceHashSubmitted event. */ function submitPriceHashSubmitter(address _sender, uint256 _epochId, bytes32 _hash) external; /** * @notice Reveals submitted price during epoch reveal period - only price submitter * @param _voter Voter address * @param _epochId Id of the epoch in which the price hash was submitted * @param _price Submitted price in USD * @param _random Submitted random number * @notice The hash of _price and _random must be equal to the submitted hash * @notice Emits PriceRevealed event */ function revealPriceSubmitter( address _voter, uint256 _epochId, uint256 _price, uint256 _random, uint256 _wNatVP ) external; /** * @notice Get (and cache) wNat vote power for specified voter and given epoch id * @param _voter Voter address * @param _epochId Id of the epoch in which the price hash was submitted * @return wNat vote power */ function wNatVotePowerCached(address _voter, uint256 _epochId) external returns (uint256); } // End of inlining: ../../../genesis/interface/IFtsoGenesis.sol // Inlining: PriceProviderMockContracts.sol // INLINED-SPDX-INLINED-License-Identifier: MIT pragma solidity 0.7.6; // pragma abicoder v2; // import "./priceProviderMockFtso.sol"; // import "../../userInterfaces/IPriceSubmitter.sol"; // import "../../userInterfaces/IFtsoRegistry.sol"; // import "../../userInterfaces/IVoterWhitelister.sol"; // import "../../governance/implementation/Governed.sol"; /* * This file and ./priceProviderMockFtso.sol contains core contracts needed for Flare price providers. * All the mock contracts implement the same user interfaces that will be available to price providers in * real network. Governance and administrative methods are mocked, but user facing methods work in a similar * fashion. * * PriceProvider works in the same way. It provides access to VoterWhitelister for whitelisting and FtsoRegistry * to get asset indices. Both submit and reveal prices are available and work in the same way as real ones. * * FtsoRegistry provides information about ftsos and corresponding assets. * It works in the same way as in the real network. * * VoterWhitelister works similarly as in real network with few changes: * - At most one voter can be whitelisted at time. * - No vote power calculation is done during whitelisting, previously whitelisted user is always kicked out. * * MockFtso implements only a minimal subset of methods required for submission and reveal. * Notably, no median calculation, vote power calculation or rewarding is done. */ /** * @title A contract for FTSO registry */ contract MockFtsoRegistry is Governed, IFtsoRegistry{ // constants uint256 internal constant MAX_HISTORY_LENGTH = 5; // errors string internal constant ERR_TOKEN_NOT_SUPPORTED = "FTSO index not supported"; string internal constant ERR_FTSO_MANAGER_ONLY = "FTSO manager only"; // storage IIFtso[MAX_HISTORY_LENGTH][] private ftsoHistory; constructor(address _governance) Governed(_governance) { } /** * @notice Update current active FTSO contracts mapping * @param _ftsoContract new target FTSO contract */ function addFtso(IIFtso _ftsoContract) external onlyGovernance { uint256 len = ftsoHistory.length; string memory _symbol = _ftsoContract.symbol(); bytes32 _encodedSymbol = keccak256(abi.encode(_symbol)); uint256 i = 0; // Iterate over supported symbol array for ( ; i < len; i++) { // Deletion of symbols leaves an empty address "hole", so the address might be zero IFtso current = ftsoHistory[i][0]; if (address(current) == address(0)) { continue; } if (_encodedSymbol == keccak256(abi.encode(current.symbol()))) { break; } } // ftso with the same symbol is not yet in history array, add it if (i == len) { ftsoHistory.push(); } else { // Shift history _shiftHistory(i); } ftsoHistory[i][0] = _ftsoContract; } /** * Removes the ftso at specified index and keeps part of the history * @dev Reverts if the provided index is unsupported * @param _ftso ftso to remove */ function removeFtso(IIFtso _ftso) external onlyGovernance { bytes32 _encodedSymbol = keccak256(abi.encode(_ftso.symbol())); uint256 len = ftsoHistory.length; for (uint256 i = 0; i < len; ++i) { IFtso current = ftsoHistory[i][0]; if (address(current) == address(0)) { continue; } // Removal behaves the same as setting null value as current if (_encodedSymbol == keccak256(abi.encode(current.symbol()))) { _shiftHistory(i); ftsoHistory[i][0] = IIFtso(address(0)); return; } } revert(ERR_TOKEN_NOT_SUPPORTED); } /** * @dev Reverts if unsupported index is passed * @return _activeFtso FTSO contract for provided index */ function getFtso(uint256 _assetIndex) external view override returns(IIFtso _activeFtso) { return _getFtso(_assetIndex); } /** * @dev Reverts if unsupported symbol is passed * @return _activeFtso FTSO contract for provided symbol */ function getFtsoBySymbol(string memory _symbol) external view override returns(IIFtso _activeFtso) { return _getFtso(_getFtsoIndex(_symbol)); } /** * @notice Public view function to get the price of active FTSO for given asset index * @dev Reverts if unsupported index is passed * @return _price current price of asset in USD * @return _timestamp timestamp for when this price was updated */ function getCurrentPrice(uint256 _assetIndex) external view override returns(uint256 _price, uint256 _timestamp) { return _getFtso(_assetIndex).getCurrentPrice(); } function getCurrentPrice(string memory _symbol) external view override returns(uint256 _price, uint256 _timestamp) { return _getFtso(_getFtsoIndex(_symbol)).getCurrentPrice(); } /** * @return _supportedIndices the array of all active FTSO indices in increasing order. * Active FTSOs are ones that currently receive price feeds. */ function getSupportedIndices() external view override returns(uint256[] memory _supportedIndices) { return _getSupportedIndices(); } /** * @return _supportedSymbols the array of all active FTSO symbols in increasing order. * Active FTSOs are ones that currently receive price feeds. */ function getSupportedSymbols() external view override returns(string[] memory _supportedSymbols) { uint256[] memory _supportedIndices = _getSupportedIndices(); uint256 len = _supportedIndices.length; _supportedSymbols = new string[](len); while (len > 0) { --len; IIFtso ftso = ftsoHistory[_supportedIndices[len]][0]; _supportedSymbols[len] = ftso.symbol(); } } /** * @notice Get array of all supported indices and corresponding FTSOs * @return _supportedIndices the array of all supported indices * @return _ftsos the array of all supported ftsos */ function getSupportedIndicesAndFtsos() external view override returns(uint256[] memory _supportedIndices, IIFtso[] memory _ftsos) { _supportedIndices = _getSupportedIndices(); uint256 len = _supportedIndices.length; _ftsos = new IIFtso[](len); while (len > 0) { --len; _ftsos[len] = ftsoHistory[_supportedIndices[len]][0]; } } /** * @notice Get array of all supported symbols and corresponding FTSOs * @return _supportedSymbols the array of all supported symbols * @return _ftsos the array of all supported ftsos */ function getSupportedSymbolsAndFtsos() external view override returns(string[] memory _supportedSymbols, IIFtso[] memory _ftsos) { uint256[] memory _supportedIndices = _getSupportedIndices(); uint256 len = _supportedIndices.length; _ftsos = new IIFtso[](len); _supportedSymbols = new string[](len); while (len > 0) { --len; _ftsos[len] = ftsoHistory[_supportedIndices[len]][0]; _supportedSymbols[len] = _ftsos[len].symbol(); } } /** * @notice Get array of all supported indices and corresponding symbols * @return _supportedIndices the array of all supported indices * @return _supportedSymbols the array of all supported symbols */ function getSupportedIndicesAndSymbols() external view override returns(uint256[] memory _supportedIndices, string[] memory _supportedSymbols) { _supportedIndices = _getSupportedIndices(); uint256 len = _supportedIndices.length; _supportedSymbols = new string[](len); while (len > 0) { --len; IIFtso ftso = ftsoHistory[_supportedIndices[len]][0]; _supportedSymbols[len] = ftso.symbol(); } } /** * @notice Get array of all supported indices, corresponding symbols and FTSOs * @return _supportedIndices the array of all supported indices * @return _supportedSymbols the array of all supported symbols * @return _ftsos the array of all supported ftsos */ function getSupportedIndicesSymbolsAndFtsos() external view override returns(uint256[] memory _supportedIndices, string[] memory _supportedSymbols, IIFtso[] memory _ftsos) { _supportedIndices = _getSupportedIndices(); uint256 len = _supportedIndices.length; _ftsos = new IIFtso[](len); _supportedSymbols = new string[](len); while (len > 0) { --len; _ftsos[len] = ftsoHistory[_supportedIndices[len]][0]; _supportedSymbols[len] = _ftsos[len].symbol(); } } /** * @notice Get array of all FTSO contracts for all supported asset indices. * The index of FTSO in returned array does not necessarily correspond to _assetIndex * Due to deletion, some indices might be unsupported. * @dev See `getSupportedIndicesAndFtsos` for pair of correct indices and `getAllFtsos` * for FTSOs at valid indices but with possible "null" holes. * @return _ftsos the array of all supported FTSOs */ function getSupportedFtsos() external view override returns(IIFtso[] memory _ftsos) { uint256[] memory supportedIndices = _getSupportedIndices(); uint256 len = supportedIndices.length; _ftsos = new IIFtso[](len); while (len > 0) { --len; _ftsos[len] = ftsoHistory[supportedIndices[len]][0]; } } /** * @notice Get the active FTSOs for given indices * @return _ftsos the array of FTSOs */ function getFtsos(uint256[] memory _assetIndices) external view override returns(IFtsoGenesis[] memory _ftsos) { uint256 ftsoLength = ftsoHistory.length; uint256 len = _assetIndices.length; _ftsos = new IFtsoGenesis[](len); while (len > 0) { --len; uint256 assetIndex = _assetIndices[len]; require(assetIndex < ftsoLength, ERR_TOKEN_NOT_SUPPORTED); _ftsos[len] = ftsoHistory[assetIndex][0]; if (address(_ftsos[len]) == address(0)) { // Invalid index, revert if address is zero address revert(ERR_TOKEN_NOT_SUPPORTED); } } } /** * @notice Get array of all FTSO contracts for all supported asset indices * @return _ftsos the array of all FTSOs * @dev Return value might contain uninitialized FTSOS at zero address. */ function getAllFtsos() external view returns(IIFtso[] memory _ftsos) { uint256 len = ftsoHistory.length; IIFtso[] memory ftsos = new IIFtso[](len); while (len > 0) { --len; ftsos[len] = ftsoHistory[len][0]; } return ftsos; } /** * @notice Get the history of FTSOs for given index * @dev If there are less then MAX_HISTORY_LENGTH the remaining addresses will be 0 addresses * @param _assetIndex asset index * @return _ftsoAddressHistory the history of FTSOs contract for provided index */ function getFtsoHistory(uint256 _assetIndex) external view returns(IIFtso[MAX_HISTORY_LENGTH] memory _ftsoAddressHistory) { require(_assetIndex < ftsoHistory.length && address(ftsoHistory[_assetIndex][0]) != address(0), ERR_TOKEN_NOT_SUPPORTED); return ftsoHistory[_assetIndex]; } function getFtsoIndex(string memory _symbol) external view override returns (uint256 _assetIndex) { return _getFtsoIndex(_symbol); } function getFtsoSymbol(uint256 _assetIndex) external view override returns (string memory _symbol) { return _getFtso(_assetIndex).symbol(); } /** * @notice Shift the FTSOs history by one so the FTSO at index 0 can be overwritten * @dev Internal helper function */ function _shiftHistory(uint256 _assetIndex) internal { for (uint256 i = MAX_HISTORY_LENGTH-1; i > 0; i--) { ftsoHistory[_assetIndex][i] = ftsoHistory[_assetIndex][i-1]; } } function _getFtsoIndex(string memory _symbol) private view returns (uint256 _assetIndex) { bytes32 _encodedSymbol = keccak256(abi.encode(_symbol)); uint256 len = ftsoHistory.length; for (uint256 i = 0; i < len; ++i) { IIFtso current = ftsoHistory[i][0]; if (address(current) == address(0)) { continue; } if (_encodedSymbol == keccak256(abi.encode(current.symbol()))) { return i; } } revert(ERR_TOKEN_NOT_SUPPORTED); } /** * @notice Get the active FTSO for given index * @dev Internal get ftso function so it can be used within other methods */ function _getFtso(uint256 _assetIndex) private view returns(IIFtso _activeFtso) { require(_assetIndex < ftsoHistory.length, ERR_TOKEN_NOT_SUPPORTED); IIFtso ftso = ftsoHistory[_assetIndex][0]; if (address(ftso) == address(0)) { // Invalid index, revert if address is zero address revert(ERR_TOKEN_NOT_SUPPORTED); } _activeFtso = ftso; } function _getSupportedIndices() private view returns(uint256[] memory _supportedIndices) { uint256 len = ftsoHistory.length; uint256[] memory supportedIndices = new uint256[](len); address zeroAddress = address(0); uint256 taken = 0; for (uint256 i = 0; i < len; ++i) { if (address(ftsoHistory[i][0]) != zeroAddress) { supportedIndices[taken] = i; ++taken; } } _supportedIndices = new uint256[](taken); while (taken > 0) { --taken; _supportedIndices[taken] = supportedIndices[taken]; } return _supportedIndices; } } contract MockVoterWhitelister is IVoterWhitelister { uint256 public override defaultMaxVotersForFtso = 1; mapping (uint256 => uint256) public override maxVotersForFtso; // mapping: ftsoIndex => array of whitelisted voters for this ftso mapping (uint256 => address) internal whitelist; MockPriceSubmitter internal priceSubmitter; IFtsoRegistry internal ftsoRegistry; modifier onlyPriceSubmitter { require(msg.sender == address(priceSubmitter), "only price submitter"); _; } constructor(MockPriceSubmitter _priceSubmitter) { priceSubmitter = _priceSubmitter; } /** * Request to whitelist `_voter` account to all active ftsos. * May be called by any address. * It returns an array of supported ftso indices and success flag per index. */ function requestFullVoterWhitelisting( address _voter ) external override returns ( uint256[] memory _supportedIndices, bool[] memory _success ) { if (_isTrustedAddress(_voter)) { revert("trusted address"); } _supportedIndices = ftsoRegistry.getSupportedIndices(); uint256 len = _supportedIndices.length; _success = new bool[](len); for (uint256 i = 0; i < len; i++) { _success[i] = _requestWhitelistingVoter(_voter, _supportedIndices[i]); } } /** * Request to whitelist `_voter` account to ftso at `_ftsoIndex`. Will revert if vote power too low. * May be called by any address. */ function requestWhitelistingVoter(address _voter, uint256 _ftsoIndex) external override { if (_isTrustedAddress(_voter)) { revert("trusted address"); } bool success = _requestWhitelistingVoter(_voter, _ftsoIndex); require(success, "vote power too low"); } /** * Request to whitelist `_voter` account to ftso at `_ftsoIndex` - mock implementation. */ function _requestWhitelistingVoter(address _voter, uint256 _ftsoIndex) internal returns(bool) { uint256 maxVoters = maxVotersForFtso[_ftsoIndex]; require(maxVoters > 0, "FTSO index not supported"); address addr = whitelist[_ftsoIndex]; if (addr == _voter) { // _voter is already whitelisted, return return true; } whitelist[_ftsoIndex] = _voter; address[] memory removedVoters = new address[](1); removedVoters[0] = addr; _votersRemovedFromWhitelist(removedVoters, _ftsoIndex); _voterWhitelisted(_voter, _ftsoIndex); return true; } /** * Update a voter whitelisting and emit an event. */ function _voterWhitelisted(address _voter, uint256 _ftsoIndex) private { emit VoterWhitelisted(_voter, _ftsoIndex); priceSubmitter.voterWhitelisted(_voter, _ftsoIndex); } /** * Update when a voter is removed from the whitelist. And emit an event. */ function _votersRemovedFromWhitelist(address[] memory _removedVoters, uint256 _ftsoIndex) private { for (uint256 i = 0; i < _removedVoters.length; i++) { emit VoterRemovedFromWhitelist(_removedVoters[i], _ftsoIndex); } priceSubmitter.votersRemovedFromWhitelist(_removedVoters, _ftsoIndex); } /** * Get whitelisted price providers for ftso with `_symbol` */ function getFtsoWhitelistedPriceProvidersBySymbol( string memory _symbol ) external view override returns ( address[] memory ) { uint256 ftsoIndex = ftsoRegistry.getFtsoIndex(_symbol); return getFtsoWhitelistedPriceProviders(ftsoIndex); } /** * Get whitelisted price providers for ftso at `_ftsoIndex` */ function getFtsoWhitelistedPriceProviders(uint256 _ftsoIndex) public view override returns (address[] memory) { uint256 maxVoters = maxVotersForFtso[_ftsoIndex]; require(maxVoters > 0, "FTSO index not supported"); address addr = whitelist[_ftsoIndex]; if (addr == address(0)) { return new address[](0); } else { address[] memory result = new address[](1); result[0] = addr; return result; } } /** * Changes ftsoRegistry address. */ function setFtsoRegistry(IFtsoRegistry _ftsoRegistry) external onlyPriceSubmitter { ftsoRegistry = _ftsoRegistry; } function addFtso(uint256 _ftsoIndex) external onlyPriceSubmitter { require(maxVotersForFtso[_ftsoIndex] == 0, "whitelist already exist"); maxVotersForFtso[_ftsoIndex] = defaultMaxVotersForFtso; } /** * Checks if _voter is trusted address */ function _isTrustedAddress(address /*_voter*/) internal pure returns(bool) { // Unused in mock contract return false; } } /** * @title Price submitter * @notice A contract used to submit/reveal prices to multiple Flare Time Series Oracles in one transaction */ contract MockPriceSubmitter is IPriceSubmitter { string internal constant ERR_ARRAY_LENGTHS = "Array lengths do not match"; string internal constant ERR_NOT_WHITELISTED = "Not whitelisted"; string internal constant ERR_INVALID_INDEX = "Invalid index"; string internal constant ERR_WHITELISTER_ONLY = "Voter whitelister only"; MockFtsoRegistry internal ftsoRegistry; MockVoterWhitelister internal voterWhitelister; // Bit at index `i` corresponds to being whitelisted for vote on ftso at index `i` mapping(address => uint256) private whitelistedFtsoBitmap; modifier onlyWhitelister { require(msg.sender == address(voterWhitelister), ERR_WHITELISTER_ONLY); _; } /** * Deploy all needed contracts for testing */ constructor() { ftsoRegistry = new MockFtsoRegistry(address(this)); voterWhitelister = new MockVoterWhitelister(this); voterWhitelister.setFtsoRegistry(ftsoRegistry); // Initialize all mock ftsos for pacakge string[10] memory symbols = ["SGB", "XRP", "LTC", "XLM", "XDG", "ADA", "ALGO", "BCH", "DGB", "BTC"]; for (uint256 i = 0; i < symbols.length; ++i) { string memory symbol = symbols[i]; MockNpmFtso ftso = new MockNpmFtso(symbol, this, block.timestamp - 120, 120, 30); ftsoRegistry.addFtso(ftso); uint256 ftsoIndex = ftsoRegistry.getFtsoIndex(symbol); voterWhitelister.addFtso(ftsoIndex); } } /** * Called from whitelister when new voter has been whitelisted. */ function voterWhitelisted( address _voter, uint256 _ftsoIndex ) external onlyWhitelister { whitelistedFtsoBitmap[_voter] |= 1 << _ftsoIndex; } /** * Called from whitelister when one or more voters have been removed. */ function votersRemovedFromWhitelist( address[] memory _removedVoters, uint256 _ftsoIndex ) external onlyWhitelister { for (uint256 i = 0; i < _removedVoters.length; i++) { whitelistedFtsoBitmap[_removedVoters[i]] &= ~(1 << _ftsoIndex); } } /** * @notice Submits price hashes for current epoch * @param _ftsoIndices List of ftso indices * @param _hashes List of hashed price and random number * @notice Emits PriceHashesSubmitted event */ function submitPriceHashes( uint256 _epochId, uint256[] memory _ftsoIndices, bytes32[] memory _hashes ) external override { // Submit the prices uint256 length = _ftsoIndices.length; require(length == _hashes.length, ERR_ARRAY_LENGTHS); IFtsoGenesis[] memory ftsos = ftsoRegistry.getFtsos(_ftsoIndices); uint256 allowedBitmask = whitelistedFtsoBitmap[msg.sender]; for (uint256 i = 0; i < length; i++) { uint256 ind = _ftsoIndices[i]; if (allowedBitmask & (1 << ind) == 0) { revert(ERR_NOT_WHITELISTED); } ftsos[i].submitPriceHashSubmitter(msg.sender, _epochId, _hashes[i]); } emit PriceHashesSubmitted(msg.sender, _epochId, ftsos, _hashes, block.timestamp); } /** * @notice Reveals submitted prices during epoch reveal period * @param _epochId Id of the epoch in which the price hashes was submitted * @param _ftsoIndices List of ftso indices * @param _prices List of submitted prices in USD * @param _randoms List of submitted random numbers * @notice The hash of _price and _random must be equal to the submitted hash * @notice Emits PricesRevealed event */ function revealPrices( uint256 _epochId, uint256[] memory _ftsoIndices, uint256[] memory _prices, uint256[] memory _randoms ) external override { uint256 length = _ftsoIndices.length; require(length == _prices.length, ERR_ARRAY_LENGTHS); require(length == _randoms.length, ERR_ARRAY_LENGTHS); IFtsoGenesis[] memory ftsos = ftsoRegistry.getFtsos(_ftsoIndices); uint256 allowedBitmask = whitelistedFtsoBitmap[msg.sender]; uint256 wNatVP = uint256(-1); for (uint256 i = 0; i < length; i++) { uint256 ind = _ftsoIndices[i]; if (allowedBitmask & (1 << ind) == 0) { revert(ERR_NOT_WHITELISTED); } // read native VP only once if (wNatVP == uint256(-1)) { wNatVP = ftsos[i].wNatVotePowerCached(msg.sender, _epochId); } // call reveal price on ftso ftsos[i].revealPriceSubmitter(msg.sender, _epochId, _prices[i], _randoms[i], wNatVP); } emit PricesRevealed(msg.sender, _epochId, ftsos, _prices, _randoms, block.timestamp); } /** * Returns bitmap of all ftso's for which `_voter` is allowed to submit prices/hashes. * If voter is allowed to vote for ftso at index (see *_FTSO_INDEX), the corrsponding * bit in the result will be 1. */ function voterWhitelistBitmap(address _voter) external view override returns (uint256) { return whitelistedFtsoBitmap[_voter]; } function getVoterWhitelister() public view override returns (address) { return address(voterWhitelister); } function getFtsoRegistry() public view override returns (IFtsoRegistryGenesis) { return ftsoRegistry; } function getFtsoManager() public pure override returns (address) { revert("Not in dummy contract"); } } // End of inlining: PriceProviderMockContracts.sol // Inlining: ../../interface/IIFtso.sol // INLINED-SPDX-INLINED-License-Identifier: MIT pragma solidity 0.7.6; // import "../../genesis/interface/IFtsoGenesis.sol"; // import "../../userInterfaces/IFtso.sol"; // import "../../token/interface/IIVPToken.sol"; interface IIFtso is IFtso, IFtsoGenesis { /// function finalizePriceReveal /// called by reward manager only on correct timing. /// if price reveal period for epoch x ended. finalize. /// iterate list of price submissions /// find weighted median /// find adjucant 50% of price submissions. /// Allocate reward for any price submission which is same as a "winning" submission function finalizePriceEpoch(uint256 _epochId, bool _returnRewardData) external returns( address[] memory _eligibleAddresses, uint256[] memory _natWeights, uint256 _totalNatWeight ); function fallbackFinalizePriceEpoch(uint256 _epochId) external; function forceFinalizePriceEpoch(uint256 _epochId) external; // activateFtso will be called by ftso manager once ftso is added // before this is done, FTSO can't run function activateFtso( uint256 _firstEpochStartTs, uint256 _submitPeriodSeconds, uint256 _revealPeriodSeconds ) external; function deactivateFtso() external; // update initial price and timestamp - only if not active function updateInitialPrice(uint256 _initialPriceUSD, uint256 _initialPriceTimestamp) external; function configureEpochs( uint256 _maxVotePowerNatThresholdFraction, uint256 _maxVotePowerAssetThresholdFraction, uint256 _lowAssetUSDThreshold, uint256 _highAssetUSDThreshold, uint256 _highAssetTurnoutThresholdBIPS, uint256 _lowNatTurnoutThresholdBIPS, address[] memory _trustedAddresses ) external; function setAsset(IIVPToken _asset) external; function setAssetFtsos(IIFtso[] memory _assetFtsos) external; // current vote power block will update per reward epoch. // the FTSO doesn't have notion of reward epochs. // reward manager only can set this data. function setVotePowerBlock(uint256 _blockNumber) external; function initializeCurrentEpochStateForReveal(uint256 _circulatingSupplyNat, bool _fallbackMode) external; /** * @notice Returns ftso manager address */ function ftsoManager() external view returns (address); /** * @notice Returns the FTSO asset * @dev Asset is null in case of multi-asset FTSO */ function getAsset() external view returns (IIVPToken); /** * @notice Returns the Asset FTSOs * @dev AssetFtsos is not null only in case of multi-asset FTSO */ function getAssetFtsos() external view returns (IIFtso[] memory); /** * @notice Returns current configuration of epoch state * @return _maxVotePowerNatThresholdFraction High threshold for native token vote power per voter * @return _maxVotePowerAssetThresholdFraction High threshold for asset vote power per voter * @return _lowAssetUSDThreshold Threshold for low asset vote power * @return _highAssetUSDThreshold Threshold for high asset vote power * @return _highAssetTurnoutThresholdBIPS Threshold for high asset turnout * @return _lowNatTurnoutThresholdBIPS Threshold for low nat turnout * @return _trustedAddresses Trusted addresses - use their prices if low nat turnout is not achieved */ function epochsConfiguration() external view returns ( uint256 _maxVotePowerNatThresholdFraction, uint256 _maxVotePowerAssetThresholdFraction, uint256 _lowAssetUSDThreshold, uint256 _highAssetUSDThreshold, uint256 _highAssetTurnoutThresholdBIPS, uint256 _lowNatTurnoutThresholdBIPS, address[] memory _trustedAddresses ); /** * @notice Returns parameters necessary for approximately replicating vote weighting. * @return _assets the list of Assets that are accounted in vote * @return _assetMultipliers weight of each asset in (multiasset) ftso, mutiplied by TERA * @return _totalVotePowerNat total native token vote power at block * @return _totalVotePowerAsset total combined asset vote power at block * @return _assetWeightRatio ratio of combined asset vp vs. native token vp (in BIPS) * @return _votePowerBlock vote powewr block for given epoch */ function getVoteWeightingParameters() external view returns ( IIVPToken[] memory _assets, uint256[] memory _assetMultipliers, uint256 _totalVotePowerNat, uint256 _totalVotePowerAsset, uint256 _assetWeightRatio, uint256 _votePowerBlock ); function wNat() external view returns (IIVPToken); } // End of inlining: ../../interface/IIFtso.sol // Inlining: ../priceProviderMockFtso.sol // INLINED-SPDX-INLINED-License-Identifier: MIT pragma solidity 0.7.6; // import "../interface/IIFtso.sol"; // import "../../userInterfaces/IPriceSubmitter.sol"; // In seperate library as using abicoder v2 decreases the maximum number of arguments /** * @title A contract implementing Flare Time Series Oracle */ contract MockNpmFtso is IIFtso { // number of decimal places in Asset USD price // note that the actual USD price is the integer value divided by 10^ASSET_PRICE_USD_DECIMALS uint256 public constant ASSET_PRICE_USD_DECIMALS = 5; // errors string internal constant ERR_NO_ACCESS = "Access denied"; string internal constant ERR_PRICE_TOO_HIGH = "Price too high"; string internal constant ERR_PRICE_REVEAL_FAILURE = "Reveal period not active"; string internal constant ERR_PRICE_INVALID = "Price already revealed or not valid"; string internal constant ERR_WRONG_EPOCH_ID = "Wrong epoch id"; string internal constant ERR_DUPLICATE_SUBMIT_IN_EPOCH = "Duplicate submit in epoch"; string internal constant UNAVAILABLE = "Unavailable for testing"; // storage bool public override active; // activation status of FTSO string public override symbol; // asset symbol that identifies FTSO uint256 internal assetPriceUSD; // current Asset USD price uint256 internal assetPriceTimestamp; // time when price was updated mapping(uint256 => mapping(address => bytes32)) internal epochVoterHash; // external contracts IPriceSubmitter public priceSubmitter; // Price submitter contract IIVPToken[] public assets; // array of assets IIFtso[] public assetFtsos; // FTSOs for assets (for a multi-asset FTSO) uint256 internal firstEpochStartTs; uint256 internal submitPeriodSeconds; uint256 internal revealPeriodSeconds; mapping(uint256 => uint256) internal random; mapping(uint256 => mapping (address => uint256)) internal revealedPrices; modifier onlyPriceSubmitter { if (msg.sender != address(priceSubmitter)) { revertNoAccess(); } _; } constructor( string memory _symbol, IPriceSubmitter _priceSubmitter, uint256 _firstEpochStartTs, uint256 _submitPeriodSeconds, uint256 _revealPeriodSeconds) { symbol = _symbol; assetPriceTimestamp = block.timestamp; active = true; priceSubmitter = _priceSubmitter; firstEpochStartTs = _firstEpochStartTs; submitPeriodSeconds = _submitPeriodSeconds; revealPeriodSeconds = _revealPeriodSeconds; } // This methods should only be used by price submitter /** * @notice Submits price hash for current epoch * @param _sender Sender address * @param _epochId Target epoch id to which hashes are submitted * @param _hash Hashed price and random number * @notice Emits PriceHashSubmitted event */ function submitPriceHashSubmitter( address _sender, uint256 _epochId, bytes32 _hash ) external override onlyPriceSubmitter { require(_epochId == _getCurrentEpochId(), ERR_WRONG_EPOCH_ID); require(epochVoterHash[_epochId][_sender] == 0, ERR_DUPLICATE_SUBMIT_IN_EPOCH); epochVoterHash[_epochId][_sender] = _hash; emit PriceHashSubmitted(_sender, _epochId, _hash, block.timestamp); } /** * @notice Reveals submitted price during epoch reveal period * @param _voter Voter address * @param _epochId Id of the epoch in which the price hash was submitted * @param _price Submitted price in USD * @param _random Submitted random number * @notice The hash of _price and _random must be equal to the submitted hash * @notice Emits PriceRevealed event */ function revealPriceSubmitter( address _voter, uint256 _epochId, uint256 _price, uint256 _random, uint256 /*_wNatVP*/ // just an optimization, to read native token vp only once ) external override onlyPriceSubmitter { require(_price < 2**128, ERR_PRICE_TOO_HIGH); // Check if reveal is in progress uint256 revealStartTime = firstEpochStartTs + (_epochId + 1) * submitPeriodSeconds; require(revealStartTime <= block.timestamp && block.timestamp < revealStartTime + revealPeriodSeconds, ERR_PRICE_REVEAL_FAILURE); require(epochVoterHash[_epochId][_voter] == keccak256(abi.encode(_price, _random, _voter)), ERR_PRICE_INVALID); // TODO: What about random // prevent price submission from being revealed twice delete epochVoterHash[_epochId][_voter]; revealedPrices[_epochId][_voter] = _price; // inform about price reveal result emit PriceRevealed(_voter, _epochId, _price, _random, block.timestamp, 0, 0); } function wNatVotePowerCached(address _owner, uint256 _epochId) external override returns (uint256 _wNatVP) { // TODO } /** * @notice Returns current Asset price * @return _price Price in USD multiplied by ASSET_PRICE_USD_DECIMALS * @return _timestamp Time when price was updated for the last time */ function getCurrentPrice() external view override returns (uint256 _price, uint256 _timestamp) { // TODO } /** * @notice Returns current random number */ function getCurrentRandom() external pure override returns (uint256) { return 0; } function ftsoManager() external pure override returns (address) { // TODO } /** * @notice Returns current epoch data * @return _epochId Current epoch id * @return _epochSubmitEndTime End time of the current epoch price submission as seconds from unix epoch * @return _epochRevealEndTime End time of the current epoch price reveal as seconds from unix epoch * @return _votePowerBlock Not calculated in mocks, always 0 * @return _fallbackMode Not calculated in mocks, always 0 * @dev half-closed intervals - end time not included */ function getPriceEpochData() external view override returns ( uint256 _epochId, uint256 _epochSubmitEndTime, uint256 _epochRevealEndTime, uint256 _votePowerBlock, bool _fallbackMode ) { _epochId = _getCurrentEpochId(); _epochSubmitEndTime = firstEpochStartTs + (_epochId + 1) * submitPeriodSeconds; _epochRevealEndTime = _epochSubmitEndTime + revealPeriodSeconds; _votePowerBlock = 0; _fallbackMode = false; } /** * @notice Returns current epoch data * @return _firstEpochStartTs First epoch start timestamp * @return _submitPeriodSeconds Submit period in seconds * @return _revealPeriodSeconds Reveal period in seconds */ function getPriceEpochConfiguration() external view override returns ( uint256 _firstEpochStartTs, uint256 _submitPeriodSeconds, uint256 _revealPeriodSeconds ) { return ( firstEpochStartTs, submitPeriodSeconds, revealPeriodSeconds ); } /** * @notice Returns Asset price submitted by voter in specific epoch * @param _epochId Id of the epoch * @param _voter Address of the voter * @return Price in USD multiplied by ASSET_PRICE_USD_DECIMALS */ function getEpochPriceForVoter(uint256 _epochId, address _voter) external view override returns (uint256) { return revealedPrices[_epochId][_voter]; } /** * @notice Returns current epoch id * @dev Should never revert */ function _getCurrentEpochId() internal view returns (uint256) { return _getEpochId(block.timestamp); } /** * @notice Returns id of the epoch which was opened for price submission at the specified timestamp * @param _timestamp Timestamp as seconds from unix epoch * @dev Should never revert */ function _getEpochId(uint256 _timestamp) internal view returns (uint256) { if (_timestamp < firstEpochStartTs) { return 0; } else { return (_timestamp - firstEpochStartTs) / submitPeriodSeconds; } } // Methods only used for IIFtso implementation // Will always fail function finalizePriceEpoch(uint256, bool) external pure override returns( address[] memory, uint256[] memory, uint256 ) { require(false, UNAVAILABLE); return (new address[](0), new uint256[](0), 0); } function fallbackFinalizePriceEpoch(uint256) external pure override { require(false, UNAVAILABLE); } function forceFinalizePriceEpoch(uint256) external pure override { require(false, UNAVAILABLE); } // activateFtso will be called by ftso manager once ftso is added // before this is done, FTSO can't run function activateFtso( uint256, uint256, uint256) external pure override { require(false, UNAVAILABLE); } function deactivateFtso() external pure override { require(false, UNAVAILABLE); } // update initial price and timestamp - only if not active function updateInitialPrice(uint256, uint256) external pure override { require(false, UNAVAILABLE); } function configureEpochs( uint256, uint256, uint256, uint256, uint256, uint256, address[] memory ) external pure override { require(false, UNAVAILABLE); } function setAsset(IIVPToken) external pure override { require(false, UNAVAILABLE); } function setAssetFtsos(IIFtso[] memory) external pure override { require(false, UNAVAILABLE); } // current vote power block will update per reward epoch. // the FTSO doesn't have notion of reward epochs. // reward manager only can set this data. function setVotePowerBlock(uint256) external pure override { require(false, UNAVAILABLE); } function initializeCurrentEpochStateForReveal(uint256, bool) external pure override { require(false, UNAVAILABLE); } /** * @notice Returns the FTSO asset * @dev asset is null in case of multi-asset FTSO */ function getAsset() external pure override returns (IIVPToken) { require(false, UNAVAILABLE); return IIVPToken(address(0)); } /** * @notice Returns the Asset FTSOs * @dev AssetFtsos is not null only in case of multi-asset FTSO */ function getAssetFtsos() external pure override returns (IIFtso[] memory) { require(false, UNAVAILABLE); return new IIFtso[](0); } function epochsConfiguration() external pure override returns ( uint256, uint256, uint256, uint256, uint256, uint256, address[] memory ) { require(false, UNAVAILABLE); return (0, 0, 0, 0, 0, 0, new address[](0)); } function getCurrentEpochId() external pure override returns (uint256) { require(false, UNAVAILABLE); return 0; } function getEpochId(uint256) external pure override returns (uint256) { require(false, UNAVAILABLE); return 0; } function getRandom(uint256) external pure override returns (uint256) { require(false, UNAVAILABLE); return 0; } function getEpochPrice(uint256) external pure override returns (uint256) { require(false, UNAVAILABLE); return 0; } function getVoteWeightingParameters() external pure override returns ( IIVPToken[] memory, uint256[] memory, uint256, uint256, uint256, uint256 ) { require(false, UNAVAILABLE); return (new IIVPToken[](0), new uint256[](0), 0, 0, 0, 0); } function wNat() external pure override returns (IIVPToken) { require(false, UNAVAILABLE); return IIVPToken(address(0)); } function revertNoAccess() internal pure { revert(ERR_NO_ACCESS); } } // End of inlining: ../priceProviderMockFtso.sol