{ "language": "Solidity", "settings": { "evmVersion": "london", "libraries": {}, "metadata": { "bytecodeHash": "ipfs", "useLiteralContent": true }, "optimizer": { "enabled": true, "runs": 5000 }, "remappings": [], "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } } }, "sources": { "@openzeppelin/contracts/proxy/utils/Initializable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../../utils/Address.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * contract MyToken is ERC20Upgradeable {\n * function initialize() initializer public {\n * __ERC20_init(\"MyToken\", \"MTK\");\n * }\n * }\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n * function initializeV2() reinitializer(2) public {\n * __ERC20Permit_init(\"MyToken\");\n * }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n * _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n /**\n * @dev Indicates that the contract has been initialized.\n * @custom:oz-retyped-from bool\n */\n uint8 private _initialized;\n\n /**\n * @dev Indicates that the contract is in the process of being initialized.\n */\n bool private _initializing;\n\n /**\n * @dev Triggered when the contract has been initialized or reinitialized.\n */\n event Initialized(uint8 version);\n\n /**\n * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n * `onlyInitializing` functions can be used to initialize parent contracts. Equivalent to `reinitializer(1)`.\n */\n modifier initializer() {\n bool isTopLevelCall = _setInitializedVersion(1);\n if (isTopLevelCall) {\n _initializing = true;\n }\n _;\n if (isTopLevelCall) {\n _initializing = false;\n emit Initialized(1);\n }\n }\n\n /**\n * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n * used to initialize parent contracts.\n *\n * `initializer` is equivalent to `reinitializer(1)`, so a reinitializer may be used after the original\n * initialization step. This is essential to configure modules that are added through upgrades and that require\n * initialization.\n *\n * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n * a contract, executing them in the right order is up to the developer or operator.\n */\n modifier reinitializer(uint8 version) {\n bool isTopLevelCall = _setInitializedVersion(version);\n if (isTopLevelCall) {\n _initializing = true;\n }\n _;\n if (isTopLevelCall) {\n _initializing = false;\n emit Initialized(version);\n }\n }\n\n /**\n * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n * {initializer} and {reinitializer} modifiers, directly or indirectly.\n */\n modifier onlyInitializing() {\n require(_initializing, \"Initializable: contract is not initializing\");\n _;\n }\n\n /**\n * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n * through proxies.\n */\n function _disableInitializers() internal virtual {\n _setInitializedVersion(type(uint8).max);\n }\n\n function _setInitializedVersion(uint8 version) private returns (bool) {\n // If the contract is initializing we ignore whether _initialized is set in order to support multiple\n // inheritance patterns, but we only do this in the context of a constructor, and for the lowest level\n // of initializers, because in other contexts the contract may have been reentered.\n if (_initializing) {\n require(\n version == 1 && !Address.isContract(address(this)),\n \"Initializable: contract is already initialized\"\n );\n return false;\n } else {\n require(_initialized < version, \"Initializable: contract is already initialized\");\n _initialized = version;\n return true;\n }\n }\n}\n" }, "@openzeppelin/contracts/token/ERC20/IERC20.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n" }, "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n" }, "@openzeppelin/contracts/utils/Address.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n" }, "contracts/access/Governable.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.9;\n\nimport \"../core/AddressProvider.sol\";\n\n/**\n * @notice Contract module which provides access control mechanism, where\n * the governor account is granted with exclusive access to specific functions.\n * @dev Uses the AddressProvider to get the governor\n */\nabstract contract Governable {\n IAddressProvider public constant addressProvider = IAddressProvider(0xfbA0816A81bcAbBf3829bED28618177a2bf0e82A);\n\n /// @dev Throws if called by any account other than the governor.\n modifier onlyGovernor() {\n require(msg.sender == addressProvider.governor(), \"not-governor\");\n _;\n }\n}\n" }, "contracts/core/AddressProvider.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.9;\n\nimport \"@openzeppelin/contracts/proxy/utils/Initializable.sol\";\nimport \"../interfaces/core/IAddressProvider.sol\";\n\ncontract AddressProvider is IAddressProvider, Initializable {\n /// @notice The governor account\n address public governor;\n\n /// @notice The proposed governor account. Becomes the new governor after acceptance\n address public proposedGovernor;\n\n /// @notice The PriceProvidersAggregator contract\n IPriceProvidersAggregator public override providersAggregator;\n\n /// @notice The StableCoinProvider contract\n IStableCoinProvider public override stableCoinProvider;\n\n /// @notice Emitted when providers aggregator is updated\n event ProvidersAggregatorUpdated(\n IPriceProvidersAggregator oldProvidersAggregator,\n IPriceProvidersAggregator newProvidersAggregator\n );\n\n /// @notice Emitted when stable coin provider is updated\n event StableCoinProviderUpdated(\n IStableCoinProvider oldStableCoinProvider,\n IStableCoinProvider newStableCoinProvider\n );\n\n /// @notice Emitted when governor is updated\n event UpdatedGovernor(address indexed previousGovernor, address indexed proposedGovernor);\n\n /**\n * @dev Throws if called by any account other than the governor.\n */\n modifier onlyGovernor() {\n require(governor == msg.sender, \"not-governor\");\n _;\n }\n\n function initialize(address governor_) external initializer {\n governor = governor_;\n emit UpdatedGovernor(address(0), governor_);\n }\n\n /**\n * @dev Allows new governor to accept governorship of the contract.\n */\n function acceptGovernorship() external {\n require(msg.sender == proposedGovernor, \"not-the-proposed-governor\");\n emit UpdatedGovernor(governor, proposedGovernor);\n governor = proposedGovernor;\n proposedGovernor = address(0);\n }\n\n /**\n * @dev Transfers governorship of the contract to a new account (`proposedGovernor`).\n * Can only be called by the current owner.\n */\n function transferGovernorship(address _proposedGovernor) external onlyGovernor {\n require(_proposedGovernor != address(0), \"proposed-governor-is-zero\");\n proposedGovernor = _proposedGovernor;\n }\n\n /**\n * @notice Update PriceProvidersAggregator contract\n */\n function updateProvidersAggregator(IPriceProvidersAggregator providersAggregator_) external onlyGovernor {\n require(address(providersAggregator_) != address(0), \"address-is-null\");\n emit ProvidersAggregatorUpdated(providersAggregator, providersAggregator_);\n providersAggregator = providersAggregator_;\n }\n\n /**\n * @notice Update StableCoinProvider contract\n */\n function updateStableCoinProvider(IStableCoinProvider stableCoinProvider_) external onlyGovernor {\n emit StableCoinProviderUpdated(stableCoinProvider, stableCoinProvider_);\n stableCoinProvider = stableCoinProvider_;\n }\n}\n" }, "contracts/core/StableCoinProvider.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.9;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"../libraries/OracleHelpers.sol\";\nimport \"../interfaces/core/IStableCoinProvider.sol\";\nimport \"../features/UsingStalePeriod.sol\";\nimport \"../features/UsingMaxDeviation.sol\";\n\n/**\n * @title Provide pegged stable coin, useful for getting USD prices reference from DEXes\n * @dev This contract mitigates a de-peg scenario by checking price against two stable coins that should be around 1\n */\ncontract StableCoinProvider is IStableCoinProvider, UsingStalePeriod, UsingMaxDeviation {\n using OracleHelpers for uint256;\n\n uint256 public constant USD_DECIMALS = 18;\n uint256 public constant ONE_USD = 10**USD_DECIMALS;\n\n /**\n * @notice A stable coin to use as USD price reference\n * @dev Should not be called directly from other contracts, must use `getStableCoinIfPegged`\n */\n address public primaryStableCoin;\n uint8 private __primaryStableCoinDecimals;\n\n /**\n * @notice A secondary stable coin used to check USD-peg against primary\n * @dev Should not be called directly from other contracts, must use `getStableCoinIfPegged`\n */\n address public secondaryStableCoin;\n uint8 private __secondaryStableCoinDecimals;\n\n /// @notice Emitted when stable coin is updated\n event StableCoinsUpdated(\n address oldPrimaryStableCoin,\n address oldSecondaryStableCoin,\n address newPrimaryStableCoin,\n address newSecondaryStableCoin\n );\n\n constructor(\n address primaryStableCoin_,\n address secondaryStableCoin_,\n uint256 stalePeriod_,\n uint256 maxDeviation_\n ) UsingStalePeriod(stalePeriod_) UsingMaxDeviation(maxDeviation_) {\n _updateStableCoins(primaryStableCoin_, secondaryStableCoin_);\n }\n\n /// @inheritdoc IStableCoinProvider\n function getStableCoinIfPegged() external view returns (address _stableCoin) {\n // Note: Chainlink supports DAI/USDC/USDT on all chains that we're using\n IPriceProvider _chainlink = addressProvider.providersAggregator().priceProviders(DataTypes.Provider.CHAINLINK);\n\n (uint256 _priceInUsd, uint256 _lastUpdatedAt) = _chainlink.getPriceInUsd(primaryStableCoin);\n\n if (!_priceIsStale(_lastUpdatedAt) && _isDeviationOK(_priceInUsd, ONE_USD)) {\n return primaryStableCoin;\n }\n\n (_priceInUsd, _lastUpdatedAt) = _chainlink.getPriceInUsd(secondaryStableCoin);\n\n require(!_priceIsStale(_lastUpdatedAt) && _isDeviationOK(_priceInUsd, ONE_USD), \"stable-prices-invalid\");\n\n return secondaryStableCoin;\n }\n\n /// @inheritdoc IStableCoinProvider\n function toUsdRepresentation(uint256 stableCoinAmount_) external view returns (uint256 _usdAmount) {\n uint256 _stableCoinDecimals = __primaryStableCoinDecimals;\n if (_stableCoinDecimals == USD_DECIMALS) {\n return stableCoinAmount_;\n }\n _usdAmount = stableCoinAmount_.scaleDecimal(_stableCoinDecimals, USD_DECIMALS);\n }\n\n /**\n * @notice Update the stable coin keeping correct decimals value\n * @dev Must have both as set or null\n */\n function _updateStableCoins(address primaryStableCoin_, address secondaryStableCoin_) private {\n require(primaryStableCoin_ != address(0) && secondaryStableCoin_ != address(0), \"stable-coins-are-null\");\n require(primaryStableCoin_ != secondaryStableCoin_, \"stable-coins-are-the-same\");\n\n // Update both\n primaryStableCoin = primaryStableCoin_;\n secondaryStableCoin = secondaryStableCoin_;\n __primaryStableCoinDecimals = IERC20Metadata(primaryStableCoin_).decimals();\n __secondaryStableCoinDecimals = IERC20Metadata(secondaryStableCoin_).decimals();\n }\n\n /**\n * @notice Update stable coin\n * @dev Used externally by the governor\n */\n function updateStableCoins(address primaryStableCoin_, address secondaryStableCoin_) external onlyGovernor {\n emit StableCoinsUpdated(primaryStableCoin, secondaryStableCoin, primaryStableCoin_, secondaryStableCoin_);\n _updateStableCoins(primaryStableCoin_, secondaryStableCoin_);\n }\n}\n" }, "contracts/features/UsingMaxDeviation.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.9;\n\nimport \"../access/Governable.sol\";\n\n/**\n * @title Deviation check feature, useful when checking prices from different providers for the same asset\n */\nabstract contract UsingMaxDeviation is Governable {\n /**\n * @notice The max acceptable deviation\n * @dev 18-decimals scale (e.g 1e17 = 10%)\n */\n uint256 public maxDeviation;\n\n /// @notice Emitted when max deviation is updated\n event MaxDeviationUpdated(uint256 oldMaxDeviation, uint256 newMaxDeviation);\n\n constructor(uint256 maxDeviation_) {\n maxDeviation = maxDeviation_;\n }\n\n /**\n * @notice Update max deviation\n */\n function updateMaxDeviation(uint256 maxDeviation_) external onlyGovernor {\n emit MaxDeviationUpdated(maxDeviation, maxDeviation_);\n maxDeviation = maxDeviation_;\n }\n\n /**\n * @notice Check if two numbers deviation is acceptable\n */\n function _isDeviationOK(uint256 a_, uint256 b_) internal view returns (bool) {\n uint256 _deviation = a_ > b_ ? ((a_ - b_) * 1e18) / a_ : ((b_ - a_) * 1e18) / b_;\n return _deviation <= maxDeviation;\n }\n}\n" }, "contracts/features/UsingStalePeriod.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.9;\n\nimport \"../access/Governable.sol\";\n\n/**\n * @title Stale price check feature, useful when checking if prices are fresh enough\n */\nabstract contract UsingStalePeriod is Governable {\n /// @notice The stale period. It's used to determine if a price is invalid (i.e. outdated)\n uint256 public stalePeriod;\n\n /// @notice Emitted when stale period is updated\n event StalePeriodUpdated(uint256 oldStalePeriod, uint256 newStalePeriod);\n\n constructor(uint256 stalePeriod_) {\n stalePeriod = stalePeriod_;\n }\n\n /**\n * @notice Update stale period\n */\n function updateStalePeriod(uint256 stalePeriod_) external onlyGovernor {\n emit StalePeriodUpdated(stalePeriod, stalePeriod_);\n stalePeriod = stalePeriod_;\n }\n\n /**\n * @notice Check if a price timestamp is outdated\n * @dev Uses default stale period\n * @param timeOfLastUpdate_ The price timestamp\n * @return true if price is stale (outdated)\n */\n function _priceIsStale(uint256 timeOfLastUpdate_) internal view returns (bool) {\n return _priceIsStale(timeOfLastUpdate_, stalePeriod);\n }\n\n /**\n * @notice Check if a price timestamp is outdated\n * @param timeOfLastUpdate_ The price timestamp\n * @param stalePeriod_ The maximum acceptable outdated period\n * @return true if price is stale (outdated)\n */\n function _priceIsStale(uint256 timeOfLastUpdate_, uint256 stalePeriod_) internal view returns (bool) {\n return block.timestamp - timeOfLastUpdate_ > stalePeriod_;\n }\n}\n" }, "contracts/interfaces/core/IAddressProvider.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.9;\n\nimport \"./IStableCoinProvider.sol\";\nimport \"./IPriceProvidersAggregator.sol\";\n\ninterface IAddressProvider {\n function governor() external view returns (address);\n\n function providersAggregator() external view returns (IPriceProvidersAggregator);\n\n function stableCoinProvider() external view returns (IStableCoinProvider);\n}\n" }, "contracts/interfaces/core/IPriceProvider.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.9;\n\ninterface IPriceProvider {\n /**\n * @notice Get USD (or equivalent) price of an asset\n * @param token_ The address of asset\n * @return _priceInUsd The USD price\n * @return _lastUpdatedAt Last updated timestamp\n */\n function getPriceInUsd(address token_) external view returns (uint256 _priceInUsd, uint256 _lastUpdatedAt);\n\n /**\n * @notice Get quote\n * @param tokenIn_ The address of assetIn\n * @param tokenOut_ The address of assetOut\n * @param amountIn_ Amount of input token\n * @return _amountOut Amount out\n * @return _lastUpdatedAt Last updated timestamp\n */\n function quote(\n address tokenIn_,\n address tokenOut_,\n uint256 amountIn_\n ) external view returns (uint256 _amountOut, uint256 _lastUpdatedAt);\n\n /**\n * @notice Get quote in USD (or equivalent) amount\n * @param token_ The address of assetIn\n * @param amountIn_ Amount of input token.\n * @return amountOut_ Amount in USD\n * @return _lastUpdatedAt Last updated timestamp\n */\n function quoteTokenToUsd(address token_, uint256 amountIn_)\n external\n view\n returns (uint256 amountOut_, uint256 _lastUpdatedAt);\n\n /**\n * @notice Get quote from USD (or equivalent) amount to amount of token\n * @param token_ The address of assetOut\n * @param amountIn_ Input amount in USD\n * @return _amountOut Output amount of token\n * @return _lastUpdatedAt Last updated timestamp\n */\n function quoteUsdToToken(address token_, uint256 amountIn_)\n external\n view\n returns (uint256 _amountOut, uint256 _lastUpdatedAt);\n}\n" }, "contracts/interfaces/core/IPriceProvidersAggregator.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.9;\n\nimport \"../../libraries/DataTypes.sol\";\nimport \"./IPriceProvider.sol\";\n\n/**\n * @notice PriceProvidersAggregator interface\n * @dev Worth noting that the `_lastUpdatedAt` logic depends on the underlying price provider. In summary:\n * ChainLink: returns the last updated date from the aggregator\n * UniswapV2: returns the date of the latest pair oracle update\n * UniswapV3: assumes that the price is always updated (returns block.timestamp)\n * Flux: returns the last updated date from the aggregator\n * Umbrella (FCD): returns the last updated date returned from their oracle contract\n * Umbrella (Passport): returns the date of the latest pallet submission\n * Anytime that a quote performs more than one query, it uses the oldest date as the `_lastUpdatedAt`.\n * See more: https://github.com/bloqpriv/one-oracle/issues/64\n */\ninterface IPriceProvidersAggregator {\n /**\n * @notice Get USD (or equivalent) price of an asset\n * @param provider_ The price provider to get quote from\n * @param token_ The address of asset\n * @return _priceInUsd The USD price\n * @return _lastUpdatedAt Last updated timestamp\n */\n function getPriceInUsd(DataTypes.Provider provider_, address token_)\n external\n view\n returns (uint256 _priceInUsd, uint256 _lastUpdatedAt);\n\n /**\n * @notice Provider Providers' mapping\n */\n function priceProviders(DataTypes.Provider provider_) external view returns (IPriceProvider _priceProvider);\n\n /**\n * @notice Get quote\n * @param provider_ The price provider to get quote from\n * @param tokenIn_ The address of assetIn\n * @param tokenOut_ The address of assetOut\n * @param amountIn_ Amount of input token\n * @return _amountOut Amount out\n * @return _lastUpdatedAt Last updated timestamp\n */\n function quote(\n DataTypes.Provider provider_,\n address tokenIn_,\n address tokenOut_,\n uint256 amountIn_\n ) external view returns (uint256 _amountOut, uint256 _lastUpdatedAt);\n\n /**\n * @notice Get quote\n * @dev If providers aren't the same, uses native token as \"bridge\"\n * @param providerIn_ The price provider to get quote for the tokenIn\n * @param tokenIn_ The address of assetIn\n * @param providerOut_ The price provider to get quote for the tokenOut\n * @param tokenOut_ The address of assetOut\n * @param amountIn_ Amount of input token\n * @return _amountOut Amount out\n * @return _lastUpdatedAt Last updated timestamp\n */\n function quote(\n DataTypes.Provider providerIn_,\n address tokenIn_,\n DataTypes.Provider providerOut_,\n address tokenOut_,\n uint256 amountIn_\n ) external view returns (uint256 _amountOut, uint256 _lastUpdatedAt);\n\n /**\n * @notice Get quote in USD (or equivalent) amount\n * @param provider_ The price provider to get quote from\n * @param token_ The address of assetIn\n * @param amountIn_ Amount of input token.\n * @return amountOut_ Amount in USD\n * @return _lastUpdatedAt Last updated timestamp\n */\n function quoteTokenToUsd(\n DataTypes.Provider provider_,\n address token_,\n uint256 amountIn_\n ) external view returns (uint256 amountOut_, uint256 _lastUpdatedAt);\n\n /**\n * @notice Get quote from USD (or equivalent) amount to amount of token\n * @param provider_ The price provider to get quote from\n * @param token_ The address of assetOut\n * @param amountIn_ Input amount in USD\n * @return _amountOut Output amount of token\n * @return _lastUpdatedAt Last updated timestamp\n */\n function quoteUsdToToken(\n DataTypes.Provider provider_,\n address token_,\n uint256 amountIn_\n ) external view returns (uint256 _amountOut, uint256 _lastUpdatedAt);\n\n /**\n * @notice Set a price provider\n * @dev Administrative function\n * @param provider_ The provider (from enum)\n * @param priceProvider_ The price provider contract\n */\n function setPriceProvider(DataTypes.Provider provider_, IPriceProvider priceProvider_) external;\n}\n" }, "contracts/interfaces/core/IStableCoinProvider.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.9;\n\ninterface IStableCoinProvider {\n /**\n * @notice Return the stable coin if pegged\n * @dev Check price relation between both stable coins and revert if peg is too loose\n * @return _stableCoin The primary stable coin if pass all checks\n */\n function getStableCoinIfPegged() external view returns (address _stableCoin);\n\n /**\n * @notice Convert given amount of stable coin to USD representation (18 decimals)\n */\n function toUsdRepresentation(uint256 stableCoinAmount_) external view returns (uint256 _usdAmount);\n}\n" }, "contracts/libraries/DataTypes.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.9;\n\nlibrary DataTypes {\n /**\n * @notice Price providers enumeration\n */\n enum Provider {\n NONE,\n CHAINLINK,\n UNISWAP_V3,\n UNISWAP_V2,\n SUSHISWAP,\n TRADERJOE,\n PANGOLIN,\n QUICKSWAP,\n UMBRELLA_FIRST_CLASS,\n UMBRELLA_PASSPORT,\n FLUX\n }\n\n enum ExchangeType {\n UNISWAP_V2,\n SUSHISWAP,\n TRADERJOE,\n PANGOLIN,\n QUICKSWAP,\n UNISWAP_V3\n }\n\n enum SwapType {\n EXACT_INPUT,\n EXACT_OUTPUT\n }\n}\n" }, "contracts/libraries/OracleHelpers.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.2;\n\nlibrary OracleHelpers {\n function scaleDecimal(\n uint256 amount,\n uint256 _fromDecimal,\n uint256 _toDecimal\n ) internal pure returns (uint256) {\n if (_fromDecimal > _toDecimal) {\n return amount / (10**(_fromDecimal - _toDecimal));\n } else if (_fromDecimal < _toDecimal) {\n return amount * (10**(_toDecimal - _fromDecimal));\n }\n return amount;\n }\n}\n" } } }