Feature Tip: Add private address tag to any address under My Name Tag !
Source Code
Overview
ETH Balance
0 ETH
Eth Value
$0.00View more zero value Internal Transactions in Advanced View mode
Advanced mode:
Loading...
Loading
Cross-Chain Transactions
Loading...
Loading
Contract Name:
SavingFxUSD
Compiler Version
v0.8.26+commit.8a97fa7a
Optimization Enabled:
Yes with 200 runs
Other Settings:
cancun EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import { IERC20Permit } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { AccessControlUpgradeable } from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import { ERC20PermitUpgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20PermitUpgradeable.sol";
import { ERC4626Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC4626Upgradeable.sol";
import { ERC20Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import { IMultipleRewardDistributor } from "../common/rewards/distributor/IMultipleRewardDistributor.sol";
import { IHarvesterCallback } from "../helpers/interfaces/IHarvesterCallback.sol";
import { IConvexFXNBooster } from "../interfaces/Convex/IConvexFXNBooster.sol";
import { IStakingProxyERC20 } from "../interfaces/Convex/IStakingProxyERC20.sol";
import { IFxUSDBasePool } from "../interfaces/IFxUSDBasePool.sol";
import { ISavingFxUSD } from "../interfaces/ISavingFxUSD.sol";
import { ILiquidityGauge } from "../voting-escrow/interfaces/ILiquidityGauge.sol";
import { WordCodec } from "../common/codec/WordCodec.sol";
import { ConcentratorBase } from "../common/concentrator/ConcentratorBase.sol";
contract LockedFxSaveProxy {
address immutable fxSAVE;
error ErrorCallerNotFxSave();
constructor() {
fxSAVE = msg.sender;
}
function execute(address target, bytes calldata data) external {
if (msg.sender != fxSAVE) revert ErrorCallerNotFxSave();
(bool success, ) = target.call(data);
// below lines will propagate inner error up
if (!success) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
let size := returndatasize()
returndatacopy(ptr, 0, size)
revert(ptr, size)
}
}
}
}
contract SavingFxUSD is ERC20PermitUpgradeable, ERC4626Upgradeable, ConcentratorBase, ISavingFxUSD {
using SafeERC20 for IERC20;
using WordCodec for bytes32;
/**********
* Errors *
**********/
/// @dev Thrown when the threshold exceeds `MAX_THRESHOLD`.
error ErrorThresholdTooLarge();
/*************
* Constants *
*************/
/// @dev The role for `claimFor` function.
bytes32 public constant CLAIM_FOR_ROLE = keccak256("CLAIM_FOR_ROLE");
/// @dev The address of Convex's f(x) Booster contract.
address private constant BOOSTER = 0xAffe966B27ba3E4Ebb8A0eC124C7b7019CC762f8;
/// @dev The address of FXN token.
address private constant FXN = 0x365AccFCa291e7D3914637ABf1F7635dB165Bb09;
/// @dev The denominator used for precision calculation.
uint256 private constant PRECISION = 1e18;
/// @dev The number of bits for threshold.
uint256 private constant THRESHOLD_BITS = 80;
/// @dev The offset of threshold in `_miscData`.
uint256 private constant THRESHOLD_OFFSET = 60;
/// @dev The maximum value of threshold, 2^80-1.
uint256 private constant MAX_THRESHOLD = 1208925819614629174706175;
/***********************
* Immutable Variables *
***********************/
/// @notice The address of `FxUSDBasePool` contract.
address public immutable base;
/// @notice The address of `FxUSDBasePool` gauge contract.
address public immutable gauge;
/*************
* Variables *
*************/
/// @notice The address of Convex's `StakingProxyERC20` contract.
address public vault;
/// @notice Mapping from user address to `LockedFxSaveProxy` contract.
mapping(address => address) public lockedProxy;
/***************
* Constructor *
***************/
struct InitializationParameters {
string name;
string symbol;
uint256 pid;
uint256 threshold;
address treasury;
address harvester;
}
constructor(address _base, address _gauge) {
base = _base;
gauge = _gauge;
}
function initialize(address admin, InitializationParameters memory params) external initializer {
__Context_init();
__ERC165_init();
__AccessControl_init();
__ERC20_init(params.name, params.symbol);
__ERC20Permit_init(params.name);
__ERC4626_init(IERC20(base));
__ConcentratorBase_init(params.treasury, params.harvester);
_grantRole(DEFAULT_ADMIN_ROLE, admin);
vault = IConvexFXNBooster(BOOSTER).createVault(params.pid);
_updateThreshold(params.threshold);
IERC20(base).forceApprove(gauge, type(uint256).max);
}
/*************************
* Public View Functions *
*************************/
/// @inheritdoc ERC4626Upgradeable
function decimals() public view virtual override(ERC20Upgradeable, ERC4626Upgradeable) returns (uint8) {
return ERC4626Upgradeable.decimals();
}
/// @inheritdoc ERC4626Upgradeable
function totalAssets() public view virtual override returns (uint256) {
return IERC20(base).balanceOf(address(this)) + IERC20(gauge).balanceOf(vault);
}
/// @notice Return the threshold for batch deposit.
function getThreshold() public view returns (uint256) {
return _miscData.decodeUint(THRESHOLD_OFFSET, THRESHOLD_BITS);
}
/// @inheritdoc ISavingFxUSD
function nav() external view returns (uint256) {
return (IFxUSDBasePool(base).nav() * convertToAssets(PRECISION)) / PRECISION;
}
/****************************
* Public Mutated Functions *
****************************/
/// @inheritdoc ISavingFxUSD
function depositGauge(uint256 assets, address receiver) external returns (uint256) {
uint256 maxAssets = maxDeposit(receiver);
if (assets > maxAssets) {
revert ERC4626ExceededMaxDeposit(receiver, assets, maxAssets);
}
uint256 shares = previewDeposit(assets);
IERC20(gauge).safeTransferFrom(_msgSender(), vault, assets);
_mint(receiver, shares);
emit Deposit(_msgSender(), receiver, assets, shares);
return shares;
}
/// @inheritdoc ISavingFxUSD
function requestRedeem(uint256 shares) external returns (uint256) {
address owner = _msgSender();
uint256 maxShares = maxRedeem(owner);
if (shares > maxShares) {
revert ERC4626ExceededMaxRedeem(owner, shares, maxShares);
}
uint256 assets = previewRedeem(shares);
_requestRedeem(owner, assets, shares);
return assets;
}
/// @inheritdoc ISavingFxUSD
function claim(address receiver) external {
_claim(_msgSender(), receiver);
}
/// @inheritdoc ISavingFxUSD
function claimFor(address owner, address receiver) external onlyRole(CLAIM_FOR_ROLE) {
_claim(owner, receiver);
}
/// @inheritdoc ISavingFxUSD
function harvest() external {
IStakingProxyERC20(vault).getReward();
address[] memory tokens = IMultipleRewardDistributor(gauge).getActiveRewardTokens();
address cachedHarvester = harvester;
uint256 harvesterRatio = getHarvesterRatio();
uint256 expenseRatio = getExpenseRatio();
bool hasFXN = false;
for (uint256 i = 0; i < tokens.length; ++i) {
_transferRewards(tokens[i], cachedHarvester, harvesterRatio, expenseRatio);
if (tokens[i] == FXN) hasFXN = true;
}
if (!hasFXN) {
_transferRewards(FXN, cachedHarvester, harvesterRatio, expenseRatio);
}
}
/************************
* Restricted Functions *
************************/
/// @notice Update the threshold for batch deposit.
/// @param newThreshold The address of new threshold.
function updateThreshold(uint256 newThreshold) external onlyRole(DEFAULT_ADMIN_ROLE) {
_updateThreshold(newThreshold);
}
/**********************
* Internal Functions *
**********************/
/// @inheritdoc ERC4626Upgradeable
function _deposit(address caller, address receiver, uint256 assets, uint256 shares) internal virtual override {
ERC4626Upgradeable._deposit(caller, receiver, assets, shares);
// batch deposit to gauge through convex vault
uint256 balance = IERC20(base).balanceOf(address(this));
if (balance >= getThreshold()) {
ILiquidityGauge(gauge).deposit(balance, vault);
}
}
/// @inheritdoc ERC4626Upgradeable
function _withdraw(
address caller,
address receiver,
address owner,
uint256 assets,
uint256 shares
) internal virtual override {
if (caller != owner) {
_spendAllowance(owner, caller, shares);
}
// If _asset is ERC777, `transfer` can trigger a reentrancy AFTER the transfer happens through the
// `tokensReceived` hook. On the other hand, the `tokensToSend` hook, that is triggered before the transfer,
// calls the vault, which is assumed not malicious.
//
// Conclusion: we need to do the transfer after the burn so that any reentrancy would happen after the
// shares are burned and after the assets are transferred, which is a valid state.
_burn(owner, shares);
emit Withdraw(caller, receiver, owner, assets, shares);
// Withdraw from gauge
IStakingProxyERC20(vault).withdraw(assets);
IERC20(base).transfer(receiver, assets);
}
/// @inheritdoc ConcentratorBase
function _onHarvest(address token, uint256 amount) internal virtual override {
if (token == gauge) {
IERC20(gauge).safeTransfer(vault, amount);
return;
} else if (token != base) {
IERC20(token).forceApprove(base, amount);
IFxUSDBasePool(base).deposit(address(this), token, amount, 0);
}
amount = IERC20(base).balanceOf(address(this));
ILiquidityGauge(gauge).deposit(amount, vault);
}
/// @dev Internal function to update the threshold for batch deposit.
/// @param newThreshold The address of new threshold.
function _updateThreshold(uint256 newThreshold) internal {
if (newThreshold > MAX_THRESHOLD) revert ErrorThresholdTooLarge();
bytes32 _data = _miscData;
uint256 oldThreshold = _miscData.decodeUint(THRESHOLD_OFFSET, THRESHOLD_BITS);
_miscData = _data.insertUint(newThreshold, THRESHOLD_OFFSET, THRESHOLD_BITS);
emit UpdateThreshold(oldThreshold, newThreshold);
}
/// @dev Internal function to transfer rewards to harvester.
/// @param token The address of rewards.
/// @param receiver The address of harvester.
function _transferRewards(address token, address receiver, uint256 harvesterRatio, uint256 expenseRatio) internal {
if (token == base) return;
uint256 balance = IERC20(token).balanceOf(address(this));
if (balance > 0) {
uint256 performanceFee = (balance * expenseRatio) / FEE_PRECISION;
uint256 harvesterBounty = (balance * harvesterRatio) / FEE_PRECISION;
if (harvesterBounty > 0) {
IERC20(token).safeTransfer(_msgSender(), harvesterBounty);
}
if (performanceFee > 0) {
IERC20(token).safeTransfer(treasury, performanceFee);
}
IERC20(token).safeTransfer(receiver, balance - performanceFee - harvesterBounty);
}
}
/// @dev Internal function to request redeem.
function _requestRedeem(address owner, uint256 assets, uint256 shares) internal {
// burn shares
_burn(owner, shares);
// Withdraw from gauge
IStakingProxyERC20(vault).withdraw(assets);
// create locked fxSave proxy
address proxy = lockedProxy[owner];
if (proxy == address(0)) {
proxy = address(new LockedFxSaveProxy{ salt: keccak256(abi.encode(owner)) }());
lockedProxy[owner] = proxy;
}
// transfer to proxy for unlocking and request unlock
IERC20(base).transfer(proxy, assets);
LockedFxSaveProxy(proxy).execute(base, abi.encodeCall(IFxUSDBasePool.requestRedeem, (assets)));
emit RequestRedeem(owner, shares, assets);
}
/// @dev Internal function to claim unlocked tokens.
function _claim(address owner, address receiver) internal {
address proxy = lockedProxy[owner];
LockedFxSaveProxy(proxy).execute(base, abi.encodeCall(IFxUSDBasePool.redeem, (receiver, type(uint256).max)));
emit Claim(owner, receiver);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {ERC165Upgradeable} from "../utils/introspection/ERC165Upgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControl, ERC165Upgradeable {
struct RoleData {
mapping(address account => bool) hasRole;
bytes32 adminRole;
}
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/// @custom:storage-location erc7201:openzeppelin.storage.AccessControl
struct AccessControlStorage {
mapping(bytes32 role => RoleData) _roles;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControl")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800;
function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) {
assembly {
$.slot := AccessControlStorageLocation
}
}
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with an {AccessControlUnauthorizedAccount} error including the required role.
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
function __AccessControl_init() internal onlyInitializing {
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
return $._roles[role].hasRole[account];
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
* is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
* is missing `role`.
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert AccessControlUnauthorizedAccount(account, role);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
AccessControlStorage storage $ = _getAccessControlStorage();
return $._roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address callerConfirmation) public virtual {
if (callerConfirmation != _msgSender()) {
revert AccessControlBadConfirmation();
}
_revokeRole(role, callerConfirmation);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
AccessControlStorage storage $ = _getAccessControlStorage();
bytes32 previousAdminRole = getRoleAdmin(role);
$._roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
if (!hasRole(role, account)) {
$._roles[role].hasRole[account] = true;
emit RoleGranted(role, account, _msgSender());
return true;
} else {
return false;
}
}
/**
* @dev Attempts to revoke `role` to `account` and returns a boolean indicating if `role` was revoked.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
if (hasRole(role, account)) {
$._roles[role].hasRole[account] = false;
emit RoleRevoked(role, account, _msgSender());
return true;
} else {
return false;
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reininitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._initialized = version;
$._initializing = true;
_;
$._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
assembly {
$.slot := INITIALIZABLE_STORAGE
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {ContextUpgradeable} from "../../utils/ContextUpgradeable.sol";
import {IERC20Errors} from "@openzeppelin/contracts/interfaces/draft-IERC6093.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*/
abstract contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20, IERC20Metadata, IERC20Errors {
/// @custom:storage-location erc7201:openzeppelin.storage.ERC20
struct ERC20Storage {
mapping(address account => uint256) _balances;
mapping(address account => mapping(address spender => uint256)) _allowances;
uint256 _totalSupply;
string _name;
string _symbol;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC20")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ERC20StorageLocation = 0x52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace00;
function _getERC20Storage() private pure returns (ERC20Storage storage $) {
assembly {
$.slot := ERC20StorageLocation
}
}
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
ERC20Storage storage $ = _getERC20Storage();
$._name = name_;
$._symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
ERC20Storage storage $ = _getERC20Storage();
return $._name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
ERC20Storage storage $ = _getERC20Storage();
return $._symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual returns (uint256) {
ERC20Storage storage $ = _getERC20Storage();
return $._totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual returns (uint256) {
ERC20Storage storage $ = _getERC20Storage();
return $._balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual returns (uint256) {
ERC20Storage storage $ = _getERC20Storage();
return $._allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` amount of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
* this function.
*
* Emits a {Transfer} event.
*/
function _update(address from, address to, uint256 value) internal virtual {
ERC20Storage storage $ = _getERC20Storage();
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
$._totalSupply += value;
} else {
uint256 fromBalance = $._balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
$._balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
$._totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
$._balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
* true using the following override:
* ```
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
ERC20Storage storage $ = _getERC20Storage();
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
$._allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC20Permit.sol)
pragma solidity ^0.8.20;
import {IERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol";
import {ERC20Upgradeable} from "../ERC20Upgradeable.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {EIP712Upgradeable} from "../../../utils/cryptography/EIP712Upgradeable.sol";
import {NoncesUpgradeable} from "../../../utils/NoncesUpgradeable.sol";
import {Initializable} from "../../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
abstract contract ERC20PermitUpgradeable is Initializable, ERC20Upgradeable, IERC20Permit, EIP712Upgradeable, NoncesUpgradeable {
bytes32 private constant PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/**
* @dev Permit deadline has expired.
*/
error ERC2612ExpiredSignature(uint256 deadline);
/**
* @dev Mismatched signature.
*/
error ERC2612InvalidSigner(address signer, address owner);
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
function __ERC20Permit_init(string memory name) internal onlyInitializing {
__EIP712_init_unchained(name, "1");
}
function __ERC20Permit_init_unchained(string memory) internal onlyInitializing {}
/**
* @inheritdoc IERC20Permit
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
if (block.timestamp > deadline) {
revert ERC2612ExpiredSignature(deadline);
}
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
if (signer != owner) {
revert ERC2612InvalidSigner(signer, owner);
}
_approve(owner, spender, value);
}
/**
* @inheritdoc IERC20Permit
*/
function nonces(address owner) public view virtual override(IERC20Permit, NoncesUpgradeable) returns (uint256) {
return super.nonces(owner);
}
/**
* @inheritdoc IERC20Permit
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view virtual returns (bytes32) {
return _domainSeparatorV4();
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC4626.sol)
pragma solidity ^0.8.20;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {ERC20Upgradeable} from "../ERC20Upgradeable.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {Initializable} from "../../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the ERC4626 "Tokenized Vault Standard" as defined in
* https://eips.ethereum.org/EIPS/eip-4626[EIP-4626].
*
* This extension allows the minting and burning of "shares" (represented using the ERC20 inheritance) in exchange for
* underlying "assets" through standardized {deposit}, {mint}, {redeem} and {burn} workflows. This contract extends
* the ERC20 standard. Any additional extensions included along it would affect the "shares" token represented by this
* contract and not the "assets" token which is an independent contract.
*
* [CAUTION]
* ====
* In empty (or nearly empty) ERC-4626 vaults, deposits are at high risk of being stolen through frontrunning
* with a "donation" to the vault that inflates the price of a share. This is variously known as a donation or inflation
* attack and is essentially a problem of slippage. Vault deployers can protect against this attack by making an initial
* deposit of a non-trivial amount of the asset, such that price manipulation becomes infeasible. Withdrawals may
* similarly be affected by slippage. Users can protect against this attack as well as unexpected slippage in general by
* verifying the amount received is as expected, using a wrapper that performs these checks such as
* https://github.com/fei-protocol/ERC4626#erc4626router-and-base[ERC4626Router].
*
* Since v4.9, this implementation uses virtual assets and shares to mitigate that risk. The `_decimalsOffset()`
* corresponds to an offset in the decimal representation between the underlying asset's decimals and the vault
* decimals. This offset also determines the rate of virtual shares to virtual assets in the vault, which itself
* determines the initial exchange rate. While not fully preventing the attack, analysis shows that the default offset
* (0) makes it non-profitable, as a result of the value being captured by the virtual shares (out of the attacker's
* donation) matching the attacker's expected gains. With a larger offset, the attack becomes orders of magnitude more
* expensive than it is profitable. More details about the underlying math can be found
* xref:erc4626.adoc#inflation-attack[here].
*
* The drawback of this approach is that the virtual shares do capture (a very small) part of the value being accrued
* to the vault. Also, if the vault experiences losses, the users try to exit the vault, the virtual shares and assets
* will cause the first user to exit to experience reduced losses in detriment to the last users that will experience
* bigger losses. Developers willing to revert back to the pre-v4.9 behavior just need to override the
* `_convertToShares` and `_convertToAssets` functions.
*
* To learn more, check out our xref:ROOT:erc4626.adoc[ERC-4626 guide].
* ====
*/
abstract contract ERC4626Upgradeable is Initializable, ERC20Upgradeable, IERC4626 {
using Math for uint256;
/// @custom:storage-location erc7201:openzeppelin.storage.ERC4626
struct ERC4626Storage {
IERC20 _asset;
uint8 _underlyingDecimals;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC4626")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ERC4626StorageLocation = 0x0773e532dfede91f04b12a73d3d2acd361424f41f76b4fb79f090161e36b4e00;
function _getERC4626Storage() private pure returns (ERC4626Storage storage $) {
assembly {
$.slot := ERC4626StorageLocation
}
}
/**
* @dev Attempted to deposit more assets than the max amount for `receiver`.
*/
error ERC4626ExceededMaxDeposit(address receiver, uint256 assets, uint256 max);
/**
* @dev Attempted to mint more shares than the max amount for `receiver`.
*/
error ERC4626ExceededMaxMint(address receiver, uint256 shares, uint256 max);
/**
* @dev Attempted to withdraw more assets than the max amount for `receiver`.
*/
error ERC4626ExceededMaxWithdraw(address owner, uint256 assets, uint256 max);
/**
* @dev Attempted to redeem more shares than the max amount for `receiver`.
*/
error ERC4626ExceededMaxRedeem(address owner, uint256 shares, uint256 max);
/**
* @dev Set the underlying asset contract. This must be an ERC20-compatible contract (ERC20 or ERC777).
*/
function __ERC4626_init(IERC20 asset_) internal onlyInitializing {
__ERC4626_init_unchained(asset_);
}
function __ERC4626_init_unchained(IERC20 asset_) internal onlyInitializing {
ERC4626Storage storage $ = _getERC4626Storage();
(bool success, uint8 assetDecimals) = _tryGetAssetDecimals(asset_);
$._underlyingDecimals = success ? assetDecimals : 18;
$._asset = asset_;
}
/**
* @dev Attempts to fetch the asset decimals. A return value of false indicates that the attempt failed in some way.
*/
function _tryGetAssetDecimals(IERC20 asset_) private view returns (bool, uint8) {
(bool success, bytes memory encodedDecimals) = address(asset_).staticcall(
abi.encodeCall(IERC20Metadata.decimals, ())
);
if (success && encodedDecimals.length >= 32) {
uint256 returnedDecimals = abi.decode(encodedDecimals, (uint256));
if (returnedDecimals <= type(uint8).max) {
return (true, uint8(returnedDecimals));
}
}
return (false, 0);
}
/**
* @dev Decimals are computed by adding the decimal offset on top of the underlying asset's decimals. This
* "original" value is cached during construction of the vault contract. If this read operation fails (e.g., the
* asset has not been created yet), a default of 18 is used to represent the underlying asset's decimals.
*
* See {IERC20Metadata-decimals}.
*/
function decimals() public view virtual override(IERC20Metadata, ERC20Upgradeable) returns (uint8) {
ERC4626Storage storage $ = _getERC4626Storage();
return $._underlyingDecimals + _decimalsOffset();
}
/** @dev See {IERC4626-asset}. */
function asset() public view virtual returns (address) {
ERC4626Storage storage $ = _getERC4626Storage();
return address($._asset);
}
/** @dev See {IERC4626-totalAssets}. */
function totalAssets() public view virtual returns (uint256) {
ERC4626Storage storage $ = _getERC4626Storage();
return $._asset.balanceOf(address(this));
}
/** @dev See {IERC4626-convertToShares}. */
function convertToShares(uint256 assets) public view virtual returns (uint256) {
return _convertToShares(assets, Math.Rounding.Floor);
}
/** @dev See {IERC4626-convertToAssets}. */
function convertToAssets(uint256 shares) public view virtual returns (uint256) {
return _convertToAssets(shares, Math.Rounding.Floor);
}
/** @dev See {IERC4626-maxDeposit}. */
function maxDeposit(address) public view virtual returns (uint256) {
return type(uint256).max;
}
/** @dev See {IERC4626-maxMint}. */
function maxMint(address) public view virtual returns (uint256) {
return type(uint256).max;
}
/** @dev See {IERC4626-maxWithdraw}. */
function maxWithdraw(address owner) public view virtual returns (uint256) {
return _convertToAssets(balanceOf(owner), Math.Rounding.Floor);
}
/** @dev See {IERC4626-maxRedeem}. */
function maxRedeem(address owner) public view virtual returns (uint256) {
return balanceOf(owner);
}
/** @dev See {IERC4626-previewDeposit}. */
function previewDeposit(uint256 assets) public view virtual returns (uint256) {
return _convertToShares(assets, Math.Rounding.Floor);
}
/** @dev See {IERC4626-previewMint}. */
function previewMint(uint256 shares) public view virtual returns (uint256) {
return _convertToAssets(shares, Math.Rounding.Ceil);
}
/** @dev See {IERC4626-previewWithdraw}. */
function previewWithdraw(uint256 assets) public view virtual returns (uint256) {
return _convertToShares(assets, Math.Rounding.Ceil);
}
/** @dev See {IERC4626-previewRedeem}. */
function previewRedeem(uint256 shares) public view virtual returns (uint256) {
return _convertToAssets(shares, Math.Rounding.Floor);
}
/** @dev See {IERC4626-deposit}. */
function deposit(uint256 assets, address receiver) public virtual returns (uint256) {
uint256 maxAssets = maxDeposit(receiver);
if (assets > maxAssets) {
revert ERC4626ExceededMaxDeposit(receiver, assets, maxAssets);
}
uint256 shares = previewDeposit(assets);
_deposit(_msgSender(), receiver, assets, shares);
return shares;
}
/** @dev See {IERC4626-mint}.
*
* As opposed to {deposit}, minting is allowed even if the vault is in a state where the price of a share is zero.
* In this case, the shares will be minted without requiring any assets to be deposited.
*/
function mint(uint256 shares, address receiver) public virtual returns (uint256) {
uint256 maxShares = maxMint(receiver);
if (shares > maxShares) {
revert ERC4626ExceededMaxMint(receiver, shares, maxShares);
}
uint256 assets = previewMint(shares);
_deposit(_msgSender(), receiver, assets, shares);
return assets;
}
/** @dev See {IERC4626-withdraw}. */
function withdraw(uint256 assets, address receiver, address owner) public virtual returns (uint256) {
uint256 maxAssets = maxWithdraw(owner);
if (assets > maxAssets) {
revert ERC4626ExceededMaxWithdraw(owner, assets, maxAssets);
}
uint256 shares = previewWithdraw(assets);
_withdraw(_msgSender(), receiver, owner, assets, shares);
return shares;
}
/** @dev See {IERC4626-redeem}. */
function redeem(uint256 shares, address receiver, address owner) public virtual returns (uint256) {
uint256 maxShares = maxRedeem(owner);
if (shares > maxShares) {
revert ERC4626ExceededMaxRedeem(owner, shares, maxShares);
}
uint256 assets = previewRedeem(shares);
_withdraw(_msgSender(), receiver, owner, assets, shares);
return assets;
}
/**
* @dev Internal conversion function (from assets to shares) with support for rounding direction.
*/
function _convertToShares(uint256 assets, Math.Rounding rounding) internal view virtual returns (uint256) {
return assets.mulDiv(totalSupply() + 10 ** _decimalsOffset(), totalAssets() + 1, rounding);
}
/**
* @dev Internal conversion function (from shares to assets) with support for rounding direction.
*/
function _convertToAssets(uint256 shares, Math.Rounding rounding) internal view virtual returns (uint256) {
return shares.mulDiv(totalAssets() + 1, totalSupply() + 10 ** _decimalsOffset(), rounding);
}
/**
* @dev Deposit/mint common workflow.
*/
function _deposit(address caller, address receiver, uint256 assets, uint256 shares) internal virtual {
ERC4626Storage storage $ = _getERC4626Storage();
// If _asset is ERC777, `transferFrom` can trigger a reentrancy BEFORE the transfer happens through the
// `tokensToSend` hook. On the other hand, the `tokenReceived` hook, that is triggered after the transfer,
// calls the vault, which is assumed not malicious.
//
// Conclusion: we need to do the transfer before we mint so that any reentrancy would happen before the
// assets are transferred and before the shares are minted, which is a valid state.
// slither-disable-next-line reentrancy-no-eth
SafeERC20.safeTransferFrom($._asset, caller, address(this), assets);
_mint(receiver, shares);
emit Deposit(caller, receiver, assets, shares);
}
/**
* @dev Withdraw/redeem common workflow.
*/
function _withdraw(
address caller,
address receiver,
address owner,
uint256 assets,
uint256 shares
) internal virtual {
ERC4626Storage storage $ = _getERC4626Storage();
if (caller != owner) {
_spendAllowance(owner, caller, shares);
}
// If _asset is ERC777, `transfer` can trigger a reentrancy AFTER the transfer happens through the
// `tokensReceived` hook. On the other hand, the `tokensToSend` hook, that is triggered before the transfer,
// calls the vault, which is assumed not malicious.
//
// Conclusion: we need to do the transfer after the burn so that any reentrancy would happen after the
// shares are burned and after the assets are transferred, which is a valid state.
_burn(owner, shares);
SafeERC20.safeTransfer($._asset, receiver, assets);
emit Withdraw(caller, receiver, owner, assets, shares);
}
function _decimalsOffset() internal view virtual returns (uint8) {
return 0;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.20;
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {IERC721Receiver} from "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import {IERC721Metadata} from "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import {ContextUpgradeable} from "../../utils/ContextUpgradeable.sol";
import {Strings} from "@openzeppelin/contracts/utils/Strings.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {ERC165Upgradeable} from "../../utils/introspection/ERC165Upgradeable.sol";
import {IERC721Errors} from "@openzeppelin/contracts/interfaces/draft-IERC6093.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
abstract contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721, IERC721Metadata, IERC721Errors {
using Strings for uint256;
/// @custom:storage-location erc7201:openzeppelin.storage.ERC721
struct ERC721Storage {
// Token name
string _name;
// Token symbol
string _symbol;
mapping(uint256 tokenId => address) _owners;
mapping(address owner => uint256) _balances;
mapping(uint256 tokenId => address) _tokenApprovals;
mapping(address owner => mapping(address operator => bool)) _operatorApprovals;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC721")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ERC721StorageLocation = 0x80bb2b638cc20bc4d0a60d66940f3ab4a00c1d7b313497ca82fb0b4ab0079300;
function _getERC721Storage() private pure returns (ERC721Storage storage $) {
assembly {
$.slot := ERC721StorageLocation
}
}
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
ERC721Storage storage $ = _getERC721Storage();
$._name = name_;
$._symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual returns (uint256) {
ERC721Storage storage $ = _getERC721Storage();
if (owner == address(0)) {
revert ERC721InvalidOwner(address(0));
}
return $._balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual returns (address) {
return _requireOwned(tokenId);
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual returns (string memory) {
ERC721Storage storage $ = _getERC721Storage();
return $._name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual returns (string memory) {
ERC721Storage storage $ = _getERC721Storage();
return $._symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual returns (string memory) {
_requireOwned(tokenId);
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string.concat(baseURI, tokenId.toString()) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overridden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual {
_approve(to, tokenId, _msgSender());
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual returns (address) {
_requireOwned(tokenId);
return _getApproved(tokenId);
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual returns (bool) {
ERC721Storage storage $ = _getERC721Storage();
return $._operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual {
if (to == address(0)) {
revert ERC721InvalidReceiver(address(0));
}
// Setting an "auth" arguments enables the `_isAuthorized` check which verifies that the token exists
// (from != 0). Therefore, it is not needed to verify that the return value is not 0 here.
address previousOwner = _update(to, tokenId, _msgSender());
if (previousOwner != from) {
revert ERC721IncorrectOwner(from, tokenId, previousOwner);
}
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual {
transferFrom(from, to, tokenId);
_checkOnERC721Received(from, to, tokenId, data);
}
/**
* @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist
*
* IMPORTANT: Any overrides to this function that add ownership of tokens not tracked by the
* core ERC721 logic MUST be matched with the use of {_increaseBalance} to keep balances
* consistent with ownership. The invariant to preserve is that for any address `a` the value returned by
* `balanceOf(a)` must be equal to the number of tokens such that `_ownerOf(tokenId)` is `a`.
*/
function _ownerOf(uint256 tokenId) internal view virtual returns (address) {
ERC721Storage storage $ = _getERC721Storage();
return $._owners[tokenId];
}
/**
* @dev Returns the approved address for `tokenId`. Returns 0 if `tokenId` is not minted.
*/
function _getApproved(uint256 tokenId) internal view virtual returns (address) {
ERC721Storage storage $ = _getERC721Storage();
return $._tokenApprovals[tokenId];
}
/**
* @dev Returns whether `spender` is allowed to manage `owner`'s tokens, or `tokenId` in
* particular (ignoring whether it is owned by `owner`).
*
* WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this
* assumption.
*/
function _isAuthorized(address owner, address spender, uint256 tokenId) internal view virtual returns (bool) {
return
spender != address(0) &&
(owner == spender || isApprovedForAll(owner, spender) || _getApproved(tokenId) == spender);
}
/**
* @dev Checks if `spender` can operate on `tokenId`, assuming the provided `owner` is the actual owner.
* Reverts if `spender` does not have approval from the provided `owner` for the given token or for all its assets
* the `spender` for the specific `tokenId`.
*
* WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this
* assumption.
*/
function _checkAuthorized(address owner, address spender, uint256 tokenId) internal view virtual {
if (!_isAuthorized(owner, spender, tokenId)) {
if (owner == address(0)) {
revert ERC721NonexistentToken(tokenId);
} else {
revert ERC721InsufficientApproval(spender, tokenId);
}
}
}
/**
* @dev Unsafe write access to the balances, used by extensions that "mint" tokens using an {ownerOf} override.
*
* NOTE: the value is limited to type(uint128).max. This protect against _balance overflow. It is unrealistic that
* a uint256 would ever overflow from increments when these increments are bounded to uint128 values.
*
* WARNING: Increasing an account's balance using this function tends to be paired with an override of the
* {_ownerOf} function to resolve the ownership of the corresponding tokens so that balances and ownership
* remain consistent with one another.
*/
function _increaseBalance(address account, uint128 value) internal virtual {
ERC721Storage storage $ = _getERC721Storage();
unchecked {
$._balances[account] += value;
}
}
/**
* @dev Transfers `tokenId` from its current owner to `to`, or alternatively mints (or burns) if the current owner
* (or `to`) is the zero address. Returns the owner of the `tokenId` before the update.
*
* The `auth` argument is optional. If the value passed is non 0, then this function will check that
* `auth` is either the owner of the token, or approved to operate on the token (by the owner).
*
* Emits a {Transfer} event.
*
* NOTE: If overriding this function in a way that tracks balances, see also {_increaseBalance}.
*/
function _update(address to, uint256 tokenId, address auth) internal virtual returns (address) {
ERC721Storage storage $ = _getERC721Storage();
address from = _ownerOf(tokenId);
// Perform (optional) operator check
if (auth != address(0)) {
_checkAuthorized(from, auth, tokenId);
}
// Execute the update
if (from != address(0)) {
// Clear approval. No need to re-authorize or emit the Approval event
_approve(address(0), tokenId, address(0), false);
unchecked {
$._balances[from] -= 1;
}
}
if (to != address(0)) {
unchecked {
$._balances[to] += 1;
}
}
$._owners[tokenId] = to;
emit Transfer(from, to, tokenId);
return from;
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal {
if (to == address(0)) {
revert ERC721InvalidReceiver(address(0));
}
address previousOwner = _update(to, tokenId, address(0));
if (previousOwner != address(0)) {
revert ERC721InvalidSender(address(0));
}
}
/**
* @dev Mints `tokenId`, transfers it to `to` and checks for `to` acceptance.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory data) internal virtual {
_mint(to, tokenId);
_checkOnERC721Received(address(0), to, tokenId, data);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
* This is an internal function that does not check if the sender is authorized to operate on the token.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal {
address previousOwner = _update(address(0), tokenId, address(0));
if (previousOwner == address(0)) {
revert ERC721NonexistentToken(tokenId);
}
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal {
if (to == address(0)) {
revert ERC721InvalidReceiver(address(0));
}
address previousOwner = _update(to, tokenId, address(0));
if (previousOwner == address(0)) {
revert ERC721NonexistentToken(tokenId);
} else if (previousOwner != from) {
revert ERC721IncorrectOwner(from, tokenId, previousOwner);
}
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking that contract recipients
* are aware of the ERC721 standard to prevent tokens from being forever locked.
*
* `data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is like {safeTransferFrom} in the sense that it invokes
* {IERC721Receiver-onERC721Received} on the receiver, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `tokenId` token must exist and be owned by `from`.
* - `to` cannot be the zero address.
* - `from` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId) internal {
_safeTransfer(from, to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeTransfer-address-address-uint256-}[`_safeTransfer`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual {
_transfer(from, to, tokenId);
_checkOnERC721Received(from, to, tokenId, data);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* The `auth` argument is optional. If the value passed is non 0, then this function will check that `auth` is
* either the owner of the token, or approved to operate on all tokens held by this owner.
*
* Emits an {Approval} event.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address to, uint256 tokenId, address auth) internal {
_approve(to, tokenId, auth, true);
}
/**
* @dev Variant of `_approve` with an optional flag to enable or disable the {Approval} event. The event is not
* emitted in the context of transfers.
*/
function _approve(address to, uint256 tokenId, address auth, bool emitEvent) internal virtual {
ERC721Storage storage $ = _getERC721Storage();
// Avoid reading the owner unless necessary
if (emitEvent || auth != address(0)) {
address owner = _requireOwned(tokenId);
// We do not use _isAuthorized because single-token approvals should not be able to call approve
if (auth != address(0) && owner != auth && !isApprovedForAll(owner, auth)) {
revert ERC721InvalidApprover(auth);
}
if (emitEvent) {
emit Approval(owner, to, tokenId);
}
}
$._tokenApprovals[tokenId] = to;
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Requirements:
* - operator can't be the address zero.
*
* Emits an {ApprovalForAll} event.
*/
function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {
ERC721Storage storage $ = _getERC721Storage();
if (operator == address(0)) {
revert ERC721InvalidOperator(operator);
}
$._operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Reverts if the `tokenId` doesn't have a current owner (it hasn't been minted, or it has been burned).
* Returns the owner.
*
* Overrides to ownership logic should be done to {_ownerOf}.
*/
function _requireOwned(uint256 tokenId) internal view returns (address) {
address owner = _ownerOf(tokenId);
if (owner == address(0)) {
revert ERC721NonexistentToken(tokenId);
}
return owner;
}
/**
* @dev Private function to invoke {IERC721Receiver-onERC721Received} on a target address. This will revert if the
* recipient doesn't accept the token transfer. The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param data bytes optional data to send along with the call
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory data) private {
if (to.code.length > 0) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {
if (retval != IERC721Receiver.onERC721Received.selector) {
revert ERC721InvalidReceiver(to);
}
} catch (bytes memory reason) {
if (reason.length == 0) {
revert ERC721InvalidReceiver(to);
} else {
/// @solidity memory-safe-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/EIP712.sol)
pragma solidity ^0.8.20;
import {MessageHashUtils} from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";
import {IERC5267} from "@openzeppelin/contracts/interfaces/IERC5267.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose
* encoding is very generic and therefore its implementation in Solidity is not feasible, thus this contract
* does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in order to
* produce the hash of their typed data using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
* separator of the implementation contract. This will cause the {_domainSeparatorV4} function to always rebuild the
* separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
*/
abstract contract EIP712Upgradeable is Initializable, IERC5267 {
bytes32 private constant TYPE_HASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
/// @custom:storage-location erc7201:openzeppelin.storage.EIP712
struct EIP712Storage {
/// @custom:oz-renamed-from _HASHED_NAME
bytes32 _hashedName;
/// @custom:oz-renamed-from _HASHED_VERSION
bytes32 _hashedVersion;
string _name;
string _version;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.EIP712")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant EIP712StorageLocation = 0xa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d100;
function _getEIP712Storage() private pure returns (EIP712Storage storage $) {
assembly {
$.slot := EIP712StorageLocation
}
}
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
function __EIP712_init(string memory name, string memory version) internal onlyInitializing {
__EIP712_init_unchained(name, version);
}
function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing {
EIP712Storage storage $ = _getEIP712Storage();
$._name = name;
$._version = version;
// Reset prior values in storage if upgrading
$._hashedName = 0;
$._hashedVersion = 0;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
return _buildDomainSeparator();
}
function _buildDomainSeparator() private view returns (bytes32) {
return keccak256(abi.encode(TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash(), block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash);
}
/**
* @dev See {IERC-5267}.
*/
function eip712Domain()
public
view
virtual
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
)
{
EIP712Storage storage $ = _getEIP712Storage();
// If the hashed name and version in storage are non-zero, the contract hasn't been properly initialized
// and the EIP712 domain is not reliable, as it will be missing name and version.
require($._hashedName == 0 && $._hashedVersion == 0, "EIP712: Uninitialized");
return (
hex"0f", // 01111
_EIP712Name(),
_EIP712Version(),
block.chainid,
address(this),
bytes32(0),
new uint256[](0)
);
}
/**
* @dev The name parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712Name() internal view virtual returns (string memory) {
EIP712Storage storage $ = _getEIP712Storage();
return $._name;
}
/**
* @dev The version parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712Version() internal view virtual returns (string memory) {
EIP712Storage storage $ = _getEIP712Storage();
return $._version;
}
/**
* @dev The hash of the name parameter for the EIP712 domain.
*
* NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Name` instead.
*/
function _EIP712NameHash() internal view returns (bytes32) {
EIP712Storage storage $ = _getEIP712Storage();
string memory name = _EIP712Name();
if (bytes(name).length > 0) {
return keccak256(bytes(name));
} else {
// If the name is empty, the contract may have been upgraded without initializing the new storage.
// We return the name hash in storage if non-zero, otherwise we assume the name is empty by design.
bytes32 hashedName = $._hashedName;
if (hashedName != 0) {
return hashedName;
} else {
return keccak256("");
}
}
}
/**
* @dev The hash of the version parameter for the EIP712 domain.
*
* NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Version` instead.
*/
function _EIP712VersionHash() internal view returns (bytes32) {
EIP712Storage storage $ = _getEIP712Storage();
string memory version = _EIP712Version();
if (bytes(version).length > 0) {
return keccak256(bytes(version));
} else {
// If the version is empty, the contract may have been upgraded without initializing the new storage.
// We return the version hash in storage if non-zero, otherwise we assume the version is empty by design.
bytes32 hashedVersion = $._hashedVersion;
if (hashedVersion != 0) {
return hashedVersion;
} else {
return keccak256("");
}
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*/
abstract contract ERC165Upgradeable is Initializable, IERC165 {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Nonces.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides tracking nonces for addresses. Nonces will only increment.
*/
abstract contract NoncesUpgradeable is Initializable {
/**
* @dev The nonce used for an `account` is not the expected current nonce.
*/
error InvalidAccountNonce(address account, uint256 currentNonce);
/// @custom:storage-location erc7201:openzeppelin.storage.Nonces
struct NoncesStorage {
mapping(address account => uint256) _nonces;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Nonces")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant NoncesStorageLocation = 0x5ab42ced628888259c08ac98db1eb0cf702fc1501344311d8b100cd1bfe4bb00;
function _getNoncesStorage() private pure returns (NoncesStorage storage $) {
assembly {
$.slot := NoncesStorageLocation
}
}
function __Nonces_init() internal onlyInitializing {
}
function __Nonces_init_unchained() internal onlyInitializing {
}
/**
* @dev Returns the next unused nonce for an address.
*/
function nonces(address owner) public view virtual returns (uint256) {
NoncesStorage storage $ = _getNoncesStorage();
return $._nonces[owner];
}
/**
* @dev Consumes a nonce.
*
* Returns the current value and increments nonce.
*/
function _useNonce(address owner) internal virtual returns (uint256) {
NoncesStorage storage $ = _getNoncesStorage();
// For each account, the nonce has an initial value of 0, can only be incremented by one, and cannot be
// decremented or reset. This guarantees that the nonce never overflows.
unchecked {
// It is important to do x++ and not ++x here.
return $._nonces[owner]++;
}
}
/**
* @dev Same as {_useNonce} but checking that `nonce` is the next valid for `owner`.
*/
function _useCheckedNonce(address owner, uint256 nonce) internal virtual {
uint256 current = _useNonce(owner);
if (nonce != current) {
revert InvalidAccountNonce(owner, current);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/// @custom:storage-location erc7201:openzeppelin.storage.Pausable
struct PausableStorage {
bool _paused;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Pausable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant PausableStorageLocation = 0xcd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300;
function _getPausableStorage() private pure returns (PausableStorage storage $) {
assembly {
$.slot := PausableStorageLocation
}
}
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal onlyInitializing {
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
PausableStorage storage $ = _getPausableStorage();
$._paused = false;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
PausableStorage storage $ = _getPausableStorage();
return $._paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
if (!paused()) {
revert ExpectedPause();
}
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
PausableStorage storage $ = _getPausableStorage();
$._paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
PausableStorage storage $ = _getPausableStorage();
$._paused = false;
emit Unpaused(_msgSender());
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
/// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard
struct ReentrancyGuardStorage {
uint256 _status;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {
assembly {
$.slot := ReentrancyGuardStorageLocation
}
}
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
$._status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// On the first call to nonReentrant, _status will be NOT_ENTERED
if ($._status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
$._status = ENTERED;
}
function _nonReentrantAfter() private {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
$._status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
return $._status == ENTERED;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1, "Math: mulDiv overflow");
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {ERC165} from "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address account => bool) hasRole;
bytes32 adminRole;
}
mapping(bytes32 role => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with an {AccessControlUnauthorizedAccount} error including the required role.
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual returns (bool) {
return _roles[role].hasRole[account];
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
* is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
* is missing `role`.
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert AccessControlUnauthorizedAccount(account, role);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address callerConfirmation) public virtual {
if (callerConfirmation != _msgSender()) {
revert AccessControlBadConfirmation();
}
_revokeRole(role, callerConfirmation);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
if (!hasRole(role, account)) {
_roles[role].hasRole[account] = true;
emit RoleGranted(role, account, _msgSender());
return true;
} else {
return false;
}
}
/**
* @dev Attempts to revoke `role` to `account` and returns a boolean indicating if `role` was revoked.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
if (hasRole(role, account)) {
_roles[role].hasRole[account] = false;
emit RoleRevoked(role, account, _msgSender());
return true;
} else {
return false;
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/IAccessControl.sol)
pragma solidity ^0.8.20;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev The `account` is missing a role.
*/
error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);
/**
* @dev The caller of a function is not the expected one.
*
* NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
*/
error AccessControlBadConfirmation();
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*/
function renounceRole(bytes32 role, address callerConfirmation) external;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable2Step.sol)
pragma solidity ^0.8.20;
import {Ownable} from "./Ownable.sol";
/**
* @dev Contract module which provides access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is specified at deployment time in the constructor for `Ownable`. This
* can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2Step is Ownable {
address private _pendingOwner;
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
return _pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
_pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
delete _pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() public virtual {
address sender = _msgSender();
if (pendingOwner() != sender) {
revert OwnableUnauthorizedAccount(sender);
}
_transferOwnership(sender);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard ERC20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC4626.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../token/ERC20/IERC20.sol";
import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";
/**
* @dev Interface of the ERC4626 "Tokenized Vault Standard", as defined in
* https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
*/
interface IERC4626 is IERC20, IERC20Metadata {
event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);
event Withdraw(
address indexed sender,
address indexed receiver,
address indexed owner,
uint256 assets,
uint256 shares
);
/**
* @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
*
* - MUST be an ERC-20 token contract.
* - MUST NOT revert.
*/
function asset() external view returns (address assetTokenAddress);
/**
* @dev Returns the total amount of the underlying asset that is “managed” by Vault.
*
* - SHOULD include any compounding that occurs from yield.
* - MUST be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT revert.
*/
function totalAssets() external view returns (uint256 totalManagedAssets);
/**
* @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
* scenario where all the conditions are met.
*
* - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT show any variations depending on the caller.
* - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
* - MUST NOT revert.
*
* NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
* “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
* from.
*/
function convertToShares(uint256 assets) external view returns (uint256 shares);
/**
* @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
* scenario where all the conditions are met.
*
* - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT show any variations depending on the caller.
* - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
* - MUST NOT revert.
*
* NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
* “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
* from.
*/
function convertToAssets(uint256 shares) external view returns (uint256 assets);
/**
* @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
* through a deposit call.
*
* - MUST return a limited value if receiver is subject to some deposit limit.
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
* - MUST NOT revert.
*/
function maxDeposit(address receiver) external view returns (uint256 maxAssets);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
* current on-chain conditions.
*
* - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
* call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
* in the same transaction.
* - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
* deposit would be accepted, regardless if the user has enough tokens approved, etc.
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewDeposit(uint256 assets) external view returns (uint256 shares);
/**
* @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
*
* - MUST emit the Deposit event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* deposit execution, and are accounted for during deposit.
* - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function deposit(uint256 assets, address receiver) external returns (uint256 shares);
/**
* @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
* - MUST return a limited value if receiver is subject to some mint limit.
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
* - MUST NOT revert.
*/
function maxMint(address receiver) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
* current on-chain conditions.
*
* - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
* in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
* same transaction.
* - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
* would be accepted, regardless if the user has enough tokens approved, etc.
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by minting.
*/
function previewMint(uint256 shares) external view returns (uint256 assets);
/**
* @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
*
* - MUST emit the Deposit event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
* execution, and are accounted for during mint.
* - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function mint(uint256 shares, address receiver) external returns (uint256 assets);
/**
* @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
* Vault, through a withdraw call.
*
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
* - MUST NOT revert.
*/
function maxWithdraw(address owner) external view returns (uint256 maxAssets);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
* given current on-chain conditions.
*
* - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
* call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
* called
* in the same transaction.
* - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
* the withdrawal would be accepted, regardless if the user has enough shares, etc.
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewWithdraw(uint256 assets) external view returns (uint256 shares);
/**
* @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
*
* - MUST emit the Withdraw event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* withdraw execution, and are accounted for during withdraw.
* - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
* not having enough shares, etc).
*
* Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);
/**
* @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
* through a redeem call.
*
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
* - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
* - MUST NOT revert.
*/
function maxRedeem(address owner) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,
* given current on-chain conditions.
*
* - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
* in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
* same transaction.
* - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
* redemption would be accepted, regardless if the user has enough shares, etc.
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by redeeming.
*/
function previewRedeem(uint256 shares) external view returns (uint256 assets);
/**
* @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
*
* - MUST emit the Withdraw event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* redeem execution, and are accounted for during redeem.
* - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
* not having enough shares, etc).
*
* NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC5267.sol)
pragma solidity ^0.8.20;
interface IERC5267 {
/**
* @dev MAY be emitted to signal that the domain could have changed.
*/
event EIP712DomainChanged();
/**
* @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
* signature.
*/
function eip712Domain()
external
view
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @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);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) 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 a `value` amount of tokens 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 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev An operation with an ERC20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data);
if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.20;
import {IERC721} from "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
* a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or
* {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
* a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the address zero.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.20;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be
* reverted.
*
* The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error AddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedInnerCall();
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert AddressInsufficientBalance(address(this));
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert FailedInnerCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {FailedInnerCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert AddressInsufficientBalance(address(this));
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
* unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {FailedInnerCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert FailedInnerCall();
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.20;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS
}
/**
* @dev The signature derives the `address(0)`.
*/
error ECDSAInvalidSignature();
/**
* @dev The signature has an invalid length.
*/
error ECDSAInvalidSignatureLength(uint256 length);
/**
* @dev The signature has an S value that is in the upper half order.
*/
error ECDSAInvalidSignatureS(bytes32 s);
/**
* @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
* return address(0) without also returning an error description. Errors are documented using an enum (error type)
* and a bytes32 providing additional information about the error.
*
* If no error is returned, then the address can be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError, bytes32) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
/// @solidity memory-safe-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*/
function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError, bytes32) {
unchecked {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
// We do not check for an overflow here since the shift operation results in 0 or 1.
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError, bytes32) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS, s);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature, bytes32(0));
}
return (signer, RecoverError.NoError, bytes32(0));
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
*/
function _throwError(RecoverError error, bytes32 errorArg) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert ECDSAInvalidSignature();
} else if (error == RecoverError.InvalidSignatureLength) {
revert ECDSAInvalidSignatureLength(uint256(errorArg));
} else if (error == RecoverError.InvalidSignatureS) {
revert ECDSAInvalidSignatureS(errorArg);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/MessageHashUtils.sol)
pragma solidity ^0.8.20;
import {Strings} from "../Strings.sol";
/**
* @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
*
* The library provides methods for generating a hash of a message that conforms to the
* https://eips.ethereum.org/EIPS/eip-191[EIP 191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
* specifications.
*/
library MessageHashUtils {
/**
* @dev Returns the keccak256 digest of an EIP-191 signed data with version
* `0x45` (`personal_sign` messages).
*
* The digest is calculated by prefixing a bytes32 `messageHash` with
* `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the
* hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
*
* NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with
* keccak256, although any bytes32 value can be safely used because the final digest will
* be re-hashed.
*
* See {ECDSA-recover}.
*/
function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash
mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix
digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)
}
}
/**
* @dev Returns the keccak256 digest of an EIP-191 signed data with version
* `0x45` (`personal_sign` messages).
*
* The digest is calculated by prefixing an arbitrary `message` with
* `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the
* hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
*
* See {ECDSA-recover}.
*/
function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {
return
keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message));
}
/**
* @dev Returns the keccak256 digest of an EIP-191 signed data with version
* `0x00` (data with intended validator).
*
* The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended
* `validator` address. Then hashing the result.
*
* See {ECDSA-recover}.
*/
function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(hex"19_00", validator, data));
}
/**
* @dev Returns the keccak256 digest of an EIP-712 typed data (EIP-191 version `0x01`).
*
* The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
* `\x19\x01` and hashing the result. It corresponds to the hash signed by the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
*
* See {ECDSA-recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {
/// @solidity memory-safe-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, hex"19_01")
mstore(add(ptr, 0x02), domainSeparator)
mstore(add(ptr, 0x22), structHash)
digest := keccak256(ptr, 0x42)
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Muldiv operation overflow.
*/
error MathOverflowedMulDiv();
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an overflow flag.
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
return a / b;
}
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0 = x * y; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
if (denominator <= prod1) {
revert MathOverflowedMulDiv();
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol)
pragma solidity ^0.8.20;
import {Math} from "./math/Math.sol";
import {SignedMath} from "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant HEX_DIGITS = "0123456789abcdef";
uint8 private constant ADDRESS_LENGTH = 20;
/**
* @dev The `value` string doesn't fit in the specified `length`.
*/
error StringsInsufficientHexLength(uint256 value, uint256 length);
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toStringSigned(int256 value) internal pure returns (string memory) {
return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
uint256 localValue = value;
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = HEX_DIGITS[localValue & 0xf];
localValue >>= 4;
}
if (localValue != 0) {
revert StringsInsufficientHexLength(value, length);
}
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
* representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
pragma solidity ^0.8.20;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```solidity
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*
* [WARNING]
* ====
* Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
* unusable.
* See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
*
* In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
* array of EnumerableSet.
* ====
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position is the index of the value in the `values` array plus 1.
// Position 0 is used to mean a value is not in the set.
mapping(bytes32 value => uint256) _positions;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._positions[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We cache the value's position to prevent multiple reads from the same storage slot
uint256 position = set._positions[value];
if (position != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 valueIndex = position - 1;
uint256 lastIndex = set._values.length - 1;
if (valueIndex != lastIndex) {
bytes32 lastValue = set._values[lastIndex];
// Move the lastValue to the index where the value to delete is
set._values[valueIndex] = lastValue;
// Update the tracked position of the lastValue (that was just moved)
set._positions[lastValue] = position;
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the tracked position for the deleted slot
delete set._positions[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._positions[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
bytes32[] memory store = _values(set._inner);
bytes32[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// solhint-disable no-inline-assembly
/// @dev A subset copied from the following contracts:
///
/// + `balancer-labs/v2-solidity-utils/contracts/helpers/WordCodec.sol`
/// + `balancer-labs/v2-solidity-utils/contracts/helpers/WordCodecHelpers.sol`
library WordCodec {
/// @dev Inserts an unsigned integer of bitLength, shifted by an offset, into a 256 bit word,
/// replacing the old value. Returns the new word.
function insertUint(
bytes32 word,
uint256 value,
uint256 offset,
uint256 bitLength
) internal pure returns (bytes32 result) {
// Equivalent to:
// uint256 mask = (1 << bitLength) - 1;
// bytes32 clearedWord = bytes32(uint256(word) & ~(mask << offset));
// result = clearedWord | bytes32(value << offset);
assembly {
let mask := sub(shl(bitLength, 1), 1)
let clearedWord := and(word, not(shl(offset, mask)))
result := or(clearedWord, shl(offset, value))
}
}
/// @dev Decodes and returns an unsigned integer with `bitLength` bits, shifted by an offset, from a 256 bit word.
function decodeUint(
bytes32 word,
uint256 offset,
uint256 bitLength
) internal pure returns (uint256 result) {
// Equivalent to:
// result = uint256(word >> offset) & ((1 << bitLength) - 1);
assembly {
result := and(shr(offset, word), sub(shl(bitLength, 1), 1))
}
}
/// @dev Inserts a signed integer shifted by an offset into a 256 bit word, replacing the old value. Returns
/// the new word.
///
/// Assumes `value` can be represented using `bitLength` bits.
function insertInt(
bytes32 word,
int256 value,
uint256 offset,
uint256 bitLength
) internal pure returns (bytes32) {
unchecked {
uint256 mask = (1 << bitLength) - 1;
bytes32 clearedWord = bytes32(uint256(word) & ~(mask << offset));
// Integer values need masking to remove the upper bits of negative values.
return clearedWord | bytes32((uint256(value) & mask) << offset);
}
}
/// @dev Decodes and returns a signed integer with `bitLength` bits, shifted by an offset, from a 256 bit word.
function decodeInt(
bytes32 word,
uint256 offset,
uint256 bitLength
) internal pure returns (int256 result) {
unchecked {
int256 maxInt = int256((1 << (bitLength - 1)) - 1);
uint256 mask = (1 << bitLength) - 1;
int256 value = int256(uint256(word >> offset) & mask);
// In case the decoded value is greater than the max positive integer that can be represented with bitLength
// bits, we know it was originally a negative integer. Therefore, we mask it to restore the sign in the 256 bit
// representation.
//
// Equivalent to:
// result = value > maxInt ? (value | int256(~mask)) : value;
assembly {
result := or(mul(gt(value, maxInt), not(mask)), value)
}
}
}
/// @dev Decodes and returns a boolean shifted by an offset from a 256 bit word.
function decodeBool(bytes32 word, uint256 offset) internal pure returns (bool result) {
// Equivalent to:
// result = (uint256(word >> offset) & 1) == 1;
assembly {
result := and(shr(offset, word), 1)
}
}
/// @dev Inserts a boolean value shifted by an offset into a 256 bit word, replacing the old value. Returns the new
/// word.
function insertBool(
bytes32 word,
bool value,
uint256 offset
) internal pure returns (bytes32 result) {
// Equivalent to:
// bytes32 clearedWord = bytes32(uint256(word) & ~(1 << offset));
// bytes32 referenceInsertBool = clearedWord | bytes32(uint256(value ? 1 : 0) << offset);
assembly {
let clearedWord := and(word, not(shl(offset, 1)))
result := or(clearedWord, shl(offset, value))
}
}
function clearWordAtPosition(
bytes32 word,
uint256 offset,
uint256 bitLength
) internal pure returns (bytes32 clearedWord) {
unchecked {
uint256 mask = (1 << bitLength) - 1;
clearedWord = bytes32(uint256(word) & ~(mask << offset));
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { AccessControlUpgradeable } from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import { WordCodec } from "../codec/WordCodec.sol";
import { IHarvesterCallback } from "../../helpers/interfaces/IHarvesterCallback.sol";
import { IConcentratorBase } from "./IConcentratorBase.sol";
// solhint-disable func-name-mixedcase
// solhint-disable no-inline-assembly
abstract contract ConcentratorBase is AccessControlUpgradeable, IConcentratorBase, IHarvesterCallback {
using WordCodec for bytes32;
/**********
* Errors *
**********/
/// @dev Thrown when the address is zero.
error ErrorZeroAddress();
/// @dev Thrown when the expense ratio exceeds `MAX_EXPENSE_RATIO`.
error ErrorExpenseRatioTooLarge();
/// @dev Thrown when the harvester ratio exceeds `MAX_HARVESTER_RATIO`.
error ErrorHarvesterRatioTooLarge();
/// @dev Thrown when caller is not harvester and try to call some harvester only functions.
error ErrorCallerNotHarvester();
/*************
* Constants *
*************/
/// @dev The fee denominator used for rate calculation.
uint256 internal constant FEE_PRECISION = 1e9;
/// @dev The maximum expense ratio.
uint256 private constant MAX_EXPENSE_RATIO = 5e8; // 50%
/// @dev The maximum harvester ratio.
uint256 private constant MAX_HARVESTER_RATIO = 1e8; // 10%
/// @dev The number of bits for fee ratios.
uint256 private constant RATIO_BITS = 30;
/// @dev The offset of expense ratio in `_miscData`.
uint256 private constant EXPENSE_RATIO_OFFSET = 0;
/// @dev The offset of harvester ratio in `_miscData`.
uint256 private constant HARVESTER_RATIO_OFFSET = 30;
/*************
* Variables *
*************/
/// @inheritdoc IConcentratorBase
address public treasury;
/// @inheritdoc IConcentratorBase
address public harvester;
/// @dev `_miscData` is a storage slot that can be used to store unrelated pieces of information.
/// All pools store the *expense ratio*, *harvester ratio* and *withdraw fee percentage*, but
/// the `miscData`can be extended to store more pieces of information.
///
/// The *expense ratio* is stored in the first most significant 32 bits, and the *harvester ratio* is
/// stored in the next most significant 32 bits, and the *withdraw fee percentage* is stored in the
/// next most significant 32 bits, leaving the remaining 160 bits free to store any other information
/// derived pools might need.
///
/// - The *expense ratio* and *harvester ratio* are charged each time when harvester harvest the pool revenue.
///
/// [ expense ratio | harvester ratio | available ]
/// [ 30 bits | 30 bits | 196 bits ]
/// [ MSB LSB ]
bytes32 internal _miscData;
/// @dev reserved slots.
uint256[47] private __gap;
/***************
* Constructor *
***************/
function __ConcentratorBase_init(address _treasury, address _harvester) internal onlyInitializing {
_updateTreasury(_treasury);
_updateHarvester(_harvester);
}
/*************************
* Public View Functions *
*************************/
/// @inheritdoc IConcentratorBase
function getExpenseRatio() public view override returns (uint256) {
return _miscData.decodeUint(EXPENSE_RATIO_OFFSET, RATIO_BITS);
}
/// @inheritdoc IConcentratorBase
function getHarvesterRatio() public view override returns (uint256) {
return _miscData.decodeUint(HARVESTER_RATIO_OFFSET, RATIO_BITS);
}
/// @inheritdoc IHarvesterCallback
function onHarvest(address token, uint256 amount) external override {
if (_msgSender() != harvester) revert ErrorCallerNotHarvester();
_onHarvest(token, amount);
}
/************************
* Restricted Functions *
************************/
/// @notice Update the address of treasury contract.
///
/// @param _newTreasury The address of the new treasury contract.
function updateTreasury(address _newTreasury) external onlyRole(DEFAULT_ADMIN_ROLE) {
_updateTreasury(_newTreasury);
}
/// @notice Update the address of harvester contract.
///
/// @param _newHarvester The address of the new harvester contract.
function updateHarvester(address _newHarvester) external onlyRole(DEFAULT_ADMIN_ROLE) {
_updateHarvester(_newHarvester);
}
/// @notice Update the fee ratio distributed to treasury.
/// @param _newRatio The new ratio to update, multiplied by 1e9.
function updateExpenseRatio(uint32 _newRatio) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (uint256(_newRatio) > MAX_EXPENSE_RATIO) {
revert ErrorExpenseRatioTooLarge();
}
bytes32 _data = _miscData;
uint256 _oldRatio = _miscData.decodeUint(EXPENSE_RATIO_OFFSET, RATIO_BITS);
_miscData = _data.insertUint(_newRatio, EXPENSE_RATIO_OFFSET, RATIO_BITS);
emit UpdateExpenseRatio(_oldRatio, _newRatio);
}
/// @notice Update the fee ratio distributed to harvester.
/// @param _newRatio The new ratio to update, multiplied by 1e9.
function updateHarvesterRatio(uint32 _newRatio) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (uint256(_newRatio) > MAX_HARVESTER_RATIO) {
revert ErrorHarvesterRatioTooLarge();
}
bytes32 _data = _miscData;
uint256 _oldRatio = _miscData.decodeUint(HARVESTER_RATIO_OFFSET, RATIO_BITS);
_miscData = _data.insertUint(_newRatio, HARVESTER_RATIO_OFFSET, RATIO_BITS);
emit UpdateHarvesterRatio(_oldRatio, _newRatio);
}
/**********************
* Internal Functions *
**********************/
/// @dev Internal function to update the address of treasury contract.
///
/// @param _newTreasury The address of the new treasury contract.
function _updateTreasury(address _newTreasury) private {
if (_newTreasury == address(0)) revert ErrorZeroAddress();
address _oldTreasury = treasury;
treasury = _newTreasury;
emit UpdateTreasury(_oldTreasury, _newTreasury);
}
/// @dev Internal function to update the address of harvester contract.
///
/// @param _newHarvester The address of the new harvester contract.
function _updateHarvester(address _newHarvester) private {
address _oldHarvester = harvester;
harvester = _newHarvester;
emit UpdateHarvester(_oldHarvester, _newHarvester);
}
/// @dev Actual logic of onHarvest callback.
function _onHarvest(address token, uint256 amount) internal virtual;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IConcentratorBase {
/**********
* Events *
**********/
/// @notice Emitted when the treasury contract is updated.
///
/// @param oldTreasury The address of the previous treasury contract.
/// @param newTreasury The address of the current treasury contract.
event UpdateTreasury(address indexed oldTreasury, address indexed newTreasury);
/// @notice Emitted when the harvester contract is updated.
///
/// @param oldHarvester The address of the previous harvester contract.
/// @param newHarvester The address of the current harvester contract.
event UpdateHarvester(address indexed oldHarvester, address indexed newHarvester);
/// @notice Emitted when the ratio for treasury is updated.
/// @param oldRatio The value of the previous ratio, multiplied by 1e9.
/// @param newRatio The value of the current ratio, multiplied by 1e9.
event UpdateExpenseRatio(uint256 oldRatio, uint256 newRatio);
/// @notice Emitted when the ratio for harvester is updated.
/// @param oldRatio The value of the previous ratio, multiplied by 1e9.
/// @param newRatio The value of the current ratio, multiplied by 1e9.
event UpdateHarvesterRatio(uint256 oldRatio, uint256 newRatio);
/*************************
* Public View Functions *
*************************/
/// @notice The address of protocol revenue holder.
function treasury() external view returns (address);
/// @notice The address of harvester contract.
function harvester() external view returns (address);
/// @notice Return the fee ratio distributed to treasury, multiplied by 1e9.
function getExpenseRatio() external view returns (uint256);
/// @notice Return the fee ratio distributed to harvester, multiplied by 1e9.
function getHarvesterRatio() external view returns (uint256);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IERC3156FlashBorrower {
/**
* @dev Receive a flash loan.
* @param initiator The initiator of the loan.
* @param token The loan currency.
* @param amount The amount of tokens lent.
* @param fee The additional amount of tokens to repay.
* @param data Arbitrary data structure, intended to contain user-defined parameters.
* @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan"
*/
function onFlashLoan(
address initiator,
address token,
uint256 amount,
uint256 fee,
bytes calldata data
) external returns (bytes32);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IERC3156FlashBorrower } from "./IERC3156FlashBorrower.sol";
interface IERC3156FlashLender {
/**
* @dev The amount of currency available to be lent.
* @param token The loan currency.
* @return The amount of `token` that can be borrowed.
*/
function maxFlashLoan(address token) external view returns (uint256);
/**
* @dev The fee to be charged for a given loan.
* @param token The loan currency.
* @param amount The amount of tokens lent.
* @return The amount of `token` to be charged for the loan, on top of the returned principal.
*/
function flashFee(address token, uint256 amount) external view returns (uint256);
/**
* @dev Initiate a flash loan.
* @param receiver The receiver of the tokens in the loan, and the receiver of the callback.
* @param token The loan currency.
* @param amount The amount of tokens lent.
* @param data Arbitrary data structure, intended to contain user-defined parameters.
*/
function flashLoan(
IERC3156FlashBorrower receiver,
address token,
uint256 amount,
bytes calldata data
) external returns (bool);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IMultipleRewardDistributor {
/**********
* Events *
**********/
/// @notice Emitted when new reward token is registered.
///
/// @param token The address of reward token.
/// @param distributor The address of reward distributor.
event RegisterRewardToken(address indexed token, address indexed distributor);
/// @notice Emitted when the reward distributor is updated.
///
/// @param token The address of reward token.
/// @param oldDistributor The address of previous reward distributor.
/// @param newDistributor The address of current reward distributor.
event UpdateRewardDistributor(address indexed token, address indexed oldDistributor, address indexed newDistributor);
/// @notice Emitted when a reward token is unregistered.
///
/// @param token The address of reward token.
event UnregisterRewardToken(address indexed token);
/// @notice Emitted when a reward token is deposited.
///
/// @param token The address of reward token.
/// @param amount The amount of reward token deposited.
event DepositReward(address indexed token, uint256 amount);
/**********
* Errors *
**********/
/// @dev Thrown when caller access an unactive reward token.
error NotActiveRewardToken();
/// @dev Thrown when the address of reward distributor is `address(0)`.
error RewardDistributorIsZero();
/// @dev Thrown when caller is not reward distributor.
error NotRewardDistributor();
/// @dev Thrown when caller try to register an existing reward token.
error DuplicatedRewardToken();
/// @dev Thrown when caller try to unregister a reward with pending rewards.
error RewardDistributionNotFinished();
/*************************
* Public View Functions *
*************************/
/// @notice Return the address of reward distributor.
///
/// @param token The address of reward token.
function distributors(address token) external view returns (address);
/// @notice Return the list of active reward tokens.
function getActiveRewardTokens() external view returns (address[] memory);
/// @notice Return the list of historical reward tokens.
function getHistoricalRewardTokens() external view returns (address[] memory);
/// @notice Return the amount of pending distributed rewards in current period.
///
/// @param token The address of reward token.
/// @return distributable The amount of reward token can be distributed in current period.
/// @return undistributed The amount of reward token still locked in current period.
function pendingRewards(address token) external view returns (uint256 distributable, uint256 undistributed);
/****************************
* Public Mutated Functions *
****************************/
/// @notice Deposit new rewards to this contract.
///
/// @param token The address of reward token.
/// @param amount The amount of new rewards.
function depositReward(address token, uint256 amount) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { AccessControlUpgradeable } from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// solhint-disable avoid-low-level-calls
// solhint-disable no-inline-assembly
abstract contract PermissionedSwap is AccessControlUpgradeable {
using SafeERC20 for IERC20;
/**********
* Errors *
**********/
/// @dev Thrown when the amount of output token is not enough.
error InsufficientOutputToken();
/*************
* Constants *
*************/
/// @notice The role for permissioned trader.
bytes32 public constant PERMISSIONED_TRADER_ROLE = keccak256("PERMISSIONED_TRADER_ROLE");
/// @notice The role for permissioned trading router.
bytes32 public constant PERMISSIONED_ROUTER_ROLE = keccak256("PERMISSIONED_ROUTER_ROLE");
/***********
* Structs *
***********/
/// @notice The struct for trading parameters.
///
/// @param router The address of trading router.
/// @param data The calldata passing to the router contract.
/// @param minOut The minimum amount of output token should receive.
struct TradingParameter {
address router;
bytes data;
uint256 minOut;
}
/*************
* Variables *
*************/
/// @dev reserved slots.
uint256[50] private __gap;
/************************
* Restricted Functions *
************************/
/// @notice Withdraw base token to someone else.
/// @dev This should be only used when we are retiring this contract.
/// @param baseToken The address of base token.
function withdraw(address baseToken, address recipient) external onlyRole(DEFAULT_ADMIN_ROLE) {
uint256 amountIn = IERC20(baseToken).balanceOf(address(this));
IERC20(baseToken).safeTransfer(recipient, amountIn);
}
/**********************
* Internal Functions *
**********************/
/// @dev Internal function to convert token with routes.
/// @param srcToken The address of source token.
/// @param dstToken The address of destination token.
/// @param amountIn The amount of input token.
/// @param params The token converting parameters.
/// @return amountOut The amount of output token received.
function _doTrade(
address srcToken,
address dstToken,
uint256 amountIn,
TradingParameter memory params
) internal virtual onlyRole(PERMISSIONED_TRADER_ROLE) returns (uint256 amountOut) {
if (srcToken == dstToken) return amountIn;
// router should be permissioned
_checkRole(PERMISSIONED_ROUTER_ROLE, params.router);
// approve to router
IERC20(srcToken).forceApprove(params.router, amountIn);
// do trading
amountOut = IERC20(dstToken).balanceOf(address(this));
(bool success, ) = params.router.call(params.data);
if (!success) {
// below lines will propagate inner error up
assembly {
let ptr := mload(0x40)
let size := returndatasize()
returndatacopy(ptr, 0, size)
revert(ptr, size)
}
}
amountOut = IERC20(dstToken).balanceOf(address(this)) - amountOut;
if (amountOut < params.minOut) {
revert InsufficientOutputToken();
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.25;
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { ReentrancyGuardUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import { IERC3156FlashBorrower } from "../common/ERC3156/IERC3156FlashBorrower.sol";
import { IERC3156FlashLender } from "../common/ERC3156/IERC3156FlashLender.sol";
import { ProtocolFees } from "./ProtocolFees.sol";
contract FlashLoans is ProtocolFees, ReentrancyGuardUpgradeable, IERC3156FlashLender {
using SafeERC20 for IERC20;
/**********
* Errors *
**********/
/// @dev Thrown when the returned balance after flash loan is not enough.
error ErrorInsufficientFlashLoanReturn();
/// @dev Thrown when the returned value of `ERC3156Callback` is wrong.
error ErrorERC3156CallbackFailed();
/*************
* Constants *
*************/
/// @dev The correct value of the return value of `ERC3156FlashBorrower.onFlashLoan`.
bytes32 private constant CALLBACK_SUCCESS = keccak256("ERC3156FlashBorrower.onFlashLoan");
/*************
* Variables *
*************/
/// @dev Slots for future use.
uint256[50] private _gap;
/***************
* Constructor *
***************/
function __FlashLoans_init() internal onlyInitializing {}
/*************************
* Public View Functions *
*************************/
/// @inheritdoc IERC3156FlashLender
function maxFlashLoan(address token) external view override returns (uint256) {
return IERC20(token).balanceOf(address(this));
}
/// @inheritdoc IERC3156FlashLender
function flashFee(address /*token*/, uint256 amount) public view returns (uint256) {
return (amount * getFlashLoanFeeRatio()) / FEE_PRECISION;
}
/****************************
* Public Mutated Functions *
****************************/
/// @inheritdoc IERC3156FlashLender
function flashLoan(
IERC3156FlashBorrower receiver,
address token,
uint256 amount,
bytes calldata data
) external nonReentrant whenNotPaused returns (bool) {
// save the current balance
uint256 prevBalance = IERC20(token).balanceOf(address(this));
uint256 fee = flashFee(token, amount);
// transfer token to receiver
IERC20(token).safeTransfer(address(receiver), amount);
// invoke the recipient's callback
if (receiver.onFlashLoan(_msgSender(), token, amount, fee, data) != CALLBACK_SUCCESS) {
revert ErrorERC3156CallbackFailed();
}
// ensure that the tokens + fee have been deposited back to the network
uint256 returnedAmount = IERC20(token).balanceOf(address(this)) - prevBalance;
if (returnedAmount < amount + fee) {
revert ErrorInsufficientFlashLoanReturn();
}
if (fee > 0) {
IERC20(token).safeTransfer(treasury, fee);
}
return true;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.25;
import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { AccessControlUpgradeable } from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import { ERC20PermitUpgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20PermitUpgradeable.sol";
import { ERC20Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import { ReentrancyGuardUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import { IStrategy } from "../fund/IStrategy.sol";
import { AggregatorV3Interface } from "../interfaces/Chainlink/AggregatorV3Interface.sol";
import { IPegKeeper } from "../interfaces/IPegKeeper.sol";
import { IPool } from "../interfaces/IPool.sol";
import { IPoolManager } from "../interfaces/IPoolManager.sol";
import { IFxUSDBasePool } from "../interfaces/IFxUSDBasePool.sol";
import { AssetManagement } from "../fund/AssetManagement.sol";
import { Math } from "../libraries/Math.sol";
contract FxUSDBasePool is
ERC20PermitUpgradeable,
AccessControlUpgradeable,
ReentrancyGuardUpgradeable,
AssetManagement,
IFxUSDBasePool
{
using SafeERC20 for IERC20;
/**********
* Errors *
**********/
/// @dev Thrown when the deposited amount is zero.
error ErrDepositZeroAmount();
/// @dev Thrown when the minted shares are not enough.
error ErrInsufficientSharesOut();
/// @dev Thrown the input token in invalid.
error ErrInvalidTokenIn();
/// @dev Thrown when the redeemed shares is zero.
error ErrRedeemZeroShares();
error ErrorCallerNotPegKeeper();
error ErrorStableTokenDepeg();
error ErrorSwapExceedBalance();
error ErrorInsufficientOutput();
error ErrorInsufficientArbitrage();
error ErrorRedeemCoolDownPeriodTooLarge();
error ErrorRedeemMoreThanBalance();
error ErrorRedeemLockedShares();
error ErrorInsufficientFreeBalance();
error ErrorInstantRedeemFeeTooLarge();
/*************
* Constants *
*************/
/// @dev The exchange rate precision.
uint256 internal constant PRECISION = 1e18;
uint256 internal constant MAX_INSTANT_REDEEM_FEE = 5e16; // 5%
/***********************
* Immutable Variables *
***********************/
/// @notice The address of `PoolManager` contract.
address public immutable poolManager;
/// @notice The address of `PegKeeper` contract.
address public immutable pegKeeper;
/// @inheritdoc IFxUSDBasePool
/// @dev This is also the address of FxUSD token.
address public immutable yieldToken;
/// @inheritdoc IFxUSDBasePool
/// @dev The address of USDC token.
address public immutable stableToken;
uint256 private immutable stableTokenScale;
/// @notice The Chainlink USDC/USD price feed.
/// @dev The encoding is below.
/// ```text
/// | 32 bits | 64 bits | 160 bits |
/// | heartbeat | scale | price_feed |
/// |low high |
/// ```
bytes32 public immutable Chainlink_USDC_USD_Spot;
/***********
* Structs *
***********/
struct RebalanceMemoryVar {
uint256 stablePrice;
uint256 totalYieldToken;
uint256 totalStableToken;
uint256 yieldTokenToUse;
uint256 stableTokenToUse;
uint256 colls;
uint256 yieldTokenUsed;
uint256 stableTokenUsed;
}
struct RedeemRequest {
uint128 amount;
uint128 unlockAt;
}
/*************
* Variables *
*************/
/// @inheritdoc IFxUSDBasePool
uint256 public totalYieldToken;
/// @inheritdoc IFxUSDBasePool
uint256 public totalStableToken;
/// @notice The depeg price for stable token.
uint256 public stableDepegPrice;
/// @notice Mapping from user address to redeem request.
mapping(address => RedeemRequest) public redeemRequests;
/// @notice The number of seconds of cool down before redeem from this pool.
uint256 public redeemCoolDownPeriod;
/// @notice The fee ratio for instantly redeem.
uint256 public instantRedeemFeeRatio;
/*************
* Modifiers *
*************/
modifier onlyValidToken(address token) {
if (token != stableToken && token != yieldToken) {
revert ErrInvalidTokenIn();
}
_;
}
modifier onlyPegKeeper() {
if (_msgSender() != pegKeeper) revert ErrorCallerNotPegKeeper();
_;
}
modifier sync() {
{
// we only manage stable token
Allocation memory b = allocations[stableToken];
if (b.strategy != address(0)) {
totalStableToken = IStrategy(b.strategy).totalSupply() + IERC20(stableToken).balanceOf(address(this));
}
}
_;
}
/***************
* Constructor *
***************/
constructor(
address _poolManager,
address _pegKeeper,
address _yieldToken,
address _stableToken,
bytes32 _Chainlink_USDC_USD_Spot
) {
poolManager = _poolManager;
pegKeeper = _pegKeeper;
yieldToken = _yieldToken;
stableToken = _stableToken;
Chainlink_USDC_USD_Spot = _Chainlink_USDC_USD_Spot;
stableTokenScale = 10 ** (18 - IERC20Metadata(_stableToken).decimals());
}
function initialize(
address admin,
string memory _name,
string memory _symbol,
uint256 _stableDepegPrice,
uint256 _redeemCoolDownPeriod
) external initializer {
__Context_init();
__ERC165_init();
__AccessControl_init();
__ReentrancyGuard_init();
__ERC20_init(_name, _symbol);
__ERC20Permit_init(_name);
_grantRole(DEFAULT_ADMIN_ROLE, admin);
_updateStableDepegPrice(_stableDepegPrice);
_updateRedeemCoolDownPeriod(_redeemCoolDownPeriod);
// approve
IERC20(yieldToken).forceApprove(poolManager, type(uint256).max);
IERC20(stableToken).forceApprove(poolManager, type(uint256).max);
}
/*************************
* Public View Functions *
*************************/
/// @inheritdoc IFxUSDBasePool
function previewDeposit(
address tokenIn,
uint256 amountTokenToDeposit
) public view override onlyValidToken(tokenIn) returns (uint256 amountSharesOut) {
uint256 price = getStableTokenPriceWithScale();
uint256 amountUSD = amountTokenToDeposit;
if (tokenIn == stableToken) {
amountUSD = (amountUSD * price) / PRECISION;
}
uint256 _totalSupply = totalSupply();
if (_totalSupply == 0) {
amountSharesOut = amountUSD;
} else {
uint256 totalUSD = totalYieldToken + (totalStableToken * price) / PRECISION;
amountSharesOut = (amountUSD * _totalSupply) / totalUSD;
}
}
/// @inheritdoc IFxUSDBasePool
function previewRedeem(
uint256 amountSharesToRedeem
) external view returns (uint256 amountYieldOut, uint256 amountStableOut) {
uint256 cachedTotalYieldToken = totalYieldToken;
uint256 cachedTotalStableToken = totalStableToken;
uint256 cachedTotalSupply = totalSupply();
amountYieldOut = (amountSharesToRedeem * cachedTotalYieldToken) / cachedTotalSupply;
amountStableOut = (amountSharesToRedeem * cachedTotalStableToken) / cachedTotalSupply;
}
/// @inheritdoc IFxUSDBasePool
function nav() external view returns (uint256) {
uint256 _totalSupply = totalSupply();
if (_totalSupply == 0) {
return PRECISION;
} else {
uint256 stablePrice = getStableTokenPriceWithScale();
uint256 yieldPrice = IPegKeeper(pegKeeper).getFxUSDPrice();
return (totalYieldToken * yieldPrice + totalStableToken * stablePrice) / _totalSupply;
}
}
/// @inheritdoc IFxUSDBasePool
function getStableTokenPrice() public view returns (uint256) {
bytes32 encoding = Chainlink_USDC_USD_Spot;
address aggregator;
uint256 scale;
uint256 heartbeat;
assembly {
aggregator := shr(96, encoding)
scale := and(shr(32, encoding), 0xffffffffffffffff)
heartbeat := and(encoding, 0xffffffff)
}
(, int256 answer, , uint256 updatedAt, ) = AggregatorV3Interface(aggregator).latestRoundData();
if (answer < 0) revert("invalid");
if (block.timestamp - updatedAt > heartbeat) revert("expired");
return uint256(answer) * scale;
}
/// @inheritdoc IFxUSDBasePool
function getStableTokenPriceWithScale() public view returns (uint256) {
return getStableTokenPrice() * stableTokenScale;
}
/****************************
* Public Mutated Functions *
****************************/
/// @inheritdoc IFxUSDBasePool
function deposit(
address receiver,
address tokenIn,
uint256 amountTokenToDeposit,
uint256 minSharesOut
) external override nonReentrant onlyValidToken(tokenIn) sync returns (uint256 amountSharesOut) {
if (amountTokenToDeposit == 0) revert ErrDepositZeroAmount();
// we are very sure every token is normal token, so no fot check here.
IERC20(tokenIn).safeTransferFrom(_msgSender(), address(this), amountTokenToDeposit);
amountSharesOut = _deposit(tokenIn, amountTokenToDeposit);
if (amountSharesOut < minSharesOut) revert ErrInsufficientSharesOut();
_mint(receiver, amountSharesOut);
emit Deposit(_msgSender(), receiver, tokenIn, amountTokenToDeposit, amountSharesOut);
}
/// @inheritdoc IFxUSDBasePool
function requestRedeem(uint256 shares) external {
address caller = _msgSender();
uint256 balance = balanceOf(caller);
RedeemRequest memory request = redeemRequests[caller];
if (request.amount + shares > balance) revert ErrorRedeemMoreThanBalance();
request.amount += uint128(shares);
request.unlockAt = uint128(block.timestamp + redeemCoolDownPeriod);
redeemRequests[caller] = request;
emit RequestRedeem(caller, shares, request.unlockAt);
}
/// @inheritdoc IFxUSDBasePool
function redeem(
address receiver,
uint256 amountSharesToRedeem
) external nonReentrant sync returns (uint256 amountYieldOut, uint256 amountStableOut) {
address caller = _msgSender();
RedeemRequest memory request = redeemRequests[caller];
if (request.unlockAt > block.timestamp) revert ErrorRedeemLockedShares();
if (request.amount < amountSharesToRedeem) {
amountSharesToRedeem = request.amount;
}
if (amountSharesToRedeem == 0) revert ErrRedeemZeroShares();
request.amount -= uint128(amountSharesToRedeem);
redeemRequests[caller] = request;
uint256 cachedTotalYieldToken = totalYieldToken;
uint256 cachedTotalStableToken = totalStableToken;
uint256 cachedTotalSupply = totalSupply();
amountYieldOut = (amountSharesToRedeem * cachedTotalYieldToken) / cachedTotalSupply;
amountStableOut = (amountSharesToRedeem * cachedTotalStableToken) / cachedTotalSupply;
_burn(caller, amountSharesToRedeem);
if (amountYieldOut > 0) {
_transferOut(yieldToken, amountYieldOut, receiver);
unchecked {
totalYieldToken = cachedTotalYieldToken - amountYieldOut;
}
}
if (amountStableOut > 0) {
_transferOut(stableToken, amountStableOut, receiver);
unchecked {
totalStableToken = cachedTotalStableToken - amountStableOut;
}
}
emit Redeem(caller, receiver, amountSharesToRedeem, amountYieldOut, amountStableOut);
}
/// @inheritdoc IFxUSDBasePool
function instantRedeem(
address receiver,
uint256 amountSharesToRedeem
) external nonReentrant sync returns (uint256 amountYieldOut, uint256 amountStableOut) {
if (amountSharesToRedeem == 0) revert ErrRedeemZeroShares();
address caller = _msgSender();
uint256 leftover = balanceOf(caller) - redeemRequests[caller].amount;
if (amountSharesToRedeem > leftover) revert ErrorInsufficientFreeBalance();
uint256 cachedTotalYieldToken = totalYieldToken;
uint256 cachedTotalStableToken = totalStableToken;
uint256 cachedTotalSupply = totalSupply();
amountYieldOut = (amountSharesToRedeem * cachedTotalYieldToken) / cachedTotalSupply;
amountStableOut = (amountSharesToRedeem * cachedTotalStableToken) / cachedTotalSupply;
uint256 feeRatio = instantRedeemFeeRatio;
_burn(caller, amountSharesToRedeem);
if (amountYieldOut > 0) {
uint256 fee = (amountYieldOut * feeRatio) / PRECISION;
amountYieldOut -= fee;
_transferOut(yieldToken, amountYieldOut, receiver);
unchecked {
totalYieldToken = cachedTotalYieldToken - amountYieldOut;
}
}
if (amountStableOut > 0) {
uint256 fee = (amountStableOut * feeRatio) / PRECISION;
amountStableOut -= fee;
_transferOut(stableToken, amountStableOut, receiver);
unchecked {
totalStableToken = cachedTotalStableToken - amountStableOut;
}
}
emit InstantRedeem(caller, receiver, amountSharesToRedeem, amountYieldOut, amountStableOut);
}
/// @inheritdoc IFxUSDBasePool
function rebalance(
address pool,
int16 tickId,
address tokenIn,
uint256 maxAmount,
uint256 minCollOut
) external onlyValidToken(tokenIn) nonReentrant sync returns (uint256 tokenUsed, uint256 colls) {
RebalanceMemoryVar memory op = _beforeRebalanceOrLiquidate(tokenIn, maxAmount);
(op.colls, op.yieldTokenUsed, op.stableTokenUsed) = IPoolManager(poolManager).rebalance(
pool,
_msgSender(),
tickId,
op.yieldTokenToUse,
op.stableTokenToUse
);
tokenUsed = _afterRebalanceOrLiquidate(tokenIn, minCollOut, op);
colls = op.colls;
}
/// @inheritdoc IFxUSDBasePool
function rebalance(
address pool,
address tokenIn,
uint256 maxAmount,
uint256 minCollOut
) external onlyValidToken(tokenIn) nonReentrant sync returns (uint256 tokenUsed, uint256 colls) {
RebalanceMemoryVar memory op = _beforeRebalanceOrLiquidate(tokenIn, maxAmount);
(op.colls, op.yieldTokenUsed, op.stableTokenUsed) = IPoolManager(poolManager).rebalance(
pool,
_msgSender(),
op.yieldTokenToUse,
op.stableTokenToUse
);
tokenUsed = _afterRebalanceOrLiquidate(tokenIn, minCollOut, op);
colls = op.colls;
}
/// @inheritdoc IFxUSDBasePool
function liquidate(
address pool,
address tokenIn,
uint256 maxAmount,
uint256 minCollOut
) external onlyValidToken(tokenIn) nonReentrant sync returns (uint256 tokenUsed, uint256 colls) {
RebalanceMemoryVar memory op = _beforeRebalanceOrLiquidate(tokenIn, maxAmount);
(op.colls, op.yieldTokenUsed, op.stableTokenUsed) = IPoolManager(poolManager).liquidate(
pool,
_msgSender(),
op.yieldTokenToUse,
op.stableTokenToUse
);
tokenUsed = _afterRebalanceOrLiquidate(tokenIn, minCollOut, op);
colls = op.colls;
}
/// @inheritdoc IFxUSDBasePool
function arbitrage(
address srcToken,
uint256 amountIn,
address receiver,
bytes calldata data
) external onlyValidToken(srcToken) onlyPegKeeper nonReentrant sync returns (uint256 amountOut, uint256 bonusOut) {
address dstToken;
uint256 expectedOut;
uint256 cachedTotalYieldToken = totalYieldToken;
uint256 cachedTotalStableToken = totalStableToken;
{
uint256 price = getStableTokenPrice();
uint256 scaledPrice = price * stableTokenScale;
if (srcToken == yieldToken) {
// check if usdc depeg
if (price < stableDepegPrice) revert ErrorStableTokenDepeg();
if (amountIn > cachedTotalYieldToken) revert ErrorSwapExceedBalance();
dstToken = stableToken;
unchecked {
// rounding up
expectedOut = Math.mulDivUp(amountIn, PRECISION, scaledPrice);
cachedTotalYieldToken -= amountIn;
cachedTotalStableToken += expectedOut;
}
} else {
if (amountIn > cachedTotalStableToken) revert ErrorSwapExceedBalance();
dstToken = yieldToken;
unchecked {
// rounding up
expectedOut = Math.mulDivUp(amountIn, scaledPrice, PRECISION);
cachedTotalStableToken -= amountIn;
cachedTotalYieldToken += expectedOut;
}
}
}
_transferOut(srcToken, amountIn, pegKeeper);
uint256 actualOut = IERC20(dstToken).balanceOf(address(this));
amountOut = IPegKeeper(pegKeeper).onSwap(srcToken, dstToken, amountIn, data);
actualOut = IERC20(dstToken).balanceOf(address(this)) - actualOut;
// check actual fxUSD swapped in case peg keeper is hacked.
if (amountOut > actualOut) revert ErrorInsufficientOutput();
// check swapped token has no loss
if (amountOut < expectedOut) revert ErrorInsufficientArbitrage();
totalYieldToken = cachedTotalYieldToken;
totalStableToken = cachedTotalStableToken;
bonusOut = amountOut - expectedOut;
if (bonusOut > 0) {
_transferOut(dstToken, bonusOut, receiver);
}
emit Arbitrage(_msgSender(), srcToken, amountIn, amountOut, bonusOut);
}
/************************
* Restricted Functions *
************************/
/// @notice Update depeg price for stable token.
/// @param newPrice The new depeg price of stable token, multiplied by 1e18
function updateStableDepegPrice(uint256 newPrice) external onlyRole(DEFAULT_ADMIN_ROLE) {
_updateStableDepegPrice(newPrice);
}
/// @notice Update redeem cool down period.
/// @param newPeriod The new redeem cool down period, in seconds.
function updateRedeemCoolDownPeriod(uint256 newPeriod) external onlyRole(DEFAULT_ADMIN_ROLE) {
_updateRedeemCoolDownPeriod(newPeriod);
}
function updateInstantRedeemFeeRatio(uint256 newRatio) external onlyRole(DEFAULT_ADMIN_ROLE) {
_updateInstantRedeemFeeRatio(newRatio);
}
/**********************
* Internal Functions *
**********************/
/// @inheritdoc ERC20Upgradeable
function _update(address from, address to, uint256 value) internal virtual override {
// make sure from don't transfer more than free balance
if (from != address(0) && to != address(0)) {
uint256 leftover = balanceOf(from) - redeemRequests[from].amount;
if (value > leftover) revert ErrorInsufficientFreeBalance();
}
super._update(from, to, value);
}
/// @dev Internal function to update depeg price for stable token.
/// @param newPrice The new depeg price of stable token, multiplied by 1e18
function _updateStableDepegPrice(uint256 newPrice) internal {
uint256 oldPrice = stableDepegPrice;
stableDepegPrice = newPrice;
emit UpdateStableDepegPrice(oldPrice, newPrice);
}
/// @dev Internal function to update redeem cool down period.
/// @param newPeriod The new redeem cool down period, in seconds.
function _updateRedeemCoolDownPeriod(uint256 newPeriod) internal {
if (newPeriod > 7 days) revert ErrorRedeemCoolDownPeriodTooLarge();
uint256 oldPeriod = redeemCoolDownPeriod;
redeemCoolDownPeriod = newPeriod;
emit UpdateRedeemCoolDownPeriod(oldPeriod, newPeriod);
}
/// @dev Internal function to update the instant redeem fee ratio.
/// @param newRatio The new instant redeem fee ratio, multiplied by 1e18.
function _updateInstantRedeemFeeRatio(uint256 newRatio) internal {
if (newRatio > MAX_INSTANT_REDEEM_FEE) revert ErrorInstantRedeemFeeTooLarge();
uint256 oldRatio = instantRedeemFeeRatio;
instantRedeemFeeRatio = newRatio;
emit UpdateInstantRedeemFeeRatio(oldRatio, newRatio);
}
/// @dev mint shares based on the deposited base tokens
/// @param tokenIn base token address used to mint shares
/// @param amountDeposited amount of base tokens deposited
/// @return amountSharesOut amount of shares minted
function _deposit(address tokenIn, uint256 amountDeposited) internal virtual returns (uint256 amountSharesOut) {
uint256 price = getStableTokenPriceWithScale();
if (price < stableDepegPrice * stableTokenScale) revert ErrorStableTokenDepeg();
uint256 amountUSD = amountDeposited;
if (tokenIn == stableToken) {
amountUSD = (amountUSD * price) / PRECISION;
}
uint256 cachedTotalYieldToken = totalYieldToken;
uint256 cachedTotalStableToken = totalStableToken;
uint256 totalUSD = cachedTotalYieldToken + (cachedTotalStableToken * price) / PRECISION;
uint256 cachedTotalSupply = totalSupply();
if (cachedTotalSupply == 0) {
amountSharesOut = amountUSD;
} else {
amountSharesOut = (amountUSD * cachedTotalSupply) / totalUSD;
}
if (tokenIn == stableToken) {
totalStableToken = cachedTotalStableToken + amountDeposited;
} else {
totalYieldToken = cachedTotalYieldToken + amountDeposited;
}
}
/// @dev Internal hook function to prepare before rebalance or liquidate.
/// @param tokenIn The address of input token.
/// @param maxAmount The maximum amount of input tokens.
function _beforeRebalanceOrLiquidate(
address tokenIn,
uint256 maxAmount
) internal view returns (RebalanceMemoryVar memory op) {
op.stablePrice = getStableTokenPriceWithScale();
op.totalYieldToken = totalYieldToken;
op.totalStableToken = totalStableToken;
uint256 amountYieldToken = op.totalYieldToken;
uint256 amountStableToken;
// we always, try use fxUSD first then USDC
if (tokenIn == yieldToken) {
// user pays fxUSD
if (maxAmount < amountYieldToken) amountYieldToken = maxAmount;
else {
amountStableToken = ((maxAmount - amountYieldToken) * PRECISION) / op.stablePrice;
}
} else {
// user pays USDC
uint256 maxAmountInUSD = (maxAmount * op.stablePrice) / PRECISION;
if (maxAmountInUSD < amountYieldToken) amountYieldToken = maxAmountInUSD;
else {
amountStableToken = ((maxAmountInUSD - amountYieldToken) * PRECISION) / op.stablePrice;
}
}
if (amountStableToken > op.totalStableToken) {
amountStableToken = op.totalStableToken;
}
op.yieldTokenToUse = amountYieldToken;
op.stableTokenToUse = amountStableToken;
}
/// @dev Internal hook function after rebalance or liquidate.
/// @param tokenIn The address of input token.
/// @param minCollOut The minimum expected collateral tokens.
/// @param op The memory variable for rebalance or liquidate.
/// @return tokenUsed The amount of input token used.
function _afterRebalanceOrLiquidate(
address tokenIn,
uint256 minCollOut,
RebalanceMemoryVar memory op
) internal returns (uint256 tokenUsed) {
if (op.colls < minCollOut) revert ErrorInsufficientOutput();
op.totalYieldToken -= op.yieldTokenUsed;
op.totalStableToken -= op.stableTokenUsed;
uint256 amountUSD = op.yieldTokenUsed + (op.stableTokenUsed * op.stablePrice) / PRECISION;
if (tokenIn == yieldToken) {
tokenUsed = amountUSD;
op.totalYieldToken += tokenUsed;
} else {
// rounding up
tokenUsed = Math.mulDivUp(amountUSD, PRECISION, op.stablePrice);
op.totalStableToken += tokenUsed;
}
totalYieldToken = op.totalYieldToken;
totalStableToken = op.totalStableToken;
// transfer token from caller, the collateral is already transferred to caller.
IERC20(tokenIn).safeTransferFrom(_msgSender(), address(this), tokenUsed);
emit Rebalance(_msgSender(), tokenIn, tokenUsed, op.colls, op.yieldTokenUsed, op.stableTokenUsed);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { AccessControlUpgradeable } from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import { IMultiPathConverter } from "../helpers/interfaces/IMultiPathConverter.sol";
import { ICurveStableSwapNG } from "../interfaces/Curve/ICurveStableSwapNG.sol";
import { IFxUSDRegeneracy } from "../interfaces/IFxUSDRegeneracy.sol";
import { IPegKeeper } from "../interfaces/IPegKeeper.sol";
import { IFxUSDBasePool } from "../interfaces/IFxUSDBasePool.sol";
contract PegKeeper is AccessControlUpgradeable, IPegKeeper {
using SafeERC20 for IERC20;
/**********
* Errors *
**********/
error ErrorNotInCallbackContext();
error ErrorZeroAddress();
error ErrorInsufficientOutput();
/*************
* Constants *
*************/
/// @dev The precision used to compute nav.
uint256 private constant PRECISION = 1e18;
/// @notice The role for buyback.
bytes32 public constant BUYBACK_ROLE = keccak256("BUYBACK_ROLE");
/// @notice The role for stabilize.
bytes32 public constant STABILIZE_ROLE = keccak256("STABILIZE_ROLE");
/// @dev contexts for buyback and stabilize callback
uint8 private constant CONTEXT_NO_CONTEXT = 1;
uint8 private constant CONTEXT_BUYBACK = 2;
uint8 private constant CONTEXT_STABILIZE = 3;
/***********************
* Immutable Variables *
***********************/
/// @notice The address of fxUSD.
address public immutable fxUSD;
/// @notice The address of stable token.
address public immutable stable;
/// @notice The address of FxUSDBasePool.
address public immutable fxBASE;
/*********************
* Storage Variables *
*********************/
/// @dev The context for buyback and stabilize callback.
uint8 private context;
/// @notice The address of MultiPathConverter.
address public converter;
/// @notice The curve pool for stable and fxUSD
address public curvePool;
/// @notice The fxUSD depeg price threshold.
uint256 public priceThreshold;
/*************
* Modifiers *
*************/
modifier setContext(uint8 c) {
context = c;
_;
context = CONTEXT_NO_CONTEXT;
}
/***************
* Constructor *
***************/
constructor(address _fxBASE) {
fxBASE = _fxBASE;
fxUSD = IFxUSDBasePool(_fxBASE).yieldToken();
stable = IFxUSDBasePool(_fxBASE).stableToken();
}
function initialize(address admin, address _converter, address _curvePool) external initializer {
__Context_init();
__ERC165_init();
__AccessControl_init();
_grantRole(DEFAULT_ADMIN_ROLE, admin);
_updateConverter(_converter);
_updateCurvePool(_curvePool);
_updatePriceThreshold(995000000000000000); // 0.995
context = CONTEXT_NO_CONTEXT;
}
/*************************
* Public View Functions *
*************************/
/// @inheritdoc IPegKeeper
function isBorrowAllowed() external view returns (bool) {
return _getFxUSDEmaPrice() >= priceThreshold;
}
/// @inheritdoc IPegKeeper
function isFundingEnabled() external view returns (bool) {
return _getFxUSDEmaPrice() < priceThreshold;
}
/// @inheritdoc IPegKeeper
function getFxUSDPrice() external view returns (uint256) {
return _getFxUSDEmaPrice();
}
/****************************
* Public Mutated Functions *
****************************/
/// @inheritdoc IPegKeeper
function buyback(
uint256 amountIn,
bytes calldata data
) external onlyRole(BUYBACK_ROLE) setContext(CONTEXT_BUYBACK) returns (uint256 amountOut, uint256 bonus) {
(amountOut, bonus) = IFxUSDRegeneracy(fxUSD).buyback(amountIn, _msgSender(), data);
}
/// @inheritdoc IPegKeeper
function stabilize(
address srcToken,
uint256 amountIn,
bytes calldata data
) external onlyRole(STABILIZE_ROLE) setContext(CONTEXT_STABILIZE) returns (uint256 amountOut, uint256 bonus) {
(amountOut, bonus) = IFxUSDBasePool(fxBASE).arbitrage(srcToken, amountIn, _msgSender(), data);
}
/// @inheritdoc IPegKeeper
/// @dev This function will be called in `buyback`, `stabilize`.
function onSwap(
address srcToken,
address targetToken,
uint256 amountIn,
bytes calldata data
) external returns (uint256 amountOut) {
// check callback validity
if (context == CONTEXT_NO_CONTEXT) revert ErrorNotInCallbackContext();
amountOut = _doSwap(srcToken, amountIn, data);
IERC20(targetToken).safeTransfer(_msgSender(), amountOut);
}
/************************
* Restricted Functions *
************************/
/// @notice Update the address of converter.
/// @param newConverter The address of converter.
function updateConverter(address newConverter) external onlyRole(DEFAULT_ADMIN_ROLE) {
_updateConverter(newConverter);
}
/// @notice Update the address of curve pool.
/// @param newPool The address of curve pool.
function updateCurvePool(address newPool) external onlyRole(DEFAULT_ADMIN_ROLE) {
_updateCurvePool(newPool);
}
/// @notice Update the value of depeg price threshold.
/// @param newThreshold The value of new price threshold.
function updatePriceThreshold(uint256 newThreshold) external onlyRole(DEFAULT_ADMIN_ROLE) {
_updatePriceThreshold(newThreshold);
}
/**********************
* Internal Functions *
**********************/
/// @dev Internal function to update the address of converter.
/// @param newConverter The address of converter.
function _updateConverter(address newConverter) internal {
if (newConverter == address(0)) revert ErrorZeroAddress();
address oldConverter = converter;
converter = newConverter;
emit UpdateConverter(oldConverter, newConverter);
}
/// @dev Internal function to update the address of curve pool.
/// @param newPool The address of curve pool.
function _updateCurvePool(address newPool) internal {
if (newPool == address(0)) revert ErrorZeroAddress();
address oldPool = curvePool;
curvePool = newPool;
emit UpdateCurvePool(oldPool, newPool);
}
/// @dev Internal function to update the value of depeg price threshold.
/// @param newThreshold The value of new price threshold.
function _updatePriceThreshold(uint256 newThreshold) internal {
uint256 oldThreshold = priceThreshold;
priceThreshold = newThreshold;
emit UpdatePriceThreshold(oldThreshold, newThreshold);
}
/// @dev Internal function to do swap.
/// @param srcToken The address of source token.
/// @param amountIn The amount of token to use.
/// @param data The callback data.
/// @return amountOut The amount of token swapped.
function _doSwap(address srcToken, uint256 amountIn, bytes calldata data) internal returns (uint256 amountOut) {
IERC20(srcToken).forceApprove(converter, amountIn);
(uint256 minOut, uint256 encoding, uint256[] memory routes) = abi.decode(data, (uint256, uint256, uint256[]));
amountOut = IMultiPathConverter(converter).convert(srcToken, amountIn, encoding, routes);
if (amountOut < minOut) revert ErrorInsufficientOutput();
}
/// @dev Internal function to get curve ema price for fxUSD.
/// @return price The value of ema price, multiplied by 1e18.
function _getFxUSDEmaPrice() internal view returns (uint256 price) {
address cachedCurvePool = curvePool; // gas saving
address firstCoin = ICurveStableSwapNG(cachedCurvePool).coins(0);
price = ICurveStableSwapNG(cachedCurvePool).price_oracle(0);
if (firstCoin == fxUSD) {
price = (PRECISION * PRECISION) / price;
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import { IAaveV3Pool } from "../../interfaces/Aave/IAaveV3Pool.sol";
import { IAaveFundingPool } from "../../interfaces/IAaveFundingPool.sol";
import { IPegKeeper } from "../../interfaces/IPegKeeper.sol";
import { WordCodec } from "../../common/codec/WordCodec.sol";
import { Math } from "../../libraries/Math.sol";
import { BasePool } from "./BasePool.sol";
contract AaveFundingPool is BasePool, IAaveFundingPool {
using WordCodec for bytes32;
/*************
* Constants *
*************/
/// @dev The offset of *open ratio* in `fundingMiscData`.
uint256 private constant OPEN_RATIO_OFFSET = 0;
/// @dev The offset of *open ratio step* in `fundingMiscData`.
uint256 private constant OPEN_RATIO_STEP_OFFSET = 30;
/// @dev The offset of *close fee ratio* in `fundingMiscData`.
uint256 private constant CLOSE_FEE_RATIO_OFFSET = 90;
/// @dev The offset of *funding ratio* in `fundingMiscData`.
uint256 private constant FUNDING_RATIO_OFFSET = 120;
/// @dev The offset of *interest rate* in `fundingMiscData`.
uint256 private constant INTEREST_RATE_OFFSET = 152;
/// @dev The offset of *timestamp* in `fundingMiscData`.
uint256 private constant TIMESTAMP_OFFSET = 220;
/// @dev The maximum value of *funding ratio*.
uint256 private constant MAX_FUNDING_RATIO = 4294967295;
/// @dev The minimum Aave borrow index snapshot delay.
uint256 private constant MIN_SNAPSHOT_DELAY = 30 minutes;
/***********************
* Immutable Variables *
***********************/
/// @dev The address of Aave V3 `LendingPool` contract.
address private immutable lendingPool;
/// @dev The address of asset used for interest calculation.
address private immutable baseAsset;
/***********
* Structs *
***********/
/// @dev The struct for AAVE borrow rate snapshot.
/// @param borrowIndex The current borrow index of AAVE, multiplied by 1e27.
/// @param lastInterestRate The last recorded interest rate, multiplied by 1e18.
/// @param timestamp The timestamp when the snapshot is taken.
struct BorrowRateSnapshot {
// The initial value of `borrowIndex` is `10^27`, it is very unlikely this value will exceed `2^128`.
uint128 borrowIndex;
uint80 lastInterestRate;
uint48 timestamp;
}
/*********************
* Storage Variables *
*********************/
/// @dev `fundingMiscData` is a storage slot that can be used to store unrelated pieces of information.
///
/// - The *open ratio* is the fee ratio for opening position, multiplied by 1e9.
/// - The *open ratio step* is the fee ratio step for opening position, multiplied by 1e18.
/// - The *close fee ratio* is the fee ratio for closing position, multiplied by 1e9.
/// - The *funding ratio* is the scalar for funding rate, multiplied by 1e9.
/// The maximum value is `4.294967296`.
///
/// [ open ratio | open ratio step | close fee ratio | funding ratio | reserved ]
/// [ 30 bits | 60 bits | 30 bits | 32 bits | 104 bits ]
/// [ MSB LSB ]
bytes32 private fundingMiscData;
/// @notice The snapshot for AAVE borrow rate.
BorrowRateSnapshot public borrowRateSnapshot;
/***************
* Constructor *
***************/
constructor(address _poolManager, address _lendingPool, address _baseAsset) BasePool(_poolManager) {
_checkAddressNotZero(_lendingPool);
_checkAddressNotZero(_baseAsset);
lendingPool = _lendingPool;
baseAsset = _baseAsset;
}
function initialize(
address admin,
string memory name_,
string memory symbol_,
address _collateralToken,
address _priceOracle
) external initializer {
__Context_init();
__ERC165_init();
__ERC721_init(name_, symbol_);
__AccessControl_init();
__PoolStorage_init(_collateralToken, _priceOracle);
__TickLogic_init();
__PositionLogic_init();
__BasePool_init();
_grantRole(DEFAULT_ADMIN_ROLE, admin);
_updateOpenRatio(1000000, 50000000000000000); // 0.1% and 5%
_updateCloseFeeRatio(1000000); // 0.1%
uint256 borrowIndex = IAaveV3Pool(lendingPool).getReserveNormalizedVariableDebt(baseAsset);
IAaveV3Pool.ReserveDataLegacy memory reserveData = IAaveV3Pool(lendingPool).getReserveData(baseAsset);
_updateInterestRate(borrowIndex, reserveData.currentVariableBorrowRate / 1e9);
}
/*************************
* Public View Functions *
*************************/
/// @notice Get open fee ratio related parameters.
/// @return ratio The value of open ratio, multiplied by 1e9.
/// @return step The value of open ratio step, multiplied by 1e18.
function getOpenRatio() external view returns (uint256 ratio, uint256 step) {
return _getOpenRatio();
}
/// @notice Return the value of funding ratio, multiplied by 1e9.
function getFundingRatio() external view returns (uint256) {
return _getFundingRatio();
}
/// @notice Return the fee ratio for opening position, multiplied by 1e9.
function getOpenFeeRatio() public view returns (uint256) {
(uint256 openRatio, uint256 openRatioStep) = _getOpenRatio();
(, uint256 rate) = _getAverageInterestRate(borrowRateSnapshot);
unchecked {
uint256 aaveRatio = rate <= openRatioStep ? 1 : (rate - 1) / openRatioStep;
return aaveRatio * openRatio;
}
}
/// @notice Return the fee ratio for closing position, multiplied by 1e9.
function getCloseFeeRatio() external view returns (uint256) {
return _getCloseFeeRatio();
}
/************************
* Restricted Functions *
************************/
/// @notice Update the fee ratio for opening position.
/// @param ratio The open ratio value, multiplied by 1e9.
/// @param step The open ratio step value, multiplied by 1e18.
function updateOpenRatio(uint256 ratio, uint256 step) external onlyRole(DEFAULT_ADMIN_ROLE) {
_updateOpenRatio(ratio, step);
}
/// @notice Update the fee ratio for closing position.
/// @param ratio The close ratio value, multiplied by 1e9.
function updateCloseFeeRatio(uint256 ratio) external onlyRole(DEFAULT_ADMIN_ROLE) {
_updateCloseFeeRatio(ratio);
}
/// @notice Update the funding ratio.
/// @param ratio The funding ratio value, multiplied by 1e9.
function updateFundingRatio(uint256 ratio) external onlyRole(DEFAULT_ADMIN_ROLE) {
_updateFundingRatio(ratio);
}
/**********************
* Internal Functions *
**********************/
/// @dev Internal function to get open ratio and open ratio step.
/// @return ratio The value of open ratio, multiplied by 1e9.
/// @return step The value of open ratio step, multiplied by 1e18.
function _getOpenRatio() internal view returns (uint256 ratio, uint256 step) {
bytes32 data = fundingMiscData;
ratio = data.decodeUint(OPEN_RATIO_OFFSET, 30);
step = data.decodeUint(OPEN_RATIO_STEP_OFFSET, 60);
}
/// @dev Internal function to update the fee ratio for opening position.
/// @param ratio The open ratio value, multiplied by 1e9.
/// @param step The open ratio step value, multiplied by 1e18.
function _updateOpenRatio(uint256 ratio, uint256 step) internal {
_checkValueTooLarge(ratio, FEE_PRECISION);
_checkValueTooLarge(step, PRECISION);
bytes32 data = fundingMiscData;
data = data.insertUint(ratio, OPEN_RATIO_OFFSET, 30);
fundingMiscData = data.insertUint(step, OPEN_RATIO_STEP_OFFSET, 60);
emit UpdateOpenRatio(ratio, step);
}
/// @dev Internal function to get the value of close ratio, multiplied by 1e9.
function _getCloseFeeRatio() internal view returns (uint256) {
return fundingMiscData.decodeUint(CLOSE_FEE_RATIO_OFFSET, 30);
}
/// @dev Internal function to update the fee ratio for closing position.
/// @param newRatio The close fee ratio value, multiplied by 1e9.
function _updateCloseFeeRatio(uint256 newRatio) internal {
_checkValueTooLarge(newRatio, FEE_PRECISION);
bytes32 data = fundingMiscData;
uint256 oldRatio = data.decodeUint(CLOSE_FEE_RATIO_OFFSET, 30);
fundingMiscData = data.insertUint(newRatio, CLOSE_FEE_RATIO_OFFSET, 30);
emit UpdateCloseFeeRatio(oldRatio, newRatio);
}
/// @dev Internal function to get the value of funding ratio, multiplied by 1e9.
function _getFundingRatio() internal view returns (uint256) {
return fundingMiscData.decodeUint(FUNDING_RATIO_OFFSET, 32);
}
/// @dev Internal function to update the funding ratio.
/// @param newRatio The funding ratio value, multiplied by 1e9.
function _updateFundingRatio(uint256 newRatio) internal {
_checkValueTooLarge(newRatio, MAX_FUNDING_RATIO);
bytes32 data = fundingMiscData;
uint256 oldRatio = data.decodeUint(FUNDING_RATIO_OFFSET, 32);
fundingMiscData = data.insertUint(newRatio, FUNDING_RATIO_OFFSET, 32);
emit UpdateFundingRatio(oldRatio, newRatio);
}
/// @dev Internal function to return interest rate snapshot.
/// @param snapshot The previous borrow index snapshot.
/// @return newBorrowIndex The current borrow index, multiplied by 1e27.
/// @return rate The annual interest rate, multiplied by 1e18.
function _getAverageInterestRate(
BorrowRateSnapshot memory snapshot
) internal view returns (uint256 newBorrowIndex, uint256 rate) {
uint256 prevBorrowIndex = snapshot.borrowIndex;
newBorrowIndex = IAaveV3Pool(lendingPool).getReserveNormalizedVariableDebt(baseAsset);
// absolute rate change is (new - prev) / prev
// annual interest rate is (new - prev) / prev / duration * 365 days
uint256 duration = block.timestamp - snapshot.timestamp;
// @note Users can trigger this every `MIN_SNAPSHOT_DELAY` seconds and make the interest rate never change.
// We allow users to do so, since the risk is not very high. And if we remove this if, the computed interest
// rate may not correct due to small `duration`.
if (duration < MIN_SNAPSHOT_DELAY) {
rate = snapshot.lastInterestRate;
} else {
rate = ((newBorrowIndex - prevBorrowIndex) * 365 days * PRECISION) / (prevBorrowIndex * duration);
if (rate == 0) rate = snapshot.lastInterestRate;
}
}
/// @dev Internal function to update interest rate snapshot.
function _updateInterestRate(uint256 newBorrowIndex, uint256 lastInterestRate) internal {
BorrowRateSnapshot memory snapshot = borrowRateSnapshot;
snapshot.borrowIndex = uint128(newBorrowIndex);
snapshot.lastInterestRate = uint80(lastInterestRate);
snapshot.timestamp = uint48(block.timestamp);
borrowRateSnapshot = snapshot;
emit SnapshotAaveBorrowIndex(newBorrowIndex, block.timestamp);
}
/// @inheritdoc BasePool
function _updateCollAndDebtIndex() internal virtual override returns (uint256 newCollIndex, uint256 newDebtIndex) {
(newDebtIndex, newCollIndex) = _getDebtAndCollateralIndex();
BorrowRateSnapshot memory snapshot = borrowRateSnapshot;
uint256 duration = block.timestamp - snapshot.timestamp;
if (duration > 0) {
(uint256 borrowIndex, uint256 interestRate) = _getAverageInterestRate(snapshot);
if (IPegKeeper(pegKeeper).isFundingEnabled()) {
(, uint256 totalColls) = _getDebtAndCollateralShares();
uint256 totalRawColls = _convertToRawColl(totalColls, newCollIndex, Math.Rounding.Down);
uint256 funding = (totalRawColls * interestRate * duration) / (365 days * PRECISION);
funding = ((funding * _getFundingRatio()) / FEE_PRECISION);
// update collateral index with funding costs
newCollIndex = (newCollIndex * totalRawColls) / (totalRawColls - funding);
_updateCollateralIndex(newCollIndex);
}
// update interest snapshot
_updateInterestRate(borrowIndex, interestRate);
}
}
/// @inheritdoc BasePool
function _deductProtocolFees(int256 rawColl) internal view virtual override returns (uint256) {
if (rawColl > 0) {
// open position or add collateral
uint256 feeRatio = getOpenFeeRatio();
if (feeRatio > FEE_PRECISION) feeRatio = FEE_PRECISION;
return (uint256(rawColl) * feeRatio) / FEE_PRECISION;
} else {
// close position or remove collateral
return (uint256(-rawColl) * _getCloseFeeRatio()) / FEE_PRECISION;
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import { IPegKeeper } from "../../interfaces/IPegKeeper.sol";
import { IPool } from "../../interfaces/IPool.sol";
import { IPoolManager } from "../../interfaces/IPoolManager.sol";
import { IPriceOracle } from "../../price-oracle/interfaces/IPriceOracle.sol";
import { WordCodec } from "../../common/codec/WordCodec.sol";
import { Math } from "../../libraries/Math.sol";
import { TickBitmap } from "../../libraries/TickBitmap.sol";
import { PositionLogic } from "./PositionLogic.sol";
import { TickLogic } from "./TickLogic.sol";
abstract contract BasePool is TickLogic, PositionLogic {
using TickBitmap for mapping(int8 => uint256);
using WordCodec for bytes32;
/***********
* Structs *
***********/
struct OperationMemoryVar {
int256 tick;
uint48 node;
uint256 positionColl;
uint256 positionDebt;
int256 newColl;
int256 newDebt;
uint256 collIndex;
uint256 debtIndex;
uint256 globalColl;
uint256 globalDebt;
uint256 price;
}
/*************
* Modifiers *
*************/
modifier onlyPoolManager() {
if (_msgSender() != poolManager) {
revert ErrorCallerNotPoolManager();
}
_;
}
/***************
* Constructor *
***************/
constructor(address _poolManager) {
_checkAddressNotZero(_poolManager);
poolManager = _poolManager;
fxUSD = IPoolManager(_poolManager).fxUSD();
pegKeeper = IPoolManager(_poolManager).pegKeeper();
}
function __BasePool_init() internal onlyInitializing {
_updateDebtIndex(E96);
_updateCollateralIndex(E96);
_updateDebtRatioRange(500000000000000000, 857142857142857142); // 1/2 ~ 6/7
_updateMaxRedeemRatioPerTick(200000000); // 20%
}
/****************************
* Public Mutated Functions *
****************************/
/// @inheritdoc IPool
function operate(
uint256 positionId,
int256 newRawColl,
int256 newRawDebt,
address owner
) external onlyPoolManager returns (uint256, int256, int256, uint256) {
if (newRawColl == 0 && newRawDebt == 0) revert ErrorNoSupplyAndNoBorrow();
if (newRawColl != 0 && (newRawColl > -MIN_COLLATERAL && newRawColl < MIN_COLLATERAL)) {
revert ErrorCollateralTooSmall();
}
if (newRawDebt != 0 && (newRawDebt > -MIN_DEBT && newRawDebt < MIN_DEBT)) {
revert ErrorDebtTooSmall();
}
if (newRawDebt > 0 && (_isBorrowPaused() || !IPegKeeper(pegKeeper).isBorrowAllowed())) {
revert ErrorBorrowPaused();
}
OperationMemoryVar memory op;
// price precision and ratio precision are both 1e18, use min price here
op.price = IPriceOracle(priceOracle).getExchangePrice();
(op.globalDebt, op.globalColl) = _getDebtAndCollateralShares();
(op.collIndex, op.debtIndex) = _updateCollAndDebtIndex();
if (positionId == 0) {
positionId = _mintPosition(owner);
} else {
// make sure position is owned and check owner only in case of withdraw or borrow
if (ownerOf(positionId) != owner && (newRawColl < 0 || newRawDebt > 0)) {
revert ErrorNotPositionOwner();
}
PositionInfo memory position = _getAndUpdatePosition(positionId);
// temporarily remove position from tick tree for simplicity
_removePositionFromTick(position);
op.tick = position.tick;
op.node = position.nodeId;
op.positionDebt = position.debts;
op.positionColl = position.colls;
// cannot withdraw or borrow when the position is above liquidation ratio
if (newRawColl < 0 || newRawDebt > 0) {
uint256 rawColls = _convertToRawColl(op.positionColl, op.collIndex, Math.Rounding.Down);
uint256 rawDebts = _convertToRawDebt(op.positionDebt, op.debtIndex, Math.Rounding.Down);
(uint256 debtRatio, ) = _getLiquidateRatios();
if (rawDebts * PRECISION * PRECISION > debtRatio * rawColls * op.price) revert ErrorPositionInLiquidationMode();
}
}
uint256 protocolFees;
// supply or withdraw
if (newRawColl > 0) {
protocolFees = _deductProtocolFees(newRawColl);
newRawColl -= int256(protocolFees);
op.newColl = int256(_convertToCollShares(uint256(newRawColl), op.collIndex, Math.Rounding.Down));
op.positionColl += uint256(op.newColl);
op.globalColl += uint256(op.newColl);
} else if (newRawColl < 0) {
if (newRawColl == type(int256).min) {
// this is max withdraw
newRawColl = -int256(_convertToRawColl(op.positionColl, op.collIndex, Math.Rounding.Down));
op.newColl = -int256(op.positionColl);
} else {
// this is partial withdraw, rounding up removing extra wei from collateral
op.newColl = -int256(_convertToCollShares(uint256(-newRawColl), op.collIndex, Math.Rounding.Up));
if (uint256(-op.newColl) > op.positionColl) revert ErrorWithdrawExceedSupply();
}
unchecked {
op.positionColl -= uint256(-op.newColl);
op.globalColl -= uint256(-op.newColl);
}
protocolFees = _deductProtocolFees(newRawColl);
newRawColl += int256(protocolFees);
}
// borrow or repay
if (newRawDebt > 0) {
// rounding up adding extra wei in debt
op.newDebt = int256(_convertToDebtShares(uint256(newRawDebt), op.debtIndex, Math.Rounding.Up));
op.positionDebt += uint256(op.newDebt);
op.globalDebt += uint256(op.newDebt);
} else if (newRawDebt < 0) {
if (newRawDebt == type(int256).min) {
// this is max repay, rounding up amount that will be transferred in to pay back full debt:
// subtracting -1 of negative debtAmount newDebt_ for safe rounding (increasing payback)
newRawDebt = -int256(_convertToRawDebt(op.positionDebt, op.debtIndex, Math.Rounding.Up));
op.newDebt = -int256(op.positionDebt);
} else {
// this is partial repay, safe rounding up negative amount to rounding reduce payback
op.newDebt = -int256(_convertToDebtShares(uint256(-newRawDebt), op.debtIndex, Math.Rounding.Up));
}
op.positionDebt -= uint256(-op.newDebt);
op.globalDebt -= uint256(-op.newDebt);
}
// final debt ratio check
{
// check position debt ratio is between `minDebtRatio` and `maxDebtRatio`.
uint256 rawColls = _convertToRawColl(op.positionColl, op.collIndex, Math.Rounding.Down);
uint256 rawDebts = _convertToRawDebt(op.positionDebt, op.debtIndex, Math.Rounding.Down);
(uint256 minDebtRatio, uint256 maxDebtRatio) = _getDebtRatioRange();
if (rawDebts * PRECISION * PRECISION > maxDebtRatio * rawColls * op.price) revert ErrorDebtRatioTooLarge();
if (rawDebts * PRECISION * PRECISION < minDebtRatio * rawColls * op.price) revert ErrorDebtRatioTooSmall();
}
// update position state to storage
(op.tick, op.node) = _addPositionToTick(op.positionColl, op.positionDebt, true);
if (op.positionColl > type(uint96).max) revert ErrorOverflow();
if (op.positionDebt > type(uint96).max) revert ErrorOverflow();
positionData[positionId] = PositionInfo(int16(op.tick), op.node, uint96(op.positionColl), uint96(op.positionDebt));
// update global state to storage
_updateDebtAndCollateralShares(op.globalDebt, op.globalColl);
emit PositionSnapshot(positionId, int16(op.tick), op.positionColl, op.positionDebt, op.price);
return (positionId, newRawColl, newRawDebt, protocolFees);
}
/// @inheritdoc IPool
function redeem(uint256 rawDebts) external onlyPoolManager returns (uint256 rawColls) {
if (_isRedeemPaused()) revert ErrorRedeemPaused();
(uint256 cachedCollIndex, uint256 cachedDebtIndex) = _updateCollAndDebtIndex();
(uint256 cachedTotalDebts, uint256 cachedTotalColls) = _getDebtAndCollateralShares();
uint256 price = IPriceOracle(priceOracle).getRedeemPrice();
// check global debt ratio, if global debt ratio >= 1, disable redeem
{
uint256 totalRawColls = _convertToRawColl(cachedTotalColls, cachedCollIndex, Math.Rounding.Down);
uint256 totalRawDebts = _convertToRawDebt(cachedTotalDebts, cachedDebtIndex, Math.Rounding.Down);
if (totalRawDebts * PRECISION >= totalRawColls * price) revert ErrorPoolUnderCollateral();
}
int16 tick = _getTopTick();
bool hasDebt = true;
uint256 debtShare = _convertToDebtShares(rawDebts, cachedDebtIndex, Math.Rounding.Down);
while (debtShare > 0) {
if (!hasDebt) {
(tick, hasDebt) = tickBitmap.nextDebtPositionWithinOneWord(tick - 1);
} else {
uint256 node = tickData[tick];
bytes32 value = tickTreeData[node].value;
uint256 tickDebtShare = value.decodeUint(DEBT_SHARE_OFFSET, 128);
// skip bad debt
{
uint256 tickCollShare = value.decodeUint(COLL_SHARE_OFFSET, 128);
if (
_convertToRawDebt(tickDebtShare, cachedDebtIndex, Math.Rounding.Down) * PRECISION >
_convertToRawColl(tickCollShare, cachedCollIndex, Math.Rounding.Down) * price
) {
hasDebt = false;
tick = tick;
continue;
}
}
// redeem at most `maxRedeemRatioPerTick`
uint256 debtShareToRedeem = (tickDebtShare * _getMaxRedeemRatioPerTick()) / FEE_PRECISION;
if (debtShareToRedeem > debtShare) debtShareToRedeem = debtShare;
uint256 rawCollRedeemed = (_convertToRawDebt(debtShareToRedeem, cachedDebtIndex, Math.Rounding.Down) *
PRECISION) / price;
uint256 collShareRedeemed = _convertToCollShares(rawCollRedeemed, cachedCollIndex, Math.Rounding.Down);
_liquidateTick(tick, collShareRedeemed, debtShareToRedeem, price);
debtShare -= debtShareToRedeem;
rawColls += rawCollRedeemed;
cachedTotalColls -= collShareRedeemed;
cachedTotalDebts -= debtShareToRedeem;
(tick, hasDebt) = tickBitmap.nextDebtPositionWithinOneWord(tick - 1);
}
if (tick == type(int16).min) break;
}
_updateDebtAndCollateralShares(cachedTotalDebts, cachedTotalColls);
}
/// @inheritdoc IPool
function rebalance(int16 tick, uint256 maxRawDebts) external onlyPoolManager returns (RebalanceResult memory result) {
(uint256 cachedCollIndex, uint256 cachedDebtIndex) = _updateCollAndDebtIndex();
(, uint256 price, ) = IPriceOracle(priceOracle).getPrice(); // use min price
uint256 node = tickData[tick];
bytes32 value = tickTreeData[node].value;
uint256 tickRawColl = _convertToRawColl(
value.decodeUint(COLL_SHARE_OFFSET, 128),
cachedCollIndex,
Math.Rounding.Down
);
uint256 tickRawDebt = _convertToRawDebt(
value.decodeUint(DEBT_SHARE_OFFSET, 128),
cachedDebtIndex,
Math.Rounding.Down
);
(uint256 rebalanceDebtRatio, uint256 rebalanceBonusRatio) = _getRebalanceRatios();
(uint256 liquidateDebtRatio, ) = _getLiquidateRatios();
// rebalance only debt ratio >= `rebalanceDebtRatio` and ratio < `liquidateDebtRatio`
if (tickRawDebt * PRECISION * PRECISION < rebalanceDebtRatio * tickRawColl * price) {
revert ErrorRebalanceDebtRatioNotReached();
}
if (tickRawDebt * PRECISION * PRECISION >= liquidateDebtRatio * tickRawColl * price) {
revert ErrorRebalanceOnLiquidatableTick();
}
// compute debts to rebalance to make debt ratio to `rebalanceDebtRatio`
result.rawDebts = _getRawDebtToRebalance(tickRawColl, tickRawDebt, price, rebalanceDebtRatio, rebalanceBonusRatio);
if (maxRawDebts < result.rawDebts) result.rawDebts = maxRawDebts;
uint256 debtShareToRebalance = _convertToDebtShares(result.rawDebts, cachedDebtIndex, Math.Rounding.Down);
result.rawColls = (result.rawDebts * PRECISION) / price;
result.bonusRawColls = (result.rawColls * rebalanceBonusRatio) / FEE_PRECISION;
if (result.bonusRawColls > tickRawColl - result.rawColls) {
result.bonusRawColls = tickRawColl - result.rawColls;
}
uint256 collShareToRebalance = _convertToCollShares(
result.rawColls + result.bonusRawColls,
cachedCollIndex,
Math.Rounding.Down
);
_liquidateTick(tick, collShareToRebalance, debtShareToRebalance, price);
unchecked {
(uint256 totalDebts, uint256 totalColls) = _getDebtAndCollateralShares();
_updateDebtAndCollateralShares(totalDebts - debtShareToRebalance, totalColls - collShareToRebalance);
}
}
struct RebalanceVars {
uint256 tickCollShares;
uint256 tickDebtShares;
uint256 tickRawColls;
uint256 tickRawDebts;
uint256 maxRawDebts;
uint256 rebalanceDebtRatio;
uint256 rebalanceBonusRatio;
uint256 price;
uint256 collIndex;
uint256 debtIndex;
uint256 totalCollShares;
uint256 totalDebtShares;
}
/// @inheritdoc IPool
function rebalance(uint256 maxRawDebts) external onlyPoolManager returns (RebalanceResult memory result) {
RebalanceVars memory vars;
vars.maxRawDebts = maxRawDebts;
(vars.rebalanceDebtRatio, vars.rebalanceBonusRatio) = _getRebalanceRatios();
(, vars.price, ) = IPriceOracle(priceOracle).getPrice();
(vars.collIndex, vars.debtIndex) = _updateCollAndDebtIndex();
(vars.totalDebtShares, vars.totalCollShares) = _getDebtAndCollateralShares();
(uint256 liquidateDebtRatio, ) = _getLiquidateRatios();
int16 tick = _getTopTick();
bool hasDebt = true;
while (vars.maxRawDebts > 0) {
if (!hasDebt) {
(tick, hasDebt) = tickBitmap.nextDebtPositionWithinOneWord(tick - 1);
} else {
(vars.tickCollShares, vars.tickDebtShares, vars.tickRawColls, vars.tickRawDebts) = _getTickRawCollAndDebts(
tick,
vars.collIndex,
vars.debtIndex
);
// skip bad debt and liquidatable positions: coll * price * liquidateDebtRatio <= debts
if (vars.tickRawColls * vars.price * liquidateDebtRatio <= vars.tickRawDebts * PRECISION * PRECISION) {
hasDebt = false;
tick = tick;
continue;
}
// skip dust
if (vars.tickRawDebts < uint256(MIN_DEBT)) {
hasDebt = false;
tick = tick;
continue;
}
// no more rebalanceable tick: coll * price * rebalanceDebtRatio > debts
if (vars.tickRawColls * vars.price * vars.rebalanceDebtRatio > vars.tickRawDebts * PRECISION * PRECISION) {
break;
}
// rebalance this tick
(uint256 rawDebts, uint256 rawColls, uint256 bonusRawColls) = _rebalanceTick(tick, vars);
result.rawDebts += rawDebts;
result.rawColls += rawColls;
result.bonusRawColls += bonusRawColls;
// goto next tick
(tick, hasDebt) = tickBitmap.nextDebtPositionWithinOneWord(tick - 1);
}
if (tick == type(int16).min) break;
}
_updateDebtAndCollateralShares(vars.totalDebtShares, vars.totalCollShares);
}
struct LiquidateVars {
uint256 tickCollShares;
uint256 tickDebtShares;
uint256 tickRawColls;
uint256 tickRawDebts;
uint256 maxRawDebts;
uint256 reservedRawColls;
uint256 liquidateDebtRatio;
uint256 liquidateBonusRatio;
uint256 price;
uint256 collIndex;
uint256 debtIndex;
uint256 totalCollShares;
uint256 totalDebtShares;
}
/// @inheritdoc IPool
function liquidate(
uint256 maxRawDebts,
uint256 reservedRawColls
) external onlyPoolManager returns (LiquidateResult memory result) {
LiquidateVars memory vars;
vars.maxRawDebts = maxRawDebts;
vars.reservedRawColls = reservedRawColls;
(vars.liquidateDebtRatio, vars.liquidateBonusRatio) = _getLiquidateRatios();
(, vars.price, ) = IPriceOracle(priceOracle).getPrice();
(vars.collIndex, vars.debtIndex) = _updateCollAndDebtIndex();
(vars.totalDebtShares, vars.totalCollShares) = _getDebtAndCollateralShares();
int16 tick = _getTopTick();
bool hasDebt = true;
while (vars.maxRawDebts > 0) {
if (!hasDebt) {
(tick, hasDebt) = tickBitmap.nextDebtPositionWithinOneWord(tick - 1);
} else {
(vars.tickCollShares, vars.tickDebtShares, vars.tickRawColls, vars.tickRawDebts) = _getTickRawCollAndDebts(
tick,
vars.collIndex,
vars.debtIndex
);
// no more liquidatable tick: coll * price * liquidateDebtRatio > debts
if (vars.tickRawColls * vars.price * vars.liquidateDebtRatio > vars.tickRawDebts * PRECISION * PRECISION) {
// skip dust, since the results might be wrong
if (vars.tickRawDebts < uint256(MIN_DEBT)) {
hasDebt = false;
tick = tick;
continue;
}
break;
}
// rebalance this tick
(uint256 rawDebts, uint256 rawColls, uint256 bonusRawColls, uint256 bonusFromReserve) = _liquidateTick(
tick,
vars
);
result.rawDebts += rawDebts;
result.rawColls += rawColls;
result.bonusRawColls += bonusRawColls;
result.bonusFromReserve += bonusFromReserve;
// goto next tick
(tick, hasDebt) = tickBitmap.nextDebtPositionWithinOneWord(tick - 1);
}
if (tick == type(int16).min) break;
}
_updateDebtAndCollateralShares(vars.totalDebtShares, vars.totalCollShares);
_updateDebtIndex(vars.debtIndex);
}
/************************
* Restricted Functions *
************************/
/// @notice Update the borrow and redeem status.
/// @param borrowStatus The new borrow status.
/// @param redeemStatus The new redeem status.
function updateBorrowAndRedeemStatus(bool borrowStatus, bool redeemStatus) external onlyRole(EMERGENCY_ROLE) {
_updateBorrowStatus(borrowStatus);
_updateRedeemStatus(redeemStatus);
}
/// @notice Update debt ratio range.
/// @param minRatio The minimum allowed debt ratio to update, multiplied by 1e18.
/// @param maxRatio The maximum allowed debt ratio to update, multiplied by 1e18.
function updateDebtRatioRange(uint256 minRatio, uint256 maxRatio) external onlyRole(DEFAULT_ADMIN_ROLE) {
_updateDebtRatioRange(minRatio, maxRatio);
}
/// @notice Update maximum redeem ratio per tick.
/// @param ratio The ratio to update, multiplied by 1e9.
function updateMaxRedeemRatioPerTick(uint256 ratio) external onlyRole(DEFAULT_ADMIN_ROLE) {
_updateMaxRedeemRatioPerTick(ratio);
}
/// @notice Update ratio for rebalance.
/// @param debtRatio The minimum debt ratio to start rebalance, multiplied by 1e18.
/// @param bonusRatio The bonus ratio during rebalance, multiplied by 1e9.
function updateRebalanceRatios(uint256 debtRatio, uint256 bonusRatio) external onlyRole(DEFAULT_ADMIN_ROLE) {
_updateRebalanceRatios(debtRatio, bonusRatio);
}
/// @notice Update ratio for liquidate.
/// @param debtRatio The minimum debt ratio to start liquidate, multiplied by 1e18.
/// @param bonusRatio The bonus ratio during liquidate, multiplied by 1e9.
function updateLiquidateRatios(uint256 debtRatio, uint256 bonusRatio) external onlyRole(DEFAULT_ADMIN_ROLE) {
_updateLiquidateRatios(debtRatio, bonusRatio);
}
/// @notice Update the address of price oracle.
/// @param newOracle The address of new price oracle.
function updatePriceOracle(address newOracle) external onlyRole(DEFAULT_ADMIN_ROLE) {
_updatePriceOracle(newOracle);
}
/**********************
* Internal Functions *
**********************/
/// @dev Internal function to compute the amount of debt to rebalance to reach certain debt ratio.
/// @param coll The amount of collateral tokens.
/// @param debt The amount of debt tokens.
/// @param price The price of the collateral token.
/// @param targetDebtRatio The target debt ratio, multiplied by 1e18.
/// @param incentiveRatio The bonus ratio, multiplied by 1e9.
/// @return rawDebts The amount of debt tokens to rebalance.
function _getRawDebtToRebalance(
uint256 coll,
uint256 debt,
uint256 price,
uint256 targetDebtRatio,
uint256 incentiveRatio
) internal pure returns (uint256 rawDebts) {
// we have
// 1. (debt - x) / (price * (coll - y * (1 + incentive))) <= target_ratio
// 2. debt / (price * coll) >= target_ratio
// then
// => debt - x <= target * price * (coll - y * (1 + incentive)) and y = x / price
// => debt - target_ratio * price * coll <= (1 - (1 + incentive) * target) * x
// => x >= (debt - target_ratio * price * coll) / (1 - (1 + incentive) * target)
rawDebts =
(debt * PRECISION * PRECISION - targetDebtRatio * price * coll) /
(PRECISION * PRECISION - (PRECISION * targetDebtRatio * (FEE_PRECISION + incentiveRatio)) / FEE_PRECISION);
}
function _getTickRawCollAndDebts(
int16 tick,
uint256 collIndex,
uint256 debtIndex
) internal view returns (uint256 colls, uint256 debts, uint256 rawColls, uint256 rawDebts) {
uint256 node = tickData[tick];
bytes32 value = tickTreeData[node].value;
colls = value.decodeUint(COLL_SHARE_OFFSET, 128);
debts = value.decodeUint(DEBT_SHARE_OFFSET, 128);
rawColls = _convertToRawColl(colls, collIndex, Math.Rounding.Down);
rawDebts = _convertToRawDebt(debts, debtIndex, Math.Rounding.Down);
}
function _rebalanceTick(
int16 tick,
RebalanceVars memory vars
) internal returns (uint256 rawDebts, uint256 rawColls, uint256 bonusRawColls) {
// compute debts to rebalance to make debt ratio to `rebalanceDebtRatio`
rawDebts = _getRawDebtToRebalance(
vars.tickRawColls,
vars.tickRawDebts,
vars.price,
vars.rebalanceDebtRatio,
vars.rebalanceBonusRatio
);
if (vars.maxRawDebts < rawDebts) rawDebts = vars.maxRawDebts;
uint256 debtShares = _convertToDebtShares(rawDebts, vars.debtIndex, Math.Rounding.Down);
rawColls = (rawDebts * PRECISION) / vars.price;
bonusRawColls = (rawColls * vars.rebalanceBonusRatio) / FEE_PRECISION;
if (bonusRawColls > vars.tickRawColls - rawColls) {
bonusRawColls = vars.tickRawColls - rawColls;
}
uint256 collShares = _convertToCollShares(rawColls + bonusRawColls, vars.collIndex, Math.Rounding.Down);
_liquidateTick(tick, collShares, debtShares, vars.price);
vars.totalCollShares -= collShares;
vars.totalDebtShares -= debtShares;
vars.maxRawDebts -= rawDebts;
}
function _liquidateTick(
int16 tick,
LiquidateVars memory vars
) internal returns (uint256 rawDebts, uint256 rawColls, uint256 bonusRawColls, uint256 bonusFromReserve) {
uint256 virtualTickRawColls = vars.tickRawColls + vars.reservedRawColls;
rawDebts = vars.tickRawDebts;
if (rawDebts > vars.maxRawDebts) rawDebts = vars.maxRawDebts;
rawColls = (rawDebts * PRECISION) / vars.price;
uint256 debtShares;
uint256 collShares;
if (rawDebts == vars.tickRawDebts) {
// full liquidation
debtShares = vars.tickDebtShares;
} else {
// partial liquidation
debtShares = _convertToDebtShares(rawDebts, vars.debtIndex, Math.Rounding.Down);
}
if (virtualTickRawColls <= rawColls) {
// even reserve funds cannot cover bad debts, no bonus and will trigger bad debt redistribution
rawColls = virtualTickRawColls;
bonusFromReserve = vars.reservedRawColls;
rawDebts = (virtualTickRawColls * vars.price) / PRECISION;
debtShares = _convertToDebtShares(rawDebts, vars.debtIndex, Math.Rounding.Down);
collShares = vars.tickCollShares;
} else {
// Bonus is from colls in tick, if it is not enough will use reserve funds
bonusRawColls = (rawColls * vars.liquidateBonusRatio) / FEE_PRECISION;
uint256 rawCollWithBonus = bonusRawColls + rawColls;
if (rawCollWithBonus > virtualTickRawColls) {
rawCollWithBonus = virtualTickRawColls;
bonusRawColls = rawCollWithBonus - rawColls;
}
if (rawCollWithBonus >= vars.tickRawColls) {
bonusFromReserve = rawCollWithBonus - vars.tickRawColls;
collShares = vars.tickCollShares;
} else {
collShares = _convertToCollShares(rawCollWithBonus, vars.collIndex, Math.Rounding.Down);
}
}
vars.reservedRawColls -= bonusFromReserve;
if (collShares == vars.tickCollShares && debtShares < vars.tickDebtShares) {
// trigger bad debt redistribution
uint256 rawBadDebt = _convertToRawDebt(vars.tickDebtShares - debtShares, vars.debtIndex, Math.Rounding.Down);
debtShares = vars.tickDebtShares;
vars.totalCollShares -= collShares;
vars.totalDebtShares -= debtShares;
vars.debtIndex += (rawBadDebt * E96) / vars.totalDebtShares;
} else {
vars.totalCollShares -= collShares;
vars.totalDebtShares -= debtShares;
}
vars.maxRawDebts -= rawDebts;
_liquidateTick(tick, collShares, debtShares, vars.price);
}
/// @dev Internal function to update collateral and debt index.
/// @return newCollIndex The updated collateral index.
/// @return newDebtIndex The updated debt index.
function _updateCollAndDebtIndex() internal virtual returns (uint256 newCollIndex, uint256 newDebtIndex);
/// @dev Internal function to compute the protocol fees.
/// @param rawColl The amount of collateral tokens involved.
/// @return fees The expected protocol fees.
function _deductProtocolFees(int256 rawColl) internal view virtual returns (uint256 fees);
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
*/
uint256[50] private __gap;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import { IPool } from "../../interfaces/IPool.sol";
abstract contract PoolConstant is IPool {
/*************
* Constants *
*************/
/// @dev The role for emergency operations.
bytes32 public constant EMERGENCY_ROLE = keccak256("EMERGENCY_ROLE");
/// @dev The value of minimum collateral.
int256 internal constant MIN_COLLATERAL = 1e9;
/// @dev The value of minimum debts.
int256 internal constant MIN_DEBT = 1e9;
/// @dev The precision used for various calculation.
uint256 internal constant PRECISION = 1e18;
/// @dev The precision used for fee ratio calculation.
uint256 internal constant FEE_PRECISION = 1e9;
/// @dev bit operation related constants
uint256 internal constant E60 = 2 ** 60; // 2^60
uint256 internal constant E96 = 2 ** 96; // 2^96
uint256 internal constant X60 = 0xfffffffffffffff; // 2^60 - 1
uint256 internal constant X96 = 0xffffffffffffffffffffffff; // 2^96 - 1
/***********************
* Immutable Variables *
***********************/
/// @inheritdoc IPool
address public immutable fxUSD;
/// @inheritdoc IPool
address public immutable poolManager;
/// @inheritdoc IPool
address public immutable pegKeeper;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
abstract contract PoolErrors {
/**********
* Errors *
**********/
/// @dev Thrown when the given address is zero.
error ErrorZeroAddress();
/// @dev Thrown when the given value exceeds maximum value.
error ErrorValueTooLarge();
/// @dev Thrown when the caller is not pool manager.
error ErrorCallerNotPoolManager();
/// @dev Thrown when the debt amount is too small.
error ErrorDebtTooSmall();
/// @dev Thrown when the collateral amount is too small.
error ErrorCollateralTooSmall();
/// @dev Thrown when both collateral amount and debt amount are zero.
error ErrorNoSupplyAndNoBorrow();
/// @dev Thrown when borrow is paused.
error ErrorBorrowPaused();
/// @dev Thrown when redeem is paused.
error ErrorRedeemPaused();
/// @dev Thrown when the caller is not position owner during withdraw or borrow.
error ErrorNotPositionOwner();
/// @dev Thrown when withdraw more than supplied.
error ErrorWithdrawExceedSupply();
/// @dev Thrown when the debt ratio is too small.
error ErrorDebtRatioTooSmall();
/// @dev Thrown when the debt ratio is too large.
error ErrorDebtRatioTooLarge();
/// @dev Thrown when pool is under collateral.
error ErrorPoolUnderCollateral();
/// @dev Thrown when the current debt ratio <= rebalance debt ratio.
error ErrorRebalanceDebtRatioNotReached();
/// @dev Thrown when the current debt ratio > liquidate debt ratio.
error ErrorPositionInLiquidationMode();
error ErrorRebalanceOnLiquidatableTick();
error ErrorRebalanceOnLiquidatablePosition();
error ErrorInsufficientCollateralToLiquidate();
error ErrorOverflow();
/**********************
* Internal Functions *
**********************/
/// @dev Internal function to check value not too large.
/// @param value The value to check.
/// @param upperBound The upper bound for the given value.
function _checkValueTooLarge(uint256 value, uint256 upperBound) internal pure {
if (value > upperBound) revert ErrorValueTooLarge();
}
function _checkAddressNotZero(address value) internal pure {
if (value == address(0)) revert ErrorZeroAddress();
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import { AccessControlUpgradeable } from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import { ERC721Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import { IPool } from "../../interfaces/IPool.sol";
import { WordCodec } from "../../common/codec/WordCodec.sol";
import { PoolConstant } from "./PoolConstant.sol";
import { PoolErrors } from "./PoolErrors.sol";
abstract contract PoolStorage is ERC721Upgradeable, AccessControlUpgradeable, PoolConstant, PoolErrors {
using WordCodec for bytes32;
/*************
* Constants *
*************/
/// @dev Below are offsets of each variables in `miscData`.
uint256 private constant BORROW_FLAG_OFFSET = 0;
uint256 private constant REDEEM_FLAG_OFFSET = 1;
uint256 private constant TOP_TICK_OFFSET = 2;
uint256 private constant NEXT_POSITION_OFFSET = 18;
uint256 private constant NEXT_NODE_OFFSET = 50;
uint256 private constant MIN_DEBT_RATIO_OFFSET = 98;
uint256 private constant MAX_DEBT_RATIO_OFFSET = 158;
uint256 private constant MAX_REDEEM_RATIO_OFFSET = 218;
/// @dev Below are offsets of each variables in `rebalanceRatioData`.
uint256 private constant REBALANCE_DEBT_RATIO_OFFSET = 0;
uint256 private constant REBALANCE_BONUS_RATIO_OFFSET = 60;
uint256 private constant LIQUIDATE_DEBT_RATIO_OFFSET = 90;
uint256 private constant LIQUIDATE_BONUS_RATIO_OFFSET = 150;
/// @dev Below are offsets of each variables in `indexData`.
uint256 private constant DEBT_INDEX_OFFSET = 0;
uint256 private constant COLLATERAL_INDEX_OFFSET = 128;
/// @dev Below are offsets of each variables in `sharesData`.
uint256 private constant DEBT_SHARES_OFFSET = 0;
uint256 private constant COLLATERAL_SHARES_OFFSET = 128;
/***********
* Structs *
***********/
/// @dev if nodeId = 0, tick is not used and this position only has collateral
///
/// @param tick The tick this position belongs to at the beginning.
/// @param nodeId The tree node id this position belongs to at the beginning.
/// @param colls The collateral shares this position has.
/// @param debts The debt shares this position has.
struct PositionInfo {
int16 tick;
uint48 nodeId;
// `uint96` is enough, since we use `86` bits in `PoolManager`.
uint96 colls;
// `uint96` is enough, since we use `96` bits in `PoolManager`.
uint96 debts;
}
/// @dev The compiler will pack it into two `uint256`.
/// @param metadata The metadata for tree node.
/// ```text
/// * Field Bits Index Comments
/// * parent 48 0 The index for parent tree node.
/// * tick 16 48 The original tick for this tree node.
/// * coll ratio 64 64 The remained coll share ratio base on parent node, the value is real ratio * 2^60.
/// * debt ratio 64 128 The remained debt share ratio base on parent node, the value is real ratio * 2^60.
/// ```
/// @param value The value for tree node
/// ```text
/// * Field Bits Index Comments
/// * coll share 128 0 The original total coll share before rebalance or redeem.
/// * debt share 128 128 The original total debt share before rebalance or redeem.
/// ```
struct TickTreeNode {
bytes32 metadata;
bytes32 value;
}
/*********************
* Storage Variables *
*********************/
/// @inheritdoc IPool
address public collateralToken;
/// @inheritdoc IPool
address public priceOracle;
/// @dev `miscData` is a storage slot that can be used to store unrelated pieces of information.
///
/// - The *borrow flag* indicates whether borrow fxUSD is allowed, 1 means paused.
/// - The *redeem flag* indicates whether redeem fxUSD is allowed, 1 means paused.
/// - The *top tick* is the largest tick with debts.
/// - The *next position* is the next unassigned position id.
/// - The *next node* is the next unassigned tree node id.
/// - The *min debt ratio* is the minimum allowed debt ratio, multiplied by 1e18.
/// - The *max debt ratio* is the maximum allowed debt ratio, multiplied by 1e18.
/// - The *max redeem ratio* is the maximum allowed redeem ratio per tick, multiplied by 1e9.
///
/// [ borrow flag | redeem flag | top tick | next position | next node | min debt ratio | max debt ratio | max redeem ratio | reserved ]
/// [ 1 bit | 1 bit | 16 bits | 32 bits | 48 bits | 60 bits | 60 bits | 30 bits | 8 bits ]
/// [ MSB LSB ]
bytes32 private miscData;
/// @dev `rebalanceRatioData` is a storage slot used to store rebalance and liquidate information.
///
/// - The *rebalance debt ratio* is the min debt ratio to start rebalance, multiplied by 1e18.
/// - The *rebalance bonus ratio* is the bonus ratio during rebalance, multiplied by 1e9.
/// - The *liquidate debt ratio* is the min debt ratio to start liquidate, multiplied by 1e18.
/// - The *liquidate bonus ratio* is the bonus ratio during liquidate, multiplied by 1e9.
///
/// [ rebalance debt ratio | rebalance bonus ratio | liquidate debt ratio | liquidate bonus ratio | reserved ]
/// [ 60 bits | 30 bits | 60 bits | 30 bits | 76 bits ]
/// [ MSB LSB ]
bytes32 private rebalanceRatioData;
/// @dev `indexData` is a storage slot used to store debt/collateral index.
///
/// - The *debt index* is the index for each debt shares, only increasing, starting from 2^96, max 2^128-1.
/// - The *collateral index* is the index for each collateral shares, only increasing, starting from 2^96, max 2^128-1
///
/// [ debt index | collateral index ]
/// [ 128 bits | 128 bits ]
/// [ MSB LSB ]
bytes32 private indexData;
/// @dev `sharesData` is a storage slot used to store debt/collateral shares.
///
/// - The *debt shares* is the total debt shares. The actual number of total debts
/// is `<debt shares> * <debt index>`.
/// - The *collateral shares* is the total collateral shares. The actual number of
/// total collateral is `<collateral shares> / <collateral index>`.
///
/// [ debt shares | collateral shares ]
/// [ 128 bits | 128 bits ]
/// [ MSB LSB ]
bytes32 private sharesData;
/// @dev Mapping from position id to position information.
mapping(uint256 => PositionInfo) public positionData;
/// @dev Mapping from position id to position metadata.
/// [ open timestamp | reserved ]
/// [ 40 bits | 216 bits ]
/// [ MSB LSB ]
mapping(uint256 => bytes32) public positionMetadata;
/// @dev The bitmap for ticks with debts.
mapping(int8 => uint256) public tickBitmap;
/// @dev Mapping from tick to tree node id.
mapping(int256 => uint48) public tickData;
/// @dev Mapping from tree node id to tree node data.
mapping(uint256 => TickTreeNode) public tickTreeData;
/***************
* Constructor *
***************/
function __PoolStorage_init(address _collateralToken, address _priceOracle) internal onlyInitializing {
_checkAddressNotZero(_collateralToken);
collateralToken = _collateralToken;
_updatePriceOracle(_priceOracle);
}
/*************************
* Public View Functions *
*************************/
/// @inheritdoc AccessControlUpgradeable
function supportsInterface(
bytes4 interfaceId
) public view virtual override(AccessControlUpgradeable, ERC721Upgradeable) returns (bool) {
return super.supportsInterface(interfaceId);
}
/// @inheritdoc IPool
function isBorrowPaused() external view returns (bool) {
return _isBorrowPaused();
}
/// @inheritdoc IPool
function isRedeemPaused() external view returns (bool) {
return _isRedeemPaused();
}
/// @inheritdoc IPool
function getTopTick() external view returns (int16) {
return _getTopTick();
}
/// @inheritdoc IPool
function getNextPositionId() external view returns (uint32) {
return _getNextPositionId();
}
/// @inheritdoc IPool
function getNextTreeNodeId() external view returns (uint48) {
return _getNextTreeNodeId();
}
/// @inheritdoc IPool
function getDebtRatioRange() external view returns (uint256, uint256) {
return _getDebtRatioRange();
}
/// @inheritdoc IPool
function getMaxRedeemRatioPerTick() external view returns (uint256) {
return _getMaxRedeemRatioPerTick();
}
/// @inheritdoc IPool
function getRebalanceRatios() external view returns (uint256, uint256) {
return _getRebalanceRatios();
}
/// @inheritdoc IPool
function getLiquidateRatios() external view returns (uint256, uint256) {
return _getLiquidateRatios();
}
/// @inheritdoc IPool
function getDebtAndCollateralIndex() external view returns (uint256, uint256) {
return _getDebtAndCollateralIndex();
}
/// @inheritdoc IPool
function getDebtAndCollateralShares() external view returns (uint256, uint256) {
return _getDebtAndCollateralShares();
}
/**********************
* Internal Functions *
**********************/
/// @dev Internal function to update price oracle.
/// @param newOracle The address of new price oracle;
function _updatePriceOracle(address newOracle) internal {
_checkAddressNotZero(newOracle);
address oldOracle = priceOracle;
priceOracle = newOracle;
emit UpdatePriceOracle(oldOracle, newOracle);
}
/*************************************
* Internal Functions For `miscData` *
*************************************/
/// @dev Internal function to get the borrow pause status.
function _isBorrowPaused() internal view returns (bool) {
return miscData.decodeBool(BORROW_FLAG_OFFSET);
}
/// @dev Internal function to update borrow pause status.
/// @param status The status to update.
function _updateBorrowStatus(bool status) internal {
miscData = miscData.insertBool(status, BORROW_FLAG_OFFSET);
emit UpdateBorrowStatus(status);
}
/// @dev Internal function to get the redeem pause status.
function _isRedeemPaused() internal view returns (bool) {
return miscData.decodeBool(REDEEM_FLAG_OFFSET);
}
/// @dev Internal function to update redeem pause status.
/// @param status The status to update.
function _updateRedeemStatus(bool status) internal {
miscData = miscData.insertBool(status, REDEEM_FLAG_OFFSET);
emit UpdateRedeemStatus(status);
}
/// @dev Internal function to get the value of top tick.
function _getTopTick() internal view returns (int16) {
return int16(miscData.decodeInt(TOP_TICK_OFFSET, 16));
}
/// @dev Internal function to update the top tick.
/// @param tick The new top tick.
function _updateTopTick(int16 tick) internal {
miscData = miscData.insertInt(tick, TOP_TICK_OFFSET, 16);
}
/// @dev Internal function to get next available position id.
function _getNextPositionId() internal view returns (uint32) {
return uint32(miscData.decodeUint(NEXT_POSITION_OFFSET, 32));
}
/// @dev Internal function to update next available position id.
/// @param id The position id to update.
function _updateNextPositionId(uint32 id) internal {
miscData = miscData.insertUint(id, NEXT_POSITION_OFFSET, 32);
}
/// @dev Internal function to get next available tree node id.
function _getNextTreeNodeId() internal view returns (uint48) {
return uint48(miscData.decodeUint(NEXT_NODE_OFFSET, 48));
}
/// @dev Internal function to update next available tree node id.
/// @param id The tree node id to update.
function _updateNextTreeNodeId(uint48 id) internal {
miscData = miscData.insertUint(id, NEXT_NODE_OFFSET, 48);
}
/// @dev Internal function to get `minDebtRatio` and `maxDebtRatio`, both multiplied by 1e18.
function _getDebtRatioRange() internal view returns (uint256 minDebtRatio, uint256 maxDebtRatio) {
bytes32 data = miscData;
minDebtRatio = data.decodeUint(MIN_DEBT_RATIO_OFFSET, 60);
maxDebtRatio = data.decodeUint(MAX_DEBT_RATIO_OFFSET, 60);
}
/// @dev Internal function to update debt ratio range.
/// @param minDebtRatio The minimum allowed debt ratio to update, multiplied by 1e18.
/// @param maxDebtRatio The maximum allowed debt ratio to update, multiplied by 1e18.
function _updateDebtRatioRange(uint256 minDebtRatio, uint256 maxDebtRatio) internal {
_checkValueTooLarge(minDebtRatio, maxDebtRatio);
_checkValueTooLarge(maxDebtRatio, PRECISION);
bytes32 data = miscData;
data = data.insertUint(minDebtRatio, MIN_DEBT_RATIO_OFFSET, 60);
miscData = data.insertUint(maxDebtRatio, MAX_DEBT_RATIO_OFFSET, 60);
emit UpdateDebtRatioRange(minDebtRatio, maxDebtRatio);
}
/// @dev Internal function to get the `maxRedeemRatioPerTick`.
function _getMaxRedeemRatioPerTick() internal view returns (uint256) {
return miscData.decodeUint(MAX_REDEEM_RATIO_OFFSET, 30);
}
/// @dev Internal function to update maximum redeem ratio per tick.
/// @param ratio The ratio to update, multiplied by 1e9.
function _updateMaxRedeemRatioPerTick(uint256 ratio) internal {
_checkValueTooLarge(ratio, FEE_PRECISION);
miscData = miscData.insertUint(ratio, MAX_REDEEM_RATIO_OFFSET, 30);
emit UpdateMaxRedeemRatioPerTick(ratio);
}
/***********************************************
* Internal Functions For `rebalanceRatioData` *
***********************************************/
/// @dev Internal function to get `debtRatio` and `bonusRatio` for rebalance.
/// @return debtRatio The minimum debt ratio to start rebalance, multiplied by 1e18.
/// @return bonusRatio The bonus ratio during rebalance, multiplied by 1e9.
function _getRebalanceRatios() internal view returns (uint256 debtRatio, uint256 bonusRatio) {
bytes32 data = rebalanceRatioData;
debtRatio = data.decodeUint(REBALANCE_DEBT_RATIO_OFFSET, 60);
bonusRatio = data.decodeUint(REBALANCE_BONUS_RATIO_OFFSET, 30);
}
/// @dev Internal function to update ratio for rebalance.
/// @param debtRatio The minimum debt ratio to start rebalance, multiplied by 1e18.
/// @param bonusRatio The bonus ratio during rebalance, multiplied by 1e9.
function _updateRebalanceRatios(uint256 debtRatio, uint256 bonusRatio) internal {
_checkValueTooLarge(debtRatio, PRECISION);
_checkValueTooLarge(bonusRatio, FEE_PRECISION);
bytes32 data = rebalanceRatioData;
data = data.insertUint(debtRatio, REBALANCE_DEBT_RATIO_OFFSET, 60);
rebalanceRatioData = data.insertUint(bonusRatio, REBALANCE_BONUS_RATIO_OFFSET, 30);
emit UpdateRebalanceRatios(debtRatio, bonusRatio);
}
/// @dev Internal function to get `debtRatio` and `bonusRatio` for liquidate.
/// @return debtRatio The minimum debt ratio to start liquidate, multiplied by 1e18.
/// @return bonusRatio The bonus ratio during liquidate, multiplied by 1e9.
function _getLiquidateRatios() internal view returns (uint256 debtRatio, uint256 bonusRatio) {
bytes32 data = rebalanceRatioData;
debtRatio = data.decodeUint(LIQUIDATE_DEBT_RATIO_OFFSET, 60);
bonusRatio = data.decodeUint(LIQUIDATE_BONUS_RATIO_OFFSET, 30);
}
/// @dev Internal function to update ratio for liquidate.
/// @param debtRatio The minimum debt ratio to start liquidate, multiplied by 1e18.
/// @param bonusRatio The bonus ratio during liquidate, multiplied by 1e9.
function _updateLiquidateRatios(uint256 debtRatio, uint256 bonusRatio) internal {
_checkValueTooLarge(debtRatio, PRECISION);
_checkValueTooLarge(bonusRatio, FEE_PRECISION);
bytes32 data = rebalanceRatioData;
data = data.insertUint(debtRatio, LIQUIDATE_DEBT_RATIO_OFFSET, 60);
rebalanceRatioData = data.insertUint(bonusRatio, LIQUIDATE_BONUS_RATIO_OFFSET, 30);
emit UpdateLiquidateRatios(debtRatio, bonusRatio);
}
/**************************************
* Internal Functions For `indexData` *
**************************************/
/// @dev Internal function to get debt and collateral index.
/// @return debtIndex The index for debt shares.
/// @return collIndex The index for collateral shares.
function _getDebtAndCollateralIndex() internal view returns (uint256 debtIndex, uint256 collIndex) {
bytes32 data = indexData;
debtIndex = data.decodeUint(DEBT_INDEX_OFFSET, 128);
collIndex = data.decodeUint(COLLATERAL_INDEX_OFFSET, 128);
}
/// @dev Internal function to update debt index.
/// @param index The debt index to update.
function _updateDebtIndex(uint256 index) internal {
indexData = indexData.insertUint(index, DEBT_INDEX_OFFSET, 128);
emit DebtIndexSnapshot(index);
}
/// @dev Internal function to update collateral index.
/// @param index The collateral index to update.
function _updateCollateralIndex(uint256 index) internal {
indexData = indexData.insertUint(index, COLLATERAL_INDEX_OFFSET, 128);
emit CollateralIndexSnapshot(index);
}
/**************************************
* Internal Functions For `sharesData` *
**************************************/
/// @dev Internal function to get debt and collateral shares.
/// @return debtShares The total number of debt shares.
/// @return collShares The total number of collateral shares.
function _getDebtAndCollateralShares() internal view returns (uint256 debtShares, uint256 collShares) {
bytes32 data = sharesData;
debtShares = data.decodeUint(DEBT_SHARES_OFFSET, 128);
collShares = data.decodeUint(COLLATERAL_SHARES_OFFSET, 128);
}
/// @dev Internal function to update debt and collateral shares.
/// @param debtShares The debt shares to update.
/// @param collShares The collateral shares to update.
function _updateDebtAndCollateralShares(uint256 debtShares, uint256 collShares) internal {
bytes32 data = sharesData;
data = data.insertUint(debtShares, DEBT_SHARES_OFFSET, 128);
sharesData = data.insertUint(collShares, COLLATERAL_SHARES_OFFSET, 128);
}
/// @dev Internal function to update debt shares.
/// @param shares The debt shares to update.
function _updateDebtShares(uint256 shares) internal {
sharesData = sharesData.insertUint(shares, DEBT_SHARES_OFFSET, 128);
}
/// @dev Internal function to update collateral shares.
/// @param shares The collateral shares to update.
function _updateCollateralShares(uint256 shares) internal {
sharesData = sharesData.insertUint(shares, COLLATERAL_SHARES_OFFSET, 128);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
*/
uint256[40] private __gap;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import { IPool } from "../../interfaces/IPool.sol";
import { IPriceOracle } from "../../price-oracle/interfaces/IPriceOracle.sol";
import { WordCodec } from "../../common/codec/WordCodec.sol";
import { Math } from "../../libraries/Math.sol";
import { TickLogic } from "./TickLogic.sol";
abstract contract PositionLogic is TickLogic {
using WordCodec for bytes32;
/***************
* Constructor *
***************/
function __PositionLogic_init() internal onlyInitializing {
_updateNextPositionId(1);
}
/*************************
* Public View Functions *
*************************/
/// @inheritdoc IPool
function getPosition(uint256 tokenId) public view returns (uint256 rawColls, uint256 rawDebts) {
// compute actual shares
PositionInfo memory position = positionData[tokenId];
rawColls = position.colls;
rawDebts = position.debts;
if (position.nodeId > 0) {
(, uint256 collRatio, uint256 debtRatio) = _getRootNode(position.nodeId);
rawColls = (rawColls * collRatio) >> 60;
rawDebts = (rawDebts * debtRatio) >> 60;
}
// convert shares to actual amount
(uint256 debtIndex, uint256 collIndex) = _getDebtAndCollateralIndex();
rawColls = _convertToRawColl(rawColls, collIndex, Math.Rounding.Down);
rawDebts = _convertToRawDebt(rawDebts, debtIndex, Math.Rounding.Down);
}
/// @inheritdoc IPool
function getPositionDebtRatio(uint256 tokenId) external view returns (uint256 debtRatio) {
(uint256 rawColls, uint256 rawDebts) = getPosition(tokenId);
// price precision and ratio precision are both 1e18, use anchor price here
(uint256 price, , ) = IPriceOracle(priceOracle).getPrice();
if (rawColls == 0) return 0;
return (rawDebts * PRECISION * PRECISION) / (price * rawColls);
}
/// @inheritdoc IPool
function getTotalRawCollaterals() external view returns (uint256) {
(, uint256 totalColls) = _getDebtAndCollateralShares();
(, uint256 collIndex) = _getDebtAndCollateralIndex();
return _convertToRawColl(totalColls, collIndex, Math.Rounding.Down);
}
/// @inheritdoc IPool
function getTotalRawDebts() external view returns (uint256) {
(uint256 totalDebts, ) = _getDebtAndCollateralShares();
(uint256 debtIndex, ) = _getDebtAndCollateralIndex();
return _convertToRawDebt(totalDebts, debtIndex, Math.Rounding.Down);
}
/**********************
* Internal Functions *
**********************/
/// @dev Internal function to mint a new position.
/// @param owner The address of position owner.
/// @return positionId The id of the position.
function _mintPosition(address owner) internal returns (uint32 positionId) {
unchecked {
positionId = _getNextPositionId();
_updateNextPositionId(positionId + 1);
}
positionMetadata[positionId] = bytes32(0).insertUint(block.timestamp, 0, 40);
_mint(owner, positionId);
}
/// @dev Internal function to get and update position.
/// @param tokenId The id of the position.
/// @return position The position struct.
function _getAndUpdatePosition(uint256 tokenId) internal returns (PositionInfo memory position) {
position = positionData[tokenId];
if (position.nodeId > 0) {
(uint256 root, uint256 collRatio, uint256 debtRatio) = _getRootNodeAndCompress(position.nodeId);
position.colls = uint96((position.colls * collRatio) >> 60);
position.debts = uint96((position.debts * debtRatio) >> 60);
position.nodeId = uint32(root);
positionData[tokenId] = position;
}
}
/// @dev Internal function to convert raw collateral amounts to collateral shares.
function _convertToCollShares(
uint256 raw,
uint256 index,
Math.Rounding rounding
) internal pure returns (uint256 shares) {
shares = Math.mulDiv(raw, index, E96, rounding);
}
/// @dev Internal function to convert raw debt amounts to debt shares.
function _convertToDebtShares(
uint256 raw,
uint256 index,
Math.Rounding rounding
) internal pure returns (uint256 shares) {
shares = Math.mulDiv(raw, E96, index, rounding);
}
/// @dev Internal function to convert raw collateral shares to collateral amounts.
function _convertToRawColl(
uint256 shares,
uint256 index,
Math.Rounding rounding
) internal pure returns (uint256 raw) {
raw = Math.mulDiv(shares, E96, index, rounding);
}
/// @dev Internal function to convert raw debt shares to debt amounts.
function _convertToRawDebt(
uint256 shares,
uint256 index,
Math.Rounding rounding
) internal pure returns (uint256 raw) {
raw = Math.mulDiv(shares, index, E96, rounding);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
*/
uint256[50] private __gap;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import { WordCodec } from "../../common/codec/WordCodec.sol";
import { TickBitmap } from "../../libraries/TickBitmap.sol";
import { TickMath } from "../../libraries/TickMath.sol";
import { PoolStorage } from "./PoolStorage.sol";
abstract contract TickLogic is PoolStorage {
using TickBitmap for mapping(int8 => uint256);
using WordCodec for bytes32;
/*************
* Constants *
*************/
/// @dev Below are offsets of each variables in `TickTreeNode.metadata`.
uint256 private constant PARENT_OFFSET = 0;
uint256 private constant TICK_OFFSET = 48;
uint256 private constant COLL_RATIO_OFFSET = 64;
uint256 private constant DEBT_RATIO_OFFSET = 128;
/// @dev Below are offsets of each variables in `TickTreeNode.value`.
uint256 internal constant COLL_SHARE_OFFSET = 0;
uint256 internal constant DEBT_SHARE_OFFSET = 128;
/***************
* Constructor *
***************/
function __TickLogic_init() internal onlyInitializing {
_updateNextTreeNodeId(1);
_updateTopTick(type(int16).min);
}
/**********************
* Internal Functions *
**********************/
/// @dev Internal function to get the root of the given tree node.
/// @param node The id of the given tree node.
/// @return root The root node id.
/// @return collRatio The actual collateral ratio of the given node, multiplied by 2^60.
/// @return debtRatio The actual debt ratio of the given node, multiplied by 2^60.
function _getRootNode(uint256 node) internal view returns (uint256 root, uint256 collRatio, uint256 debtRatio) {
collRatio = E60;
debtRatio = E60;
while (true) {
bytes32 metadata = tickTreeData[node].metadata;
uint256 parent = metadata.decodeUint(PARENT_OFFSET, 48);
collRatio = (collRatio * metadata.decodeUint(COLL_RATIO_OFFSET, 64)) >> 60;
debtRatio = (debtRatio * metadata.decodeUint(DEBT_RATIO_OFFSET, 64)) >> 60;
if (parent == 0) break;
node = parent;
}
root = node;
}
/// @dev Internal function to get the root of the given tree node and compress path.
/// @param node The id of the given tree node.
/// @return root The root node id.
/// @return collRatio The actual collateral ratio of the given node, multiplied by 2^60.
/// @return debtRatio The actual debt ratio of the given node, multiplied by 2^60.
function _getRootNodeAndCompress(uint256 node) internal returns (uint256 root, uint256 collRatio, uint256 debtRatio) {
// @note We can change it to non-recursive version to avoid stack overflow. Normally, the depth should be `log(n)`,
// where `n` is the total number of tree nodes. So we don't need to worry much about this.
bytes32 metadata = tickTreeData[node].metadata;
uint256 parent = metadata.decodeUint(PARENT_OFFSET, 48);
collRatio = metadata.decodeUint(COLL_RATIO_OFFSET, 64);
debtRatio = metadata.decodeUint(DEBT_RATIO_OFFSET, 64);
if (parent == 0) {
root = node;
} else {
uint256 collRatioCompressed;
uint256 debtRatioCompressed;
(root, collRatioCompressed, debtRatioCompressed) = _getRootNodeAndCompress(parent);
collRatio = (collRatio * collRatioCompressed) >> 60;
debtRatio = (debtRatio * debtRatioCompressed) >> 60;
metadata = metadata.insertUint(root, PARENT_OFFSET, 48);
metadata = metadata.insertUint(collRatio, COLL_RATIO_OFFSET, 64);
metadata = metadata.insertUint(debtRatio, DEBT_RATIO_OFFSET, 64);
tickTreeData[node].metadata = metadata;
}
}
/// @dev Internal function to create a new tree node.
/// @param tick The tick where this tree node belongs to.
/// @return node The created tree node id.
function _newTickTreeNode(int16 tick) internal returns (uint48 node) {
unchecked {
node = _getNextTreeNodeId();
_updateNextTreeNodeId(node + 1);
}
tickData[tick] = node;
bytes32 metadata = bytes32(0);
metadata = metadata.insertInt(tick, TICK_OFFSET, 16); // set tick
metadata = metadata.insertUint(E60, COLL_RATIO_OFFSET, 64); // set coll ratio
metadata = metadata.insertUint(E60, DEBT_RATIO_OFFSET, 64); // set debt ratio
tickTreeData[node].metadata = metadata;
}
/// @dev Internal function to find first tick such that `TickMath.getRatioAtTick(tick) >= debts/colls`.
/// @param colls The collateral shares.
/// @param debts The debt shares.
/// @return tick The value of found first tick.
function _getTick(uint256 colls, uint256 debts) internal pure returns (int256 tick) {
uint256 ratio = (debts * TickMath.ZERO_TICK_SCALED_RATIO) / colls;
uint256 ratioAtTick;
(tick, ratioAtTick) = TickMath.getTickAtRatio(ratio);
if (ratio != ratioAtTick) {
tick++;
ratio = (ratioAtTick * 10015) / 10000;
}
}
/// @dev Internal function to retrieve or create a tree node.
/// @param tick The tick where this tree node belongs to.
/// @return node The tree node id.
function _getOrCreateTickNode(int256 tick) internal returns (uint48 node) {
node = tickData[tick];
if (node == 0) {
node = _newTickTreeNode(int16(tick));
}
}
/// @dev Internal function to add position collaterals and debts to some tick.
/// @param colls The collateral shares.
/// @param debts The debt shares.
/// @param checkDebts Whether we should check the value of `debts`.
/// @return tick The tick where this position belongs to.
/// @return node The corresponding tree node id for this tick.
function _addPositionToTick(
uint256 colls,
uint256 debts,
bool checkDebts
) internal returns (int256 tick, uint48 node) {
if (debts > 0) {
if (checkDebts && int256(debts) < MIN_DEBT) {
revert ErrorDebtTooSmall();
}
tick = _getTick(colls, debts);
node = _getOrCreateTickNode(tick);
bytes32 value = tickTreeData[node].value;
uint256 newColls = value.decodeUint(COLL_SHARE_OFFSET, 128) + colls;
uint256 newDebts = value.decodeUint(DEBT_SHARE_OFFSET, 128) + debts;
value = value.insertUint(newColls, COLL_SHARE_OFFSET, 128);
value = value.insertUint(newDebts, DEBT_SHARE_OFFSET, 128);
tickTreeData[node].value = value;
if (newDebts == debts) {
tickBitmap.flipTick(int16(tick));
}
// update top tick
if (tick > _getTopTick()) {
_updateTopTick(int16(tick));
}
}
}
/// @dev Internal function to remove position from tick.
/// @param position The position struct to remove.
function _removePositionFromTick(PositionInfo memory position) internal {
if (position.nodeId == 0) return;
bytes32 value = tickTreeData[position.nodeId].value;
uint256 oldDebts = value.decodeUint(DEBT_SHARE_OFFSET, 128);
uint256 newColls = value.decodeUint(COLL_SHARE_OFFSET, 128) - position.colls;
uint256 newDebts = oldDebts - position.debts;
value = value.insertUint(newColls, COLL_SHARE_OFFSET, 128);
value = value.insertUint(newDebts, DEBT_SHARE_OFFSET, 128);
tickTreeData[position.nodeId].value = value;
if (newDebts == 0 && oldDebts > 0) {
int16 tick = int16(tickTreeData[position.nodeId].metadata.decodeInt(TICK_OFFSET, 16));
tickBitmap.flipTick(tick);
// top tick gone, update it to new one
int16 topTick = _getTopTick();
if (topTick == tick) {
_resetTopTick(topTick);
}
}
}
/// @dev Internal function to liquidate a tick.
/// The caller make sure `max(liquidatedColl, liquidatedDebt) > 0`.
///
/// @param tick The id of tick to liquidate.
/// @param liquidatedColl The amount of collateral shares liquidated.
/// @param liquidatedDebt The amount of debt shares liquidated.
function _liquidateTick(int16 tick, uint256 liquidatedColl, uint256 liquidatedDebt, uint256 price) internal {
uint48 node = tickData[tick];
// create new tree node for this tick
_newTickTreeNode(tick);
// clear bitmap first, and it will be updated later if needed.
tickBitmap.flipTick(tick);
bytes32 value = tickTreeData[node].value;
bytes32 metadata = tickTreeData[node].metadata;
uint256 tickColl = value.decodeUint(COLL_SHARE_OFFSET, 128);
uint256 tickDebt = value.decodeUint(DEBT_SHARE_OFFSET, 128);
uint256 tickCollAfter = tickColl - liquidatedColl;
uint256 tickDebtAfter = tickDebt - liquidatedDebt;
uint256 collRatio = (tickCollAfter * E60) / tickColl;
uint256 debtRatio = (tickDebtAfter * E60) / tickDebt;
// update metadata
metadata = metadata.insertUint(collRatio, COLL_RATIO_OFFSET, 64);
metadata = metadata.insertUint(debtRatio, DEBT_RATIO_OFFSET, 64);
int256 newTick = type(int256).min;
if (tickDebtAfter > 0) {
// partial liquidated, move funds to another tick
uint48 parentNode;
(newTick, parentNode) = _addPositionToTick(tickCollAfter, tickDebtAfter, false);
metadata = metadata.insertUint(parentNode, PARENT_OFFSET, 48);
}
emit TickMovement(tick, int16(newTick), tickCollAfter, tickDebtAfter, price);
// top tick liquidated, update it to new one
int16 topTick = _getTopTick();
if (topTick == tick && newTick != int256(tick)) {
_resetTopTick(topTick);
}
tickTreeData[node].metadata = metadata;
}
/// @dev Internal function to reset top tick.
/// @param oldTopTick The previous value of top tick.
function _resetTopTick(int16 oldTopTick) internal {
while (oldTopTick > type(int16).min) {
bool hasDebt;
(oldTopTick, hasDebt) = tickBitmap.nextDebtPositionWithinOneWord(oldTopTick - 1);
if (hasDebt) break;
}
_updateTopTick(oldTopTick);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
*/
uint256[50] private __gap;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import { IFxUSDRegeneracy } from "../interfaces/IFxUSDRegeneracy.sol";
import { IPool } from "../interfaces/IPool.sol";
import { IPoolManager } from "../interfaces/IPoolManager.sol";
import { IReservePool } from "../interfaces/IReservePool.sol";
import { IRewardSplitter } from "../interfaces/IRewardSplitter.sol";
import { IFxUSDBasePool } from "../interfaces/IFxUSDBasePool.sol";
import { IRateProvider } from "../rate-provider/interfaces/IRateProvider.sol";
import { WordCodec } from "../common/codec/WordCodec.sol";
import { AssetManagement } from "../fund/AssetManagement.sol";
import { FlashLoans } from "./FlashLoans.sol";
import { ProtocolFees } from "./ProtocolFees.sol";
contract PoolManager is ProtocolFees, FlashLoans, AssetManagement, IPoolManager {
using EnumerableSet for EnumerableSet.AddressSet;
using SafeERC20 for IERC20;
using WordCodec for bytes32;
/**********
* Errors *
**********/
error ErrorCollateralExceedCapacity();
error ErrorDebtExceedCapacity();
error ErrorPoolNotRegistered();
error ErrorInvalidPool();
error ErrorCallerNotFxUSDSave();
error ErrorRedeemExceedBalance();
error ErrorInsufficientRedeemedCollateral();
/*************
* Constants *
*************/
/// @dev The role for emergency operations.
bytes32 public constant EMERGENCY_ROLE = keccak256("EMERGENCY_ROLE");
/// @dev The role for harvester
bytes32 public constant HARVESTER_ROLE = keccak256("HARVESTER_ROLE");
/// @dev The precision for token rate.
uint256 internal constant PRECISION = 1e18;
/// @dev The precision for token rate.
int256 internal constant PRECISION_I256 = 1e18;
uint256 private constant COLLATERAL_CAPACITY_OFFSET = 0;
uint256 private constant COLLATERAL_BALANCE_OFFSET = 85;
uint256 private constant RAW_COLLATERAL_BALANCE_OFFSET = 170;
uint256 private constant COLLATERAL_DATA_BITS = 85;
uint256 private constant RAW_COLLATERAL_DATA_BITS = 86;
uint256 private constant DEBT_CAPACITY_OFFSET = 0;
uint256 private constant DEBT_BALANCE_OFFSET = 96;
uint256 private constant DEBT_DATA_BITS = 96;
/***********************
* Immutable Variables *
***********************/
/// @inheritdoc IPoolManager
address public immutable fxUSD;
/// @inheritdoc IPoolManager
address public immutable fxBASE;
/// @inheritdoc IPoolManager
address public immutable pegKeeper;
/***********
* Structs *
***********/
/// @dev The struct for pool information.
/// @param collateralData The data for collateral.
/// ```text
/// * Field Bits Index Comments
/// * collateral capacity 85 0 The maximum allowed amount of collateral tokens.
/// * collateral balance 85 85 The amount of collateral tokens deposited.
/// * raw collateral balance 86 170 The amount of raw collateral tokens (without token rate) managed in pool.
/// ```
/// @param debtData The data for debt.
/// ```text
/// * Field Bits Index Comments
/// * debt capacity 96 0 The maximum allowed amount of debt tokens.
/// * debt balance 96 96 The amount of debt tokens borrowed.
/// * reserved 64 192 Reserved data.
/// ```
struct PoolStruct {
bytes32 collateralData;
bytes32 debtData;
}
/// @dev The struct for token rate information.
/// @param scalar The token scalar to reach 18 decimals.
/// @param rateProvider The address of token rate provider.
struct TokenRate {
uint96 scalar;
address rateProvider;
}
/// @dev Memory variables for liquidate or rebalance.
/// @param stablePrice The USD price of stable token (with scalar).
/// @param scalingFactor The scaling factor for collateral token.
/// @param collateralToken The address of collateral token.
/// @param rawColls The amount of raw collateral tokens liquidated or rebalanced, including bonus.
/// @param bonusRawColls The amount of raw collateral tokens used as bonus.
/// @param rawDebts The amount of raw debt tokens liquidated or rebalanced.
struct LiquidateOrRebalanceMemoryVar {
uint256 stablePrice;
uint256 scalingFactor;
address collateralToken;
uint256 rawColls;
uint256 bonusRawColls;
uint256 rawDebts;
}
/*********************
* Storage Variables *
*********************/
/// @dev The list of registered pools.
EnumerableSet.AddressSet private pools;
/// @notice Mapping to pool address to pool struct.
mapping(address => PoolStruct) private poolInfo;
/// @notice Mapping from pool address to rewards splitter.
mapping(address => address) public rewardSplitter;
/// @notice Mapping from token address to token rate struct.
mapping(address => TokenRate) public tokenRates;
/// @notice The threshold for permissioned liquidate or rebalance.
uint256 public permissionedLiquidationThreshold;
/*************
* Modifiers *
*************/
modifier onlyRegisteredPool(address pool) {
if (!pools.contains(pool)) revert ErrorPoolNotRegistered();
_;
}
modifier onlyFxUSDSave() {
if (_msgSender() != fxBASE) {
// allow permissonless rebalance or liquidate when insufficient fxUSD/USDC in fxBASE.
uint256 totalYieldToken = IFxUSDBasePool(fxBASE).totalYieldToken();
uint256 totalStableToken = IFxUSDBasePool(fxBASE).totalStableToken();
uint256 price = IFxUSDBasePool(fxBASE).getStableTokenPriceWithScale();
if (totalYieldToken + (totalStableToken * price) / PRECISION >= permissionedLiquidationThreshold) {
revert ErrorCallerNotFxUSDSave();
}
}
_;
}
/***************
* Constructor *
***************/
constructor(address _fxUSD, address _fxBASE, address _pegKeeper) {
fxUSD = _fxUSD;
fxBASE = _fxBASE;
pegKeeper = _pegKeeper;
}
function initialize(
address admin,
uint256 _expenseRatio,
uint256 _harvesterRatio,
uint256 _flashLoanFeeRatio,
address _treasury,
address _revenuePool,
address _reservePool
) external initializer {
__Context_init();
__AccessControl_init();
__ERC165_init();
_grantRole(DEFAULT_ADMIN_ROLE, admin);
__ProtocolFees_init(_expenseRatio, _harvesterRatio, _flashLoanFeeRatio, _treasury, _revenuePool, _reservePool);
__FlashLoans_init();
// default 10000 fxUSD
_updateThreshold(10000 ether);
}
function initializeV2(address pool) external onlyRegisteredPool(pool) reinitializer(2) {
// fix state of pool
address collateralToken = IPool(pool).collateralToken();
uint256 scalingFactor = _getTokenScalingFactor(collateralToken);
uint256 rawCollaterals = IPool(pool).getTotalRawCollaterals();
uint256 collaterals = _scaleDown(rawCollaterals, scalingFactor);
bytes32 data = poolInfo[pool].collateralData;
data = data.insertUint(collaterals, COLLATERAL_BALANCE_OFFSET, COLLATERAL_DATA_BITS);
poolInfo[pool].collateralData = data.insertUint(
rawCollaterals,
RAW_COLLATERAL_BALANCE_OFFSET,
RAW_COLLATERAL_DATA_BITS
);
}
/*************************
* Public View Functions *
*************************/
/// @notice Return the pool information.
/// @param pool The address of pool to query.
/// @return collateralCapacity The maximum allowed amount of collateral tokens.
/// @return collateralBalance The amount of collateral tokens deposited.
/// @return rawCollateral The amount of raw collateral tokens deposited.
/// @return debtCapacity The maximum allowed amount of debt tokens.
/// @return debtBalance The amount of debt tokens borrowed.
function getPoolInfo(
address pool
)
external
view
returns (
uint256 collateralCapacity,
uint256 collateralBalance,
uint256 rawCollateral,
uint256 debtCapacity,
uint256 debtBalance
)
{
bytes32 data = poolInfo[pool].collateralData;
collateralCapacity = data.decodeUint(COLLATERAL_CAPACITY_OFFSET, COLLATERAL_DATA_BITS);
collateralBalance = data.decodeUint(COLLATERAL_BALANCE_OFFSET, COLLATERAL_DATA_BITS);
rawCollateral = data.decodeUint(RAW_COLLATERAL_BALANCE_OFFSET, RAW_COLLATERAL_DATA_BITS);
data = poolInfo[pool].debtData;
debtCapacity = data.decodeUint(DEBT_CAPACITY_OFFSET, DEBT_DATA_BITS);
debtBalance = data.decodeUint(DEBT_BALANCE_OFFSET, DEBT_DATA_BITS);
}
/****************************
* Public Mutated Functions *
****************************/
/// @inheritdoc IPoolManager
function operate(
address pool,
uint256 positionId,
int256 newColl,
int256 newDebt
) external onlyRegisteredPool(pool) nonReentrant whenNotPaused returns (uint256) {
address collateralToken = IPool(pool).collateralToken();
uint256 scalingFactor = _getTokenScalingFactor(collateralToken);
int256 newRawColl = newColl;
if (newRawColl != type(int256).min) {
newRawColl = _scaleUp(newRawColl, scalingFactor);
}
uint256 rawProtocolFees;
// the `newRawColl` is the result without `protocolFees`
(positionId, newRawColl, newDebt, rawProtocolFees) = IPool(pool).operate(
positionId,
newRawColl,
newDebt,
_msgSender()
);
newColl = _scaleDown(newRawColl, scalingFactor);
uint256 protocolFees = _scaleDown(rawProtocolFees, scalingFactor);
_changePoolDebts(pool, newDebt);
if (newRawColl > 0) {
_accumulatePoolOpenFee(pool, protocolFees);
_changePoolCollateral(pool, newColl, newRawColl);
IERC20(collateralToken).safeTransferFrom(_msgSender(), address(this), uint256(newColl) + protocolFees);
} else if (newRawColl < 0) {
_accumulatePoolCloseFee(pool, protocolFees);
_changePoolCollateral(pool, newColl - int256(protocolFees), newRawColl - int256(rawProtocolFees));
_transferOut(collateralToken, uint256(-newColl), _msgSender());
}
if (newDebt > 0) {
IFxUSDRegeneracy(fxUSD).mint(_msgSender(), uint256(newDebt));
} else if (newDebt < 0) {
IFxUSDRegeneracy(fxUSD).burn(_msgSender(), uint256(-newDebt));
}
emit Operate(pool, positionId, newColl, newDebt, protocolFees);
return positionId;
}
/// @inheritdoc IPoolManager
function redeem(
address pool,
uint256 debts,
uint256 minColls
) external onlyRegisteredPool(pool) nonReentrant whenNotPaused returns (uint256 colls) {
if (debts > IERC20(fxUSD).balanceOf(_msgSender())) {
revert ErrorRedeemExceedBalance();
}
uint256 rawColls = IPool(pool).redeem(debts);
address collateralToken = IPool(pool).collateralToken();
uint256 scalingFactor = _getTokenScalingFactor(collateralToken);
colls = _scaleDown(rawColls, scalingFactor);
_changePoolCollateral(pool, -int256(colls), -int256(rawColls));
_changePoolDebts(pool, -int256(debts));
uint256 protocolFees = (colls * getRedeemFeeRatio()) / FEE_PRECISION;
_accumulatePoolMiscFee(pool, protocolFees);
colls -= protocolFees;
if (colls < minColls) revert ErrorInsufficientRedeemedCollateral();
_transferOut(collateralToken, colls, _msgSender());
IFxUSDRegeneracy(fxUSD).burn(_msgSender(), debts);
emit Redeem(pool, colls, debts, protocolFees);
}
/// @inheritdoc IPoolManager
function rebalance(
address pool,
address receiver,
int16 tick,
uint256 maxFxUSD,
uint256 maxStable
)
external
onlyRegisteredPool(pool)
nonReentrant
whenNotPaused
onlyFxUSDSave
returns (uint256 colls, uint256 fxUSDUsed, uint256 stableUsed)
{
LiquidateOrRebalanceMemoryVar memory op = _beforeRebalanceOrLiquidate(pool);
IPool.RebalanceResult memory result = IPool(pool).rebalance(tick, maxFxUSD + _scaleUp(maxStable, op.stablePrice));
op.rawColls = result.rawColls + result.bonusRawColls;
op.bonusRawColls = result.bonusRawColls;
op.rawDebts = result.rawDebts;
(colls, fxUSDUsed, stableUsed) = _afterRebalanceOrLiquidate(pool, maxFxUSD, op, receiver);
emit RebalanceTick(pool, tick, colls, fxUSDUsed, stableUsed);
}
/// @inheritdoc IPoolManager
function rebalance(
address pool,
address receiver,
uint256 maxFxUSD,
uint256 maxStable
)
external
onlyRegisteredPool(pool)
nonReentrant
whenNotPaused
onlyFxUSDSave
returns (uint256 colls, uint256 fxUSDUsed, uint256 stableUsed)
{
LiquidateOrRebalanceMemoryVar memory op = _beforeRebalanceOrLiquidate(pool);
IPool.RebalanceResult memory result = IPool(pool).rebalance(maxFxUSD + _scaleUp(maxStable, op.stablePrice));
op.rawColls = result.rawColls + result.bonusRawColls;
op.bonusRawColls = result.bonusRawColls;
op.rawDebts = result.rawDebts;
(colls, fxUSDUsed, stableUsed) = _afterRebalanceOrLiquidate(pool, maxFxUSD, op, receiver);
emit Rebalance(pool, colls, fxUSDUsed, stableUsed);
}
/// @inheritdoc IPoolManager
function liquidate(
address pool,
address receiver,
uint256 maxFxUSD,
uint256 maxStable
)
external
onlyRegisteredPool(pool)
nonReentrant
whenNotPaused
onlyFxUSDSave
returns (uint256 colls, uint256 fxUSDUsed, uint256 stableUsed)
{
LiquidateOrRebalanceMemoryVar memory op = _beforeRebalanceOrLiquidate(pool);
{
IPool.LiquidateResult memory result;
uint256 reservedRawColls = IReservePool(reservePool).getBalance(op.collateralToken);
reservedRawColls = _scaleUp(reservedRawColls, op.scalingFactor);
result = IPool(pool).liquidate(maxFxUSD + _scaleUp(maxStable, op.stablePrice), reservedRawColls);
op.rawColls = result.rawColls + result.bonusRawColls;
op.bonusRawColls = result.bonusRawColls;
op.rawDebts = result.rawDebts;
// take bonus or shortfall from reserve pool
uint256 bonusFromReserve = result.bonusFromReserve;
if (bonusFromReserve > 0) {
bonusFromReserve = _scaleDown(result.bonusFromReserve, op.scalingFactor);
IReservePool(reservePool).requestBonus(IPool(pool).collateralToken(), address(this), bonusFromReserve);
// increase pool reserve first
_changePoolCollateral(pool, int256(bonusFromReserve), int256(result.bonusFromReserve));
}
}
(colls, fxUSDUsed, stableUsed) = _afterRebalanceOrLiquidate(pool, maxFxUSD, op, receiver);
emit Liquidate(pool, colls, fxUSDUsed, stableUsed);
}
/// @inheritdoc IPoolManager
function harvest(
address pool
)
external
onlyRegisteredPool(pool)
onlyRole(HARVESTER_ROLE)
nonReentrant
returns (uint256 amountRewards, uint256 amountFunding)
{
address collateralToken = IPool(pool).collateralToken();
uint256 scalingFactor = _getTokenScalingFactor(collateralToken);
uint256 collateralRecorded;
uint256 rawCollateralRecorded;
{
bytes32 data = poolInfo[pool].collateralData;
collateralRecorded = data.decodeUint(COLLATERAL_BALANCE_OFFSET, COLLATERAL_DATA_BITS);
rawCollateralRecorded = data.decodeUint(RAW_COLLATERAL_BALANCE_OFFSET, RAW_COLLATERAL_DATA_BITS);
}
uint256 performanceFee;
uint256 harvestBounty;
uint256 pendingRewards;
// compute funding
uint256 rawCollateral = IPool(pool).getTotalRawCollaterals();
if (rawCollateralRecorded > rawCollateral) {
unchecked {
amountFunding = _scaleDown(rawCollateralRecorded - rawCollateral, scalingFactor);
_changePoolCollateral(pool, -int256(amountFunding), -int256(rawCollateralRecorded - rawCollateral));
performanceFee = (getFundingExpenseRatio() * amountFunding) / FEE_PRECISION;
harvestBounty = (getHarvesterRatio() * amountFunding) / FEE_PRECISION;
pendingRewards = amountFunding - harvestBounty - performanceFee;
}
// recorded data changed, update local cache
{
bytes32 data = poolInfo[pool].collateralData;
collateralRecorded = data.decodeUint(COLLATERAL_BALANCE_OFFSET, COLLATERAL_DATA_BITS);
rawCollateralRecorded = data.decodeUint(RAW_COLLATERAL_BALANCE_OFFSET, RAW_COLLATERAL_DATA_BITS);
}
}
// compute rewards
rawCollateral = _scaleUp(collateralRecorded, scalingFactor);
if (rawCollateral > rawCollateralRecorded) {
unchecked {
amountRewards = _scaleDown(rawCollateral - rawCollateralRecorded, scalingFactor);
_changePoolCollateral(pool, -int256(amountRewards), 0);
uint256 performanceFeeRewards = (getRewardsExpenseRatio() * amountRewards) / FEE_PRECISION;
uint256 harvestBountyRewards = (getHarvesterRatio() * amountRewards) / FEE_PRECISION;
pendingRewards += amountRewards - harvestBountyRewards - performanceFeeRewards;
performanceFee += performanceFeeRewards;
harvestBounty += harvestBountyRewards;
}
}
// transfer performance fee to treasury
if (performanceFee > 0) {
_transferOut(collateralToken, performanceFee, treasury);
}
// transfer various fees to revenue pool
_takeAccumulatedPoolFee(pool);
// transfer harvest bounty
if (harvestBounty > 0) {
_transferOut(collateralToken, harvestBounty, _msgSender());
}
// transfer rewards for fxBASE
if (pendingRewards > 0) {
address splitter = rewardSplitter[pool];
_transferOut(collateralToken, pendingRewards, splitter);
IRewardSplitter(splitter).split(collateralToken);
}
emit Harvest(_msgSender(), pool, amountRewards, amountFunding, performanceFee, harvestBounty);
}
/************************
* Restricted Functions *
************************/
/// @notice Pause or unpause the system.
/// @param status The pause status to update.
function setPause(bool status) external onlyRole(EMERGENCY_ROLE) {
if (status) _pause();
else _unpause();
}
/// @notice Register a new pool with reward splitter.
/// @param pool The address of pool.
/// @param splitter The address of reward splitter.
function registerPool(
address pool,
address splitter,
uint96 collateralCapacity,
uint96 debtCapacity
) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (fxUSD != IPool(pool).fxUSD()) revert ErrorInvalidPool();
if (pools.add(pool)) {
emit RegisterPool(pool);
_updateRewardSplitter(pool, splitter);
_updatePoolCapacity(pool, collateralCapacity, debtCapacity);
}
}
/// @notice Update rate provider for the given token.
/// @param token The address of the token.
/// @param provider The address of corresponding rate provider.
function updateRateProvider(address token, address provider) external onlyRole(DEFAULT_ADMIN_ROLE) {
uint256 scale = 10 ** (18 - IERC20Metadata(token).decimals());
tokenRates[token] = TokenRate(uint96(scale), provider);
emit UpdateTokenRate(token, scale, provider);
}
/// @notice Update the address of reward splitter for the given pool.
/// @param pool The address of the pool.
/// @param newSplitter The address of reward splitter.
function updateRewardSplitter(
address pool,
address newSplitter
) external onlyRole(DEFAULT_ADMIN_ROLE) onlyRegisteredPool(pool) {
_updateRewardSplitter(pool, newSplitter);
}
/// @notice Update the pool capacity.
/// @param pool The address of fx pool.
/// @param collateralCapacity The capacity for collateral token.
/// @param debtCapacity The capacity for debt token.
function updatePoolCapacity(
address pool,
uint96 collateralCapacity,
uint96 debtCapacity
) external onlyRole(DEFAULT_ADMIN_ROLE) onlyRegisteredPool(pool) {
_updatePoolCapacity(pool, collateralCapacity, debtCapacity);
}
/// @notice Update threshold for permissionless liquidation.
/// @param newThreshold The value of new threshold.
function updateThreshold(uint256 newThreshold) external onlyRole(DEFAULT_ADMIN_ROLE) {
_updateThreshold(newThreshold);
}
/**********************
* Internal Functions *
**********************/
/// @dev Internal function to update the address of reward splitter for the given pool.
/// @param pool The address of the pool.
/// @param newSplitter The address of reward splitter.
function _updateRewardSplitter(address pool, address newSplitter) internal {
address oldSplitter = rewardSplitter[pool];
rewardSplitter[pool] = newSplitter;
emit UpdateRewardSplitter(pool, oldSplitter, newSplitter);
}
/// @dev Internal function to update the pool capacity.
/// @param pool The address of fx pool.
/// @param collateralCapacity The capacity for collateral token.
/// @param debtCapacity The capacity for debt token.
function _updatePoolCapacity(address pool, uint96 collateralCapacity, uint96 debtCapacity) internal {
poolInfo[pool].collateralData = poolInfo[pool].collateralData.insertUint(
collateralCapacity,
COLLATERAL_CAPACITY_OFFSET,
COLLATERAL_DATA_BITS
);
poolInfo[pool].debtData = poolInfo[pool].debtData.insertUint(debtCapacity, DEBT_CAPACITY_OFFSET, DEBT_DATA_BITS);
emit UpdatePoolCapacity(pool, collateralCapacity, debtCapacity);
}
/// @dev Internal function to update threshold for permissionless liquidation.
/// @param newThreshold The value of new threshold.
function _updateThreshold(uint256 newThreshold) internal {
uint256 oldThreshold = permissionedLiquidationThreshold;
permissionedLiquidationThreshold = newThreshold;
emit UpdatePermissionedLiquidationThreshold(oldThreshold, newThreshold);
}
/// @dev Internal function to scaler up for `uint256`.
function _scaleUp(uint256 value, uint256 scale) internal pure returns (uint256) {
return (value * scale) / PRECISION;
}
/// @dev Internal function to scaler up for `int256`.
function _scaleUp(int256 value, uint256 scale) internal pure returns (int256) {
return (value * int256(scale)) / PRECISION_I256;
}
/// @dev Internal function to scaler down for `uint256`, rounding down.
function _scaleDown(uint256 value, uint256 scale) internal pure returns (uint256) {
return (value * PRECISION) / scale;
}
/// @dev Internal function to scaler down for `uint256`, rounding up.
function _scaleDownRoundingUp(uint256 value, uint256 scale) internal pure returns (uint256) {
return (value * PRECISION + scale - 1) / scale;
}
/// @dev Internal function to scaler down for `int256`.
function _scaleDown(int256 value, uint256 scale) internal pure returns (int256) {
return (value * PRECISION_I256) / int256(scale);
}
/// @dev Internal function to prepare variables before rebalance or liquidate.
/// @param pool The address of pool to liquidate or rebalance.
function _beforeRebalanceOrLiquidate(address pool) internal view returns (LiquidateOrRebalanceMemoryVar memory op) {
op.stablePrice = IFxUSDBasePool(fxBASE).getStableTokenPriceWithScale();
op.collateralToken = IPool(pool).collateralToken();
op.scalingFactor = _getTokenScalingFactor(op.collateralToken);
}
/// @dev Internal function to do actions after rebalance or liquidate.
/// @param pool The address of pool to liquidate or rebalance.
/// @param maxFxUSD The maximum amount of fxUSD can be used.
/// @param op The memory helper variable.
/// @param receiver The address collateral token receiver.
/// @return colls The actual amount of collateral token rebalanced or liquidated.
/// @return fxUSDUsed The amount of fxUSD used.
/// @return stableUsed The amount of stable token (a.k.a USDC) used.
function _afterRebalanceOrLiquidate(
address pool,
uint256 maxFxUSD,
LiquidateOrRebalanceMemoryVar memory op,
address receiver
) internal returns (uint256 colls, uint256 fxUSDUsed, uint256 stableUsed) {
colls = _scaleDown(op.rawColls, op.scalingFactor);
_changePoolCollateral(pool, -int256(colls), -int256(op.rawColls));
_changePoolDebts(pool, -int256(op.rawDebts));
// burn fxUSD or transfer USDC
fxUSDUsed = op.rawDebts;
if (fxUSDUsed > maxFxUSD) {
// rounding up here
stableUsed = _scaleDownRoundingUp(fxUSDUsed - maxFxUSD, op.stablePrice);
fxUSDUsed = maxFxUSD;
}
if (fxUSDUsed > 0) {
IFxUSDRegeneracy(fxUSD).burn(_msgSender(), fxUSDUsed);
}
if (stableUsed > 0) {
IERC20(IFxUSDBasePool(fxBASE).stableToken()).safeTransferFrom(_msgSender(), fxUSD, stableUsed);
IFxUSDRegeneracy(fxUSD).onRebalanceWithStable(stableUsed, op.rawDebts - maxFxUSD);
}
// transfer collateral
uint256 protocolRevenue = (_scaleDown(op.bonusRawColls, op.scalingFactor) * getLiquidationExpenseRatio()) /
FEE_PRECISION;
_accumulatePoolMiscFee(pool, protocolRevenue);
unchecked {
colls -= protocolRevenue;
}
_transferOut(op.collateralToken, colls, receiver);
}
/// @dev Internal function to update collateral balance.
function _changePoolCollateral(address pool, int256 delta, int256 rawDelta) internal {
bytes32 data = poolInfo[pool].collateralData;
uint256 capacity = data.decodeUint(COLLATERAL_CAPACITY_OFFSET, COLLATERAL_DATA_BITS);
uint256 balance = uint256(int256(data.decodeUint(COLLATERAL_BALANCE_OFFSET, COLLATERAL_DATA_BITS)) + delta);
if (balance > capacity) revert ErrorCollateralExceedCapacity();
data = data.insertUint(balance, COLLATERAL_BALANCE_OFFSET, COLLATERAL_DATA_BITS);
balance = uint256(int256(data.decodeUint(RAW_COLLATERAL_BALANCE_OFFSET, RAW_COLLATERAL_DATA_BITS)) + rawDelta);
poolInfo[pool].collateralData = data.insertUint(balance, RAW_COLLATERAL_BALANCE_OFFSET, RAW_COLLATERAL_DATA_BITS);
}
/// @dev Internal function to update debt balance.
function _changePoolDebts(address pool, int256 delta) internal {
bytes32 data = poolInfo[pool].debtData;
uint256 capacity = data.decodeUint(DEBT_CAPACITY_OFFSET, DEBT_DATA_BITS);
uint256 balance = uint256(int256(data.decodeUint(DEBT_BALANCE_OFFSET, DEBT_DATA_BITS)) + delta);
if (balance > capacity) revert ErrorDebtExceedCapacity();
poolInfo[pool].debtData = data.insertUint(balance, DEBT_BALANCE_OFFSET, DEBT_DATA_BITS);
}
/// @dev Internal function to get token scaling factor.
function _getTokenScalingFactor(address token) internal view returns (uint256 value) {
TokenRate memory rate = tokenRates[token];
value = rate.scalar;
unchecked {
if (rate.rateProvider != address(0)) {
value *= IRateProvider(rate.rateProvider).getRate();
} else {
value *= PRECISION;
}
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { AccessControlUpgradeable } from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import { PausableUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import { IPool } from "../interfaces/IPool.sol";
import { IProtocolFees } from "../interfaces/IProtocolFees.sol";
import { WordCodec } from "../common/codec/WordCodec.sol";
abstract contract ProtocolFees is AccessControlUpgradeable, PausableUpgradeable, IProtocolFees {
using SafeERC20 for IERC20;
using WordCodec for bytes32;
/**********
* Errors *
**********/
/// @dev Thrown when the given address is zero.
error ErrorZeroAddress();
/// @dev Thrown when the expense ratio exceeds `MAX_EXPENSE_RATIO`.
error ErrorExpenseRatioTooLarge();
/// @dev Thrown when the harvester ratio exceeds `MAX_HARVESTER_RATIO`.
error ErrorHarvesterRatioTooLarge();
/// @dev Thrown when the flash loan fee ratio exceeds `MAX_FLASH_LOAN_FEE_RATIO`.
error ErrorFlashLoanFeeRatioTooLarge();
/// @dev Thrown when the redeem fee ratio exceeds `MAX_REDEEM_FEE_RATIO`.
error ErrorRedeemFeeRatioTooLarge();
/*************
* Constants *
*************/
/// @dev The maximum expense ratio.
uint256 private constant MAX_EXPENSE_RATIO = 5e8; // 50%
/// @dev The maximum harvester ratio.
uint256 private constant MAX_HARVESTER_RATIO = 2e8; // 20%
/// @dev The maximum flash loan fee ratio.
uint256 private constant MAX_FLASH_LOAN_FEE_RATIO = 1e8; // 10%
/// @dev The maximum redeem fee ratio.
uint256 private constant MAX_REDEEM_FEE_RATIO = 1e8; // 10%
/// @dev The offset of general expense ratio in `_miscData`.
uint256 private constant REWARDS_EXPENSE_RATIO_OFFSET = 0;
/// @dev The offset of harvester ratio in `_miscData`.
uint256 private constant HARVESTER_RATIO_OFFSET = 30;
/// @dev The offset of flash loan ratio in `_miscData`.
uint256 private constant FLASH_LOAN_RATIO_OFFSET = 60;
/// @dev The offset of redeem fee ratio in `_miscData`.
uint256 private constant REDEEM_FEE_RATIO_OFFSET = 90;
/// @dev The offset of funding expense ratio in `_miscData`.
uint256 private constant FUNDING_EXPENSE_RATIO_OFFSET = 120;
/// @dev The offset of liquidation expense ratio in `_miscData`.
uint256 private constant LIQUIDATION_EXPENSE_RATIO_OFFSET = 150;
/// @dev The precision used to compute fees.
uint256 internal constant FEE_PRECISION = 1e9;
/*************
* Variables *
*************/
/// @dev `_miscData` is a storage slot that can be used to store unrelated pieces of information.
/// All pools store the *expense ratio*, *harvester ratio* and *withdraw fee percentage*, but
/// the `miscData`can be extended to store more pieces of information.
///
/// The *expense ratio* is stored in the first most significant 32 bits, and the *harvester ratio* is
/// stored in the next most significant 32 bits, and the *withdraw fee percentage* is stored in the
/// next most significant 32 bits, leaving the remaining 160 bits free to store any other information
/// derived pools might need.
///
/// - The *expense ratio* and *harvester ratio* are charged each time when harvester harvest the pool revenue.
/// - The *withdraw fee percentage* is charged each time when user try to withdraw assets from the pool.
///
/// [ rewards expense ratio | harvester ratio | flash loan ratio | redeem ratio | funding expense ratio | liquidation expense ratio | available ]
/// [ 30 bits | 30 bits | 30 bits | 30 bits | 30 bits | 30 bits | 76 bits ]
/// [ MSB LSB ]
bytes32 internal _miscData;
/// @inheritdoc IProtocolFees
address public treasury;
/// @inheritdoc IProtocolFees
/// @dev Hold fees including open.
address public openRevenuePool;
/// @inheritdoc IProtocolFees
address public reservePool;
/// @inheritdoc IProtocolFees
mapping(address => uint256) public accumulatedPoolOpenFees;
/// @inheritdoc IProtocolFees
/// @dev Hold fees including close
address public closeRevenuePool;
/// @inheritdoc IProtocolFees
mapping(address => uint256) public accumulatedPoolCloseFees;
/// @inheritdoc IProtocolFees
/// @dev Hold fees including redeem, liquidation and rebalance.
address public miscRevenuePool;
/// @inheritdoc IProtocolFees
mapping(address => uint256) public accumulatedPoolMiscFees;
/***************
* Constructor *
***************/
function __ProtocolFees_init(
uint256 _expenseRatio,
uint256 _harvesterRatio,
uint256 _flashLoanFeeRatio,
address _treasury,
address _revenuePool,
address _reservePool
) internal onlyInitializing {
_updateFundingExpenseRatio(_expenseRatio);
_updateRewardsExpenseRatio(_expenseRatio);
_updateLiquidationExpenseRatio(_expenseRatio);
_updateHarvesterRatio(_harvesterRatio);
_updateFlashLoanFeeRatio(_flashLoanFeeRatio);
_updateTreasury(_treasury);
_updateOpenRevenuePool(_revenuePool);
_updateCloseRevenuePool(_revenuePool);
_updateMiscRevenuePool(_revenuePool);
_updateReservePool(_reservePool);
}
/*************************
* Public View Functions *
*************************/
/// @inheritdoc IProtocolFees
function getFundingExpenseRatio() public view returns (uint256) {
return _miscData.decodeUint(FUNDING_EXPENSE_RATIO_OFFSET, 30);
}
/// @inheritdoc IProtocolFees
function getRewardsExpenseRatio() public view returns (uint256) {
return _miscData.decodeUint(REWARDS_EXPENSE_RATIO_OFFSET, 30);
}
/// @inheritdoc IProtocolFees
function getLiquidationExpenseRatio() public view returns (uint256) {
return _miscData.decodeUint(LIQUIDATION_EXPENSE_RATIO_OFFSET, 30);
}
/// @inheritdoc IProtocolFees
function getHarvesterRatio() public view returns (uint256) {
return _miscData.decodeUint(HARVESTER_RATIO_OFFSET, 30);
}
/// @inheritdoc IProtocolFees
function getFundingFxSaveRatio() external view returns (uint256) {
return FEE_PRECISION - getFundingExpenseRatio() - getHarvesterRatio();
}
/// @inheritdoc IProtocolFees
function getRewardsFxSaveRatio() external view returns (uint256) {
return FEE_PRECISION - getRewardsExpenseRatio() - getHarvesterRatio();
}
/// @inheritdoc IProtocolFees
function getFlashLoanFeeRatio() public view returns (uint256) {
return _miscData.decodeUint(FLASH_LOAN_RATIO_OFFSET, 30);
}
/// @inheritdoc IProtocolFees
function getRedeemFeeRatio() public view returns (uint256) {
return _miscData.decodeUint(REDEEM_FEE_RATIO_OFFSET, 30);
}
/****************************
* Public Mutated Functions *
****************************/
/// @inheritdoc IProtocolFees
function withdrawAccumulatedPoolFee(address[] memory pools) external {
for (uint256 i = 0; i < pools.length; ++i) {
_takeAccumulatedPoolFee(pools[i]);
}
}
/************************
* Restricted Functions *
************************/
/// @notice Change address of reserve pool contract.
/// @param _newReservePool The new address of reserve pool contract.
function updateReservePool(address _newReservePool) external onlyRole(DEFAULT_ADMIN_ROLE) {
_updateReservePool(_newReservePool);
}
/// @notice Change address of treasury contract.
/// @param _newTreasury The new address of treasury contract.
function updateTreasury(address _newTreasury) external onlyRole(DEFAULT_ADMIN_ROLE) {
_updateTreasury(_newTreasury);
}
/// @notice Change address of open revenue pool contract.
/// @param _newPool The new address of revenue pool contract.
function updateOpenRevenuePool(address _newPool) external onlyRole(DEFAULT_ADMIN_ROLE) {
_updateOpenRevenuePool(_newPool);
}
/// @notice Change address of close revenue pool contract.
/// @param _newPool The new address of revenue pool contract.
function updateCloseRevenuePool(address _newPool) external onlyRole(DEFAULT_ADMIN_ROLE) {
_updateCloseRevenuePool(_newPool);
}
/// @notice Change address of misc revenue pool contract.
/// @param _newPool The new address of revenue pool contract.
function updateMiscRevenuePool(address _newPool) external onlyRole(DEFAULT_ADMIN_ROLE) {
_updateMiscRevenuePool(_newPool);
}
/// @notice Update the fee ratio distributed to treasury.
/// @param newRewardsRatio The new ratio for rewards to update, multiplied by 1e9.
/// @param newFundingRatio The new ratio for funding to update, multiplied by 1e9.
/// @param newLiquidationRatio The new ratio for liquidation/rebalance to update, multiplied by 1e9.
function updateExpenseRatio(
uint32 newRewardsRatio,
uint32 newFundingRatio,
uint32 newLiquidationRatio
) external onlyRole(DEFAULT_ADMIN_ROLE) {
_updateRewardsExpenseRatio(newRewardsRatio);
_updateFundingExpenseRatio(newFundingRatio);
_updateLiquidationExpenseRatio(newLiquidationRatio);
}
/// @notice Update the fee ratio distributed to harvester.
/// @param newRatio The new ratio to update, multiplied by 1e9.
function updateHarvesterRatio(uint32 newRatio) external onlyRole(DEFAULT_ADMIN_ROLE) {
_updateHarvesterRatio(newRatio);
}
/// @notice Update the flash loan fee ratio.
/// @param newRatio The new ratio to update, multiplied by 1e9.
function updateFlashLoanFeeRatio(uint32 newRatio) external onlyRole(DEFAULT_ADMIN_ROLE) {
_updateFlashLoanFeeRatio(newRatio);
}
/// @notice Update the redeem fee ratio.
/// @param newRatio The new ratio to update, multiplied by 1e9.
function updateRedeemFeeRatio(uint32 newRatio) external onlyRole(DEFAULT_ADMIN_ROLE) {
_updateRedeemFeeRatio(newRatio);
}
/**********************
* Internal Functions *
**********************/
/// @dev Internal function to change address of treasury contract.
/// @param _newTreasury The new address of treasury contract.
function _updateTreasury(address _newTreasury) private {
if (_newTreasury == address(0)) revert ErrorZeroAddress();
address _oldTreasury = treasury;
treasury = _newTreasury;
emit UpdateTreasury(_oldTreasury, _newTreasury);
}
/// @dev Internal function to change address of revenue pool contract.
/// @param _newPool The new address of revenue pool contract.
function _updateOpenRevenuePool(address _newPool) private {
if (_newPool == address(0)) revert ErrorZeroAddress();
address _oldPool = openRevenuePool;
openRevenuePool = _newPool;
emit UpdateOpenRevenuePool(_oldPool, _newPool);
}
/// @dev Internal function to change address of revenue pool contract.
/// @param _newPool The new address of revenue pool contract.
function _updateCloseRevenuePool(address _newPool) private {
if (_newPool == address(0)) revert ErrorZeroAddress();
address _oldPool = closeRevenuePool;
closeRevenuePool = _newPool;
emit UpdateCloseRevenuePool(_oldPool, _newPool);
}
/// @dev Internal function to change address of revenue pool contract.
/// @param _newPool The new address of revenue pool contract.
function _updateMiscRevenuePool(address _newPool) private {
if (_newPool == address(0)) revert ErrorZeroAddress();
address _oldPool = miscRevenuePool;
miscRevenuePool = _newPool;
emit UpdateMiscRevenuePool(_oldPool, _newPool);
}
/// @dev Internal function to change the address of reserve pool contract.
/// @param newReservePool The new address of reserve pool contract.
function _updateReservePool(address newReservePool) private {
if (newReservePool == address(0)) revert ErrorZeroAddress();
address oldReservePool = reservePool;
reservePool = newReservePool;
emit UpdateReservePool(oldReservePool, newReservePool);
}
/// @dev Internal function to update the fee ratio distributed to treasury.
/// @param newRatio The new ratio to update, multiplied by 1e9.
function _updateRewardsExpenseRatio(uint256 newRatio) private {
if (uint256(newRatio) > MAX_EXPENSE_RATIO) {
revert ErrorExpenseRatioTooLarge();
}
bytes32 _data = _miscData;
uint256 _oldRatio = _miscData.decodeUint(REWARDS_EXPENSE_RATIO_OFFSET, 30);
_miscData = _data.insertUint(newRatio, REWARDS_EXPENSE_RATIO_OFFSET, 30);
emit UpdateRewardsExpenseRatio(_oldRatio, newRatio);
}
/// @dev Internal function to update the fee ratio distributed to treasury.
/// @param newRatio The new ratio to update, multiplied by 1e9.
function _updateLiquidationExpenseRatio(uint256 newRatio) private {
if (uint256(newRatio) > MAX_EXPENSE_RATIO) {
revert ErrorExpenseRatioTooLarge();
}
bytes32 _data = _miscData;
uint256 _oldRatio = _miscData.decodeUint(LIQUIDATION_EXPENSE_RATIO_OFFSET, 30);
_miscData = _data.insertUint(newRatio, LIQUIDATION_EXPENSE_RATIO_OFFSET, 30);
emit UpdateLiquidationExpenseRatio(_oldRatio, newRatio);
}
/// @dev Internal function to update the fee ratio distributed to treasury.
/// @param newRatio The new ratio to update, multiplied by 1e9.
function _updateFundingExpenseRatio(uint256 newRatio) private {
if (uint256(newRatio) > MAX_EXPENSE_RATIO) {
revert ErrorExpenseRatioTooLarge();
}
bytes32 _data = _miscData;
uint256 _oldRatio = _miscData.decodeUint(FUNDING_EXPENSE_RATIO_OFFSET, 30);
_miscData = _data.insertUint(newRatio, FUNDING_EXPENSE_RATIO_OFFSET, 30);
emit UpdateFundingExpenseRatio(_oldRatio, newRatio);
}
/// @dev Internal function to update the fee ratio distributed to harvester.
/// @param newRatio The new ratio to update, multiplied by 1e9.
function _updateHarvesterRatio(uint256 newRatio) private {
if (uint256(newRatio) > MAX_HARVESTER_RATIO) {
revert ErrorHarvesterRatioTooLarge();
}
bytes32 _data = _miscData;
uint256 _oldRatio = _miscData.decodeUint(HARVESTER_RATIO_OFFSET, 30);
_miscData = _data.insertUint(newRatio, HARVESTER_RATIO_OFFSET, 30);
emit UpdateHarvesterRatio(_oldRatio, newRatio);
}
/// @dev Internal function to update the flash loan fee ratio.
/// @param newRatio The new ratio to update, multiplied by 1e9.
function _updateFlashLoanFeeRatio(uint256 newRatio) private {
if (uint256(newRatio) > MAX_FLASH_LOAN_FEE_RATIO) {
revert ErrorFlashLoanFeeRatioTooLarge();
}
bytes32 _data = _miscData;
uint256 _oldRatio = _miscData.decodeUint(FLASH_LOAN_RATIO_OFFSET, 30);
_miscData = _data.insertUint(newRatio, FLASH_LOAN_RATIO_OFFSET, 30);
emit UpdateFlashLoanFeeRatio(_oldRatio, newRatio);
}
/// @dev Internal function to update the redeem fee ratio.
/// @param newRatio The new ratio to update, multiplied by 1e9.
function _updateRedeemFeeRatio(uint256 newRatio) private {
if (uint256(newRatio) > MAX_REDEEM_FEE_RATIO) {
revert ErrorRedeemFeeRatioTooLarge();
}
bytes32 _data = _miscData;
uint256 _oldRatio = _miscData.decodeUint(REDEEM_FEE_RATIO_OFFSET, 30);
_miscData = _data.insertUint(newRatio, REDEEM_FEE_RATIO_OFFSET, 30);
emit UpdateRedeemFeeRatio(_oldRatio, newRatio);
}
/// @dev Internal function to accumulate protocol fee for the given pool.
/// @param pool The address of pool.
/// @param amount The amount of protocol fee.
function _accumulatePoolOpenFee(address pool, uint256 amount) internal {
if (amount > 0) {
accumulatedPoolOpenFees[pool] += amount;
}
}
/// @dev Internal function to accumulate protocol fee for the given pool.
/// @param pool The address of pool.
/// @param amount The amount of protocol fee.
function _accumulatePoolCloseFee(address pool, uint256 amount) internal {
if (amount > 0) {
accumulatedPoolCloseFees[pool] += amount;
}
}
/// @dev Internal function to accumulate protocol fee for the given pool.
/// @param pool The address of pool.
/// @param amount The amount of protocol fee.
function _accumulatePoolMiscFee(address pool, uint256 amount) internal {
if (amount > 0) {
accumulatedPoolMiscFees[pool] += amount;
}
}
/// @dev Internal function to withdraw accumulated protocol fee for the given pool.
/// @param pool The address of pool.
function _takeAccumulatedPoolFee(address pool) internal returns (uint256 fees) {
address collateralToken = IPool(pool).collateralToken();
fees = accumulatedPoolOpenFees[pool];
if (fees > 0) {
IERC20(collateralToken).safeTransfer(openRevenuePool, fees);
accumulatedPoolOpenFees[pool] = 0;
}
fees = accumulatedPoolCloseFees[pool];
if (fees > 0) {
IERC20(collateralToken).safeTransfer(closeRevenuePool, fees);
accumulatedPoolCloseFees[pool] = 0;
}
fees = accumulatedPoolMiscFees[pool];
if (fees > 0) {
IERC20(collateralToken).safeTransfer(miscRevenuePool, fees);
accumulatedPoolMiscFees[pool] = 0;
}
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
*/
uint256[41] private __gap;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { AccessControlUpgradeable } from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import { IStrategy } from "./IStrategy.sol";
abstract contract AssetManagement is AccessControlUpgradeable {
using SafeERC20 for IERC20;
bytes32 public constant ASSET_MANAGER_ROLE = keccak256("ASSET_MANAGER_ROLE");
struct Allocation {
address strategy;
uint96 capacity;
}
mapping(address => Allocation) public allocations;
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
*/
uint256[49] private __gap;
function kill(address asset) public onlyRole(DEFAULT_ADMIN_ROLE) {
Allocation memory curAlloc = allocations[asset];
if (curAlloc.strategy != address(0)) {
IStrategy(curAlloc.strategy).kill();
curAlloc.strategy = address(0);
curAlloc.capacity = 0;
allocations[asset] = curAlloc;
}
}
function alloc(address asset, address strategy, uint96 capacity) external onlyRole(DEFAULT_ADMIN_ROLE) {
Allocation memory oldAlloc = allocations[asset];
if (oldAlloc.strategy != address(0)) kill(asset);
allocations[asset] = Allocation({ strategy: strategy, capacity: capacity });
}
function manage(address asset, uint256 amount) external onlyRole(ASSET_MANAGER_ROLE) {
Allocation memory curAlloc = allocations[asset];
uint256 managed = IStrategy(curAlloc.strategy).totalSupply();
if (managed + amount > curAlloc.capacity) revert();
IERC20(asset).safeTransfer(curAlloc.strategy, amount);
IStrategy(curAlloc.strategy).deposit(amount);
}
function _transferOut(address asset, uint256 amount, address receiver) internal {
uint256 balance = IERC20(asset).balanceOf(address(this));
if (balance >= amount) {
IERC20(asset).safeTransfer(receiver, amount);
} else {
IERC20(asset).safeTransfer(receiver, balance);
uint256 diff = amount - balance;
Allocation memory curAlloc = allocations[asset];
if (curAlloc.strategy == address(0)) revert();
IStrategy(curAlloc.strategy).withdraw(diff, receiver);
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IStrategy {
function totalSupply() external view returns (uint256);
function deposit(uint256 amount) external;
function withdraw(uint256 amount, address recipient) external;
function kill() external;
function harvest(address receiver) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IAaveRewardsController } from "../../interfaces/Aave/IAaveRewardsController.sol";
import { IAaveV3Pool } from "../../interfaces/Aave/IAaveV3Pool.sol";
import { StrategyBase } from "./StrategyBase.sol";
contract AaveV3Strategy is StrategyBase {
using SafeERC20 for IERC20;
address public immutable POOL;
address public immutable INCENTIVE;
address public immutable ASSET;
address public immutable ATOKEN;
uint256 public principal;
constructor(
address _admin,
address _operator,
address _pool,
address _incentive,
address _asset,
address _atoken
) StrategyBase(_admin, _operator) {
POOL = _pool;
INCENTIVE = _incentive;
ASSET = _asset;
ATOKEN = _atoken;
IERC20(ASSET).forceApprove(POOL, type(uint256).max);
}
function totalSupply() public view returns (uint256) {
return IERC20(ATOKEN).balanceOf(address(this));
}
function deposit(uint256 amount) external onlyOperator {
unchecked {
principal += amount;
}
IAaveV3Pool(POOL).supply(ASSET, amount, address(this), 0);
}
function withdraw(uint256 amount, address recipient) external onlyOperator {
uint256 cachedPrincipal = principal;
if (amount > cachedPrincipal) amount = cachedPrincipal;
unchecked {
principal = cachedPrincipal - amount;
}
IAaveV3Pool(POOL).withdraw(ASSET, amount, recipient);
}
function kill() external onlyOperator {
if (totalSupply() > 0) {
IAaveV3Pool(POOL).withdraw(ASSET, type(uint256).max, operator);
}
principal = 0;
}
function _harvest(address receiver) internal virtual override {
uint256 rewards = totalSupply() - principal;
if (rewards > 0) {
IAaveV3Pool(POOL).withdraw(ASSET, rewards, receiver);
}
address[] memory assets = new address[](1);
assets[0] = ATOKEN;
IAaveRewardsController(INCENTIVE).claimAllRewards(assets, receiver);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import { AccessControl } from "@openzeppelin/contracts/access/AccessControl.sol";
abstract contract StrategyBase is AccessControl {
bytes32 public constant HARVESTER_ROLE = keccak256("HARVESTER_ROLE");
address public immutable operator;
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
*/
uint256[50] private __gap;
modifier onlyOperator() {
if (msg.sender != operator) revert();
_;
}
constructor(address _admin, address _operator) {
operator = _operator;
_grantRole(DEFAULT_ADMIN_ROLE, _admin);
}
function harvest(address receiver) external onlyRole(HARVESTER_ROLE) {
_harvest(receiver);
}
function execute(
address to,
uint256 value,
bytes calldata data
) external onlyOperator returns (bool success, bytes memory returnData) {
(success, returnData) = to.call{ value: value }(data);
}
function _harvest(address receiver) internal virtual;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IHarvesterCallback {
/// @notice Hook function to handle harvested rewards.
/// @param token The address of token.
/// @param amount The amount of tokens.
function onHarvest(address token, uint256 amount) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IMultiPathConverter {
function queryConvert(
uint256 _amount,
uint256 _encoding,
uint256[] calldata _routes
) external returns (uint256 amountOut);
function convert(
address _tokenIn,
uint256 _amount,
uint256 _encoding,
uint256[] calldata _routes
) external payable returns (uint256 amountOut);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IStrategy } from "../fund/IStrategy.sol";
import { PermissionedSwap } from "../common/utils/PermissionedSwap.sol";
contract StrategyHarvester is PermissionedSwap {
using SafeERC20 for IERC20;
/***********************
* Immutable Variables *
***********************/
/// @notice The address of strategy contract.
address public immutable strategy;
/// @notice The address of rewards receiver.
address public immutable receiver;
/***************
* Constructor *
***************/
constructor(address _strategy, address _receiver) initializer {
__Context_init();
__ERC165_init();
__AccessControl_init();
strategy = _strategy;
receiver = _receiver;
_grantRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
/****************************
* Public Mutated Functions *
****************************/
/// @notice Harvest pending rewards from strategy.
function harvest() external onlyRole(PERMISSIONED_TRADER_ROLE) {
IStrategy(strategy).harvest(address(this));
}
/// @notice Harvest base token to target token by amm trading and distribute to fxSAVE.
/// @param amountIn The amount of input tokens.
/// @param baseToken The address of base token to use.
/// @param targetToken The address target token.
/// @param params The parameters used for trading.
/// @return amountOut The amount of target token received.
function swapAndDistribute(
uint256 amountIn,
address baseToken,
address targetToken,
TradingParameter memory params
) external returns (uint256 amountOut) {
// swap base token to target
amountOut = _doTrade(baseToken, targetToken, amountIn, params);
// transfer target token to receiver
IERC20(targetToken).safeTransfer(receiver, amountOut);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IAaveRewardsController {
/**
* @dev Whitelists an address to claim the rewards on behalf of another address
* @param user The address of the user
* @param claimer The address of the claimer
*/
function setClaimer(address user, address claimer) external;
/**
* @dev Claims reward for a user to the desired address, on all the assets of the pool, accumulating the pending rewards
* @param assets List of assets to check eligible distributions before claiming rewards
* @param amount The amount of rewards to claim
* @param to The address that will be receiving the rewards
* @param reward The address of the reward token
* @return The amount of rewards claimed
**/
function claimRewards(
address[] calldata assets,
uint256 amount,
address to,
address reward
) external returns (uint256);
/**
* @dev Claims all rewards for a user to the desired address, on all the assets of the pool, accumulating the pending rewards
* @param assets The list of assets to check eligible distributions before claiming rewards
* @param to The address that will be receiving the rewards
* @return rewardsList List of addresses of the reward tokens
* @return claimedAmounts List that contains the claimed amount per reward, following same order as "rewardList"
**/
function claimAllRewards(
address[] calldata assets,
address to
) external returns (address[] memory rewardsList, uint256[] memory claimedAmounts);
/**
* @dev Claims all rewards for a user on behalf, on all the assets of the pool, accumulating the pending rewards. The caller must
* be whitelisted via "allowClaimOnBehalf" function by the RewardsAdmin role manager
* @param assets The list of assets to check eligible distributions before claiming rewards
* @param user The address to check and claim rewards
* @param to The address that will be receiving the rewards
* @return rewardsList List of addresses of the reward tokens
* @return claimedAmounts List that contains the claimed amount per reward, following same order as "rewardsList"
**/
function claimAllRewardsOnBehalf(
address[] calldata assets,
address user,
address to
) external returns (address[] memory rewardsList, uint256[] memory claimedAmounts);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IAaveV3Pool {
struct ReserveConfigurationMap {
//bit 0-15: LTV
//bit 16-31: Liq. threshold
//bit 32-47: Liq. bonus
//bit 48-55: Decimals
//bit 56: reserve is active
//bit 57: reserve is frozen
//bit 58: borrowing is enabled
//bit 59: DEPRECATED: stable rate borrowing enabled
//bit 60: asset is paused
//bit 61: borrowing in isolation mode is enabled
//bit 62: siloed borrowing enabled
//bit 63: flashloaning enabled
//bit 64-79: reserve factor
//bit 80-115: borrow cap in whole tokens, borrowCap == 0 => no cap
//bit 116-151: supply cap in whole tokens, supplyCap == 0 => no cap
//bit 152-167: liquidation protocol fee
//bit 168-175: DEPRECATED: eMode category
//bit 176-211: unbacked mint cap in whole tokens, unbackedMintCap == 0 => minting disabled
//bit 212-251: debt ceiling for isolation mode with (ReserveConfiguration::DEBT_CEILING_DECIMALS) decimals
//bit 252: virtual accounting is enabled for the reserve
//bit 253-255 unused
uint256 data;
}
/**
* This exists specifically to maintain the `getReserveData()` interface, since the new, internal
* `ReserveData` struct includes the reserve's `virtualUnderlyingBalance`.
*/
struct ReserveDataLegacy {
//stores the reserve configuration
ReserveConfigurationMap configuration;
//the liquidity index. Expressed in ray
uint128 liquidityIndex;
//the current supply rate. Expressed in ray
uint128 currentLiquidityRate;
//variable borrow index. Expressed in ray
uint128 variableBorrowIndex;
//the current variable borrow rate. Expressed in ray
uint128 currentVariableBorrowRate;
// DEPRECATED on v3.2.0
uint128 currentStableBorrowRate;
//timestamp of last update
uint40 lastUpdateTimestamp;
//the id of the reserve. Represents the position in the list of the active reserves
uint16 id;
//aToken address
address aTokenAddress;
// DEPRECATED on v3.2.0
address stableDebtTokenAddress;
//variableDebtToken address
address variableDebtTokenAddress;
//address of the interest rate strategy
address interestRateStrategyAddress;
//the current treasury balance, scaled
uint128 accruedToTreasury;
//the outstanding unbacked aTokens minted through the bridging feature
uint128 unbacked;
//the outstanding debt borrowed against this asset in isolation mode
uint128 isolationModeTotalDebt;
}
/**
* @notice Returns the state and configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The state and configuration data of the reserve
*/
function getReserveData(address asset) external view returns (ReserveDataLegacy memory);
/**
* @notice Returns the normalized variable debt per unit of asset
* @dev WARNING: This function is intended to be used primarily by the protocol itself to get a
* "dynamic" variable index based on time, current stored index and virtual rate at the current
* moment (approx. a borrower would get if opening a position). This means that is always used in
* combination with variable debt supply/balances.
* If using this function externally, consider that is possible to have an increasing normalized
* variable debt that is not equivalent to how the variable debt index would be updated in storage
* (e.g. only updates with non-zero variable debt supply)
* @param asset The address of the underlying asset of the reserve
* @return The reserve normalized variable debt
*/
function getReserveNormalizedVariableDebt(address asset) external view returns (uint256);
/**
* @notice Supplies an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.
* - E.g. User supplies 100 USDC and gets in return 100 aUSDC
* @param asset The address of the underlying asset to supply
* @param amount The amount to be supplied
* @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user
* wants to receive them on his own wallet, or a different address if the beneficiary of aTokens
* is a different wallet
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
*/
function supply(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external;
/**
* @notice Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned
* E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC
* @param asset The address of the underlying asset to withdraw
* @param amount The underlying amount to be withdrawn
* - Send the value type(uint256).max in order to withdraw the whole aToken balance
* @param to The address that will receive the underlying, same as msg.sender if the user
* wants to receive it on his own wallet, or a different address if the beneficiary is a
* different wallet
* @return The final amount withdrawn
*/
function withdraw(address asset, uint256 amount, address to) external returns (uint256);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
interface IBalancerVault {
enum JoinKind {
INIT,
EXACT_TOKENS_IN_FOR_BPT_OUT,
TOKEN_IN_FOR_EXACT_BPT_OUT,
ALL_TOKENS_IN_FOR_EXACT_BPT_OUT
}
enum ExitKind {
EXACT_BPT_IN_FOR_ONE_TOKEN_OUT,
EXACT_BPT_IN_FOR_TOKENS_OUT,
BPT_IN_FOR_EXACT_TOKENS_OUT
}
enum SwapKind {
GIVEN_IN,
GIVEN_OUT
}
struct SingleSwap {
bytes32 poolId;
SwapKind kind;
address assetIn;
address assetOut;
uint256 amount;
bytes userData;
}
struct FundManagement {
address sender;
bool fromInternalBalance;
address payable recipient;
bool toInternalBalance;
}
function getPoolTokens(bytes32 poolId)
external
view
returns (
address[] memory tokens,
uint256[] memory balances,
uint256 lastChangeBlock
);
function swap(
SingleSwap memory singleSwap,
FundManagement memory funds,
uint256 limit,
uint256 deadline
) external payable returns (uint256 amountCalculated);
struct JoinPoolRequest {
address[] assets;
uint256[] maxAmountsIn;
bytes userData;
bool fromInternalBalance;
}
function joinPool(
bytes32 poolId,
address sender,
address recipient,
JoinPoolRequest memory request
) external payable;
struct ExitPoolRequest {
address[] assets;
uint256[] minAmountsOut;
bytes userData;
bool toInternalBalance;
}
function exitPool(
bytes32 poolId,
address sender,
address payable recipient,
ExitPoolRequest memory request
) external;
/**
* @dev Data for each individual swap executed by `batchSwap`. The asset in and out fields are indexes into the
* `assets` array passed to that function, and ETH assets are converted to WETH.
*
* If `amount` is zero, the multihop mechanism is used to determine the actual amount based on the amount in/out
* from the previous swap, depending on the swap kind.
*
* The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
* used to extend swap behavior.
*/
struct BatchSwapStep {
bytes32 poolId;
uint256 assetInIndex;
uint256 assetOutIndex;
uint256 amount;
bytes userData;
}
// This function is not marked as `nonReentrant` because the underlying mechanism relies on reentrancy
function queryBatchSwap(
SwapKind kind,
BatchSwapStep[] memory swaps,
address[] memory assets,
FundManagement memory funds
) external returns (int256[] memory);
function flashLoan(
address recipient,
address[] memory tokens,
uint256[] memory amounts,
bytes memory userData
) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
function latestAnswer() external view returns (uint256);
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IConvexFXNBooster {
function createVault(uint256 _pid) external returns (address);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IStakingProxyERC20 {
//deposit into gauge
function deposit(uint256 _amount) external;
//deposit into gauge with manage flag
function deposit(uint256 _amount, bool _manage) external;
//withdraw a staked position
function withdraw(uint256 _amount) external;
//return earned tokens on staking contract and any tokens that are on this vault
function earned() external returns (address[] memory token_addresses, uint256[] memory total_earned);
/*
claim flow:
mint fxn rewards directly to vault
claim extra rewards directly to the owner
calculate fees on fxn
distribute fxn between owner and fee deposit
*/
function getReward() external;
//get reward with claim option.
function getReward(bool _claim) external;
//get reward with claim option, as well as a specific token list to claim from convex extra rewards
function getReward(bool _claim, address[] calldata _tokenList) external;
//return any tokens in vault back to owner
function transferTokens(address[] calldata _tokenList) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// solhint-disable func-name-mixedcase
interface ICurvePoolOracle {
/********************
* Common Functions *
********************/
function ma_exp_time() external view returns (uint256);
function ma_last_time() external view returns (uint256);
/***************************
* Functions of Plain Pool *
***************************/
function get_p() external view returns (uint256);
function last_price() external view returns (uint256);
function last_prices() external view returns (uint256);
function ema_price() external view returns (uint256);
function price_oracle() external view returns (uint256);
/************************
* Functions of NG Pool *
************************/
function get_p(uint256 index) external view returns (uint256);
/// @notice Returns last price of the coin at index `k` w.r.t the coin
/// at index 0.
/// @dev last_prices returns the quote by the AMM for an infinitesimally small swap
/// after the last trade. It is not equivalent to the last traded price, and
/// is computed by taking the partial differential of `x` w.r.t `y`. The
/// derivative is calculated in `get_p` and then multiplied with price_scale
/// to give last_prices.
/// @param index The index of the coin.
/// @return uint256 Last logged price of coin.
function last_price(uint256 index) external view returns (uint256);
function last_prices(uint256 index) external view returns (uint256);
function ema_price(uint256 index) external view returns (uint256);
function price_oracle(uint256 index) external view returns (uint256);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface ICurveStableSwapNG {
/*************************
* Public View Functions *
*************************/
function coins(uint256 index) external view returns (address);
function last_price(uint256 index) external view returns (uint256);
function ema_price(uint256 index) external view returns (uint256);
/// @notice Returns the AMM State price of token
/// @dev if i = 0, it will return the state price of coin[1].
/// @param i index of state price (0 for coin[1], 1 for coin[2], ...)
/// @return uint256 The state price quoted by the AMM for coin[i+1]
function get_p(uint256 i) external view returns (uint256);
function price_oracle(uint256 index) external view returns (uint256);
function D_oracle() external view returns (uint256);
function A() external view returns (uint256);
function A_precise() external view returns (uint256);
/// @notice Calculate the current input dx given output dy
/// @dev Index values can be found via the `coins` public getter method
/// @param i Index value for the coin to send
/// @param j Index value of the coin to receive
/// @param dy Amount of `j` being received after exchange
/// @return Amount of `i` predicted
function get_dx(
int128 i,
int128 j,
uint256 dy
) external view returns (uint256);
/// @notice Calculate the current output dy given input dx
/// @dev Index values can be found via the `coins` public getter method
/// @param i Index value for the coin to send
/// @param j Index value of the coin to receive
/// @param dx Amount of `i` being exchanged
/// @return Amount of `j` predicted
function get_dy(
int128 i,
int128 j,
uint256 dx
) external view returns (uint256);
/// @notice Calculate the amount received when withdrawing a single coin
/// @param burn_amount Amount of LP tokens to burn in the withdrawal
/// @param i Index value of the coin to withdraw
/// @return Amount of coin received
function calc_withdraw_one_coin(uint256 burn_amount, int128 i) external view returns (uint256);
/// @notice The current virtual price of the pool LP token
/// @dev Useful for calculating profits.
/// The method may be vulnerable to donation-style attacks if implementation
/// contains rebasing tokens. For integrators, caution is advised.
/// @return LP token virtual price normalized to 1e18
function get_virtual_price() external view returns (uint256);
/// @notice Calculate addition or reduction in token supply from a deposit or withdrawal
/// @param amounts Amount of each coin being deposited
/// @param is_deposit set True for deposits, False for withdrawals
/// @return Expected amount of LP tokens received
function calc_token_amount(uint256[] calldata amounts, bool is_deposit) external view returns (uint256);
/// @notice Get the current balance of a coin within the
/// pool, less the accrued admin fees
/// @param i Index value for the coin to query balance of
/// @return Token balance
function balances(uint256 i) external view returns (uint256);
function get_balances() external view returns (uint256[] memory);
function stored_rates() external view returns (uint256[] memory);
/// @notice Return the fee for swapping between `i` and `j`
/// @param i Index value for the coin to send
/// @param j Index value of the coin to receive
/// @return Swap fee expressed as an integer with 1e10 precision
function dynamic_fee(int128 i, int128 j) external view returns (uint256);
/****************************
* Public Mutated Functions *
****************************/
/// @notice Perform an exchange between two coins
/// @dev Index values can be found via the `coins` public getter method
/// @param i Index value for the coin to send
/// @param j Index value of the coin to receive
/// @param dx Amount of `i` being exchanged
/// @param min_dy Minimum amount of `j` to receive
/// @return Actual amount of `j` received
function exchange(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external returns (uint256);
/// @notice Perform an exchange between two coins
/// @dev Index values can be found via the `coins` public getter method
/// @param i Index value for the coin to send
/// @param j Index value of the coin to receive
/// @param dx Amount of `i` being exchanged
/// @param min_dy Minimum amount of `j` to receive
/// @param receiver Address that receives `j`
/// @return Actual amount of `j` received
function exchange(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy,
address receiver
) external returns (uint256);
/// @notice Perform an exchange between two coins without transferring token in
/// @dev The contract swaps tokens based on a change in balance of coin[i]. The
/// dx = ERC20(coin[i]).balanceOf(self) - self.stored_balances[i]. Users of
/// this method are dex aggregators, arbitrageurs, or other users who do not
/// wish to grant approvals to the contract: they would instead send tokens
/// directly to the contract and call `exchange_received`.
/// Note: This is disabled if pool contains rebasing tokens.
/// @param i Index value for the coin to send
/// @param j Index value of the coin to receive
/// @param dx Amount of `i` being exchanged
/// @param min_dy Minimum amount of `j` to receive
/// @return Actual amount of `j` received
function exchange_received(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external returns (uint256);
/// @notice Perform an exchange between two coins without transferring token in
/// @dev The contract swaps tokens based on a change in balance of coin[i]. The
/// dx = ERC20(coin[i]).balanceOf(self) - self.stored_balances[i]. Users of
/// this method are dex aggregators, arbitrageurs, or other users who do not
/// wish to grant approvals to the contract: they would instead send tokens
/// directly to the contract and call `exchange_received`.
/// Note: This is disabled if pool contains rebasing tokens.
/// @param i Index value for the coin to send
/// @param j Index value of the coin to receive
/// @param dx Amount of `i` being exchanged
/// @param min_dy Minimum amount of `j` to receive
/// @param receiver Address that receives `j`
/// @return Actual amount of `j` received
function exchange_received(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy,
address receiver
) external returns (uint256);
/// @notice Deposit coins into the pool
/// @param amounts List of amounts of coins to deposit
/// @param min_mint_amount Minimum amount of LP tokens to mint from the deposit
/// @return Amount of LP tokens received by depositing
function add_liquidity(uint256[] calldata amounts, uint256 min_mint_amount) external returns (uint256);
/// @notice Deposit coins into the pool
/// @param amounts List of amounts of coins to deposit
/// @param min_mint_amount Minimum amount of LP tokens to mint from the deposit
/// @param receiver Address that owns the minted LP tokens
/// @return Amount of LP tokens received by depositing
function add_liquidity(
uint256[] calldata amounts,
uint256 min_mint_amount,
address receiver
) external returns (uint256);
/// @notice Withdraw a single coin from the pool
/// @param burn_amount Amount of LP tokens to burn in the withdrawal
/// @param i Index value of the coin to withdraw
/// @param min_received Minimum amount of coin to receive
/// @return Amount of coin received
function remove_liquidity_one_coin(
uint256 burn_amount,
int128 i,
uint256 min_received
) external returns (uint256);
/// @notice Withdraw a single coin from the pool
/// @param burn_amount Amount of LP tokens to burn in the withdrawal
/// @param i Index value of the coin to withdraw
/// @param min_received Minimum amount of coin to receive
/// @param receiver Address that receives the withdrawn coins
/// @return Amount of coin received
function remove_liquidity_one_coin(
uint256 burn_amount,
int128 i,
uint256 min_received,
address receiver
) external returns (uint256);
/// @notice Withdraw coins from the pool in an imbalanced amount
/// @param amounts List of amounts of underlying coins to withdraw
/// @param max_burn_amount Maximum amount of LP token to burn in the withdrawal
/// @return Actual amount of the LP token burned in the withdrawal
function remove_liquidity_imbalance(uint256[] calldata amounts, uint256 max_burn_amount) external returns (uint256);
/// @notice Withdraw coins from the pool in an imbalanced amount
/// @param amounts List of amounts of underlying coins to withdraw
/// @param max_burn_amount Maximum amount of LP token to burn in the withdrawal
/// @param receiver Address that receives the withdrawn coins
/// @return Actual amount of the LP token burned in the withdrawal
function remove_liquidity_imbalance(
uint256[] calldata amounts,
uint256 max_burn_amount,
address receiver
) external returns (uint256);
/// @notice Withdraw coins from the pool
/// @dev Withdrawal amounts are based on current deposit ratios
/// @param burn_amount Quantity of LP tokens to burn in the withdrawal
/// @param min_amounts Minimum amounts of underlying coins to receive
/// @return List of amounts of coins that were withdrawn
function remove_liquidity(uint256 burn_amount, uint256[] calldata min_amounts) external returns (uint256[] memory);
/// @notice Withdraw coins from the pool
/// @dev Withdrawal amounts are based on current deposit ratios
/// @param burn_amount Quantity of LP tokens to burn in the withdrawal
/// @param min_amounts Minimum amounts of underlying coins to receive
/// @param receiver Address that receives the withdrawn coins
/// @return List of amounts of coins that were withdrawn
function remove_liquidity(
uint256 burn_amount,
uint256[] calldata min_amounts,
address receiver
) external returns (uint256[] memory);
/// @notice Withdraw coins from the pool
/// @dev Withdrawal amounts are based on current deposit ratios
/// @param burn_amount Quantity of LP tokens to burn in the withdrawal
/// @param min_amounts Minimum amounts of underlying coins to receive
/// @param receiver Address that receives the withdrawn coins
/// @return List of amounts of coins that were withdrawn
function remove_liquidity(
uint256 burn_amount,
uint256[] calldata min_amounts,
address receiver,
bool claim_admin_fees
) external returns (uint256[] memory);
/// @notice Claim admin fees. Callable by anyone.
function withdraw_admin_fees() external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IPool } from "./IPool.sol";
interface IAaveFundingPool is IPool {
/**********
* Events *
**********/
/// @notice Emitted when interest snapshot is taken.
/// @param borrowIndex The borrow index, multiplied by 1e27.
/// @param timestamp The timestamp when this snapshot is taken.
event SnapshotAaveBorrowIndex(uint256 borrowIndex, uint256 timestamp);
/// @notice Emitted when the open fee ratio related parameters are updated.
/// @param ratio The open ratio value, multiplied by 1e9.
/// @param step The open ratio step value, multiplied by 1e18.
event UpdateOpenRatio(uint256 ratio, uint256 step);
/// @notice Emitted when the open fee ratio is updated.
/// @param oldRatio The value of previous close fee ratio, multiplied by 1e9.
/// @param newRatio The value of current close fee ratio, multiplied by 1e9.
event UpdateCloseFeeRatio(uint256 oldRatio, uint256 newRatio);
/// @notice Emitted when the funding fee ratio is updated.
/// @param oldRatio The value of previous funding fee ratio, multiplied by 1e9.
/// @param newRatio The value of current funding fee ratio, multiplied by 1e9.
event UpdateFundingRatio(uint256 oldRatio, uint256 newRatio);
/*************************
* Public View Functions *
*************************/
/// @notice Return the value of funding ratio, multiplied by 1e9.
function getFundingRatio() external view returns (uint256);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IFxUSDBasePool {
/**********
* Events *
**********/
/// @notice Emitted when the stable depeg price is updated.
/// @param oldPrice The value of previous depeg price, multiplied by 1e18.
/// @param newPrice The value of current depeg price, multiplied by 1e18.
event UpdateStableDepegPrice(uint256 oldPrice, uint256 newPrice);
/// @notice Emitted when the redeem cool down period is updated.
/// @param oldPeriod The value of previous redeem cool down period.
/// @param newPeriod The value of current redeem cool down period.
event UpdateRedeemCoolDownPeriod(uint256 oldPeriod, uint256 newPeriod);
/// @notice Emitted when the instant redeem fee ratio is updated.
/// @param oldRatio The value of previous instant redeem fee ratio, multiplied by 1e18.
/// @param newRatio The value of current instant redeem fee ratio, multiplied by 1e18.
event UpdateInstantRedeemFeeRatio(uint256 oldRatio, uint256 newRatio);
/// @notice Emitted when deposit tokens.
/// @param caller The address of caller.
/// @param receiver The address of pool share recipient.
/// @param tokenIn The address of input token.
/// @param amountDeposited The amount of input tokens.
/// @param amountSharesOut The amount of pool shares minted.
event Deposit(
address indexed caller,
address indexed receiver,
address indexed tokenIn,
uint256 amountDeposited,
uint256 amountSharesOut
);
/// @notice Emitted when users request redeem.
/// @param caller The address of caller.
/// @param shares The amount of shares to redeem.
/// @param unlockAt The timestamp when this share can be redeemed.
event RequestRedeem(address indexed caller, uint256 shares, uint256 unlockAt);
/// @notice Emitted when redeem pool shares.
/// @param caller The address of caller.
/// @param receiver The address of pool share recipient.
/// @param amountSharesToRedeem The amount of pool shares burned.
/// @param amountYieldTokenOut The amount of yield tokens redeemed.
/// @param amountStableTokenOut The amount of stable tokens redeemed.
event Redeem(
address indexed caller,
address indexed receiver,
uint256 amountSharesToRedeem,
uint256 amountYieldTokenOut,
uint256 amountStableTokenOut
);
/// @notice Emitted when instant redeem pool shares.
/// @param caller The address of caller.
/// @param receiver The address of pool share recipient.
/// @param amountSharesToRedeem The amount of pool shares burned.
/// @param amountYieldTokenOut The amount of yield tokens redeemed.
/// @param amountStableTokenOut The amount of stable tokens redeemed.
event InstantRedeem(
address indexed caller,
address indexed receiver,
uint256 amountSharesToRedeem,
uint256 amountYieldTokenOut,
uint256 amountStableTokenOut
);
/// @notice Emitted when rebalance or liquidate.
/// @param caller The address of caller.
/// @param tokenIn The address of input token.
/// @param amountTokenIn The amount of input token used.
/// @param amountCollateral The amount of collateral token rebalanced.
/// @param amountYieldToken The amount of yield token used.
/// @param amountStableToken The amount of stable token used.
event Rebalance(
address indexed caller,
address indexed tokenIn,
uint256 amountTokenIn,
uint256 amountCollateral,
uint256 amountYieldToken,
uint256 amountStableToken
);
/// @notice Emitted when arbitrage in curve pool.
/// @param caller The address of caller.
/// @param tokenIn The address of input token.
/// @param amountIn The amount of input token used.
/// @param amountOut The amount of output token swapped.
/// @param bonusOut The amount of bonus token.
event Arbitrage(
address indexed caller,
address indexed tokenIn,
uint256 amountIn,
uint256 amountOut,
uint256 bonusOut
);
/*************************
* Public View Functions *
*************************/
/// @notice The address of yield token.
function yieldToken() external view returns (address);
/// @notice The address of stable token.
function stableToken() external view returns (address);
/// @notice The total amount of yield token managed in this contract
function totalYieldToken() external view returns (uint256);
/// @notice The total amount of stable token managed in this contract
function totalStableToken() external view returns (uint256);
/// @notice The net asset value, multiplied by 1e18.
function nav() external view returns (uint256);
/// @notice Return the stable token price, multiplied by 1e18.
function getStableTokenPrice() external view returns (uint256);
/// @notice Return the stable token price with scaling to 18 decimals, multiplied by 1e18.
function getStableTokenPriceWithScale() external view returns (uint256);
/// @notice Preview the result of deposit.
/// @param tokenIn The address of input token.
/// @param amount The amount of input tokens to deposit.
/// @return amountSharesOut The amount of pool shares should receive.
function previewDeposit(address tokenIn, uint256 amount) external view returns (uint256 amountSharesOut);
/// @notice Preview the result of redeem.
/// @param amountSharesToRedeem The amount of pool shares to redeem.
/// @return amountYieldOut The amount of yield token should receive.
/// @return amountStableOut The amount of stable token should receive.
function previewRedeem(
uint256 amountSharesToRedeem
) external view returns (uint256 amountYieldOut, uint256 amountStableOut);
/****************************
* Public Mutated Functions *
****************************/
/// @notice Deposit token.
/// @param receiver The address of pool shares recipient.
/// @param tokenIn The address of input token.
/// @param amountTokenToDeposit The amount of input tokens to deposit.
/// @param minSharesOut The minimum amount of pool shares should receive.
/// @return amountSharesOut The amount of pool shares received.
function deposit(
address receiver,
address tokenIn,
uint256 amountTokenToDeposit,
uint256 minSharesOut
) external returns (uint256 amountSharesOut);
/// @notice Request redeem.
/// @param shares The amount of shares to request.
function requestRedeem(uint256 shares) external;
/// @notice Redeem pool shares.
/// @param receiver The address of token recipient.
/// @param shares The amount of pool shares to redeem.
/// @return amountYieldOut The amount of yield token should received.
/// @return amountStableOut The amount of stable token should received.
function redeem(address receiver, uint256 shares) external returns (uint256 amountYieldOut, uint256 amountStableOut);
/// @notice Redeem pool shares instantly with withdraw fee.
/// @param receiver The address of token recipient.
/// @param shares The amount of pool shares to redeem.
/// @return amountYieldOut The amount of yield token should received.
/// @return amountStableOut The amount of stable token should received.
function instantRedeem(address receiver, uint256 shares) external returns (uint256 amountYieldOut, uint256 amountStableOut);
/// @notice Rebalance all positions in the given tick.
/// @param pool The address of pool to rebalance.
/// @param tick The index of tick to rebalance.
/// @param tokenIn The address of token to rebalance.
/// @param maxAmount The maximum amount of input token to rebalance.
/// @param minBaseOut The minimum amount of collateral tokens should receive.
/// @return tokenUsed The amount of input token used to rebalance.
/// @return baseOut The amount of collateral tokens rebalanced.
function rebalance(
address pool,
int16 tick,
address tokenIn,
uint256 maxAmount,
uint256 minBaseOut
) external returns (uint256 tokenUsed, uint256 baseOut);
/// @notice Rebalance all possible ticks.
/// @param pool The address of pool to rebalance.
/// @param tokenIn The address of token to rebalance.
/// @param maxAmount The maximum amount of input token to rebalance.
/// @param minBaseOut The minimum amount of collateral tokens should receive.
/// @return tokenUsed The amount of input token used to rebalance.
/// @return baseOut The amount of collateral tokens rebalanced.
function rebalance(
address pool,
address tokenIn,
uint256 maxAmount,
uint256 minBaseOut
) external returns (uint256 tokenUsed, uint256 baseOut);
/// @notice Liquidate all possible ticks.
/// @param pool The address of pool to rebalance.
/// @param tokenIn The address of token to rebalance.
/// @param maxAmount The maximum amount of input token to rebalance.
/// @param minBaseOut The minimum amount of collateral tokens should receive.
/// @return tokenUsed The amount of input token used to rebalance.
/// @return baseOut The amount of collateral tokens rebalanced.
function liquidate(
address pool,
address tokenIn,
uint256 maxAmount,
uint256 minBaseOut
) external returns (uint256 tokenUsed, uint256 baseOut);
/// @notice Arbitrage between yield token and stable token.
/// @param srcToken The address of source token.
/// @param amountIn The amount of source token to use.
/// @param receiver The address of bonus receiver.
/// @param data The hook data to `onSwap`.
/// @return amountOut The amount of target token swapped.
/// @return bonusOut The amount of bonus token.
function arbitrage(
address srcToken,
uint256 amountIn,
address receiver,
bytes calldata data
) external returns (uint256 amountOut, uint256 bonusOut);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IFxUSDRegeneracy {
/**********
* Events *
**********/
/// @notice Emitted when rebalance/liquidate with stable token.
/// @param amountStable The amount of stable token used.
/// @param amountFxUSD The corresponding amount of fxUSD.
event RebalanceWithStable(uint256 amountStable, uint256 amountFxUSD);
/// @notice Emitted when buyback fxUSD with stable reserve.
/// @param amountStable the amount of stable token used.
/// @param amountFxUSD The amount of fxUSD bought.
/// @param bonusFxUSD The amount of fxUSD as bonus for caller.
event Buyback(uint256 amountStable, uint256 amountFxUSD, uint256 bonusFxUSD);
/*************************
* Public View Functions *
*************************/
/// @notice The address of `PoolManager` contract.
function poolManager() external view returns (address);
/// @notice The address of stable token.
function stableToken() external view returns (address);
/// @notice The address of `PegKeeper` contract.
function pegKeeper() external view returns (address);
/****************************
* Public Mutated Functions *
****************************/
/// @notice Mint fxUSD token someone.
function mint(address to, uint256 amount) external;
/// @notice Burn fxUSD from someone.
function burn(address from, uint256 amount) external;
/// @notice Hook for rebalance/liquidate with stable token.
/// @param amountStableToken The amount of stable token.
/// @param amountFxUSD The amount of fxUSD.
function onRebalanceWithStable(uint256 amountStableToken, uint256 amountFxUSD) external;
/// @notice Buyback fxUSD with stable token.
/// @param amountIn the amount of stable token to use.
/// @param receiver The address of bonus receiver.
/// @param data The hook data to PegKeeper.
/// @return amountOut The amount of fxUSD swapped.
/// @return bonusOut The amount of bonus fxUSD.
function buyback(
uint256 amountIn,
address receiver,
bytes calldata data
) external returns (uint256 amountOut, uint256 bonusOut);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IPegKeeper {
/**********
* Events *
**********/
/// @notice Emitted when the converter contract is updated.
/// @param oldConverter The address of previous converter contract.
/// @param newConverter The address of current converter contract.
event UpdateConverter(address indexed oldConverter, address indexed newConverter);
/// @notice Emitted when the curve pool contract is updated.
/// @param oldPool The address of previous curve pool contract.
/// @param newPool The address of current curve pool contract.
event UpdateCurvePool(address indexed oldPool, address indexed newPool);
/// @notice Emitted when the price threshold is updated.
/// @param oldThreshold The value of previous price threshold
/// @param newThreshold The value of current price threshold
event UpdatePriceThreshold(uint256 oldThreshold, uint256 newThreshold);
/*************************
* Public View Functions *
*************************/
/// @notice Return whether borrow for fxUSD is allowed.
function isBorrowAllowed() external view returns (bool);
/// @notice Return whether funding costs is enabled.
function isFundingEnabled() external view returns (bool);
/// @notice Return the price of fxUSD, multiplied by 1e18
function getFxUSDPrice() external view returns (uint256);
/****************************
* Public Mutated Functions *
****************************/
/// @notice Buyback fxUSD with stable reserve in FxUSDSave.
/// @param amountIn the amount of stable token to use.
/// @param data The hook data to `onSwap`.
/// @return amountOut The amount of fxUSD swapped.
/// @return bonusOut The amount of bonus fxUSD.
function buyback(uint256 amountIn, bytes calldata data) external returns (uint256 amountOut, uint256 bonusOut);
/// @notice Stabilize the fxUSD price in curve pool.
/// @param srcToken The address of source token (fxUSD or stable token).
/// @param amountIn the amount of source token to use.
/// @param data The hook data to `onSwap`.
/// @return amountOut The amount of target token swapped.
/// @return bonusOut The amount of bonus token.
function stabilize(
address srcToken,
uint256 amountIn,
bytes calldata data
) external returns (uint256 amountOut, uint256 bonusOut);
/// @notice Swap callback from `buyback` and `stabilize`.
/// @param srcToken The address of source token.
/// @param srcToken The address of target token.
/// @param amountIn the amount of source token to use.
/// @param data The callback data.
/// @return amountOut The amount of target token swapped.
function onSwap(
address srcToken,
address targetToken,
uint256 amountIn,
bytes calldata data
) external returns (uint256 amountOut);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IPool {
/**********
* Events *
**********/
/// @notice Emitted when price oracle is updated.
/// @param oldOracle The previous address of price oracle.
/// @param newOracle The current address of price oracle.
event UpdatePriceOracle(address oldOracle, address newOracle);
/// @notice Emitted when borrow status is updated.
/// @param status The updated borrow status.
event UpdateBorrowStatus(bool status);
/// @notice Emitted when redeem status is updated.
/// @param status The updated redeem status.
event UpdateRedeemStatus(bool status);
/// @notice Emitted when debt ratio range is updated.
/// @param minDebtRatio The current value of minimum debt ratio, multiplied by 1e18.
/// @param maxDebtRatio The current value of maximum debt ratio, multiplied by 1e18.
event UpdateDebtRatioRange(uint256 minDebtRatio, uint256 maxDebtRatio);
/// @notice Emitted when max redeem ratio per tick is updated.
/// @param ratio The current value of max redeem ratio per tick, multiplied by 1e9.
event UpdateMaxRedeemRatioPerTick(uint256 ratio);
/// @notice Emitted when the rebalance ratio is updated.
/// @param debtRatio The current value of rebalance debt ratio, multiplied by 1e18.
/// @param bonusRatio The current value of rebalance bonus ratio, multiplied by 1e9.
event UpdateRebalanceRatios(uint256 debtRatio, uint256 bonusRatio);
/// @notice Emitted when the liquidate ratio is updated.
/// @param debtRatio The current value of liquidate debt ratio, multiplied by 1e18.
/// @param bonusRatio The current value of liquidate bonus ratio, multiplied by 1e9.
event UpdateLiquidateRatios(uint256 debtRatio, uint256 bonusRatio);
/// @notice Emitted when position is updated.
/// @param position The index of this position.
/// @param tick The index of tick, this position belongs to.
/// @param collShares The amount of collateral shares in this position.
/// @param debtShares The amount of debt shares in this position.
/// @param price The price used for this operation.
event PositionSnapshot(uint256 position, int16 tick, uint256 collShares, uint256 debtShares, uint256 price);
/// @notice Emitted when tick moved due to rebalance, liquidate or redeem.
/// @param oldTick The index of the previous tick.
/// @param newTick The index of the current tick.
/// @param collShares The amount of collateral shares added to new tick.
/// @param debtShares The amount of debt shares added to new tick.
/// @param price The price used for this operation.
event TickMovement(int16 oldTick, int16 newTick, uint256 collShares, uint256 debtShares, uint256 price);
/// @notice Emitted when debt index increase.
event DebtIndexSnapshot(uint256 index);
/// @notice Emitted when collateral index increase.
event CollateralIndexSnapshot(uint256 index);
/***********
* Structs *
***********/
/// @dev The result for liquidation.
/// @param rawColls The amount of collateral tokens liquidated.
/// @param rawDebts The amount of debt tokens liquidated.
/// @param bonusRawColls The amount of bonus collateral tokens given.
/// @param bonusFromReserve The amount of bonus collateral tokens coming from reserve pool.
struct LiquidateResult {
uint256 rawColls;
uint256 rawDebts;
uint256 bonusRawColls;
uint256 bonusFromReserve;
}
/// @dev The result for rebalance.
/// @param rawColls The amount of collateral tokens rebalanced.
/// @param rawDebts The amount of debt tokens rebalanced.
/// @param bonusRawColls The amount of bonus collateral tokens given.
struct RebalanceResult {
uint256 rawColls;
uint256 rawDebts;
uint256 bonusRawColls;
}
/*************************
* Public View Functions *
*************************/
/// @notice The address of fxUSD.
function fxUSD() external view returns (address);
/// @notice The address of `PoolManager` contract.
function poolManager() external view returns (address);
/// @notice The address of `PegKeeper` contract.
function pegKeeper() external view returns (address);
/// @notice The address of collateral token.
function collateralToken() external view returns (address);
/// @notice The address of price oracle.
function priceOracle() external view returns (address);
/// @notice Return whether borrow is paused.
function isBorrowPaused() external view returns (bool);
/// @notice Return whether redeem is paused.
function isRedeemPaused() external view returns (bool);
/// @notice Return the current top tick with debts.
function getTopTick() external view returns (int16);
/// @notice Return the next position id.
function getNextPositionId() external view returns (uint32);
/// @notice Return the next tick tree node id.
function getNextTreeNodeId() external view returns (uint48);
/// @notice Return the debt ratio range.
/// @param minDebtRatio The minimum required debt ratio, multiplied by 1e18.
/// @param maxDebtRatio The minimum allowed debt ratio, multiplied by 1e18.
function getDebtRatioRange() external view returns (uint256 minDebtRatio, uint256 maxDebtRatio);
/// @notice Return the maximum redeem percentage per tick, multiplied by 1e9.
function getMaxRedeemRatioPerTick() external view returns (uint256);
/// @notice Get `debtRatio` and `bonusRatio` for rebalance.
/// @return debtRatio The minimum debt ratio to start rebalance, multiplied by 1e18.
/// @return bonusRatio The bonus ratio during rebalance, multiplied by 1e9.
function getRebalanceRatios() external view returns (uint256 debtRatio, uint256 bonusRatio);
/// @notice Get `debtRatio` and `bonusRatio` for liquidate.
/// @return debtRatio The minimum debt ratio to start liquidate, multiplied by 1e18.
/// @return bonusRatio The bonus ratio during liquidate, multiplied by 1e9.
function getLiquidateRatios() external view returns (uint256 debtRatio, uint256 bonusRatio);
/// @notice Get debt and collateral index.
/// @return debtIndex The index for debt shares.
/// @return collIndex The index for collateral shares.
function getDebtAndCollateralIndex() external view returns (uint256 debtIndex, uint256 collIndex);
/// @notice Get debt and collateral shares.
/// @return debtShares The total number of debt shares.
/// @return collShares The total number of collateral shares.
function getDebtAndCollateralShares() external view returns (uint256 debtShares, uint256 collShares);
/// @notice Return the details of the given position.
/// @param tokenId The id of position to query.
/// @return rawColls The amount of collateral tokens supplied in this position.
/// @return rawDebts The amount of debt tokens borrowed in this position.
function getPosition(uint256 tokenId) external view returns (uint256 rawColls, uint256 rawDebts);
/// @notice Return the debt ratio of the given position.
/// @param tokenId The id of position to query.
/// @return debtRatio The debt ratio of this position.
function getPositionDebtRatio(uint256 tokenId) external view returns (uint256 debtRatio);
/// @notice The total amount of raw collateral tokens.
function getTotalRawCollaterals() external view returns (uint256);
/// @notice The total amount of raw debt tokens.
function getTotalRawDebts() external view returns (uint256);
/****************************
* Public Mutated Functions *
****************************/
/// @notice Open a new position or operate on an old position.
/// @param positionId The id of the position. If `positionId=0`, it means we need to open a new position.
/// @param newRawColl The amount of collateral token to supply (positive value) or withdraw (negative value).
/// @param newRawColl The amount of debt token to borrow (positive value) or repay (negative value).
/// @param owner The address of position owner.
/// @return actualPositionId The id of this position.
/// @return actualRawColl The actual amount of collateral tokens supplied (positive value) or withdrawn (negative value).
/// @return actualRawDebt The actual amount of debt tokens borrowed (positive value) or repay (negative value).
function operate(
uint256 positionId,
int256 newRawColl,
int256 newRawDebt,
address owner
) external returns (uint256 actualPositionId, int256 actualRawColl, int256 actualRawDebt, uint256 protocolFees);
/// @notice Redeem debt tokens to get collateral tokens.
/// @param rawDebts The amount of debt tokens to redeem.
/// @return rawColls The amount of collateral tokens to redeemed.
function redeem(uint256 rawDebts) external returns (uint256 rawColls);
/// @notice Rebalance all positions in the given tick.
/// @param tick The id of tick to rebalance.
/// @param maxRawDebts The maximum amount of debt tokens to rebalance.
/// @return result The result of rebalance.
function rebalance(int16 tick, uint256 maxRawDebts) external returns (RebalanceResult memory result);
/// @notice Rebalance all ticks in the decreasing order of LTV.
/// @param maxRawDebts The maximum amount of debt tokens to rebalance.
/// @return result The result of rebalance.
function rebalance(uint256 maxRawDebts) external returns (RebalanceResult memory result);
/// @notice Liquidate all ticks in the decreasing order of LTV.
/// @param maxRawDebts The maximum amount of debt tokens to liquidate.
/// @param reservedRawColls The amount of collateral tokens in reserve pool.
/// @return result The result of liquidate.
function liquidate(uint256 maxRawDebts, uint256 reservedRawColls) external returns (LiquidateResult memory result);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IPoolManager {
/**********
* Events *
**********/
/// @notice Register a new pool.
/// @param pool The address of fx pool.
event RegisterPool(address indexed pool);
/// @notice Emitted when the reward splitter contract is updated.
/// @param pool The address of fx pool.
/// @param oldSplitter The address of previous reward splitter contract.
/// @param newSplitter The address of current reward splitter contract.
event UpdateRewardSplitter(address indexed pool, address indexed oldSplitter, address indexed newSplitter);
/// @notice Emitted when the threshold for permissionless liquidate/rebalance is updated.
/// @param oldThreshold The value of previous threshold.
/// @param newThreshold The value of current threshold.
event UpdatePermissionedLiquidationThreshold(uint256 oldThreshold, uint256 newThreshold);
/// @notice Emitted when token rate is updated.
/// @param scalar The token scalar to reach 18 decimals.
/// @param provider The address of token rate provider.
event UpdateTokenRate(address indexed token, uint256 scalar, address provider);
/// @notice Emitted when pool capacity is updated.
/// @param pool The address of fx pool.
/// @param collateralCapacity The capacity for collateral token.
/// @param debtCapacity The capacity for debt token.
event UpdatePoolCapacity(address indexed pool, uint256 collateralCapacity, uint256 debtCapacity);
/// @notice Emitted when position is updated.
/// @param pool The address of pool where the position belongs to.
/// @param position The id of the position.
/// @param deltaColls The amount of collateral token changes.
/// @param deltaDebts The amount of debt token changes.
/// @param protocolFees The amount of protocol fees charges.
event Operate(
address indexed pool,
uint256 indexed position,
int256 deltaColls,
int256 deltaDebts,
uint256 protocolFees
);
/// @notice Emitted when redeem happened.
/// @param pool The address of pool redeemed.
/// @param colls The amount of collateral tokens redeemed.
/// @param debts The amount of debt tokens redeemed.
/// @param protocolFees The amount of protocol fees charges.
event Redeem(address indexed pool, uint256 colls, uint256 debts, uint256 protocolFees);
/// @notice Emitted when rebalance for a tick happened.
/// @param pool The address of pool rebalanced.
/// @param tick The index of tick rebalanced.
/// @param colls The amount of collateral tokens rebalanced.
/// @param fxUSDDebts The amount of fxUSD rebalanced.
/// @param stableDebts The amount of stable token (a.k.a USDC) rebalanced.
event RebalanceTick(address indexed pool, int16 indexed tick, uint256 colls, uint256 fxUSDDebts, uint256 stableDebts);
/// @notice Emitted when rebalance happened.
/// @param pool The address of pool rebalanced.
/// @param colls The amount of collateral tokens rebalanced.
/// @param fxUSDDebts The amount of fxUSD rebalanced.
/// @param stableDebts The amount of stable token (a.k.a USDC) rebalanced.
event Rebalance(address indexed pool, uint256 colls, uint256 fxUSDDebts, uint256 stableDebts);
/// @notice Emitted when liquidate happened.
/// @param pool The address of pool liquidated.
/// @param colls The amount of collateral tokens liquidated.
/// @param fxUSDDebts The amount of fxUSD liquidated.
/// @param stableDebts The amount of stable token (a.k.a USDC) liquidated.
event Liquidate(address indexed pool, uint256 colls, uint256 fxUSDDebts, uint256 stableDebts);
/// @notice Emitted when someone harvest pending rewards.
/// @param caller The address of caller.
/// @param amountRewards The amount of total harvested rewards.
/// @param amountFunding The amount of total harvested funding.
/// @param performanceFee The amount of harvested rewards distributed to protocol revenue.
/// @param harvestBounty The amount of harvested rewards distributed to caller as harvest bounty.
event Harvest(
address indexed caller,
address indexed pool,
uint256 amountRewards,
uint256 amountFunding,
uint256 performanceFee,
uint256 harvestBounty
);
/*************************
* Public View Functions *
*************************/
/// @notice The address of fxUSD.
function fxUSD() external view returns (address);
/// @notice The address of FxUSDSave.
function fxBASE() external view returns (address);
/// @notice The address of `PegKeeper`.
function pegKeeper() external view returns (address);
/// @notice The address of reward splitter.
function rewardSplitter(address pool) external view returns (address);
/****************************
* Public Mutated Functions *
****************************/
/// @notice Open a new position or operate on an old position.
/// @param pool The address of pool to operate.
/// @param positionId The id of the position. If `positionId=0`, it means we need to open a new position.
/// @param newColl The amount of collateral token to supply (positive value) or withdraw (negative value).
/// @param newDebt The amount of debt token to borrow (positive value) or repay (negative value).
/// @return actualPositionId The id of this position.
function operate(
address pool,
uint256 positionId,
int256 newColl,
int256 newDebt
) external returns (uint256 actualPositionId);
/// @notice Redeem debt tokens to get collateral tokens.
/// @param pool The address of pool to redeem.
/// @param debts The amount of debt tokens to redeem.
/// @param minColls The minimum amount of collateral tokens should redeem.
/// @return colls The amount of collateral tokens redeemed.
function redeem(address pool, uint256 debts, uint256 minColls) external returns (uint256 colls);
/// @notice Rebalance all positions in the given tick.
/// @param pool The address of pool to rebalance.
/// @param receiver The address of recipient for rebalanced tokens.
/// @param tick The index of tick to rebalance.
/// @param maxFxUSD The maximum amount of fxUSD to rebalance.
/// @param maxStable The maximum amount of stable token (a.k.a USDC) to rebalance.
/// @return colls The amount of collateral tokens rebalanced.
/// @return fxUSDUsed The amount of fxUSD used to rebalance.
/// @return stableUsed The amount of stable token used to rebalance.
function rebalance(
address pool,
address receiver,
int16 tick,
uint256 maxFxUSD,
uint256 maxStable
) external returns (uint256 colls, uint256 fxUSDUsed, uint256 stableUsed);
/// @notice Rebalance all positions in the given tick.
/// @param pool The address of pool to rebalance.
/// @param receiver The address of recipient for rebalanced tokens.
/// @param maxFxUSD The maximum amount of fxUSD to rebalance.
/// @param maxStable The maximum amount of stable token (a.k.a USDC) to rebalance.
/// @return colls The amount of collateral tokens rebalanced.
/// @return fxUSDUsed The amount of fxUSD used to rebalance.
/// @return stableUsed The amount of stable token used to rebalance.
function rebalance(
address pool,
address receiver,
uint256 maxFxUSD,
uint256 maxStable
) external returns (uint256 colls, uint256 fxUSDUsed, uint256 stableUsed);
/// @notice Liquidate a given position.
/// @param pool The address of pool to liquidate.
/// @param receiver The address of recipient for liquidated tokens.
/// @param maxFxUSD The maximum amount of fxUSD to liquidate.
/// @param maxStable The maximum amount of stable token (a.k.a USDC) to liquidate.
/// @return colls The amount of collateral tokens liquidated.
/// @return fxUSDUsed The amount of fxUSD used to liquidate.
/// @return stableUsed The amount of stable token used to liquidate.
function liquidate(
address pool,
address receiver,
uint256 maxFxUSD,
uint256 maxStable
) external returns (uint256 colls, uint256 fxUSDUsed, uint256 stableUsed);
/// @notice Harvest pending rewards of the given pool.
/// @param pool The address of pool to harvest.
/// @return amountRewards The amount of rewards harvested.
/// @return amountFunding The amount of funding harvested.
function harvest(address pool) external returns (uint256 amountRewards, uint256 amountFunding);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IProtocolFees {
/**********
* Events *
**********/
/// @notice Emitted when the reserve pool contract is updated.
/// @param oldReservePool The address of previous reserve pool.
/// @param newReservePool The address of current reserve pool.
event UpdateReservePool(address indexed oldReservePool, address indexed newReservePool);
/// @notice Emitted when the treasury contract is updated.
/// @param oldTreasury The address of previous treasury contract.
/// @param newTreasury The address of current treasury contract.
event UpdateTreasury(address indexed oldTreasury, address indexed newTreasury);
/// @notice Emitted when the open revenue pool contract is updated.
/// @param oldPool The address of previous revenue pool contract.
/// @param newPool The address of current revenue pool contract.
event UpdateOpenRevenuePool(address indexed oldPool, address indexed newPool);
/// @notice Emitted when the close revenue pool contract is updated.
/// @param oldPool The address of previous revenue pool contract.
/// @param newPool The address of current revenue pool contract.
event UpdateCloseRevenuePool(address indexed oldPool, address indexed newPool);
/// @notice Emitted when the misc revenue pool contract is updated.
/// @param oldPool The address of previous revenue pool contract.
/// @param newPool The address of current revenue pool contract.
event UpdateMiscRevenuePool(address indexed oldPool, address indexed newPool);
/// @notice Emitted when the ratio for treasury is updated.
/// @param oldRatio The value of the previous ratio, multiplied by 1e9.
/// @param newRatio The value of the current ratio, multiplied by 1e9.
event UpdateRewardsExpenseRatio(uint256 oldRatio, uint256 newRatio);
/// @notice Emitted when the ratio for treasury is updated.
/// @param oldRatio The value of the previous ratio, multiplied by 1e9.
/// @param newRatio The value of the current ratio, multiplied by 1e9.
event UpdateFundingExpenseRatio(uint256 oldRatio, uint256 newRatio);
/// @notice Emitted when the ratio for treasury is updated.
/// @param oldRatio The value of the previous ratio, multiplied by 1e9.
/// @param newRatio The value of the current ratio, multiplied by 1e9.
event UpdateLiquidationExpenseRatio(uint256 oldRatio, uint256 newRatio);
/// @notice Emitted when the ratio for harvester is updated.
/// @param oldRatio The value of the previous ratio, multiplied by 1e9.
/// @param newRatio The value of the current ratio, multiplied by 1e9.
event UpdateHarvesterRatio(uint256 oldRatio, uint256 newRatio);
/// @notice Emitted when the flash loan fee ratio is updated.
/// @param oldRatio The value of the previous ratio, multiplied by 1e9.
/// @param newRatio The value of the current ratio, multiplied by 1e9.
event UpdateFlashLoanFeeRatio(uint256 oldRatio, uint256 newRatio);
/// @notice Emitted when the redeem fee ratio is updated.
/// @param oldRatio The value of the previous ratio, multiplied by 1e9.
/// @param newRatio The value of the current ratio, multiplied by 1e9.
event UpdateRedeemFeeRatio(uint256 oldRatio, uint256 newRatio);
/*************************
* Public View Functions *
*************************/
/// @notice Return the fee ratio distributed as protocol revenue in funding costs, multiplied by 1e9.
function getFundingExpenseRatio() external view returns (uint256);
/// @notice Return the fee ratio distributed as protocol revenue in general rewards, multiplied by 1e9.
function getRewardsExpenseRatio() external view returns (uint256);
/// @notice Return the fee ratio distributed as protocol revenue in liquidation/rebalance, multiplied by 1e9.
function getLiquidationExpenseRatio() external view returns (uint256);
/// @notice Return the fee ratio distributed to fxBASE in funding costs, multiplied by 1e9.
function getFundingFxSaveRatio() external view returns (uint256);
/// @notice Return the fee ratio distributed to fxBASE in general rewards, multiplied by 1e9.
function getRewardsFxSaveRatio() external view returns (uint256);
/// @notice Return the fee ratio distributed ad harvester bounty, multiplied by 1e9.
function getHarvesterRatio() external view returns (uint256);
/// @notice Return the flash loan fee ratio, multiplied by 1e9.
function getFlashLoanFeeRatio() external view returns (uint256);
/// @notice Return the redeem fee ratio, multiplied by 1e9.
function getRedeemFeeRatio() external view returns (uint256);
/// @notice Return the address of reserve pool.
function reservePool() external view returns (address);
/// @notice Return the address of protocol treasury.
function treasury() external view returns (address);
/// @notice Return the address of protocol revenue pool.
function openRevenuePool() external view returns (address);
/// @notice Return the address of protocol revenue pool.
function closeRevenuePool() external view returns (address);
/// @notice Return the address of protocol revenue pool.
function miscRevenuePool() external view returns (address);
/// @notice Return the amount of protocol open fees accumulated by the given pool.
function accumulatedPoolOpenFees(address pool) external view returns (uint256);
/// @notice Return the amount of protocol close fees accumulated by the given pool.
function accumulatedPoolCloseFees(address pool) external view returns (uint256);
/// @notice Return the amount of protocol misc fees accumulated by the given pool.
function accumulatedPoolMiscFees(address pool) external view returns (uint256);
/****************************
* Public Mutated Functions *
****************************/
/// @notice Withdraw accumulated pool fee for the given pool lists.
/// @param pools The list of pool addresses to withdraw.
function withdrawAccumulatedPoolFee(address[] memory pools) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IReservePool {
/// @notice Emitted when the market request bonus.
/// @param token The address of the token requested.
/// @param receiver The address of token receiver.
/// @param bonus The amount of bonus token.
event RequestBonus(address indexed token, address indexed receiver, uint256 bonus);
/*************************
* Public View Functions *
*************************/
/// @notice Return the balance of token in this contract.
function getBalance(address token) external view returns (uint256);
/****************************
* Public Mutated Functions *
****************************/
/// @notice Request bonus token from Reserve Pool.
/// @param token The address of token to request.
/// @param receiver The address recipient for the bonus token.
/// @param bonus The amount of bonus token to send.
function requestBonus(address token, address receiver, uint256 bonus) external;
/// @notice Withdraw dust assets in this contract.
/// @param token The address of token to withdraw.
/// @param amount The amount of token to withdraw.
/// @param recipient The address of token receiver.
function withdrawFund(address token, uint256 amount, address recipient) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IRewardSplitter {
/****************************
* Public Mutated Functions *
****************************/
/// @notice Split token to different RebalancePool.
/// @param token The address of token to split.
function split(address token) external;
/// @notice Deposit new rewards to this contract.
///
/// @param token The address of reward token.
/// @param amount The amount of new rewards.
function depositReward(address token, uint256 amount) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface ISavingFxUSD {
/**********
* Events *
**********/
/// @notice Emitted when the threshold for batch deposit is updated.
/// @param oldThreshold The value of the previous threshold.
/// @param newThreshold The value of the current threshold.
event UpdateThreshold(uint256 oldThreshold, uint256 newThreshold);
/// @notice Emitted when user direct request unlocking through this contract.
/// @param owner The address of token owner.
/// @param shares The amount of shares to unlock.
/// @param assets The amount of corresponding assets.
event RequestRedeem(address owner, uint256 shares, uint256 assets);
/// @notice Emitted when user claim unlocked tokens.
/// @param owner The address of token owner.
/// @param receiver The address of token receiver.
event Claim(address owner, address receiver);
/*************************
* Public View Functions *
*************************/
/// @notice Return the net asset value, multiplied by 1e18.
function nav() external view returns (uint256);
/****************************
* Public Mutated Functions *
****************************/
/// @notice Deposit with gauge token.
/// @param assets The amount of gauge token.
/// @param receiver The address of pool share recipient.
function depositGauge(uint256 assets, address receiver) external returns (uint256);
/// @notice Harvest the pending rewards.
function harvest() external;
/// @notice Request redeem.
/// @param shares The amount of shares to request.
/// @return assets The amount of corresponding assets.
function requestRedeem(uint256 shares) external returns (uint256);
/// @notice Claim unlocked tokens.
/// @param receiver The address of recipient.
function claim(address receiver) external;
/// @notice Claim unlocked tokens for someone.
/// @param owner The address of token owner.
/// @param receiver The address of recipient.
function claimFor(address owner, address receiver) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IWrappedEther {
function deposit() external payable;
function withdraw(uint256 wad) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IMorpho {
/// @notice Executes a flash loan.
/// @dev Flash loans have access to the whole balance of the contract (the liquidity and deposited collateral of all
/// markets combined, plus donations).
/// @dev Warning: Not ERC-3156 compliant but compatibility is easily reached:
/// - `flashFee` is zero.
/// - `maxFlashLoan` is the token's balance of this contract.
/// - The receiver of `assets` is the caller.
/// @param token The token to flash loan.
/// @param assets The amount of assets to flash loan.
/// @param data Arbitrary data to pass to the `onMorphoFlashLoan` callback.
function flashLoan(address token, uint256 assets, bytes calldata data) external;
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
/// @title BitMath
/// @dev This library provides functionality for computing bit properties of an unsigned integer
///
/// copy from: https://github.com/Uniswap/v3-core/blob/main/contracts/libraries/BitMath.sol
library BitMath {
/// @notice Returns the index of the most significant bit of the number,
/// where the least significant bit is at index 0 and the most significant bit is at index 255
/// @dev The function satisfies the property:
/// x >= 2**mostSignificantBit(x) and x < 2**(mostSignificantBit(x)+1)
/// @param x the value for which to compute the most significant bit, must be greater than 0
/// @return r the index of the most significant bit
function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0);
if (x >= 0x100000000000000000000000000000000) {
x >>= 128;
r += 128;
}
if (x >= 0x10000000000000000) {
x >>= 64;
r += 64;
}
if (x >= 0x100000000) {
x >>= 32;
r += 32;
}
if (x >= 0x10000) {
x >>= 16;
r += 16;
}
if (x >= 0x100) {
x >>= 8;
r += 8;
}
if (x >= 0x10) {
x >>= 4;
r += 4;
}
if (x >= 0x4) {
x >>= 2;
r += 2;
}
if (x >= 0x2) r += 1;
}
/// @notice Returns the index of the least significant bit of the number,
/// where the least significant bit is at index 0 and the most significant bit is at index 255
/// @dev The function satisfies the property:
/// (x & 2**leastSignificantBit(x)) != 0 and (x & (2**(leastSignificantBit(x)) - 1)) == 0)
/// @param x the value for which to compute the least significant bit, must be greater than 0
/// @return r the index of the least significant bit
function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0);
r = 255;
if (x & type(uint128).max > 0) {
r -= 128;
} else {
x >>= 128;
}
if (x & type(uint64).max > 0) {
r -= 64;
} else {
x >>= 64;
}
if (x & type(uint32).max > 0) {
r -= 32;
} else {
x >>= 32;
}
if (x & type(uint16).max > 0) {
r -= 16;
} else {
x >>= 16;
}
if (x & type(uint8).max > 0) {
r -= 8;
} else {
x >>= 8;
}
if (x & 0xf > 0) {
r -= 4;
} else {
x >>= 4;
}
if (x & 0x3 > 0) {
r -= 2;
} else {
x >>= 2;
}
if (x & 0x1 > 0) r -= 1;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
library Math {
enum Rounding {
Up,
Down
}
/// @dev Internal return the value of min(a, b).
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/// @dev Internal return the value of max(a, b).
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/// @dev Internal return the value of a * b / c, with rounding.
function mulDiv(uint256 a, uint256 b, uint256 c, Rounding rounding) internal pure returns (uint256) {
return rounding == Rounding.Down ? mulDivDown(a, b, c) : mulDivUp(a, b, c);
}
/// @dev Internal return the value of ceil(a * b / c).
function mulDivUp(uint256 a, uint256 b, uint256 c) internal pure returns (uint256) {
return (a * b + c - 1) / c;
}
/// @dev Internal return the value of floor(a * b / c).
function mulDivDown(uint256 a, uint256 b, uint256 c) internal pure returns (uint256) {
return (a * b) / c;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import { BitMath } from "./BitMath.sol";
library TickBitmap {
function position(int16 tick) private pure returns (int8 wordPos, uint8 bitPos) {
assembly {
wordPos := shr(8, tick)
bitPos := and(tick, 255)
}
}
function flipTick(mapping(int8 => uint256) storage self, int16 tick) internal {
(int8 wordPos, uint8 bitPos) = position(tick);
uint256 mask = 1 << bitPos;
self[wordPos] ^= mask;
}
function isBitSet(mapping(int8 => uint256) storage self, int16 tick) internal view returns (bool) {
(int8 wordPos, uint8 bitPos) = position(tick);
uint256 mask = 1 << bitPos;
return (self[wordPos] & mask) > 0;
}
/// @notice Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is
/// to the left (less than or equal to).
function nextDebtPositionWithinOneWord(
mapping(int8 => uint256) storage self,
int16 tick
) internal view returns (int16 next, bool hasDebt) {
unchecked {
// start from the word of the next tick, since the current tick state doesn't matter
(int8 wordPos, uint8 bitPos) = position(tick);
// all the 1s at or to the right of the current bitPos
uint256 mask = (1 << bitPos) - 1 + (1 << bitPos);
uint256 masked = self[wordPos] & mask;
// if there are no initialized ticks to the left of the current tick, return leftmost in the word
hasDebt = masked != 0;
// overflow/underflow is possible, but prevented externally by limiting tick
next = hasDebt
? (tick - int16(uint16(bitPos - BitMath.mostSignificantBit(masked))))
: (tick - int16(uint16(bitPos)));
}
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.26;
/// @title library that calculates number "tick" and "ratioX96" from this: ratioX96 = (1.0015^tick) * 2^96
/// @notice this library is used in Fluid Vault protocol for optimiziation.
/// @dev "tick" supports between -32767 and 32767. "ratioX96" supports between 37075072 and 169307877264527972847801929085841449095838922544595
///
/// @dev Copy from https://github.com/Instadapp/fluid-contracts-public/blob/main/contracts/libraries/tickMath.sol
library TickMath {
/// The minimum tick that can be passed in getRatioAtTick. 1.0015**-32767
int24 internal constant MIN_TICK = -32767;
/// The maximum tick that can be passed in getRatioAtTick. 1.0015**32767
int24 internal constant MAX_TICK = 32767;
uint256 internal constant FACTOR00 = 0x100000000000000000000000000000000;
uint256 internal constant FACTOR01 = 0xff9dd7de423466c20352b1246ce4856f; // 2^128/1.0015**1 = 339772707859149738855091969477551883631
uint256 internal constant FACTOR02 = 0xff3bd55f4488ad277531fa1c725a66d0; // 2^128/1.0015**2 = 339263812140938331358054887146831636176
uint256 internal constant FACTOR03 = 0xfe78410fd6498b73cb96a6917f853259; // 2^128/1.0015**4 = 338248306163758188337119769319392490073
uint256 internal constant FACTOR04 = 0xfcf2d9987c9be178ad5bfeffaa123273; // 2^128/1.0015**8 = 336226404141693512316971918999264834163
uint256 internal constant FACTOR05 = 0xf9ef02c4529258b057769680fc6601b3; // 2^128/1.0015**16 = 332218786018727629051611634067491389875
uint256 internal constant FACTOR06 = 0xf402d288133a85a17784a411f7aba082; // 2^128/1.0015**32 = 324346285652234375371948336458280706178
uint256 internal constant FACTOR07 = 0xe895615b5beb6386553757b0352bda90; // 2^128/1.0015**64 = 309156521885964218294057947947195947664
uint256 internal constant FACTOR08 = 0xd34f17a00ffa00a8309940a15930391a; // 2^128/1.0015**128 = 280877777739312896540849703637713172762
uint256 internal constant FACTOR09 = 0xae6b7961714e20548d88ea5123f9a0ff; // 2^128/1.0015**256 = 231843708922198649176471782639349113087
uint256 internal constant FACTOR10 = 0x76d6461f27082d74e0feed3b388c0ca1; // 2^128/1.0015**512 = 157961477267171621126394973980180876449
uint256 internal constant FACTOR11 = 0x372a3bfe0745d8b6b19d985d9a8b85bb; // 2^128/1.0015**1024 = 73326833024599564193373530205717235131
uint256 internal constant FACTOR12 = 0x0be32cbee48979763cf7247dd7bb539d; // 2^128/1.0015**2048 = 15801066890623697521348224657638773661
uint256 internal constant FACTOR13 = 0x8d4f70c9ff4924dac37612d1e2921e; // 2^128/1.0015**4096 = 733725103481409245883800626999235102
uint256 internal constant FACTOR14 = 0x4e009ae5519380809a02ca7aec77; // 2^128/1.0015**8192 = 1582075887005588088019997442108535
uint256 internal constant FACTOR15 = 0x17c45e641b6e95dee056ff10; // 2^128/1.0015**16384 = 7355550435635883087458926352
/// The minimum value that can be returned from getRatioAtTick. Equivalent to getRatioAtTick(MIN_TICK). ~ Equivalent to `(1 << 96) * (1.0015**-32767)`
uint256 internal constant MIN_RATIOX96 = 37075072;
/// The maximum value that can be returned from getRatioAtTick. Equivalent to getRatioAtTick(MAX_TICK).
/// ~ Equivalent to `(1 << 96) * (1.0015**32767)`, rounding etc. leading to minor difference
uint256 internal constant MAX_RATIOX96 = 169307877264527972847801929085841449095838922544595;
uint256 internal constant ZERO_TICK_SCALED_RATIO = 0x1000000000000000000000000; // 1 << 96 // 79228162514264337593543950336
uint256 internal constant _1E26 = 1e26;
/// @notice ratioX96 = (1.0015^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return ratioX96 ratio = (debt amount/collateral amount)
function getRatioAtTick(int tick) internal pure returns (uint256 ratioX96) {
assembly {
let absTick_ := sub(xor(tick, sar(255, tick)), sar(255, tick))
if gt(absTick_, MAX_TICK) {
revert(0, 0)
}
let factor_ := FACTOR00
if and(absTick_, 0x1) {
factor_ := FACTOR01
}
if and(absTick_, 0x2) {
factor_ := shr(128, mul(factor_, FACTOR02))
}
if and(absTick_, 0x4) {
factor_ := shr(128, mul(factor_, FACTOR03))
}
if and(absTick_, 0x8) {
factor_ := shr(128, mul(factor_, FACTOR04))
}
if and(absTick_, 0x10) {
factor_ := shr(128, mul(factor_, FACTOR05))
}
if and(absTick_, 0x20) {
factor_ := shr(128, mul(factor_, FACTOR06))
}
if and(absTick_, 0x40) {
factor_ := shr(128, mul(factor_, FACTOR07))
}
if and(absTick_, 0x80) {
factor_ := shr(128, mul(factor_, FACTOR08))
}
if and(absTick_, 0x100) {
factor_ := shr(128, mul(factor_, FACTOR09))
}
if and(absTick_, 0x200) {
factor_ := shr(128, mul(factor_, FACTOR10))
}
if and(absTick_, 0x400) {
factor_ := shr(128, mul(factor_, FACTOR11))
}
if and(absTick_, 0x800) {
factor_ := shr(128, mul(factor_, FACTOR12))
}
if and(absTick_, 0x1000) {
factor_ := shr(128, mul(factor_, FACTOR13))
}
if and(absTick_, 0x2000) {
factor_ := shr(128, mul(factor_, FACTOR14))
}
if and(absTick_, 0x4000) {
factor_ := shr(128, mul(factor_, FACTOR15))
}
let precision_ := 0
if iszero(and(tick, 0x8000000000000000000000000000000000000000000000000000000000000000)) {
factor_ := div(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, factor_)
// we round up in the division so getTickAtRatio of the output price is always consistent
if mod(factor_, 0x100000000) {
precision_ := 1
}
}
ratioX96 := add(shr(32, factor_), precision_)
}
}
/// @notice ratioX96 = (1.0015^tick) * 2^96
/// @dev Throws if ratioX96 > max ratio || ratioX96 < min ratio
/// @param ratioX96 The input ratio; ratio = (debt amount/collateral amount)
/// @return tick The output tick for the above formula. Returns in round down form. if tick is 123.23 then 123, if tick is -123.23 then returns -124
/// @return perfectRatioX96 perfect ratio for the above tick
function getTickAtRatio(uint256 ratioX96) internal pure returns (int tick, uint perfectRatioX96) {
assembly {
if or(gt(ratioX96, MAX_RATIOX96), lt(ratioX96, MIN_RATIOX96)) {
revert(0, 0)
}
let cond := lt(ratioX96, ZERO_TICK_SCALED_RATIO)
let factor_
if iszero(cond) {
// if ratioX96 >= ZERO_TICK_SCALED_RATIO
factor_ := div(mul(ratioX96, _1E26), ZERO_TICK_SCALED_RATIO)
}
if cond {
// ratioX96 < ZERO_TICK_SCALED_RATIO
factor_ := div(mul(ZERO_TICK_SCALED_RATIO, _1E26), ratioX96)
}
// put in https://www.wolframalpha.com/ whole equation: (1.0015^tick) * 2^96 * 10^26 / 79228162514264337593543950336
// for tick = 16384
// ratioX96 = (1.0015^16384) * 2^96 = 3665252098134783297721995888537077351735
// 3665252098134783297721995888537077351735 * 10^26 / 79228162514264337593543950336 =
// 4626198540796508716348404308345255985.06131964639489434655721
if iszero(lt(factor_, 4626198540796508716348404308345255985)) {
tick := or(tick, 0x4000)
factor_ := div(mul(factor_, _1E26), 4626198540796508716348404308345255985)
}
// for tick = 8192
// ratioX96 = (1.0015^8192) * 2^96 = 17040868196391020479062776466509865
// 17040868196391020479062776466509865 * 10^26 / 79228162514264337593543950336 =
// 21508599537851153911767490449162.3037648642153898377655505172
if iszero(lt(factor_, 21508599537851153911767490449162)) {
tick := or(tick, 0x2000)
factor_ := div(mul(factor_, _1E26), 21508599537851153911767490449162)
}
// for tick = 4096
// ratioX96 = (1.0015^4096) * 2^96 = 36743933851015821532611831851150
// 36743933851015821532611831851150 * 10^26 / 79228162514264337593543950336 =
// 46377364670549310883002866648.9777607649742626173648716941385
if iszero(lt(factor_, 46377364670549310883002866649)) {
tick := or(tick, 0x1000)
factor_ := div(mul(factor_, _1E26), 46377364670549310883002866649)
}
// for tick = 2048
// ratioX96 = (1.0015^2048) * 2^96 = 1706210527034005899209104452335
// 1706210527034005899209104452335 * 10^26 / 79228162514264337593543950336 =
// 2153540449365864845468344760.06357108484096046743300420319322
if iszero(lt(factor_, 2153540449365864845468344760)) {
tick := or(tick, 0x800)
factor_ := div(mul(factor_, _1E26), 2153540449365864845468344760)
}
// for tick = 1024
// ratioX96 = (1.0015^1024) * 2^96 = 367668226692760093024536487236
// 367668226692760093024536487236 * 10^26 / 79228162514264337593543950336 =
// 464062544207767844008185024.950588990554136265212906454481127
if iszero(lt(factor_, 464062544207767844008185025)) {
tick := or(tick, 0x400)
factor_ := div(mul(factor_, _1E26), 464062544207767844008185025)
}
// for tick = 512
// ratioX96 = (1.0015^512) * 2^96 = 170674186729409605620119663668
// 170674186729409605620119663668 * 10^26 / 79228162514264337593543950336 =
// 215421109505955298802281577.031879604792139232258508172947569
if iszero(lt(factor_, 215421109505955298802281577)) {
tick := or(tick, 0x200)
factor_ := div(mul(factor_, _1E26), 215421109505955298802281577)
}
// for tick = 256
// ratioX96 = (1.0015^256) * 2^96 = 116285004205991934861656513301
// 116285004205991934861656513301 * 10^26 / 79228162514264337593543950336 =
// 146772309890508740607270614.667650899656438875541505058062410
if iszero(lt(factor_, 146772309890508740607270615)) {
tick := or(tick, 0x100)
factor_ := div(mul(factor_, _1E26), 146772309890508740607270615)
}
// for tick = 128
// ratioX96 = (1.0015^128) * 2^96 = 95984619659632141743747099590
// 95984619659632141743747099590 * 10^26 / 79228162514264337593543950336 =
// 121149622323187099817270416.157248837742741760456796835775887
if iszero(lt(factor_, 121149622323187099817270416)) {
tick := or(tick, 0x80)
factor_ := div(mul(factor_, _1E26), 121149622323187099817270416)
}
// for tick = 64
// ratioX96 = (1.0015^64) * 2^96 = 87204845308406958006717891124
// 87204845308406958006717891124 * 10^26 / 79228162514264337593543950336 =
// 110067989135437147685980801.568068573422377364214113968609839
if iszero(lt(factor_, 110067989135437147685980801)) {
tick := or(tick, 0x40)
factor_ := div(mul(factor_, _1E26), 110067989135437147685980801)
}
// for tick = 32
// ratioX96 = (1.0015^32) * 2^96 = 83120873769022354029916374475
// 83120873769022354029916374475 * 10^26 / 79228162514264337593543950336 =
// 104913292358707887270979599.831816586773651266562785765558183
if iszero(lt(factor_, 104913292358707887270979600)) {
tick := or(tick, 0x20)
factor_ := div(mul(factor_, _1E26), 104913292358707887270979600)
}
// for tick = 16
// ratioX96 = (1.0015^16) * 2^96 = 81151180492336368327184716176
// 81151180492336368327184716176 * 10^26 / 79228162514264337593543950336 =
// 102427189924701091191840927.762844039579442328381455567932128
if iszero(lt(factor_, 102427189924701091191840928)) {
tick := or(tick, 0x10)
factor_ := div(mul(factor_, _1E26), 102427189924701091191840928)
}
// for tick = 8
// ratioX96 = (1.0015^8) * 2^96 = 80183906840906820640659903620
// 80183906840906820640659903620 * 10^26 / 79228162514264337593543950336 =
// 101206318935480056907421312.890625
if iszero(lt(factor_, 101206318935480056907421313)) {
tick := or(tick, 0x8)
factor_ := div(mul(factor_, _1E26), 101206318935480056907421313)
}
// for tick = 4
// ratioX96 = (1.0015^4) * 2^96 = 79704602139525152702959747603
// 79704602139525152702959747603 * 10^26 / 79228162514264337593543950336 =
// 100601351350506250000000000
if iszero(lt(factor_, 100601351350506250000000000)) {
tick := or(tick, 0x4)
factor_ := div(mul(factor_, _1E26), 100601351350506250000000000)
}
// for tick = 2
// ratioX96 = (1.0015^2) * 2^96 = 79466025265172787701084167660
// 79466025265172787701084167660 * 10^26 / 79228162514264337593543950336 =
// 100300225000000000000000000
if iszero(lt(factor_, 100300225000000000000000000)) {
tick := or(tick, 0x2)
factor_ := div(mul(factor_, _1E26), 100300225000000000000000000)
}
// for tick = 1
// ratioX96 = (1.0015^1) * 2^96 = 79347004758035734099934266261
// 79347004758035734099934266261 * 10^26 / 79228162514264337593543950336 =
// 100150000000000000000000000
if iszero(lt(factor_, 100150000000000000000000000)) {
tick := or(tick, 0x1)
factor_ := div(mul(factor_, _1E26), 100150000000000000000000000)
}
if iszero(cond) {
// if ratioX96 >= ZERO_TICK_SCALED_RATIO
perfectRatioX96 := div(mul(ratioX96, _1E26), factor_)
}
if cond {
// ratioX96 < ZERO_TICK_SCALED_RATIO
tick := not(tick)
perfectRatioX96 := div(mul(ratioX96, factor_), 100150000000000000000000000)
}
// perfect ratio should always be <= ratioX96
// not sure if it can ever be bigger but better to have extra checks
if gt(perfectRatioX96, ratioX96) {
revert(0, 0)
}
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import { IAaveV3Pool } from "../interfaces/Aave/IAaveV3Pool.sol";
contract MockAaveV3Pool is IAaveV3Pool {
uint128 public variableBorrowRate;
uint256 public reserveNormalizedVariableDebt;
constructor(uint128 _variableBorrowRate) {
variableBorrowRate = _variableBorrowRate;
}
function setVariableBorrowRate(uint128 _variableBorrowRate) external {
variableBorrowRate = _variableBorrowRate;
}
function setReserveNormalizedVariableDebt(uint256 _reserveNormalizedVariableDebt) external {
reserveNormalizedVariableDebt = _reserveNormalizedVariableDebt;
}
function getReserveData(address) external view returns (ReserveDataLegacy memory result) {
result.currentVariableBorrowRate = variableBorrowRate;
}
function getReserveNormalizedVariableDebt(address) external view returns (uint256) {
return reserveNormalizedVariableDebt;
}
function supply(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external override {}
function withdraw(address asset, uint256 amount, address to) external override returns (uint256) {}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import { IPriceOracle } from "../price-oracle/interfaces/IPriceOracle.sol";
contract MockPriceOracle is IPriceOracle {
uint256 public anchorPrice;
uint256 public minPrice;
uint256 public maxPrice;
constructor(uint256 _anchorPrice, uint256 _minPrice, uint256 _maxPrice) {
anchorPrice = _anchorPrice;
minPrice = _minPrice;
maxPrice = _maxPrice;
}
function setPrices(uint256 _anchorPrice, uint256 _minPrice, uint256 _maxPrice) external {
anchorPrice = _anchorPrice;
minPrice = _minPrice;
maxPrice = _maxPrice;
}
function getPrice() public view returns (uint256, uint256, uint256) {
return (anchorPrice, minPrice, maxPrice);
}
/// @inheritdoc IPriceOracle
function getExchangePrice() public view returns (uint256) {
(, uint256 price, ) = getPrice();
return price;
}
/// @inheritdoc IPriceOracle
function getLiquidatePrice() external view returns (uint256) {
return getExchangePrice();
}
/// @inheritdoc IPriceOracle
function getRedeemPrice() external view returns (uint256) {
(, , uint256 price) = getPrice();
return price;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { AggregatorV3Interface } from "../interfaces/Chainlink/AggregatorV3Interface.sol";
import { IPoolManager } from "../interfaces/IPoolManager.sol";
contract MockFxUSDSave {
/// @notice The address of `PoolManager` contract.
address public immutable poolManager;
/// @notice The address of `PegKeeper` contract.
address public immutable pegKeeper;
/// @dev This is also the address of FxUSD token.
address public immutable yieldToken;
/// @dev The address of USDC token.
address public immutable stableToken;
uint256 private immutable stableTokenScale;
/// @notice The Chainlink USDC/USD price feed.
/// @dev The encoding is below.
/// ```text
/// | 32 bits | 64 bits | 160 bits |
/// | heartbeat | scale | price_feed |
/// |low high |
/// ```
bytes32 public immutable Chainlink_USDC_USD_Spot;
constructor(
address _poolManager,
address _pegKeeper,
address _yieldToken,
address _stableToken,
bytes32 _Chainlink_USDC_USD_Spot
) {
poolManager = _poolManager;
pegKeeper = _pegKeeper;
yieldToken = _yieldToken;
stableToken = _stableToken;
Chainlink_USDC_USD_Spot = _Chainlink_USDC_USD_Spot;
stableTokenScale = 10 ** (18 - IERC20Metadata(_stableToken).decimals());
}
function totalYieldToken() external view returns (uint256) {
return IERC20Metadata(yieldToken).balanceOf(address(this));
}
/// @notice The total amount of stable token managed in this contract
function totalStableToken() external view returns (uint256) {
return IERC20Metadata(stableToken).balanceOf(address(this));
}
function getStableTokenPrice() public view returns (uint256) {
bytes32 encoding = Chainlink_USDC_USD_Spot;
address aggregator;
uint256 scale;
uint256 heartbeat;
assembly {
aggregator := shr(96, encoding)
scale := and(shr(32, encoding), 0xffffffffffffffff)
heartbeat := and(encoding, 0xffffffff)
}
(, int256 answer, , uint256 updatedAt, ) = AggregatorV3Interface(aggregator).latestRoundData();
if (answer < 0) revert("invalid");
if (block.timestamp - updatedAt > heartbeat) revert("expired");
return uint256(answer) * scale;
}
function getStableTokenPriceWithScale() public view returns (uint256) {
return getStableTokenPrice() * stableTokenScale;
}
function rebalance(
address pool,
int16 tickId,
uint256 maxFxUSD,
uint256 maxStable
) external returns (uint256 colls, uint256 yieldTokenUsed, uint256 stableTokenUsed) {
IERC20Metadata(yieldToken).approve(poolManager, type(uint256).max);
IERC20Metadata(stableToken).approve(poolManager, type(uint256).max);
(colls, yieldTokenUsed, stableTokenUsed) = IPoolManager(poolManager).rebalance(
pool,
msg.sender,
tickId,
maxFxUSD,
maxStable
);
}
function rebalance(
address pool,
uint256 maxFxUSD,
uint256 maxStable
) external returns (uint256 colls, uint256 yieldTokenUsed, uint256 stableTokenUsed) {
IERC20Metadata(yieldToken).approve(poolManager, type(uint256).max);
IERC20Metadata(stableToken).approve(poolManager, type(uint256).max);
(colls, yieldTokenUsed, stableTokenUsed) = IPoolManager(poolManager).rebalance(
pool,
msg.sender,
maxFxUSD,
maxStable
);
}
function liquidate(
address pool,
uint256 maxFxUSD,
uint256 maxStable
) external returns (uint256 colls, uint256 yieldTokenUsed, uint256 stableTokenUsed) {
IERC20Metadata(yieldToken).approve(poolManager, type(uint256).max);
IERC20Metadata(stableToken).approve(poolManager, type(uint256).max);
(colls, yieldTokenUsed, stableTokenUsed) = IPoolManager(poolManager).liquidate(
pool,
msg.sender,
maxFxUSD,
maxStable
);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { IBalancerVault } from "../../interfaces/Balancer/IBalancerVault.sol";
import { LibRouter } from "../libraries/LibRouter.sol";
abstract contract FlashLoanFacetBase {
/**********
* Errors *
**********/
/// @dev Thrown when the caller is not self.
error ErrorNotFromSelf();
/// @dev Unauthorized reentrant call.
error ReentrancyGuardReentrantCall();
/***********************
* Immutable Variables *
***********************/
/// @dev The address of Balancer V2 Vault.
address private immutable balancer;
/*************
* Modifiers *
*************/
modifier onlySelf() {
if (msg.sender != address(this)) revert ErrorNotFromSelf();
_;
}
modifier onFlashLoan() {
LibRouter.RouterStorage storage $ = LibRouter.routerStorage();
$.flashLoanContext = LibRouter.HAS_FLASH_LOAN;
_;
$.flashLoanContext = LibRouter.NOT_FLASH_LOAN;
}
modifier nonReentrant() {
LibRouter.RouterStorage storage $ = LibRouter.routerStorage();
if ($.reentrantContext == LibRouter.HAS_ENTRANT) {
revert ReentrancyGuardReentrantCall();
}
$.reentrantContext = LibRouter.HAS_ENTRANT;
_;
$.reentrantContext = LibRouter.NOT_ENTRANT;
}
/***************
* Constructor *
***************/
constructor(address _balancer) {
balancer = _balancer;
}
/**********************
* Internal Functions *
**********************/
function _invokeFlashLoan(address token, uint256 amount, bytes memory data) internal onFlashLoan {
address[] memory tokens = new address[](1);
uint256[] memory amounts = new uint256[](1);
tokens[0] = token;
amounts[0] = amount;
IBalancerVault(balancer).flashLoan(address(this), tokens, amounts, data);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IFxUSDBasePool } from "../../interfaces/IFxUSDBasePool.sol";
import { IFxShareableRebalancePool } from "../../v2/interfaces/IFxShareableRebalancePool.sol";
import { IFxUSD } from "../../v2/interfaces/IFxUSD.sol";
import { ILiquidityGauge } from "../../voting-escrow/interfaces/ILiquidityGauge.sol";
import { WordCodec } from "../../common/codec/WordCodec.sol";
import { LibRouter } from "../libraries/LibRouter.sol";
contract FxUSDBasePoolFacet {
using SafeERC20 for IERC20;
/*************
* Constants *
*************/
/// @notice The address of USDC token.
address private constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
/// @notice The address of fxUSD token.
address private constant fxUSD = 0x085780639CC2cACd35E474e71f4d000e2405d8f6;
/***********************
* Immutable Variables *
***********************/
/// @dev The address of `PoolManager` contract.
address private immutable poolManager;
/// @dev The address of `FxUSDBasePool` contract.
address private immutable fxBASE;
/// @dev The address of fxBASE gauge contract.
address private immutable gauge;
/***************
* Constructor *
***************/
constructor(address _poolManager, address _fxBASE, address _gauge) {
poolManager = _poolManager;
fxBASE = _fxBASE;
gauge = _gauge;
}
/****************************
* Public Mutated Functions *
****************************/
/// @notice Migrate fxUSD from rebalance pool to fxBASE.
/// @param pool The address of rebalance pool.
/// @param amountIn The amount of rebalance pool shares to migrate.
/// @param minShares The minimum shares should receive.
/// @param receiver The address of fxBASE share recipient.
function migrateToFxBase(address pool, uint256 amountIn, uint256 minShares, address receiver) external {
IFxShareableRebalancePool(pool).withdrawFrom(msg.sender, amountIn, address(this));
address baseToken = IFxShareableRebalancePool(pool).baseToken();
address asset = IFxShareableRebalancePool(pool).asset();
LibRouter.approve(asset, fxUSD, amountIn);
IFxUSD(fxUSD).wrap(baseToken, amountIn, address(this));
LibRouter.approve(fxUSD, fxBASE, amountIn);
IFxUSDBasePool(fxBASE).deposit(receiver, fxUSD, amountIn, minShares);
}
/// @notice Migrate fxUSD from rebalance pool to fxBASE gauge.
/// @param pool The address of rebalance pool.
/// @param amountIn The amount of rebalance pool shares to migrate.
/// @param minShares The minimum shares should receive.
/// @param receiver The address of fxBASE share recipient.
function migrateToFxBaseGauge(address pool, uint256 amountIn, uint256 minShares, address receiver) external {
IFxShareableRebalancePool(pool).withdrawFrom(msg.sender, amountIn, address(this));
address baseToken = IFxShareableRebalancePool(pool).baseToken();
address asset = IFxShareableRebalancePool(pool).asset();
LibRouter.approve(asset, fxUSD, amountIn);
IFxUSD(fxUSD).wrap(baseToken, amountIn, address(this));
LibRouter.approve(fxUSD, fxBASE, amountIn);
uint256 shares = IFxUSDBasePool(fxBASE).deposit(address(this), fxUSD, amountIn, minShares);
LibRouter.approve(fxBASE, gauge, shares);
ILiquidityGauge(gauge).deposit(shares, receiver);
}
/// @notice Deposit token to fxBASE.
/// @param params The parameters to convert source token to `tokenOut`.
/// @param tokenOut The target token, USDC or fxUSD.
/// @param minShares The minimum shares should receive.
/// @param receiver The address of fxBASE share recipient.
function depositToFxBase(
LibRouter.ConvertInParams memory params,
address tokenOut,
uint256 minShares,
address receiver
) external payable {
uint256 amountIn = LibRouter.transferInAndConvert(params, tokenOut);
LibRouter.approve(tokenOut, fxBASE, amountIn);
IFxUSDBasePool(fxBASE).deposit(receiver, tokenOut, amountIn, minShares);
}
/// @notice Deposit token to fxBase and then deposit to gauge.
/// @param params The parameters to convert source token to `tokenOut`.
/// @param tokenOut The target token, USDC or fxUSD.
/// @param minShares The minimum shares should receive.
/// @param receiver The address of gauge share recipient.
function depositToFxBaseGauge(
LibRouter.ConvertInParams memory params,
address tokenOut,
uint256 minShares,
address receiver
) external payable {
uint256 amountIn = LibRouter.transferInAndConvert(params, tokenOut);
LibRouter.approve(tokenOut, fxBASE, amountIn);
uint256 shares = IFxUSDBasePool(fxBASE).deposit(address(this), tokenOut, amountIn, minShares);
LibRouter.approve(fxBASE, gauge, shares);
ILiquidityGauge(gauge).deposit(shares, receiver);
}
/*
/// @notice Burn fxBASE shares and then convert USDC and fxUSD to another token.
/// @param fxusdParams The parameters to convert fxUSD to target token.
/// @param usdcParams The parameters to convert USDC to target token.
/// @param amountIn The amount of fxBASE to redeem.
/// @param receiver The address of token recipient.
function redeemFromFxBase(
LibRouter.ConvertOutParams memory fxusdParams,
LibRouter.ConvertOutParams memory usdcParams,
uint256 amountIn,
address receiver
) external {
IERC20(fxBASE).safeTransferFrom(msg.sender, address(this), amountIn);
(uint256 amountFxUSD, uint256 amountUSDC) = IFxUSDBasePool(fxBASE).redeem(address(this), amountIn);
LibRouter.convertAndTransferOut(fxusdParams, fxUSD, amountFxUSD, receiver);
LibRouter.convertAndTransferOut(usdcParams, USDC, amountUSDC, receiver);
}
/// @notice Burn fxBASE shares from gauge and then convert USDC and fxUSD to another token.
/// @param fxusdParams The parameters to convert fxUSD to target token.
/// @param usdcParams The parameters to convert USDC to target token.
/// @param amountIn The amount of fxBASE to redeem.
/// @param receiver The address of token recipient.
function redeemFromFxBaseGauge(
LibRouter.ConvertOutParams memory fxusdParams,
LibRouter.ConvertOutParams memory usdcParams,
uint256 amountIn,
address receiver
) external {
IERC20(gauge).safeTransferFrom(msg.sender, address(this), amountIn);
ILiquidityGauge(gauge).withdraw(amountIn);
(uint256 amountFxUSD, uint256 amountUSDC) = IFxUSDBasePool(fxBASE).redeem(address(this), amountIn);
LibRouter.convertAndTransferOut(fxusdParams, fxUSD, amountFxUSD, receiver);
LibRouter.convertAndTransferOut(usdcParams, USDC, amountUSDC, receiver);
}
*/
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IFxUSDBasePool } from "../../interfaces/IFxUSDBasePool.sol";
import { IFxShareableRebalancePool } from "../../v2/interfaces/IFxShareableRebalancePool.sol";
import { IFxUSD } from "../../v2/interfaces/IFxUSD.sol";
import { ILiquidityGauge } from "../../voting-escrow/interfaces/ILiquidityGauge.sol";
import { WordCodec } from "../../common/codec/WordCodec.sol";
import { LibRouter } from "../libraries/LibRouter.sol";
contract FxUSDBasePoolV2Facet {
using SafeERC20 for IERC20;
/*************
* Constants *
*************/
/// @notice The address of fxUSD token.
address private constant fxUSD = 0x085780639CC2cACd35E474e71f4d000e2405d8f6;
/***********************
* Immutable Variables *
***********************/
/// @dev The address of `FxUSDBasePool` contract.
address private immutable fxBASE;
/***************
* Constructor *
***************/
constructor(address _fxBASE) {
fxBASE = _fxBASE;
}
/****************************
* Public Mutated Functions *
****************************/
/// @notice Migrate fxUSD from rebalance pool to fxBASE gauge.
/// @param pool The address of rebalance pool.
/// @param amountIn The amount of rebalance pool shares to migrate.
/// @param minShares The minimum shares should receive.
/// @param receiver The address of fxBASE share recipient.
function migrateToFxBaseGaugeV2(address pool, address gauge, uint256 amountIn, uint256 minShares, address receiver) external {
LibRouter.ensureWhitelisted(gauge);
IFxShareableRebalancePool(pool).withdrawFrom(msg.sender, amountIn, address(this));
address baseToken = IFxShareableRebalancePool(pool).baseToken();
address asset = IFxShareableRebalancePool(pool).asset();
LibRouter.approve(asset, fxUSD, amountIn);
IFxUSD(fxUSD).wrap(baseToken, amountIn, address(this));
LibRouter.approve(fxUSD, fxBASE, amountIn);
uint256 shares = IFxUSDBasePool(fxBASE).deposit(address(this), fxUSD, amountIn, minShares);
LibRouter.approve(fxBASE, gauge, shares);
ILiquidityGauge(gauge).deposit(shares, receiver);
}
/// @notice Deposit token to fxBase and then deposit to gauge.
/// @param params The parameters to convert source token to `tokenOut`.
/// @param tokenOut The target token, USDC or fxUSD.
/// @param minShares The minimum shares should receive.
/// @param receiver The address of gauge share recipient.
function depositToFxBaseGaugeV2(
LibRouter.ConvertInParams memory params,
address gauge,
address tokenOut,
uint256 minShares,
address receiver
) external payable {
LibRouter.ensureWhitelisted(gauge);
uint256 amountIn = LibRouter.transferInAndConvert(params, tokenOut);
LibRouter.approve(tokenOut, fxBASE, amountIn);
uint256 shares = IFxUSDBasePool(fxBASE).deposit(address(this), tokenOut, amountIn, minShares);
LibRouter.approve(fxBASE, gauge, shares);
ILiquidityGauge(gauge).deposit(shares, receiver);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC721 } from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import { IMultiPathConverter } from "../../helpers/interfaces/IMultiPathConverter.sol";
import { IBalancerVault } from "../../interfaces/Balancer/IBalancerVault.sol";
import { IPool } from "../../interfaces/IPool.sol";
import { IPoolManager } from "../../interfaces/IPoolManager.sol";
import { IFxMarketV2 } from "../../v2/interfaces/IFxMarketV2.sol";
import { IFxUSD } from "../../v2/interfaces/IFxUSD.sol";
import { WordCodec } from "../../common/codec/WordCodec.sol";
import { LibRouter } from "../libraries/LibRouter.sol";
import { FlashLoanFacetBase } from "./FlashLoanFacetBase.sol";
contract MigrateFacet is FlashLoanFacetBase {
using SafeERC20 for IERC20;
using WordCodec for bytes32;
/**********
* Errors *
**********/
/// @dev Thrown when the amount of tokens swapped are not enough.
error ErrorInsufficientAmountSwapped();
/// @dev Thrown when debt ratio out of range.
error ErrorDebtRatioOutOfRange();
/*************
* Constants *
*************/
/// @dev The address of USDC token.
address private constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
/// @dev The address of fxUSD token.
address private constant fxUSD = 0x085780639CC2cACd35E474e71f4d000e2405d8f6;
/// @dev The address of wstETH market contract.
address private constant wstETHMarket = 0xAD9A0E7C08bc9F747dF97a3E7E7f620632CB6155;
/// @dev The address of wstETH token.
address private constant wstETH = 0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0;
/// @dev The address of fstETH token.
address private constant fstETH = 0xD6B8162e2fb9F3EFf09bb8598ca0C8958E33A23D;
/// @dev The address of xstETH token.
address private constant xstETH = 0x5a097b014C547718e79030a077A91Ae37679EfF5;
/// @dev The address of sfrxETH market contract.
address private constant sfrxETHMarket = 0x714B853b3bA73E439c652CfE79660F329E6ebB42;
/// @dev The address of sfrxETH token.
address private constant sfrxETH = 0xac3E018457B222d93114458476f3E3416Abbe38F;
/// @dev The address of ffrxETH token.
address private constant ffrxETH = 0xa87F04c9743Fd1933F82bdDec9692e9D97673769;
/// @dev The address of xfrxETH token.
address private constant xfrxETH = 0x2bb0C32101456F5960d4e994Bac183Fe0dc6C82c;
/***********************
* Immutable Variables *
***********************/
/// @dev The address of `PoolManager` contract.
address private immutable poolManager;
/// @dev The address of `MultiPathConverter` contract.
address private immutable converter;
/***************
* Constructor *
***************/
constructor(address _balancer, address _poolManager, address _converter) FlashLoanFacetBase(_balancer) {
poolManager = _poolManager;
converter = _converter;
}
/****************************
* Public Mutated Functions *
****************************/
/// @notice Migrate xstETH to fx position.
/// @param pool The address of fx position pool.
/// @param positionId The index of position.
/// @param xTokenAmount The amount of xstETH to migrate.
/// @param borrowAmount The amount of USDC to borrow.
/// @param data The calldata passing to `onMigrateXstETHPosition` hook function.
function migrateXstETHPosition(
address pool,
uint256 positionId,
uint256 xTokenAmount,
uint256 borrowAmount,
bytes calldata data
) external nonReentrant {
IERC20(xstETH).safeTransferFrom(msg.sender, address(this), xTokenAmount);
if (positionId > 0) {
IERC721(pool).transferFrom(msg.sender, address(this), positionId);
}
_invokeFlashLoan(
USDC,
borrowAmount,
abi.encodeCall(
MigrateFacet.onMigrateXstETHPosition,
(pool, positionId, xTokenAmount, borrowAmount, msg.sender, data)
)
);
// refund USDC to caller
LibRouter.refundERC20(USDC, LibRouter.routerStorage().revenuePool);
}
/// @notice Migrate xfrxETH to fx position.
/// @param pool The address of fx position pool.
/// @param positionId The index of position.
/// @param xTokenAmount The amount of xfrxETH to migrate.
/// @param borrowAmount The amount of USDC to borrow.
/// @param data The calldata passing to `onMigrateXfrxETHPosition` hook function.
function migrateXfrxETHPosition(
address pool,
uint256 positionId,
uint256 xTokenAmount,
uint256 borrowAmount,
bytes calldata data
) external nonReentrant {
IERC20(xfrxETH).safeTransferFrom(msg.sender, address(this), xTokenAmount);
if (positionId > 0) {
IERC721(pool).transferFrom(msg.sender, address(this), positionId);
}
_invokeFlashLoan(
USDC,
borrowAmount,
abi.encodeCall(
MigrateFacet.onMigrateXfrxETHPosition,
(pool, positionId, xTokenAmount, borrowAmount, msg.sender, data)
)
);
// refund USDC to caller
LibRouter.refundERC20(USDC, LibRouter.routerStorage().revenuePool);
}
/// @notice Hook for `migrateXstETHPosition`.
/// @param pool The address of fx position pool.
/// @param positionId The index of position.
/// @param xTokenAmount The amount of xstETH to migrate.
/// @param borrowAmount The amount of USDC to borrow.
/// @param recipient The address of position holder.
/// @param data Hook data.
function onMigrateXstETHPosition(
address pool,
uint256 positionId,
uint256 xTokenAmount,
uint256 borrowAmount,
address recipient,
bytes memory data
) external onlySelf {
uint256 fTokenAmount = (xTokenAmount * IERC20(fstETH).totalSupply()) / IERC20(xstETH).totalSupply();
// swap USDC to fxUSD
fTokenAmount = _swapUSDCToFxUSD(borrowAmount, fTokenAmount, data);
// unwrap fxUSD as fToken
IFxUSD(fxUSD).unwrap(wstETH, fTokenAmount, address(this));
uint256 wstETHAmount;
{
wstETHAmount = IFxMarketV2(wstETHMarket).redeemXToken(xTokenAmount, address(this), 0);
(uint256 baseOut, uint256 bonus) = IFxMarketV2(wstETHMarket).redeemFToken(fTokenAmount, address(this), 0);
wstETHAmount += baseOut + bonus;
}
// since we need to swap back to USDC, mint 0.1% more fxUSD to cover slippage.
fTokenAmount = (fTokenAmount * 1001) / 1000;
LibRouter.approve(wstETH, poolManager, wstETHAmount);
positionId = IPoolManager(poolManager).operate(pool, positionId, int256(wstETHAmount), int256(fTokenAmount));
_checkPositionDebtRatio(pool, positionId, abi.decode(data, (bytes32)));
IERC721(pool).transferFrom(address(this), recipient, positionId);
// swap fxUSD to USDC and pay debts
_swapFxUSDToUSDC(IERC20(fxUSD).balanceOf(address(this)), borrowAmount, data);
}
/// @notice Hook for `migrateXfrxETHPosition`.
/// @param pool The address of fx position pool.
/// @param positionId The index of position.
/// @param xTokenAmount The amount of xstETH to migrate.
/// @param borrowAmount The amount of USDC to borrow.
/// @param recipient The address of position holder.
/// @param data Hook data.
function onMigrateXfrxETHPosition(
address pool,
uint256 positionId,
uint256 xTokenAmount,
uint256 borrowAmount,
address recipient,
bytes memory data
) external onlySelf {
uint256 fTokenAmount = (xTokenAmount * IERC20(ffrxETH).totalSupply()) / IERC20(xfrxETH).totalSupply();
// swap USDC to fxUSD
fTokenAmount = _swapUSDCToFxUSD(borrowAmount, fTokenAmount, data);
// unwrap fxUSD as fToken
IFxUSD(fxUSD).unwrap(sfrxETH, fTokenAmount, address(this));
uint256 wstETHAmount;
{
// redeem
wstETHAmount = IFxMarketV2(sfrxETHMarket).redeemXToken(xTokenAmount, address(this), 0);
(uint256 baseOut, uint256 bonus) = IFxMarketV2(sfrxETHMarket).redeemFToken(fTokenAmount, address(this), 0);
wstETHAmount += baseOut + bonus;
// swap sfrxETH to wstETH
wstETHAmount = _swapSfrxETHToWstETH(wstETHAmount, 0, data);
}
// since we need to swap back to USDC, mint 0.1% more fxUSD to cover slippage.
fTokenAmount = (fTokenAmount * 1001) / 1000;
LibRouter.approve(wstETH, poolManager, wstETHAmount);
positionId = IPoolManager(poolManager).operate(pool, positionId, int256(wstETHAmount), int256(fTokenAmount));
_checkPositionDebtRatio(pool, positionId, abi.decode(data, (bytes32)));
IERC721(pool).transferFrom(address(this), recipient, positionId);
// swap fxUSD to USDC and pay debts
_swapFxUSDToUSDC(IERC20(fxUSD).balanceOf(address(this)), borrowAmount, data);
}
/**********************
* Internal Functions *
**********************/
/// @dev Internal function to swap USDC to fxUSD.
/// @param amountUSDC The amount of USDC to use.
/// @param minFxUSD The minimum amount of fxUSD should receive.
/// @param data The swap route encoding.
/// @return amountFxUSD The amount of fxUSD received.
function _swapUSDCToFxUSD(
uint256 amountUSDC,
uint256 minFxUSD,
bytes memory data
) internal returns (uint256 amountFxUSD) {
(, uint256 swapEncoding, uint256[] memory swapRoutes) = abi.decode(data, (bytes32, uint256, uint256[]));
return _swap(USDC, amountUSDC, minFxUSD, swapEncoding, swapRoutes);
}
/// @dev Internal function to swap fxUSD to USDC.
/// @param amountFxUSD The amount of fxUSD to use.
/// @param minUSDC The minimum amount of USDC should receive.
/// @param data The swap route encoding.
/// @return amountUSDC The amount of USDC received.
function _swapFxUSDToUSDC(
uint256 amountFxUSD,
uint256 minUSDC,
bytes memory data
) internal returns (uint256 amountUSDC) {
(, , , uint256 swapEncoding, uint256[] memory swapRoutes) = abi.decode(
data,
(bytes32, uint256, uint256[], uint256, uint256[])
);
return _swap(fxUSD, amountFxUSD, minUSDC, swapEncoding, swapRoutes);
}
/// @dev Internal function to swap sfrxETH to wstETH.
/// @param amountSfrxETH The amount of sfrxETH to use.
/// @param minWstETH The minimum amount of wstETH should receive.
/// @param data The swap route encoding.
/// @return amountWstETH The amount of wstETH received.
function _swapSfrxETHToWstETH(
uint256 amountSfrxETH,
uint256 minWstETH,
bytes memory data
) internal returns (uint256 amountWstETH) {
(, , , , , uint256 swapEncoding, uint256[] memory swapRoutes) = abi.decode(
data,
(bytes32, uint256, uint256[], uint256, uint256[], uint256, uint256[])
);
return _swap(sfrxETH, amountSfrxETH, minWstETH, swapEncoding, swapRoutes);
}
/// @dev Internal function to do swap.
/// @param token The address of input token.
/// @param amountIn The amount of input token.
/// @param minOut The minimum amount of output tokens should receive.
/// @param encoding The encoding for swap routes.
/// @param routes The swap routes to `MultiPathConverter`.
/// @return amountOut The amount of output tokens received.
function _swap(
address token,
uint256 amountIn,
uint256 minOut,
uint256 encoding,
uint256[] memory routes
) internal returns (uint256 amountOut) {
LibRouter.approve(token, converter, amountIn);
amountOut = IMultiPathConverter(converter).convert(token, amountIn, encoding, routes);
if (amountOut < minOut) revert ErrorInsufficientAmountSwapped();
}
/// @dev Internal function to check debt ratio for the position.
/// @param pool The address of fx position pool.
/// @param positionId The index of the position.
/// @param miscData The encoded data for debt ratio range.
function _checkPositionDebtRatio(address pool, uint256 positionId, bytes32 miscData) internal view {
uint256 debtRatio = IPool(pool).getPositionDebtRatio(positionId);
uint256 minDebtRatio = miscData.decodeUint(0, 60);
uint256 maxDebtRatio = miscData.decodeUint(60, 60);
if (debtRatio < minDebtRatio || debtRatio > maxDebtRatio) {
revert ErrorDebtRatioOutOfRange();
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { IMorpho } from "../../interfaces/Morpho/IMorpho.sol";
import { LibRouter } from "../libraries/LibRouter.sol";
abstract contract MorphoFlashLoanFacetBase {
/**********
* Errors *
**********/
/// @dev Thrown when the caller is not self.
error ErrorNotFromSelf();
/// @dev Unauthorized reentrant call.
error ReentrancyGuardReentrantCall();
/***********************
* Immutable Variables *
***********************/
/// @dev The address of Morpho Blue contract.
/// In ethereum, it is 0xbbbbbbbbbb9cc5e90e3b3af64bdaf62c37eeffcb.
address private immutable morpho;
/*************
* Modifiers *
*************/
modifier onlySelf() {
if (msg.sender != address(this)) revert ErrorNotFromSelf();
_;
}
modifier onFlashLoan() {
LibRouter.RouterStorage storage $ = LibRouter.routerStorage();
$.flashLoanContext = LibRouter.HAS_FLASH_LOAN;
_;
$.flashLoanContext = LibRouter.NOT_FLASH_LOAN;
}
modifier nonReentrant() {
LibRouter.RouterStorage storage $ = LibRouter.routerStorage();
if ($.reentrantContext == LibRouter.HAS_ENTRANT) {
revert ReentrancyGuardReentrantCall();
}
$.reentrantContext = LibRouter.HAS_ENTRANT;
_;
$.reentrantContext = LibRouter.NOT_ENTRANT;
}
/***************
* Constructor *
***************/
constructor(address _morpho) {
morpho = _morpho;
}
/**********************
* Internal Functions *
**********************/
function _invokeFlashLoan(address token, uint256 amount, bytes memory data) internal onFlashLoan {
IMorpho(morpho).flashLoan(token, amount, abi.encode(token, data));
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC721 } from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import { IMultiPathConverter } from "../../helpers/interfaces/IMultiPathConverter.sol";
import { IPoolManager } from "../../interfaces/IPoolManager.sol";
import { IPool } from "../../interfaces/IPool.sol";
import { WordCodec } from "../../common/codec/WordCodec.sol";
import { LibRouter } from "../libraries/LibRouter.sol";
import { FlashLoanFacetBase } from "./FlashLoanFacetBase.sol";
contract PositionOperateFlashLoanFacet is FlashLoanFacetBase {
using SafeERC20 for IERC20;
using WordCodec for bytes32;
/**********
* Events *
**********/
event OpenOrAdd(address pool, uint256 position, address recipient, uint256 colls, uint256 debts, uint256 borrows);
event CloseOrRemove(address pool, uint256 position, address recipient, uint256 colls, uint256 debts, uint256 borrows);
/**********
* Errors *
**********/
/// @dev Thrown when the amount of tokens swapped are not enough.
error ErrorInsufficientAmountSwapped();
/// @dev Thrown when debt ratio out of range.
error ErrorDebtRatioOutOfRange();
/*************
* Constants *
*************/
address private constant fxUSD = 0x085780639CC2cACd35E474e71f4d000e2405d8f6;
/***********************
* Immutable Variables *
***********************/
/// @dev The address of `PoolManager` contract.
address private immutable poolManager;
/// @dev The address of `MultiPathConverter` contract.
address private immutable converter;
/***************
* Constructor *
***************/
constructor(address _balancer, address _poolManager, address _converter) FlashLoanFacetBase(_balancer) {
poolManager = _poolManager;
converter = _converter;
}
/****************************
* Public Mutated Functions *
****************************/
/// @notice Open a new position or add collateral to position with any tokens.
/// @param params The parameters to convert source token to collateral token.
/// @param pool The address of fx position pool.
/// @param positionId The index of position.
/// @param borrowAmount The amount of collateral token to borrow.
/// @param data Hook data passing to `onOpenOrAddPositionFlashLoan`.
function openOrAddPositionFlashLoan(
LibRouter.ConvertInParams memory params,
address pool,
uint256 positionId,
uint256 borrowAmount,
bytes calldata data
) external payable nonReentrant {
uint256 amountIn = LibRouter.transferInAndConvert(params, IPool(pool).collateralToken()) + borrowAmount;
_invokeFlashLoan(
IPool(pool).collateralToken(),
borrowAmount,
abi.encodeCall(
PositionOperateFlashLoanFacet.onOpenOrAddPositionFlashLoan,
(pool, positionId, amountIn, borrowAmount, msg.sender, data)
)
);
// refund collateral token to caller
LibRouter.refundERC20(IPool(pool).collateralToken(), LibRouter.routerStorage().revenuePool);
}
/// @notice Close a position or remove collateral from position.
/// @param params The parameters to convert collateral token to target token.
/// @param positionId The index of position.
/// @param pool The address of fx position pool.
/// @param borrowAmount The amount of collateral token to borrow.
/// @param data Hook data passing to `onCloseOrRemovePositionFlashLoan`.
function closeOrRemovePositionFlashLoan(
LibRouter.ConvertOutParams memory params,
address pool,
uint256 positionId,
uint256 amountOut,
uint256 borrowAmount,
bytes calldata data
) external nonReentrant {
address collateralToken = IPool(pool).collateralToken();
_invokeFlashLoan(
collateralToken,
borrowAmount,
abi.encodeCall(
PositionOperateFlashLoanFacet.onCloseOrRemovePositionFlashLoan,
(pool, positionId, amountOut, borrowAmount, msg.sender, data)
)
);
// convert collateral token to other token
amountOut = IERC20(collateralToken).balanceOf(address(this));
LibRouter.convertAndTransferOut(params, collateralToken, amountOut, msg.sender);
// refund rest fxUSD and leveraged token
LibRouter.refundERC20(fxUSD, LibRouter.routerStorage().revenuePool);
}
/// @notice Hook for `openOrAddPositionFlashLoan`.
/// @param pool The address of fx position pool.
/// @param position The index of position.
/// @param amount The amount of collateral token to supply.
/// @param repayAmount The amount of collateral token to repay.
/// @param recipient The address of position holder.
/// @param data Hook data passing to `onOpenOrAddPositionFlashLoan`.
function onOpenOrAddPositionFlashLoan(
address pool,
uint256 position,
uint256 amount,
uint256 repayAmount,
address recipient,
bytes memory data
) external onlySelf {
(bytes32 miscData, uint256 fxUSDAmount, uint256 swapEncoding, uint256[] memory swapRoutes) = abi.decode(
data,
(bytes32, uint256, uint256, uint256[])
);
// open or add collateral to position
if (position != 0) {
IERC721(pool).transferFrom(recipient, address(this), position);
}
LibRouter.approve(IPool(pool).collateralToken(), poolManager, amount);
position = IPoolManager(poolManager).operate(pool, position, int256(amount), int256(fxUSDAmount));
_checkPositionDebtRatio(pool, position, miscData);
IERC721(pool).transferFrom(address(this), recipient, position);
emit OpenOrAdd(pool, position, recipient, amount, fxUSDAmount, repayAmount);
// swap fxUSD to collateral token
_swap(fxUSD, fxUSDAmount, repayAmount, swapEncoding, swapRoutes);
}
/// @notice Hook for `closeOrRemovePositionFlashLoan`.
/// @param pool The address of fx position pool.
/// @param position The index of position.
/// @param amount The amount of collateral token to withdraw.
/// @param repayAmount The amount of collateral token to repay.
/// @param recipient The address of position holder.
/// @param data Hook data passing to `onCloseOrRemovePositionFlashLoan`.
function onCloseOrRemovePositionFlashLoan(
address pool,
uint256 position,
uint256 amount,
uint256 repayAmount,
address recipient,
bytes memory data
) external onlySelf {
(bytes32 miscData, uint256 fxUSDAmount, uint256 swapEncoding, uint256[] memory swapRoutes) = abi.decode(
data,
(bytes32, uint256, uint256, uint256[])
);
// swap collateral token to fxUSD
_swap(IPool(pool).collateralToken(), repayAmount, fxUSDAmount, swapEncoding, swapRoutes);
// close or remove collateral from position
IERC721(pool).transferFrom(recipient, address(this), position);
(, uint256 maxFxUSD) = IPool(pool).getPosition(position);
if (fxUSDAmount >= maxFxUSD) {
// close entire position
IPoolManager(poolManager).operate(pool, position, type(int256).min, type(int256).min);
} else {
IPoolManager(poolManager).operate(pool, position, -int256(amount), -int256(fxUSDAmount));
_checkPositionDebtRatio(pool, position, miscData);
}
IERC721(pool).transferFrom(address(this), recipient, position);
emit CloseOrRemove(pool, position, recipient, amount, fxUSDAmount, repayAmount);
}
/**********************
* Internal Functions *
**********************/
/// @dev Internal function to do swap.
/// @param token The address of input token.
/// @param amountIn The amount of input token.
/// @param minOut The minimum amount of output tokens should receive.
/// @param encoding The encoding for swap routes.
/// @param routes The swap routes to `MultiPathConverter`.
/// @return amountOut The amount of output tokens received.
function _swap(
address token,
uint256 amountIn,
uint256 minOut,
uint256 encoding,
uint256[] memory routes
) internal returns (uint256 amountOut) {
if (amountIn == 0) return 0;
LibRouter.approve(token, converter, amountIn);
amountOut = IMultiPathConverter(converter).convert(token, amountIn, encoding, routes);
if (amountOut < minOut) revert ErrorInsufficientAmountSwapped();
}
/// @dev Internal function to check debt ratio for the position.
/// @param pool The address of fx position pool.
/// @param positionId The index of the position.
/// @param miscData The encoded data for debt ratio range.
function _checkPositionDebtRatio(address pool, uint256 positionId, bytes32 miscData) internal view {
uint256 debtRatio = IPool(pool).getPositionDebtRatio(positionId);
uint256 minDebtRatio = miscData.decodeUint(0, 60);
uint256 maxDebtRatio = miscData.decodeUint(60, 60);
if (debtRatio < minDebtRatio || debtRatio > maxDebtRatio) {
revert ErrorDebtRatioOutOfRange();
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import { IERC721 } from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import { IMultiPathConverter } from "../../helpers/interfaces/IMultiPathConverter.sol";
import { IPoolManager } from "../../interfaces/IPoolManager.sol";
import { IPool } from "../../interfaces/IPool.sol";
import { WordCodec } from "../../common/codec/WordCodec.sol";
import { LibRouter } from "../libraries/LibRouter.sol";
import { MorphoFlashLoanFacetBase } from "./MorphoFlashLoanFacetBase.sol";
contract PositionOperateFlashLoanFacetV2 is MorphoFlashLoanFacetBase {
using EnumerableSet for EnumerableSet.AddressSet;
using SafeERC20 for IERC20;
using WordCodec for bytes32;
/**********
* Events *
**********/
event OpenOrAdd(address pool, uint256 position, address recipient, uint256 colls, uint256 debts, uint256 borrows);
event CloseOrRemove(address pool, uint256 position, address recipient, uint256 colls, uint256 debts, uint256 borrows);
/**********
* Errors *
**********/
/// @dev Thrown when the amount of tokens swapped are not enough.
error ErrorInsufficientAmountSwapped();
/// @dev Thrown when debt ratio out of range.
error ErrorDebtRatioOutOfRange();
/*************
* Constants *
*************/
address private constant fxUSD = 0x085780639CC2cACd35E474e71f4d000e2405d8f6;
/***********************
* Immutable Variables *
***********************/
/// @dev The address of `PoolManager` contract.
address private immutable poolManager;
/***************
* Constructor *
***************/
constructor(address _morpho, address _poolManager) MorphoFlashLoanFacetBase(_morpho) {
poolManager = _poolManager;
}
/****************************
* Public Mutated Functions *
****************************/
/// @notice Open a new position or add collateral to position with any tokens.
/// @param params The parameters to convert source token to collateral token.
/// @param pool The address of fx position pool.
/// @param positionId The index of position.
/// @param borrowAmount The amount of collateral token to borrow.
/// @param data Hook data passing to `onOpenOrAddPositionFlashLoan`.
function openOrAddPositionFlashLoanV2(
LibRouter.ConvertInParams memory params,
address pool,
uint256 positionId,
uint256 borrowAmount,
bytes calldata data
) external payable nonReentrant {
uint256 amountIn = LibRouter.transferInAndConvert(params, IPool(pool).collateralToken()) + borrowAmount;
_invokeFlashLoan(
IPool(pool).collateralToken(),
borrowAmount,
abi.encodeCall(
PositionOperateFlashLoanFacetV2.onOpenOrAddPositionFlashLoanV2,
(pool, positionId, amountIn, borrowAmount, msg.sender, data)
)
);
// transfer extra collateral token to revenue pool
LibRouter.refundERC20(IPool(pool).collateralToken(), LibRouter.routerStorage().revenuePool);
}
/// @notice Close a position or remove collateral from position.
/// @param params The parameters to convert collateral token to target token.
/// @param positionId The index of position.
/// @param pool The address of fx position pool.
/// @param borrowAmount The amount of collateral token to borrow.
/// @param data Hook data passing to `onCloseOrRemovePositionFlashLoan`.
function closeOrRemovePositionFlashLoanV2(
LibRouter.ConvertOutParams memory params,
address pool,
uint256 positionId,
uint256 amountOut,
uint256 borrowAmount,
bytes calldata data
) external nonReentrant {
address collateralToken = IPool(pool).collateralToken();
_invokeFlashLoan(
collateralToken,
borrowAmount,
abi.encodeCall(
PositionOperateFlashLoanFacetV2.onCloseOrRemovePositionFlashLoanV2,
(pool, positionId, amountOut, borrowAmount, msg.sender, data)
)
);
// convert collateral token to other token
amountOut = IERC20(collateralToken).balanceOf(address(this));
LibRouter.convertAndTransferOut(params, collateralToken, amountOut, msg.sender);
// transfer extra fxUSD to revenue pool
LibRouter.refundERC20(fxUSD, LibRouter.routerStorage().revenuePool);
}
/// @notice Hook for `openOrAddPositionFlashLoan`.
/// @param pool The address of fx position pool.
/// @param position The index of position.
/// @param amount The amount of collateral token to supply.
/// @param repayAmount The amount of collateral token to repay.
/// @param recipient The address of position holder.
/// @param data Hook data passing to `onOpenOrAddPositionFlashLoan`.
function onOpenOrAddPositionFlashLoanV2(
address pool,
uint256 position,
uint256 amount,
uint256 repayAmount,
address recipient,
bytes memory data
) external onlySelf {
(bytes32 miscData, uint256 fxUSDAmount, address swapTarget, bytes memory swapData) = abi.decode(
data,
(bytes32, uint256, address, bytes)
);
// open or add collateral to position
if (position != 0) {
IERC721(pool).transferFrom(recipient, address(this), position);
}
LibRouter.approve(IPool(pool).collateralToken(), poolManager, amount);
position = IPoolManager(poolManager).operate(pool, position, int256(amount), int256(fxUSDAmount));
_checkPositionDebtRatio(pool, position, miscData);
IERC721(pool).transferFrom(address(this), recipient, position);
emit OpenOrAdd(pool, position, recipient, amount, fxUSDAmount, repayAmount);
// swap fxUSD to collateral token
_swap(fxUSD, IPool(pool).collateralToken(), fxUSDAmount, repayAmount, swapTarget, swapData);
}
/// @notice Hook for `closeOrRemovePositionFlashLoan`.
/// @param pool The address of fx position pool.
/// @param position The index of position.
/// @param amount The amount of collateral token to withdraw.
/// @param borrowAmount The amount of collateral token borrowed.
/// @param recipient The address of position holder.
/// @param data Hook data passing to `onCloseOrRemovePositionFlashLoan`.
function onCloseOrRemovePositionFlashLoanV2(
address pool,
uint256 position,
uint256 amount,
uint256 borrowAmount,
address recipient,
bytes memory data
) external onlySelf {
(bytes32 miscData, uint256 fxUSDAmount, address swapTarget, bytes memory swapData) = abi.decode(
data,
(bytes32, uint256, address, bytes)
);
// swap collateral token to fxUSD
_swap(IPool(pool).collateralToken(), fxUSD, borrowAmount, fxUSDAmount, swapTarget, swapData);
// close or remove collateral from position
IERC721(pool).transferFrom(recipient, address(this), position);
(, uint256 maxFxUSD) = IPool(pool).getPosition(position);
if (fxUSDAmount >= maxFxUSD) {
// close entire position
IPoolManager(poolManager).operate(pool, position, type(int256).min, type(int256).min);
} else {
IPoolManager(poolManager).operate(pool, position, -int256(amount), -int256(fxUSDAmount));
_checkPositionDebtRatio(pool, position, miscData);
}
IERC721(pool).transferFrom(address(this), recipient, position);
emit CloseOrRemove(pool, position, recipient, amount, fxUSDAmount, borrowAmount);
}
/**********************
* Internal Functions *
**********************/
/// @dev Internal function to do swap.
/// @param tokenIn The address of input token.
/// @param tokenOut The address of output token.
/// @param amountIn The amount of input token.
/// @param minOut The minimum amount of output tokens should receive.
/// @param swapTarget The address of target contract used for swap.
/// @param swapData The calldata passed to target contract.
/// @return amountOut The amount of output tokens received.
function _swap(
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 minOut,
address swapTarget,
bytes memory swapData
) internal returns (uint256 amountOut) {
if (amountIn == 0) return 0;
LibRouter.RouterStorage storage $ = LibRouter.routerStorage();
if (!$.approvedTargets.contains(swapTarget)) {
revert LibRouter.ErrorTargetNotApproved();
}
address spender = $.spenders[swapTarget];
if (spender == address(0)) spender = swapTarget;
LibRouter.approve(tokenIn, spender, amountIn);
amountOut = IERC20(tokenOut).balanceOf(address(this));
(bool success, ) = swapTarget.call(swapData);
// below lines will propagate inner error up
if (!success) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
let size := returndatasize()
returndatacopy(ptr, 0, size)
revert(ptr, size)
}
}
amountOut = IERC20(tokenOut).balanceOf(address(this)) - amountOut;
if (amountOut < minOut) revert ErrorInsufficientAmountSwapped();
}
/// @dev Internal function to check debt ratio for the position.
/// @param pool The address of fx position pool.
/// @param positionId The index of the position.
/// @param miscData The encoded data for debt ratio range.
function _checkPositionDebtRatio(address pool, uint256 positionId, bytes32 miscData) internal view {
uint256 debtRatio = IPool(pool).getPositionDebtRatio(positionId);
uint256 minDebtRatio = miscData.decodeUint(0, 60);
uint256 maxDebtRatio = miscData.decodeUint(60, 60);
if (debtRatio < minDebtRatio || debtRatio > maxDebtRatio) {
revert ErrorDebtRatioOutOfRange();
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { IERC4626 } from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IFxUSDBasePool } from "../../interfaces/IFxUSDBasePool.sol";
import { ISavingFxUSD } from "../../interfaces/ISavingFxUSD.sol";
import { IFxShareableRebalancePool } from "../../v2/interfaces/IFxShareableRebalancePool.sol";
import { IFxUSD } from "../../v2/interfaces/IFxUSD.sol";
import { ILiquidityGauge } from "../../voting-escrow/interfaces/ILiquidityGauge.sol";
import { WordCodec } from "../../common/codec/WordCodec.sol";
import { LibRouter } from "../libraries/LibRouter.sol";
contract SavingFxUSDFacet {
using SafeERC20 for IERC20;
/*************
* Constants *
*************/
/// @notice The address of USDC token.
address private constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
/// @notice The address of fxUSD token.
address private constant fxUSD = 0x085780639CC2cACd35E474e71f4d000e2405d8f6;
/***********************
* Immutable Variables *
***********************/
/// @dev The address of `FxUSDBasePool` contract.
address private immutable fxBASE;
/// @dev The address of `SavingFxUSD` contract.
address private immutable fxSAVE;
/***************
* Constructor *
***************/
constructor(address _fxBASE, address _fxSAVE) {
fxBASE = _fxBASE;
fxSAVE = _fxSAVE;
}
/****************************
* Public Mutated Functions *
****************************/
/// @notice Deposit token to fxSAVE.
/// @param params The parameters to convert source token to `tokenOut`.
/// @param tokenOut The target token, USDC or fxUSD.
/// @param minShares The minimum shares should receive.
/// @param receiver The address of fxSAVE share recipient.
function depositToFxSave(
LibRouter.ConvertInParams memory params,
address tokenOut,
uint256 minShares,
address receiver
) external payable {
uint256 amountIn = LibRouter.transferInAndConvert(params, tokenOut);
LibRouter.approve(tokenOut, fxBASE, amountIn);
uint256 shares = IFxUSDBasePool(fxBASE).deposit(address(this), tokenOut, amountIn, minShares);
LibRouter.approve(fxBASE, fxSAVE, shares);
IERC4626(fxSAVE).deposit(shares, receiver);
}
/// @notice Burn fxSave shares and then convert USDC and fxUSD to another token.
/// @param fxusdParams The parameters to convert fxUSD to target token.
/// @param usdcParams The parameters to convert USDC to target token.
/// @param receiver The address of token recipient.
function redeemFromFxSave(
LibRouter.ConvertOutParams memory fxusdParams,
LibRouter.ConvertOutParams memory usdcParams,
address receiver
) external {
ISavingFxUSD(fxSAVE).claimFor(msg.sender, address(this));
uint256 amountFxUSD = IERC20(fxUSD).balanceOf(address(this));
uint256 amountUSDC = IERC20(USDC).balanceOf(address(this));
LibRouter.convertAndTransferOut(fxusdParams, fxUSD, amountFxUSD, receiver);
LibRouter.convertAndTransferOut(usdcParams, USDC, amountUSDC, receiver);
}
/// @notice Burn fxSave shares and then convert USDC and fxUSD to another token instantly.
/// @param fxusdParams The parameters to convert fxUSD to target token.
/// @param usdcParams The parameters to convert USDC to target token.
/// @param receiver The address of token recipient.
function instantRedeemFromFxSave(
LibRouter.ConvertOutParams memory fxusdParams,
LibRouter.ConvertOutParams memory usdcParams,
uint256 shares,
address receiver
) external {
uint256 assets = IERC4626(fxSAVE).redeem(shares, address(this), msg.sender);
(uint256 amountFxUSD, uint256 amountUSDC) = IFxUSDBasePool(fxBASE).instantRedeem(address(this), assets);
LibRouter.convertAndTransferOut(fxusdParams, fxUSD, amountFxUSD, receiver);
LibRouter.convertAndTransferOut(usdcParams, USDC, amountUSDC, receiver);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { IMultiPathConverter } from "../../helpers/interfaces/IMultiPathConverter.sol";
import { IWrappedEther } from "../../interfaces/IWrappedEther.sol";
library LibRouter {
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
/**********
* Errors *
**********/
/// @dev Thrown when use unapproved target contract.
error ErrorTargetNotApproved();
/// @dev Thrown when msg.value is different from amount.
error ErrorMsgValueMismatch();
/// @dev Thrown when the output token is not enough.
error ErrorInsufficientOutput();
/// @dev Thrown when the whitelisted account type is incorrect.
error ErrorNotWhitelisted();
/*************
* Constants *
*************/
/// @dev The storage slot for router storage.
bytes32 private constant ROUTER_STORAGE_SLOT = keccak256("diamond.router.storage");
/// @dev The address of WETH token.
address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
uint8 internal constant NOT_FLASH_LOAN = 0;
uint8 internal constant HAS_FLASH_LOAN = 1;
uint8 internal constant NOT_ENTRANT = 0;
uint8 internal constant HAS_ENTRANT = 1;
/***********
* Structs *
***********/
/// @param spenders Mapping from target address to token spender address.
/// @param approvedTargets The list of approved target contracts.
/// @param whitelisted The list of whitelisted contracts.
struct RouterStorage {
mapping(address => address) spenders;
EnumerableSet.AddressSet approvedTargets;
EnumerableSet.AddressSet whitelisted;
address revenuePool;
uint8 flashLoanContext;
uint8 reentrantContext;
}
/// @notice The struct for input token convert parameters.
///
/// @param tokenIn The address of source token.
/// @param amount The amount of source token.
/// @param target The address of converter contract.
/// @param data The calldata passing to the target contract.
/// @param minOut The minimum amount of output token should receive.
/// @param signature The optional data for future usage.
struct ConvertInParams {
address tokenIn;
uint256 amount;
address target;
bytes data;
uint256 minOut;
bytes signature;
}
/// @notice The struct for output token convert parameters.
/// @param tokenOut The address of output token.
/// @param converter The address of converter contract.
/// @param encodings The encodings for `MultiPathConverter`.
/// @param minOut The minimum amount of output token should receive.
/// @param routes The convert route encodings.
/// @param signature The optional data for future usage.
struct ConvertOutParams {
address tokenOut;
address converter;
uint256 encodings;
uint256[] routes;
uint256 minOut;
bytes signature;
}
/**********************
* Internal Functions *
**********************/
/// @dev Return the RouterStorage reference.
function routerStorage() internal pure returns (RouterStorage storage gs) {
bytes32 position = ROUTER_STORAGE_SLOT;
assembly {
gs.slot := position
}
}
/// @dev Approve contract to be used in token converting.
function approveTarget(address target, address spender) internal {
RouterStorage storage $ = routerStorage();
if ($.approvedTargets.add(target) && target != spender) {
$.spenders[target] = spender;
}
}
/// @dev Remove approve contract in token converting.
function removeTarget(address target) internal {
RouterStorage storage $ = routerStorage();
if ($.approvedTargets.remove(target)) {
delete $.spenders[target];
}
}
/// @dev Whitelist account with type.
function updateWhitelist(address account, bool status) internal {
RouterStorage storage $ = routerStorage();
if (status) {
$.whitelisted.add(account);
} else {
$.whitelisted.remove(account);
}
}
/// @dev Check whether the account is whitelisted with specific type.
function ensureWhitelisted(address account) internal view {
RouterStorage storage $ = routerStorage();
if (!$.whitelisted.contains(account)) {
revert ErrorNotWhitelisted();
}
}
function updateRevenuePool(address revenuePool) internal {
RouterStorage storage $ = routerStorage();
$.revenuePool = revenuePool;
}
/// @dev Transfer token into this contract and convert to `tokenOut`.
/// @param params The parameters used in token converting.
/// @param tokenOut The address of final converted token.
/// @return amountOut The amount of token received.
function transferInAndConvert(ConvertInParams memory params, address tokenOut) internal returns (uint256 amountOut) {
RouterStorage storage $ = routerStorage();
if (!$.approvedTargets.contains(params.target)) {
revert ErrorTargetNotApproved();
}
transferTokenIn(params.tokenIn, address(this), params.amount);
amountOut = IERC20(tokenOut).balanceOf(address(this));
if (params.tokenIn == tokenOut) return amountOut;
bool _success;
if (params.tokenIn == address(0)) {
(_success, ) = params.target.call{ value: params.amount }(params.data);
} else {
address _spender = $.spenders[params.target];
if (_spender == address(0)) _spender = params.target;
approve(params.tokenIn, _spender, params.amount);
(_success, ) = params.target.call(params.data);
}
// below lines will propagate inner error up
if (!_success) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
let size := returndatasize()
returndatacopy(ptr, 0, size)
revert(ptr, size)
}
}
amountOut = IERC20(tokenOut).balanceOf(address(this)) - amountOut;
}
/// @dev Convert `tokenIn` to other token and transfer out.
/// @param params The parameters used in token converting.
/// @param tokenIn The address of token to convert.
/// @param amountIn The amount of token to convert.
/// @return amountOut The amount of token received.
function convertAndTransferOut(
ConvertOutParams memory params,
address tokenIn,
uint256 amountIn,
address receiver
) internal returns (uint256 amountOut) {
RouterStorage storage $ = routerStorage();
if (!$.approvedTargets.contains(params.converter)) {
revert ErrorTargetNotApproved();
}
if (amountIn == 0) return 0;
amountOut = amountIn;
if (params.routes.length > 0) {
approve(tokenIn, params.converter, amountIn);
amountOut = IMultiPathConverter(params.converter).convert(tokenIn, amountIn, params.encodings, params.routes);
}
if (amountOut < params.minOut) revert ErrorInsufficientOutput();
if (params.tokenOut == address(0)) {
IWrappedEther(WETH).withdraw(amountOut);
Address.sendValue(payable(receiver), amountOut);
} else {
IERC20(params.tokenOut).safeTransfer(receiver, amountOut);
}
}
/// @dev Internal function to transfer token to this contract.
/// @param token The address of token to transfer.
/// @param amount The amount of token to transfer.
/// @return uint256 The amount of token transferred.
function transferTokenIn(address token, address receiver, uint256 amount) internal returns (uint256) {
if (token == address(0)) {
if (msg.value != amount) revert ErrorMsgValueMismatch();
} else {
IERC20(token).safeTransferFrom(msg.sender, receiver, amount);
}
return amount;
}
/// @dev Internal function to refund extra token.
/// @param token The address of token to refund.
/// @param recipient The address of the token receiver.
function refundERC20(address token, address recipient) internal {
uint256 _balance = IERC20(token).balanceOf(address(this));
if (_balance > 0) {
IERC20(token).safeTransfer(recipient, _balance);
}
}
/// @dev Internal function to approve token.
function approve(address token, address spender, uint256 amount) internal {
IERC20(token).forceApprove(spender, amount);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { Math } from "@openzeppelin/contracts-v4/utils/math/Math.sol";
import { SpotPriceOracleBase } from "./SpotPriceOracleBase.sol";
import { IPriceOracle } from "./interfaces/IPriceOracle.sol";
abstract contract BTCDerivativeOracleBase is SpotPriceOracleBase, IPriceOracle {
/*************
* Constants *
*************/
/// @notice The Chainlink BTC/USD price feed.
/// @dev See comments of `_readSpotPriceByChainlink` for more details.
bytes32 public immutable Chainlink_BTC_USD_Spot;
/*************
* Variables *
*************/
/// @dev The encodings for BTCDerivative/USD spot sources.
bytes private onchainSpotEncodings_BTCDerivativeUSD;
/// @notice The value of maximum price deviation, multiplied by 1e18.
uint256 public maxPriceDeviation;
/***************
* Constructor *
***************/
constructor(bytes32 _Chainlink_BTC_USD_Spot) {
Chainlink_BTC_USD_Spot = _Chainlink_BTC_USD_Spot;
_updateMaxPriceDeviation(1e16); // 1%
}
/*************************
* Public View Functions *
*************************/
/// @notice Return the BTCDerivative/USD spot prices.
/// @return prices The list of spot price among all available sources, multiplied by 1e18.
function getBTCDerivativeUSDSpotPrices() public view returns (uint256[] memory prices) {
prices = _getSpotPriceByEncoding(onchainSpotEncodings_BTCDerivativeUSD);
}
/// @notice Return the BTCDerivative/USD anchor price, the price that is hard to manipulate in single tx.
/// @return price The anchor price, multiplied by 1e18.
function getBTCDerivativeUSDAnchorPrice(bool isRedeem) external view returns (uint256 price) {
price = _getBTCDerivativeUSDAnchorPrice(isRedeem);
}
/// @inheritdoc IPriceOracle
/// @dev The price is valid iff |maxPrice-minPrice|/minPrice < maxPriceDeviation
function getPrice() external view override returns (uint256 anchorPrice, uint256 minPrice, uint256 maxPrice) {
anchorPrice = _getBTCDerivativeUSDAnchorPrice(false);
(minPrice, maxPrice) = _getBTCDerivativeMinMaxPrice(anchorPrice);
uint256 cachedMaxPriceDeviation = maxPriceDeviation; // gas saving
// use anchor price when the price deviation between anchor price and min price exceed threshold
if ((anchorPrice - minPrice) * PRECISION > cachedMaxPriceDeviation * minPrice) {
minPrice = anchorPrice;
}
// use anchor price when the price deviation between anchor price and max price exceed threshold
if ((maxPrice - anchorPrice) * PRECISION > cachedMaxPriceDeviation * anchorPrice) {
maxPrice = anchorPrice;
}
}
/// @inheritdoc IPriceOracle
function getExchangePrice() public view returns (uint256) {
uint256 anchorPrice = _getBTCDerivativeUSDAnchorPrice(false);
(uint256 minPrice, ) = _getBTCDerivativeMinMaxPrice(anchorPrice);
// use anchor price when the price deviation between anchor price and min price exceed threshold
if ((anchorPrice - minPrice) * PRECISION > maxPriceDeviation * minPrice) {
minPrice = anchorPrice;
}
return minPrice;
}
/// @inheritdoc IPriceOracle
function getLiquidatePrice() external view returns (uint256) {
return getExchangePrice();
}
/// @inheritdoc IPriceOracle
function getRedeemPrice() external view returns (uint256) {
uint256 anchorPrice = _getBTCDerivativeUSDAnchorPrice(true);
(, uint256 maxPrice) = _getBTCDerivativeMinMaxPrice(anchorPrice);
// use anchor price when the price deviation between anchor price and max price exceed threshold
if ((maxPrice - anchorPrice) * PRECISION > maxPriceDeviation * anchorPrice) {
maxPrice = anchorPrice;
}
return maxPrice;
}
/************************
* Restricted Functions *
************************/
/// @notice Update the on-chain spot encodings.
/// @param encodings The encodings to update. See `_getSpotPriceByEncoding` for more details.
function updateOnchainSpotEncodings(bytes memory encodings) external onlyOwner {
// validate encoding
uint256[] memory prices = _getSpotPriceByEncoding(encodings);
if (prices.length == 0) revert();
onchainSpotEncodings_BTCDerivativeUSD = encodings;
}
/// @notice Update the value of maximum price deviation.
/// @param newMaxPriceDeviation The new value of maximum price deviation, multiplied by 1e18.
function updateMaxPriceDeviation(uint256 newMaxPriceDeviation) external onlyOwner {
_updateMaxPriceDeviation(newMaxPriceDeviation);
}
/**********************
* Internal Functions *
**********************/
/// @dev Internal function to update the value of maximum price deviation.
/// @param newMaxPriceDeviation The new value of maximum price deviation, multiplied by 1e18.
function _updateMaxPriceDeviation(uint256 newMaxPriceDeviation) private {
uint256 oldMaxPriceDeviation = maxPriceDeviation;
if (oldMaxPriceDeviation == newMaxPriceDeviation) {
revert ErrorParameterUnchanged();
}
maxPriceDeviation = newMaxPriceDeviation;
emit UpdateMaxPriceDeviation(oldMaxPriceDeviation, newMaxPriceDeviation);
}
/// @dev Internal function to return the min/max BTCDerivative/USD prices.
/// @param anchorPrice The BTCDerivative/USD anchor price, multiplied by 1e18.
/// @return minPrice The minimum price among all available sources (including anchor price), multiplied by 1e18.
/// @return maxPrice The maximum price among all available sources (including anchor price), multiplied by 1e18.
function _getBTCDerivativeMinMaxPrice(
uint256 anchorPrice
) internal view returns (uint256 minPrice, uint256 maxPrice) {
minPrice = maxPrice = anchorPrice;
uint256[] memory BTCDerivative_USD_prices = getBTCDerivativeUSDSpotPrices();
uint256 length = BTCDerivative_USD_prices.length;
for (uint256 i = 0; i < length; i++) {
uint256 price = BTCDerivative_USD_prices[i];
if (price > maxPrice) maxPrice = price;
if (price < minPrice) minPrice = price;
}
}
/// @dev Internal function to return the BTCDerivative/USD anchor price.
/// @return price The anchor price of BTCDerivative/USD, multiplied by 1e18.
function _getBTCDerivativeUSDAnchorPrice(bool isRedeem) internal view virtual returns (uint256 price);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { SpotPriceOracleBase } from "./SpotPriceOracleBase.sol";
import { IPriceOracle } from "./interfaces/IPriceOracle.sol";
import { ITwapOracle } from "./interfaces/ITwapOracle.sol";
contract ETHPriceOracle is SpotPriceOracleBase, IPriceOracle {
/*************
* Constants *
*************/
/// @notice The Chainlink ETH/USD price feed.
/// @dev See comments of `_readSpotPriceByChainlink` for more details.
bytes32 public immutable Chainlink_ETH_USD_Spot;
/*************
* Variables *
*************/
/// @dev The encodings for ETH/USD spot sources.
bytes private onchainSpotEncodings_ETHUSD;
/// @notice The value of maximum price deviation, multiplied by 1e18.
uint256 public maxPriceDeviation;
/***************
* Constructor *
***************/
constructor(address _spotPriceOracle, bytes32 _Chainlink_ETH_USD_Spot) SpotPriceOracleBase(_spotPriceOracle) {
Chainlink_ETH_USD_Spot = _Chainlink_ETH_USD_Spot;
_updateMaxPriceDeviation(1e16); // 1%
}
/*************************
* Public View Functions *
*************************/
/// @notice Return the ETH/USD spot price.
/// @return chainlinkPrice The spot price from Chainlink price feed.
/// @return minPrice The minimum spot price among all available sources.
/// @return maxPrice The maximum spot price among all available sources.
function getETHUSDSpotPrice() external view returns (uint256 chainlinkPrice, uint256 minPrice, uint256 maxPrice) {
(chainlinkPrice, minPrice, maxPrice) = _getETHUSDSpotPrice();
}
/// @notice Return the ETH/USD spot prices.
/// @return prices The list of spot price among all available sources, multiplied by 1e18.
function getETHUSDSpotPrices() external view returns (uint256[] memory prices) {
prices = _getSpotPriceByEncoding(onchainSpotEncodings_ETHUSD);
}
/// @inheritdoc IPriceOracle
/// @dev The price is valid iff |maxPrice-minPrice|/minPrice < maxPriceDeviation
function getPrice() public view override returns (uint256 anchorPrice, uint256 minPrice, uint256 maxPrice) {
(anchorPrice, minPrice, maxPrice) = _getETHUSDSpotPrice();
uint256 cachedMaxPriceDeviation = maxPriceDeviation; // gas saving
// use anchor price when the price deviation between anchor price and min price exceed threshold
if ((anchorPrice - minPrice) * PRECISION > cachedMaxPriceDeviation * minPrice) {
minPrice = anchorPrice;
}
// use anchor price when the price deviation between anchor price and max price exceed threshold
if ((maxPrice - anchorPrice) * PRECISION > cachedMaxPriceDeviation * anchorPrice) {
maxPrice = anchorPrice;
}
}
/// @inheritdoc IPriceOracle
function getExchangePrice() public view returns (uint256) {
(, uint256 price, ) = getPrice();
return price;
}
/// @inheritdoc IPriceOracle
function getLiquidatePrice() external view returns (uint256) {
return getExchangePrice();
}
/// @inheritdoc IPriceOracle
function getRedeemPrice() external view returns (uint256) {
(, , uint256 price) = getPrice();
return price;
}
/************************
* Restricted Functions *
************************/
/// @notice Update the on-chain spot encodings.
/// @param encodings The encodings to update. See `_getSpotPriceByEncoding` for more details.
function updateOnchainSpotEncodings(bytes memory encodings) external onlyOwner {
// validate encoding
_getSpotPriceByEncoding(encodings);
onchainSpotEncodings_ETHUSD = encodings;
}
/// @notice Update the value of maximum price deviation.
/// @param newMaxPriceDeviation The new value of maximum price deviation, multiplied by 1e18.
function updateMaxPriceDeviation(uint256 newMaxPriceDeviation) external onlyOwner {
_updateMaxPriceDeviation(newMaxPriceDeviation);
}
/**********************
* Internal Functions *
**********************/
/// @dev Internal function to update the value of maximum price deviation.
/// @param newMaxPriceDeviation The new value of maximum price deviation, multiplied by 1e18.
function _updateMaxPriceDeviation(uint256 newMaxPriceDeviation) private {
uint256 oldMaxPriceDeviation = maxPriceDeviation;
if (oldMaxPriceDeviation == newMaxPriceDeviation) {
revert ErrorParameterUnchanged();
}
maxPriceDeviation = newMaxPriceDeviation;
emit UpdateMaxPriceDeviation(oldMaxPriceDeviation, newMaxPriceDeviation);
}
/// @dev Internal function to calculate the ETH/USD spot price.
/// @return chainlinkPrice The spot price from Chainlink price feed, multiplied by 1e18.
/// @return minPrice The minimum spot price among all available sources, multiplied by 1e18.
/// @return maxPrice The maximum spot price among all available sources, multiplied by 1e18.
function _getETHUSDSpotPrice() internal view returns (uint256 chainlinkPrice, uint256 minPrice, uint256 maxPrice) {
chainlinkPrice = _readSpotPriceByChainlink(Chainlink_ETH_USD_Spot);
uint256[] memory prices = _getSpotPriceByEncoding(onchainSpotEncodings_ETHUSD);
minPrice = maxPrice = chainlinkPrice;
for (uint256 i = 0; i < prices.length; i++) {
if (prices[i] > maxPrice) maxPrice = prices[i];
if (prices[i] < minPrice) minPrice = prices[i];
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IPriceOracle {
/**********
* Events *
**********/
/// @notice Emitted when the value of maximum price deviation is updated.
/// @param oldValue The value of the previous maximum price deviation.
/// @param newValue The value of the current maximum price deviation.
event UpdateMaxPriceDeviation(uint256 oldValue, uint256 newValue);
/*************************
* Public View Functions *
*************************/
/// @notice Return the oracle price with 18 decimal places.
/// @return anchorPrice The anchor price for this asset, multiplied by 1e18. It should be hard to manipulate,
/// like time-weighted average price or chainlink spot price.
/// @return minPrice The minimum oracle price among all available price sources (including twap), multiplied by 1e18.
/// @return maxPrice The maximum oracle price among all available price sources (including twap), multiplied by 1e18.
function getPrice() external view returns (uint256 anchorPrice, uint256 minPrice, uint256 maxPrice);
/// @notice Return the oracle price for exchange with 18 decimal places.
function getExchangePrice() external view returns (uint256);
/// @notice Return the oracle price for liquidation with 18 decimal places.
function getLiquidatePrice() external view returns (uint256);
/// @notice Return the oracle price for redemption with 18 decimal places.
function getRedeemPrice() external view returns (uint256);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface ISpotPriceOracle {
/// @notice Return spot price with 18 decimal places.
///
/// @dev encoding for single route
/// | 8 bits | 160 bits | 88 bits |
/// | pool_type | pool | customized |
/// assume all base and quote token has no more than 18 decimals.
///
/// + pool_type = 0: UniswapV2
/// customized = | 1 bit | 8 bits | 8 bits | ... |
/// | base_index | base_scale | quote_scale | ... |
/// + pool_type = 1: UniswapV3
/// customized = | 1 bit | 8 bits | 8 bits | ... |
/// | base_index | base_scale | quote_scale | ... |
/// + pool_type = 2: Balancer V2 Weighted
/// customized = | 3 bit | 3 bit | 8 bits | 8 bits | ... |
/// | base_index | quote_index | base_scale | quote_scale | ... |
/// + pool_type = 3: Balancer V2 Stable
/// customized = | 3 bits | 3 bits | ... |
/// | base_index | quote_index | ... |
/// + pool_type = 4: Curve Plain
/// customized = | 3 bits | 3 bits | 3 bits | 1 bits | 8 bits | ... | 8 bits | ... |
/// | tokens | base_index | quote_index | has_amm_precise | scale[0] | ... | scale[n] | ... |
/// + pool_type = 5: Curve Plain with oracle
/// customized = | 1 bit | 1 bit |... |
/// | base_index | use_cache | ... |
/// + pool_type = 6: Curve Plain NG
/// customized = | 3 bits | 3 bits | 1 bit | ... |
/// | base_index | quote_index | use_cache | ... |
/// + pool_type = 7: Curve Crypto
/// customized = | 1 bit | ... |
/// | base_index | ... |
/// + pool_type = 8: Curve TriCrypto
/// customized = | 2 bits | 2 bits | ... |
/// | base_index | quote_index | ... |
/// + pool_type = 9: ERC4626
/// customized = | 1 bit | ... |
/// | base_is_underlying | ... |
/// + pool_type = 10: ETHLSD, wstETH, weETH, ezETH
/// customized = | 1 bit | ... |
/// | base_is_ETH | ... |
/// + pool_type = 11: BalancerV2CachedRate
/// customized = | 3 bits | ... |
/// | base_index | ... |
///
/// @param encoding The encoding of the price source.
/// @return spotPrice The spot price with 18 decimal places.
function getSpotPrice(uint256 encoding) external view returns (uint256 spotPrice);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface ITwapOracle {
/// @notice Return TWAP with 18 decimal places in the epoch ending at the specified timestamp.
/// Zero is returned if TWAP in the epoch is not available.
/// @param timestamp End Timestamp in seconds of the epoch
/// @return TWAP (18 decimal places) in the epoch, or zero if not available
function getTwap(uint256 timestamp) external view returns (uint256);
/// @notice Return the latest price with 18 decimal places.
function getLatest() external view returns (uint256);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { SpotPriceOracleBase } from "./SpotPriceOracleBase.sol";
import { IPriceOracle } from "./interfaces/IPriceOracle.sol";
import { ITwapOracle } from "./interfaces/ITwapOracle.sol";
abstract contract LSDPriceOracleBase is SpotPriceOracleBase, IPriceOracle {
/*************
* Constants *
*************/
/// @notice The Chainlink ETH/USD price feed.
/// @dev See comments of `_readSpotPriceByChainlink` for more details.
bytes32 public immutable Chainlink_ETH_USD_Spot;
/*************
* Variables *
*************/
/// @dev The encodings for ETH/USD spot sources.
bytes private onchainSpotEncodings_ETHUSD;
/// @dev The encodings for LSD/ETH spot sources.
bytes private onchainSpotEncodings_LSDETH;
/// @dev The encodings for LSD/USD spot sources.
bytes private onchainSpotEncodings_LSDUSD;
/// @notice The value of maximum price deviation, multiplied by 1e18.
uint256 public maxPriceDeviation;
/***************
* Constructor *
***************/
constructor(bytes32 _Chainlink_ETH_USD_Spot) {
Chainlink_ETH_USD_Spot = _Chainlink_ETH_USD_Spot;
_updateMaxPriceDeviation(1e16); // 1%
}
/*************************
* Public View Functions *
*************************/
/// @notice Return the ETH/USD spot price.
/// @return chainlinkPrice The spot price from Chainlink price feed.
/// @return minPrice The minimum spot price among all available sources.
/// @return maxPrice The maximum spot price among all available sources.
function getETHUSDSpotPrice() external view returns (uint256 chainlinkPrice, uint256 minPrice, uint256 maxPrice) {
(chainlinkPrice, minPrice, maxPrice) = _getETHUSDSpotPrice();
}
/// @notice Return the ETH/USD spot prices.
/// @return prices The list of spot price among all available sources, multiplied by 1e18.
function getETHUSDSpotPrices() external view returns (uint256[] memory prices) {
prices = _getSpotPriceByEncoding(onchainSpotEncodings_ETHUSD);
}
/// @notice Return the LSD/ETH spot prices.
/// @return prices The list of spot price among all available sources, multiplied by 1e18.
function getLSDETHSpotPrices() public view returns (uint256[] memory prices) {
prices = _getSpotPriceByEncoding(onchainSpotEncodings_LSDETH);
}
/// @notice Return the LSD/ETH spot prices.
/// @return prices The list of spot price among all available sources, multiplied by 1e18.
function getLSDUSDSpotPrices() public view returns (uint256[] memory prices) {
prices = _getSpotPriceByEncoding(onchainSpotEncodings_LSDUSD);
}
/// @notice Return the LSD/USD anchor price, the price that is hard to manipulate in single tx.
/// @return price The anchor price, multiplied by 1e18.
function getLSDUSDAnchorPrice() external view returns (uint256 price) {
price = _getLSDUSDAnchorPrice();
}
/// @inheritdoc IPriceOracle
/// @dev The price is valid iff |maxPrice-minPrice|/minPrice < maxPriceDeviation
function getPrice() public view override returns (uint256 anchorPrice, uint256 minPrice, uint256 maxPrice) {
anchorPrice = _getLSDUSDAnchorPrice();
(minPrice, maxPrice) = _getLSDMinMaxPrice(anchorPrice);
uint256 cachedMaxPriceDeviation = maxPriceDeviation; // gas saving
// use anchor price when the price deviation between anchor price and min price exceed threshold
if ((anchorPrice - minPrice) * PRECISION > cachedMaxPriceDeviation * minPrice) {
minPrice = anchorPrice;
}
// use anchor price when the price deviation between anchor price and max price exceed threshold
if ((maxPrice - anchorPrice) * PRECISION > cachedMaxPriceDeviation * anchorPrice) {
maxPrice = anchorPrice;
}
}
/// @inheritdoc IPriceOracle
function getExchangePrice() public view returns (uint256) {
(, uint256 price, ) = getPrice();
return price;
}
/// @inheritdoc IPriceOracle
function getLiquidatePrice() external view returns (uint256) {
return getExchangePrice();
}
/// @inheritdoc IPriceOracle
function getRedeemPrice() external view returns (uint256) {
(, , uint256 price) = getPrice();
return price;
}
/************************
* Restricted Functions *
************************/
/// @notice Update the on-chain spot encodings.
/// @param encodings The encodings to update. See `_getSpotPriceByEncoding` for more details.
/// @param spotType The type of the encodings.
function updateOnchainSpotEncodings(bytes memory encodings, uint256 spotType) external onlyOwner {
// validate encoding
uint256[] memory prices = _getSpotPriceByEncoding(encodings);
if (spotType == 0) {
onchainSpotEncodings_ETHUSD = encodings;
if (prices.length == 0) revert ErrorInvalidEncodings();
} else if (spotType == 1) {
onchainSpotEncodings_LSDETH = encodings;
} else if (spotType == 2) {
onchainSpotEncodings_LSDUSD = encodings;
}
}
/// @notice Update the value of maximum price deviation.
/// @param newMaxPriceDeviation The new value of maximum price deviation, multiplied by 1e18.
function updateMaxPriceDeviation(uint256 newMaxPriceDeviation) external onlyOwner {
_updateMaxPriceDeviation(newMaxPriceDeviation);
}
/**********************
* Internal Functions *
**********************/
/// @dev Internal function to update the value of maximum price deviation.
/// @param newMaxPriceDeviation The new value of maximum price deviation, multiplied by 1e18.
function _updateMaxPriceDeviation(uint256 newMaxPriceDeviation) private {
uint256 oldMaxPriceDeviation = maxPriceDeviation;
if (oldMaxPriceDeviation == newMaxPriceDeviation) {
revert ErrorParameterUnchanged();
}
maxPriceDeviation = newMaxPriceDeviation;
emit UpdateMaxPriceDeviation(oldMaxPriceDeviation, newMaxPriceDeviation);
}
/// @dev Internal function to calculate the ETH/USD spot price.
/// @return chainlinkPrice The spot price from Chainlink price feed, multiplied by 1e18.
/// @return minPrice The minimum spot price among all available sources, multiplied by 1e18.
/// @return maxPrice The maximum spot price among all available sources, multiplied by 1e18.
function _getETHUSDSpotPrice() internal view returns (uint256 chainlinkPrice, uint256 minPrice, uint256 maxPrice) {
chainlinkPrice = _readSpotPriceByChainlink(Chainlink_ETH_USD_Spot);
uint256[] memory prices = _getSpotPriceByEncoding(onchainSpotEncodings_ETHUSD);
minPrice = maxPrice = chainlinkPrice;
for (uint256 i = 0; i < prices.length; i++) {
if (prices[i] > maxPrice) maxPrice = prices[i];
if (prices[i] < minPrice) minPrice = prices[i];
}
}
/// @dev Internal function to return the min/max LSD/USD prices.
/// @param anchorPrice The LSD/USD anchor price, multiplied by 1e18.
/// @return minPrice The minimum price among all available sources (including twap), multiplied by 1e18.
/// @return maxPrice The maximum price among all available sources (including twap), multiplied by 1e18.
function _getLSDMinMaxPrice(uint256 anchorPrice) internal view returns (uint256 minPrice, uint256 maxPrice) {
minPrice = maxPrice = anchorPrice;
(, uint256 minETHUSDPrice, uint256 maxETHUSDPrice) = _getETHUSDSpotPrice();
uint256[] memory LSD_ETH_prices = getLSDETHSpotPrices();
uint256[] memory LSD_USD_prices = getLSDUSDSpotPrices();
uint256 length = LSD_ETH_prices.length;
uint256 LSD_ETH_minPrice = type(uint256).max;
uint256 LSD_ETH_maxPrice;
unchecked {
for (uint256 i = 0; i < length; i++) {
uint256 price = LSD_ETH_prices[i];
if (price > LSD_ETH_maxPrice) LSD_ETH_maxPrice = price;
if (price < LSD_ETH_minPrice) LSD_ETH_minPrice = price;
}
if (LSD_ETH_maxPrice != 0) {
minPrice = Math.min(minPrice, (LSD_ETH_minPrice * minETHUSDPrice) / PRECISION);
maxPrice = Math.max(maxPrice, (LSD_ETH_maxPrice * maxETHUSDPrice) / PRECISION);
}
length = LSD_USD_prices.length;
for (uint256 i = 0; i < length; i++) {
uint256 price = LSD_USD_prices[i];
if (price > maxPrice) maxPrice = price;
if (price < minPrice) minPrice = price;
}
}
}
/// @dev Internal function to return the LSD/USD anchor price.
/// @return price The anchor price of LSD/USD, multiplied by 1e18.
function _getLSDUSDAnchorPrice() internal view virtual returns (uint256 price);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { Ownable2Step } from "@openzeppelin/contracts/access/Ownable2Step.sol";
import { AggregatorV3Interface } from "../interfaces/Chainlink/AggregatorV3Interface.sol";
import { ISpotPriceOracle } from "./interfaces/ISpotPriceOracle.sol";
abstract contract SpotPriceOracleBase is Ownable2Step {
/**********
* Errors *
**********/
/// @dev Thrown when the given encodings are invalid.
error ErrorInvalidEncodings();
/// @dev Thrown when update some parameters to the same value.
error ErrorParameterUnchanged();
/*************
* Constants *
*************/
/// @dev The precision for oracle price.
uint256 internal constant PRECISION = 1e18;
/// @dev The address of `SpotPriceOracle` contract.
address immutable spotPriceOracle;
/***************
* Constructor *
***************/
constructor(address _spotPriceOracle) Ownable(_msgSender()) {
spotPriceOracle = _spotPriceOracle;
}
/**********************
* Internal Functions *
**********************/
/// @dev The encoding is below.
/// ```text
/// | 32 bits | 64 bits | 160 bits |
/// | heartbeat | scale | price_feed |
/// |low high |
/// ```
function _readSpotPriceByChainlink(bytes32 encoding) internal view returns (uint256) {
address aggregator;
uint256 scale;
uint256 heartbeat;
assembly {
aggregator := shr(96, encoding)
scale := and(shr(32, encoding), 0xffffffffffffffff)
heartbeat := and(encoding, 0xffffffff)
}
(, int256 answer, , uint256 updatedAt, ) = AggregatorV3Interface(aggregator).latestRoundData();
if (answer <= 0) revert("invalid");
if (block.timestamp - updatedAt > heartbeat) revert("expired");
return uint256(answer) * scale;
}
/// @dev Internal function to calculate spot price by encodings.
///
/// The details of the encoding is below
/// ```text
/// | 1 byte | ... | ... | ... | ... |
/// | num_source | source[0] | source[1] | ... | source[n] |
///
/// source encoding:
/// | 1 byte | 32 bytes | 32 bytes | ... | 32 bytes |
/// | num_pool | pool[0] | pool[1] | ... | pool[n] |
/// 1 <= num_pool <= 3
///
/// The encoding of each pool can be found in `SpotPriceOracle` contract.
/// ```
/// @return prices The list of prices of each source, multiplied by 1e18.
function _getSpotPriceByEncoding(bytes memory encodings) internal view returns (uint256[] memory prices) {
uint256 ptr;
uint256 length;
assembly {
ptr := add(encodings, 0x21)
length := byte(0, mload(sub(ptr, 1)))
}
prices = new uint256[](length);
for (uint256 i = 0; i < length; i++) {
uint256 encoding1;
uint256 encoding2;
uint256 encoding3;
assembly {
let cnt := byte(0, mload(ptr))
ptr := add(ptr, 0x01)
if gt(cnt, 0) {
encoding1 := mload(ptr)
ptr := add(ptr, 0x20)
}
if gt(cnt, 1) {
encoding2 := mload(ptr)
ptr := add(ptr, 0x20)
}
if gt(cnt, 2) {
encoding3 := mload(ptr)
ptr := add(ptr, 0x20)
}
}
if (encoding1 == 0) {
revert ErrorInvalidEncodings();
} else if (encoding2 == 0) {
prices[i] = _readSpotPrice(encoding1);
} else if (encoding3 == 0) {
prices[i] = _readSpotPrice(encoding1, encoding2);
} else {
prices[i] = _readSpotPrice(encoding1, encoding2, encoding3);
}
}
}
/// @dev Internal function to calculate spot price of single pool.
/// @param encoding The encoding for the pool.
/// @return price The spot price of the source, multiplied by 1e18.
function _readSpotPrice(uint256 encoding) private view returns (uint256 price) {
price = ISpotPriceOracle(spotPriceOracle).getSpotPrice(encoding);
}
/// @dev Internal function to calculate spot price of two pools.
/// @param encoding1 The encoding for the first pool.
/// @param encoding2 The encoding for the second pool.
/// @return price The spot price of the source, multiplied by 1e18.
function _readSpotPrice(uint256 encoding1, uint256 encoding2) private view returns (uint256 price) {
unchecked {
price = (_readSpotPrice(encoding1) * _readSpotPrice(encoding2)) / PRECISION;
}
}
/// @dev Internal function to calculate spot price of three pools.
/// @param encoding1 The encoding for the first pool.
/// @param encoding2 The encoding for the second pool.
/// @param encoding3 The encoding for the third pool.
/// @return price The spot price of the source, multiplied by 1e18.
function _readSpotPrice(
uint256 encoding1,
uint256 encoding2,
uint256 encoding3
) private view returns (uint256 price) {
unchecked {
price = (_readSpotPrice(encoding1, encoding2) * _readSpotPrice(encoding3)) / PRECISION;
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { ICurvePoolOracle } from "../interfaces/Curve/ICurvePoolOracle.sol";
import { SpotPriceOracleBase } from "./SpotPriceOracleBase.sol";
import { LSDPriceOracleBase } from "./LSDPriceOracleBase.sol";
contract StETHPriceOracle is LSDPriceOracleBase {
/***********************
* Immutable Variables *
***********************/
/// @notice The address of curve ETH/stETH pool.
address public immutable Curve_ETH_stETH_Pool;
/***************
* Constructor *
***************/
constructor(
address _spotPriceOracle,
bytes32 _Chainlink_ETH_USD_Spot,
address _Curve_ETH_stETH_Pool
) SpotPriceOracleBase(_spotPriceOracle) LSDPriceOracleBase(_Chainlink_ETH_USD_Spot) {
Curve_ETH_stETH_Pool = _Curve_ETH_stETH_Pool;
}
/**********************
* Internal Functions *
**********************/
/// @inheritdoc LSDPriceOracleBase
/// @dev [Curve stETH/ETH ema price] * [Chainlink ETH/USD spot]
function _getLSDUSDAnchorPrice() internal view virtual override returns (uint256) {
uint256 stETH_ETH_CurveEma = ICurvePoolOracle(Curve_ETH_stETH_Pool).price_oracle();
uint256 ETH_USD_ChainlinkSpot = _readSpotPriceByChainlink(Chainlink_ETH_USD_Spot);
unchecked {
return (stETH_ETH_CurveEma * ETH_USD_ChainlinkSpot) / PRECISION;
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { Math } from "@openzeppelin/contracts-v4/utils/math/Math.sol";
import { SpotPriceOracleBase } from "./SpotPriceOracleBase.sol";
import { BTCDerivativeOracleBase } from "./BTCDerivativeOracleBase.sol";
contract WBTCPriceOracle is BTCDerivativeOracleBase {
/**********
* Events *
**********/
/// @notice Emitted when the value of maximum WBTC deviation is updated.
/// @param oldValue The value of the previous maximum WBTC deviation.
/// @param newValue The value of the current maximum WBTC deviation.
event UpdateMaxWBTCDeviation(uint256 oldValue, uint256 newValue);
/*************
* Constants *
*************/
/// @notice The encoding of the Chainlink WBTC/BTC Spot.
bytes32 public immutable Chainlink_WBTC_BTC_Spot;
/*************
* Variables *
*************/
/// @notice The value of maximum WBTC price deviation, multiplied by 1e18.
uint256 public maxWBTCDeviation;
/***************
* Constructor *
***************/
constructor(
address _spotPriceOracle,
bytes32 _Chainlink_BTC_USD_Spot,
bytes32 _Chainlink_WBTC_BTC_Spot
) SpotPriceOracleBase(_spotPriceOracle) BTCDerivativeOracleBase(_Chainlink_BTC_USD_Spot) {
Chainlink_WBTC_BTC_Spot = _Chainlink_WBTC_BTC_Spot;
_updateMaxWBTCDeviation(2e16); // 2%
}
/************************
* Restricted Functions *
************************/
/// @notice Update the value of maximum WBTC deviation.
/// @param newMaxWBTCDeviation The new value of maximum WBTC deviation, multiplied by 1e18.
function updateMaxWBTCDeviation(uint256 newMaxWBTCDeviation) external onlyOwner {
_updateMaxWBTCDeviation(newMaxWBTCDeviation);
}
/**********************
* Internal Functions *
**********************/
/// @dev Internal function to update the value of maximum WBTC deviation.
/// @param newMaxWBTCDeviation The new value of maximum WBTC deviation, multiplied by 1e18.
function _updateMaxWBTCDeviation(uint256 newMaxWBTCDeviation) private {
uint256 oldMaxWBTCDeviation = maxWBTCDeviation;
if (oldMaxWBTCDeviation == newMaxWBTCDeviation) {
revert ErrorParameterUnchanged();
}
maxWBTCDeviation = newMaxWBTCDeviation;
emit UpdateMaxWBTCDeviation(oldMaxWBTCDeviation, newMaxWBTCDeviation);
}
/// @inheritdoc BTCDerivativeOracleBase
/// @dev [Chainlink BTC/USD spot] * [Chainlink WBTC/BTC spot]
function _getBTCDerivativeUSDAnchorPrice(bool isRedeem) internal view virtual override returns (uint256) {
uint256 BTC_USD_ChainlinkSpot = _readSpotPriceByChainlink(Chainlink_BTC_USD_Spot);
uint256 WBTC_BTC_ChainlinkSpot = _readSpotPriceByChainlink(Chainlink_WBTC_BTC_Spot);
uint256 WBTC_USD_ChainlinkSpot = (WBTC_BTC_ChainlinkSpot * BTC_USD_ChainlinkSpot) / PRECISION;
if (!isRedeem) return WBTC_USD_ChainlinkSpot;
else {
uint256 cachedMaxWBTCDeviation = maxWBTCDeviation;
if (
PRECISION - cachedMaxWBTCDeviation <= WBTC_BTC_ChainlinkSpot &&
WBTC_BTC_ChainlinkSpot <= PRECISION + cachedMaxWBTCDeviation
) {
return WBTC_USD_ChainlinkSpot < BTC_USD_ChainlinkSpot ? BTC_USD_ChainlinkSpot : WBTC_USD_ChainlinkSpot;
} else {
return WBTC_USD_ChainlinkSpot;
}
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IRateProvider {
/// @notice Return the exchange rate from wrapped token to underlying rate,
/// multiplied by 1e18.
function getRate() external view returns (uint256);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IFxBoostableRebalancePool {
/**********
* Events *
**********/
/// @notice Emitted when user deposit asset into this contract.
/// @param owner The address of asset owner.
/// @param reciever The address of receiver of the asset in this contract.
/// @param amount The amount of asset deposited.
event Deposit(address indexed owner, address indexed reciever, uint256 amount);
/// @notice Emitted when the amount of deposited asset changed due to liquidation or deposit or unlock.
/// @param owner The address of asset owner.
/// @param newDeposit The new amount of deposited asset.
/// @param loss The amount of asset used by liquidation.
event UserDepositChange(address indexed owner, uint256 newDeposit, uint256 loss);
/// @notice Emitted when user withdraw asset.
/// @param owner The address of asset owner.
/// @param reciever The address of receiver of the asset.
/// @param amount The amount of token to withdraw.
event Withdraw(address indexed owner, address indexed reciever, uint256 amount);
/// @notice Emitted when liquidation happens.
/// @param liquidated The amount of asset liquidated.
/// @param baseGained The amount of base token gained.
event Liquidate(uint256 liquidated, uint256 baseGained);
/// @notice Emitted when the address of reward wrapper is updated.
/// @param oldWrapper The address of previous reward wrapper.
/// @param newWrapper The address of current reward wrapper.
event UpdateWrapper(address indexed oldWrapper, address indexed newWrapper);
/// @notice Emitted when the liquidatable collateral ratio is updated.
/// @param oldRatio The previous liquidatable collateral ratio.
/// @param newRatio The current liquidatable collateral ratio.
event UpdateLiquidatableCollateralRatio(uint256 oldRatio, uint256 newRatio);
/**********
* Errors *
**********/
/// @dev Thrown then the src token mismatched.
error ErrorWrapperSrcMismatch();
/// @dev Thrown then the dst token mismatched.
error ErrorWrapperDstMismatch();
/// @dev Thrown when the deposited amount is zero.
error DepositZeroAmount();
/// @dev Thrown when the withdrawn amount is zero.
error WithdrawZeroAmount();
/// @dev Thrown the cannot liquidate.
error CannotLiquidate();
/*************************
* Public View Functions *
*************************/
/// @notice Return the address of treasury contract.
function treasury() external view returns (address);
/// @notice Return the address of market contract.
function market() external view returns (address);
/// @notice Return the address of base token.
function baseToken() external view returns (address);
/// @notice Return the address of underlying token of this contract.
function asset() external view returns (address);
/// @notice Return the total amount of asset deposited to this contract.
function totalSupply() external view returns (uint256);
/// @notice Return the amount of deposited asset for some specific user.
/// @param account The address of user to query.
function balanceOf(address account) external view returns (uint256);
/// @notice Return the current boost ratio for some specific user.
/// @param account The address of user to query, multiplied by 1e18.
function getBoostRatio(address account) external view returns (uint256);
/****************************
* Public Mutated Functions *
****************************/
/// @notice Deposit some asset to this contract.
/// @dev Use `amount=uint256(-1)` if you want to deposit all asset held.
/// @param amount The amount of asset to deposit.
/// @param receiver The address of recipient for the deposited asset.
function deposit(uint256 amount, address receiver) external;
/// @notice Withdraw asset from this contract.
function withdraw(uint256 amount, address receiver) external;
/// @notice Liquidate asset for base token.
/// @param maxAmount The maximum amount of asset to liquidate.
/// @param minBaseOut The minimum amount of base token should receive.
/// @return liquidated The amount of asset liquidated.
/// @return baseOut The amount of base token received.
function liquidate(uint256 maxAmount, uint256 minBaseOut) external returns (uint256 liquidated, uint256 baseOut);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IFxMarketV2 {
/**********
* Events *
**********/
/// @notice Emitted when fToken is minted.
/// @param owner The address of base token owner.
/// @param recipient The address of receiver for fToken or xToken.
/// @param baseTokenIn The amount of base token deposited.
/// @param fTokenOut The amount of fToken minted.
/// @param mintFee The amount of mint fee charged.
event MintFToken(
address indexed owner,
address indexed recipient,
uint256 baseTokenIn,
uint256 fTokenOut,
uint256 mintFee
);
/// @notice Emitted when xToken is minted.
/// @param owner The address of base token owner.
/// @param recipient The address of receiver for fToken or xToken.
/// @param baseTokenIn The amount of base token deposited.
/// @param xTokenOut The amount of xToken minted.
/// @param bonus The amount of base token as bonus.
/// @param mintFee The amount of mint fee charged.
event MintXToken(
address indexed owner,
address indexed recipient,
uint256 baseTokenIn,
uint256 xTokenOut,
uint256 bonus,
uint256 mintFee
);
/// @notice Emitted when someone redeem base token with fToken or xToken.
/// @param owner The address of fToken and xToken owner.
/// @param recipient The address of receiver for base token.
/// @param fTokenBurned The amount of fToken burned.
/// @param baseTokenOut The amount of base token redeemed.
/// @param bonus The amount of base token as bonus.
/// @param redeemFee The amount of redeem fee charged.
event RedeemFToken(
address indexed owner,
address indexed recipient,
uint256 fTokenBurned,
uint256 baseTokenOut,
uint256 bonus,
uint256 redeemFee
);
/// @notice Emitted when someone redeem base token with fToken or xToken.
/// @param owner The address of fToken and xToken owner.
/// @param recipient The address of receiver for base token.
/// @param xTokenBurned The amount of xToken burned.
/// @param baseTokenOut The amount of base token redeemed.
/// @param redeemFee The amount of redeem fee charged.
event RedeemXToken(
address indexed owner,
address indexed recipient,
uint256 xTokenBurned,
uint256 baseTokenOut,
uint256 redeemFee
);
/// @notice Emitted when the fee ratio for minting fToken is updated.
/// @param defaultFeeRatio The new default fee ratio, multipled by 1e18.
/// @param extraFeeRatio The new extra fee ratio, multipled by 1e18.
event UpdateMintFeeRatioFToken(uint256 defaultFeeRatio, int256 extraFeeRatio);
/// @notice Emitted when the fee ratio for minting xToken is updated.
/// @param defaultFeeRatio The new default fee ratio, multipled by 1e18.
/// @param extraFeeRatio The new extra fee ratio, multipled by 1e18.
event UpdateMintFeeRatioXToken(uint256 defaultFeeRatio, int256 extraFeeRatio);
/// @notice Emitted when the fee ratio for redeeming fToken is updated.
/// @param defaultFeeRatio The new default fee ratio, multipled by 1e18.
/// @param extraFeeRatio The new extra fee ratio, multipled by 1e18.
event UpdateRedeemFeeRatioFToken(uint256 defaultFeeRatio, int256 extraFeeRatio);
/// @notice Emitted when the fee ratio for redeeming xToken is updated.
/// @param defaultFeeRatio The new default fee ratio, multipled by 1e18.
/// @param extraFeeRatio The new extra fee ratio, multipled by 1e18.
event UpdateRedeemFeeRatioXToken(uint256 defaultFeeRatio, int256 extraFeeRatio);
/// @notice Emitted when the stability ratio is updated.
/// @param oldRatio The previous collateral ratio to enter stability mode, multiplied by 1e18.
/// @param newRatio The current collateral ratio to enter stability mode, multiplied by 1e18.
event UpdateStabilityRatio(uint256 oldRatio, uint256 newRatio);
/// @notice Emitted when the platform contract is updated.
/// @param oldPlatform The address of previous platform contract.
/// @param newPlatform The address of current platform contract.
event UpdatePlatform(address indexed oldPlatform, address indexed newPlatform);
/// @notice Emitted when the reserve pool contract is updated.
/// @param oldReservePool The address of previous reserve pool contract.
/// @param newReservePool The address of current reserve pool contract.
event UpdateReservePool(address indexed oldReservePool, address indexed newReservePool);
/// @notice Emitted when the RebalancePoolRegistry contract is updated.
/// @param oldRegistry The address of previous RebalancePoolRegistry contract.
/// @param newRegistry The address of current RebalancePoolRegistry contract.
event UpdateRebalancePoolRegistry(address indexed oldRegistry, address indexed newRegistry);
/// @notice Pause or unpause mint.
/// @param oldStatus The previous status for mint.
/// @param newStatus The current status for mint.
event UpdateMintStatus(bool oldStatus, bool newStatus);
/// @notice Pause or unpause redeem.
/// @param oldStatus The previous status for redeem.
/// @param newStatus The current status for redeem.
event UpdateRedeemStatus(bool oldStatus, bool newStatus);
/// @notice Pause or unpause fToken mint in stability mode.
/// @param oldStatus The previous status for mint.
/// @param newStatus The current status for mint.
event UpdateFTokenMintStatusInStabilityMode(bool oldStatus, bool newStatus);
/// @notice Pause or unpause xToken redeem in stability mode.
/// @param oldStatus The previous status for redeem.
/// @param newStatus The current status for redeem.
event UpdateXTokenRedeemStatusInStabilityMode(bool oldStatus, bool newStatus);
/**********
* Errors *
**********/
/// @dev Thrown when the caller if not fUSD contract.
error ErrorCallerNotFUSD();
/// @dev Thrown when token mint is paused.
error ErrorMintPaused();
/// @dev Thrown when fToken mint is paused in stability mode.
error ErrorFTokenMintPausedInStabilityMode();
/// @dev Thrown when mint with zero amount base token.
error ErrorMintZeroAmount();
/// @dev Thrown when the amount of fToken is not enough.
error ErrorInsufficientFTokenOutput();
/// @dev Thrown when the amount of xToken is not enough.
error ErrorInsufficientXTokenOutput();
/// @dev Thrown when token redeem is paused.
error ErrorRedeemPaused();
/// @dev Thrown when xToken redeem is paused in stability mode.
error ErrorXTokenRedeemPausedInStabilityMode();
/// @dev Thrown when redeem with zero amount fToken or xToken.
error ErrorRedeemZeroAmount();
/// @dev Thrown when the amount of base token is not enough.
error ErrorInsufficientBaseOutput();
/// @dev Thrown when the stability ratio is too large.
error ErrorStabilityRatioTooLarge();
/// @dev Thrown when the default fee is too large.
error ErrorDefaultFeeTooLarge();
/// @dev Thrown when the delta fee is too small.
error ErrorDeltaFeeTooSmall();
/// @dev Thrown when the sum of default fee and delta fee is too large.
error ErrorTotalFeeTooLarge();
/// @dev Thrown when the given address is zero.
error ErrorZeroAddress();
/*************************
* Public View Functions *
*************************/
/// @notice The address of Treasury contract.
function treasury() external view returns (address);
/// @notice Return the address of base token.
function baseToken() external view returns (address);
/// @notice Return the address fractional base token.
function fToken() external view returns (address);
/// @notice Return the address leveraged base token.
function xToken() external view returns (address);
/// @notice Return the address of fxUSD token.
function fxUSD() external view returns (address);
/// @notice Return the collateral ratio to enter stability mode, multiplied by 1e18.
function stabilityRatio() external view returns (uint256);
/****************************
* Public Mutated Functions *
****************************/
/// @notice Mint some fToken with some base token.
/// @param baseIn The amount of wrapped value of base token supplied, use `uint256(-1)` to supply all base token.
/// @param recipient The address of receiver for fToken.
/// @param minFTokenMinted The minimum amount of fToken should be received.
/// @return fTokenMinted The amount of fToken should be received.
function mintFToken(
uint256 baseIn,
address recipient,
uint256 minFTokenMinted
) external returns (uint256 fTokenMinted);
/// @notice Mint some xToken with some base token.
/// @param baseIn The amount of wrapped value of base token supplied, use `uint256(-1)` to supply all base token.
/// @param recipient The address of receiver for xToken.
/// @param minXTokenMinted The minimum amount of xToken should be received.
/// @return xTokenMinted The amount of xToken should be received.
/// @return bonus The amount of wrapped value of base token as bonus.
function mintXToken(
uint256 baseIn,
address recipient,
uint256 minXTokenMinted
) external returns (uint256 xTokenMinted, uint256 bonus);
/// @notice Redeem base token with fToken.
/// @param fTokenIn the amount of fToken to redeem, use `uint256(-1)` to redeem all fToken.
/// @param recipient The address of receiver for base token.
/// @param minBaseOut The minimum amount of wrapped value of base token should be received.
/// @return baseOut The amount of wrapped value of base token should be received.
/// @return bonus The amount of wrapped value of base token as bonus.
function redeemFToken(
uint256 fTokenIn,
address recipient,
uint256 minBaseOut
) external returns (uint256 baseOut, uint256 bonus);
/// @notice Redeem base token with xToken.
/// @param xTokenIn the amount of xToken to redeem, use `uint256(-1)` to redeem all xToken.
/// @param recipient The address of receiver for base token.
/// @param minBaseOut The minimum amount of wrapped value of base token should be received.
/// @return baseOut The amount of wrapped value of base token should be received.
function redeemXToken(
uint256 xTokenIn,
address recipient,
uint256 minBaseOut
) external returns (uint256 baseOut);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IFxBoostableRebalancePool } from "./IFxBoostableRebalancePool.sol";
interface IFxShareableRebalancePool is IFxBoostableRebalancePool {
/**********
* Events *
**********/
/// @notice Emitted when one user share votes to another user.
/// @param owner The address of votes owner.
/// @param staker The address of staker to share votes.
event ShareVote(address indexed owner, address indexed staker);
/// @notice Emitted when the owner cancel sharing to some staker.
/// @param owner The address of votes owner.
/// @param staker The address of staker to cancel votes share.
event CancelShareVote(address indexed owner, address indexed staker);
/// @notice Emitted when staker accept the vote sharing.
/// @param staker The address of the staker.
/// @param oldOwner The address of the previous vote sharing owner.
/// @param newOwner The address of the current vote sharing owner.
event AcceptSharedVote(address indexed staker, address indexed oldOwner, address indexed newOwner);
/**********
* Errors *
**********/
/// @dev Thrown when caller shares votes to self.
error ErrorSelfSharingIsNotAllowed();
/// @dev Thrown when a staker with shared votes try to share its votes to others.
error ErrorCascadedSharingIsNotAllowed();
/// @dev Thrown when staker try to accept non-allowed vote sharing.
error ErrorVoteShareNotAllowed();
/// @dev Thrown when staker try to reject a non-existed vote sharing.
error ErrorNoAcceptedSharedVote();
/// @dev Thrown when the staker has ability to share ve balance.
error ErrorVoteOwnerCannotStake();
/// @dev Thrown when staker try to accept twice.
error ErrorRepeatAcceptSharedVote();
/*************************
* Public View Functions *
*************************/
/// @notice Return the owner of votes of some staker.
/// @param account The address of user to query.
function getStakerVoteOwner(address account) external view returns (address);
/****************************
* Public Mutated Functions *
****************************/
/// @notice Withdraw asset from this contract on behalf of someone
function withdrawFrom(
address owner,
uint256 amount,
address receiver
) external;
/// @notice Owner changes the vote sharing state for some user.
/// @param staker The address of user to change.
function toggleVoteSharing(address staker) external;
/// @notice Staker accepts the vote sharing.
/// @param newOwner The address of the owner of the votes.
function acceptSharedVote(address newOwner) external;
/// @notice Staker reject the current vote sharing.
function rejectSharedVote() external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IFxUSD {
/**********
* Events *
**********/
/// @notice Emitted when a new market is added.
/// @param baseToken The address of base token of the market.
/// @param mintCap The mint capacity of the market.
event AddMarket(address indexed baseToken, uint256 mintCap);
/// @notice Emitted when the mint capacity is updated.
/// @param baseToken The address of base token of the market.
/// @param oldCap The value of previous mint capacity.
/// @param newCap The value of current mint capacity.
event UpdateMintCap(address indexed baseToken, uint256 oldCap, uint256 newCap);
/// @notice Emitted when a new rebalance pool is added.
/// @param baseToken The address of base token of the market.
/// @param pool The address of the rebalance pool.
event AddRebalancePool(address indexed baseToken, address indexed pool);
/// @notice Emitted when a new rebalance pool is removed.
/// @param baseToken The address of base token of the market.
/// @param pool The address of the rebalance pool.
event RemoveRebalancePool(address indexed baseToken, address indexed pool);
/// @notice Emitted when someone wrap fToken as fxUSD.
/// @param baseToken The address of base token of the market.
/// @param owner The address of fToken owner.
/// @param receiver The address of fxUSD recipient.
/// @param amount The amount of fxUSD minted.
event Wrap(address indexed baseToken, address indexed owner, address indexed receiver, uint256 amount);
/// @notice Emitted when someone unwrap fxUSD as fToken.
/// @param baseToken The address of base token of the market.
/// @param owner The address of fxUSD owner.
/// @param receiver The address of base token recipient.
/// @param amount The amount of fxUSD burned.
event Unwrap(address indexed baseToken, address indexed owner, address indexed receiver, uint256 amount);
/**********
* Errors *
**********/
/// @dev Thrown when someone tries to interact with unsupported market.
error ErrorUnsupportedMarket();
/// @dev Thrown when someone tries to interact with unsupported rebalance pool.
error ErrorUnsupportedRebalancePool();
/// @dev Thrown when someone tries to interact with market in stability mode.
error ErrorMarketInStabilityMode();
/// @dev Thrown when someone tries to interact with market has invalid price.
error ErrorMarketWithInvalidPrice();
/// @dev Thrown when someone tries to add a supported market.
error ErrorMarketAlreadySupported();
/// @dev Thrown when the total supply of fToken exceed mint capacity.
error ErrorExceedMintCap();
/// @dev Thrown when the amount of fToken is not enough for redeem.
error ErrorInsufficientLiquidity();
/// @dev Thrown when current is under collateral.
error ErrorUnderCollateral();
/// @dev Thrown when the length of two arrays is mismatch.
error ErrorLengthMismatch();
/*************************
* Public View Functions *
*************************/
/// @notice Return the list of supported markets.
function getMarkets() external view returns (address[] memory);
/// @notice Return the list of supported rebalance pools.
function getRebalancePools() external view returns (address[] memory);
/// @notice Return the nav of fxUSD.
function nav() external view returns (uint256);
/// @notice Return whether the system is under collateral.
function isUnderCollateral() external view returns (bool);
/****************************
* Public Mutated Functions *
****************************/
/// @notice Wrap fToken to fxUSD.
/// @param baseToken The address of corresponding base token.
/// @param amount The amount of fToken to wrap.
/// @param receiver The address of fxUSD recipient.
function wrap(
address baseToken,
uint256 amount,
address receiver
) external;
/// @notice Unwrap fxUSD to fToken.
/// @param baseToken The address of corresponding base token.
/// @param amount The amount of fxUSD to unwrap.
/// @param receiver The address of fToken recipient.
function unwrap(
address baseToken,
uint256 amount,
address receiver
) external;
/// @notice Wrap fToken from rebalance pool to fxUSD.
/// @param pool The address of rebalance pool.
/// @param amount The amount of fToken to wrap.
/// @param receiver The address of fxUSD recipient.
function wrapFrom(
address pool,
uint256 amount,
address receiver
) external;
/// @notice Mint fxUSD with base token.
/// @param baseToken The address of the base token.
/// @param amountIn The amount of base token to use.
/// @param receiver The address of fxUSD recipient.
/// @param minOut The minimum amount of fxUSD should receive.
/// @return amountOut The amount of fxUSD received by the receiver.
function mint(
address baseToken,
uint256 amountIn,
address receiver,
uint256 minOut
) external returns (uint256 amountOut);
/// @notice Deposit fxUSD to rebalance pool.
/// @param pool The address of rebalance pool.
/// @param amount The amount of fxUSD to use.
/// @param receiver The address of rebalance pool share recipient.
function earn(
address pool,
uint256 amount,
address receiver
) external;
/// @notice Mint fxUSD with base token and deposit to rebalance pool.
/// @param pool The address of rebalance pool.
/// @param amountIn The amount of base token to use.
/// @param receiver The address of rebalance pool recipient.
/// @param minOut The minimum amount of rebalance pool shares should receive.
/// @return amountOut The amount of rebalance pool shares received by the receiver.
function mintAndEarn(
address pool,
uint256 amountIn,
address receiver,
uint256 minOut
) external returns (uint256 amountOut);
/// @notice Redeem fxUSD to base token.
/// @param baseToken The address of the base token.
/// @param amountIn The amount of fxUSD to redeem.
/// @param receiver The address of base token recipient.
/// @param minOut The minimum amount of base token should receive.
/// @return amountOut The amount of base token received by the receiver.
/// @return bonusOut The amount of bonus base token received by the receiver.
function redeem(
address baseToken,
uint256 amountIn,
address receiver,
uint256 minOut
) external returns (uint256 amountOut, uint256 bonusOut);
/// @notice Redeem fToken from rebalance pool to base token.
/// @param amountIn The amount of fxUSD to redeem.
/// @param receiver The address of base token recipient.
/// @param minOut The minimum amount of base token should receive.
/// @return amountOut The amount of base token received by the receiver.
/// @return bonusOut The amount of bonus base token received by the receiver.
function redeemFrom(
address pool,
uint256 amountIn,
address receiver,
uint256 minOut
) external returns (uint256 amountOut, uint256 bonusOut);
/// @notice Redeem fxUSD to base token optimally.
/// @param amountIn The amount of fxUSD to redeem.
/// @param receiver The address of base token recipient.
/// @param minOuts The list of minimum amount of base token should receive.
/// @return baseTokens The list of base token received by the receiver.
/// @return amountOuts The list of amount of base token received by the receiver.
/// @return bonusOuts The list of amount of bonus base token received by the receiver.
function autoRedeem(
uint256 amountIn,
address receiver,
uint256[] memory minOuts
)
external
returns (
address[] memory baseTokens,
uint256[] memory amountOuts,
uint256[] memory bonusOuts
);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// solhint-disable func-name-mixedcase
interface ILiquidityGauge {
/**********
* Events *
**********/
/// @notice Emitted when user deposit staking token to this contract.
/// @param owner The address of token owner.
/// @param receiver The address of recipient for the pool share.
/// @param amount The amount of staking token deposited.
event Deposit(address indexed owner, address indexed receiver, uint256 amount);
/// @notice Emitted when user withdraw staking token from this contract.
/// @param owner The address of token owner.
/// @param receiver The address of recipient for the staking token
/// @param amount The amount of staking token withdrawn.
event Withdraw(address indexed owner, address indexed receiver, uint256 amount);
/// @notice Emitted then the working balance is updated.
/// @param account The address of user updated.
/// @param originalBalance The original pool share of the user.
/// @param originalSupply The original total pool share of the contract.
/// @param workingBalance The current working balance of the user.
/// @param workingSupply The current working supply of the contract.
event UpdateLiquidityLimit(
address indexed account,
uint256 originalBalance,
uint256 originalSupply,
uint256 workingBalance,
uint256 workingSupply
);
/// @notice Emitted when the address of liquidity manager is updated.
/// @param oldLiquidityManager The address of previous liquidity manager contract.
/// @param newLiquidityManager The address of current liquidity manager contract.
event UpdateLiquidityManager(address indexed oldLiquidityManager, address indexed newLiquidityManager);
/**********
* Errors *
**********/
/// @dev Thrown when someone deposit zero amount staking token.
error DepositZeroAmount();
/// @dev Thrown when someone withdraw zero amount staking token.
error WithdrawZeroAmount();
/// @dev Thrown when some unauthorized user call `user_checkpoint`.
error UnauthorizedCaller();
/// @dev Throw when someone try to kick user who has no changes on their ve balance.
error KickNotAllowed();
/// @dev Thrown when someone try to do unnecessary kick.
error KickNotNeeded();
/// @dev Thrown when try to remove an active liquidity manager.
error LiquidityManagerIsActive();
/// @dev Thrown when try to add an inactive liquidity manager.
error LiquidityManagerIsNotActive();
/*************************
* Public View Functions *
*************************/
/// @notice Return whether the gauge is active.
function isActive() external view returns (bool);
/// @notice Return the address of staking token.
function stakingToken() external view returns (address);
/// @notice Return the amount of working supply.
function workingSupply() external view returns (uint256);
/// @notice Return the amount of working balance of some user.
/// @param account The address of user to query.
function workingBalanceOf(address account) external view returns (uint256);
/// @notice Return the governance token reward integrate for some user.
///
/// @dev This is used in TokenMinter.
///
/// @param account The address of user to query.
function integrate_fraction(address account) external view returns (uint256);
/****************************
* Public Mutated Functions *
****************************/
/// @notice Initialize the state of LiquidityGauge.
///
/// @param _stakingToken The address of staking token.
function initialize(address _stakingToken) external;
/// @notice Deposit some staking token to this contract.
///
/// @dev Use `amount = type(uint256).max`, if caller wants to deposit all held staking tokens.
///
/// @param amount The amount of staking token to deposit.
function deposit(uint256 amount) external;
/// @notice Deposit some staking token to this contract and transfer the share to others.
///
/// @dev Use `amount = type(uint256).max`, if caller wants to deposit all held staking tokens.
///
/// @param amount The amount of staking token to deposit.
/// @param receiver The address of the pool share recipient.
function deposit(uint256 amount, address receiver) external;
/// @notice Deposit some staking token to this contract and transfer the share to others.
///
/// @dev Use `amount = type(uint256).max`, if caller wants to deposit all held staking tokens.
///
/// @param amount The amount of staking token to deposit.
/// @param receiver The address of the pool share recipient.
/// @param manage The parameter passed to possible `LiquidityManager`.
function deposit(
uint256 amount,
address receiver,
bool manage
) external;
/// @notice Withdraw some staking token from this contract.
///
/// @dev Use `amount = type(uint256).max`, if caller wants to deposit all held staking tokens.
///
/// @param amount The amount of staking token to withdraw.
function withdraw(uint256 amount) external;
/// @notice Withdraw some staking token from this contract and transfer the token to others.
///
/// @dev Use `amount = type(uint256).max`, if caller wants to deposit all held staking tokens.
///
/// @param amount The amount of staking token to withdraw.
/// @param receiver The address of the staking token recipient.
function withdraw(uint256 amount, address receiver) external;
/// @notice Update the snapshot for some user.
///
/// @dev This is used in TokenMinter.
///
/// @param account The address of user to update.
function user_checkpoint(address account) external returns (bool);
/// @notice Kick some user for abusing their boost.
///
/// @dev Only if either they had another voting event, or their voting escrow lock expired.
///
/// @param account The address of user to kick.
function kick(address account) external;
}{
"optimizer": {
"enabled": true,
"runs": 200
},
"evmVersion": "cancun",
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[{"internalType":"address","name":"_base","type":"address"},{"internalType":"address","name":"_gauge","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AccessControlBadConfirmation","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"bytes32","name":"neededRole","type":"bytes32"}],"name":"AccessControlUnauthorizedAccount","type":"error"},{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"AddressEmptyCode","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"AddressInsufficientBalance","type":"error"},{"inputs":[],"name":"ECDSAInvalidSignature","type":"error"},{"inputs":[{"internalType":"uint256","name":"length","type":"uint256"}],"name":"ECDSAInvalidSignatureLength","type":"error"},{"inputs":[{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"ECDSAInvalidSignatureS","type":"error"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"allowance","type":"uint256"},{"internalType":"uint256","name":"needed","type":"uint256"}],"name":"ERC20InsufficientAllowance","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"uint256","name":"balance","type":"uint256"},{"internalType":"uint256","name":"needed","type":"uint256"}],"name":"ERC20InsufficientBalance","type":"error"},{"inputs":[{"internalType":"address","name":"approver","type":"address"}],"name":"ERC20InvalidApprover","type":"error"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"}],"name":"ERC20InvalidReceiver","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"}],"name":"ERC20InvalidSender","type":"error"},{"inputs":[{"internalType":"address","name":"spender","type":"address"}],"name":"ERC20InvalidSpender","type":"error"},{"inputs":[{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"ERC2612ExpiredSignature","type":"error"},{"inputs":[{"internalType":"address","name":"signer","type":"address"},{"internalType":"address","name":"owner","type":"address"}],"name":"ERC2612InvalidSigner","type":"error"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"uint256","name":"max","type":"uint256"}],"name":"ERC4626ExceededMaxDeposit","type":"error"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"uint256","name":"max","type":"uint256"}],"name":"ERC4626ExceededMaxMint","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"uint256","name":"max","type":"uint256"}],"name":"ERC4626ExceededMaxRedeem","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"uint256","name":"max","type":"uint256"}],"name":"ERC4626ExceededMaxWithdraw","type":"error"},{"inputs":[],"name":"ErrorCallerNotHarvester","type":"error"},{"inputs":[],"name":"ErrorExpenseRatioTooLarge","type":"error"},{"inputs":[],"name":"ErrorHarvesterRatioTooLarge","type":"error"},{"inputs":[],"name":"ErrorThresholdTooLarge","type":"error"},{"inputs":[],"name":"ErrorZeroAddress","type":"error"},{"inputs":[],"name":"FailedInnerCall","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"currentNonce","type":"uint256"}],"name":"InvalidAccountNonce","type":"error"},{"inputs":[],"name":"InvalidInitialization","type":"error"},{"inputs":[],"name":"MathOverflowedMulDiv","type":"error"},{"inputs":[],"name":"NotInitializing","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"address","name":"receiver","type":"address"}],"name":"Claim","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"uint256","name":"assets","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"}],"name":"Deposit","type":"event"},{"anonymous":false,"inputs":[],"name":"EIP712DomainChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint64","name":"version","type":"uint64"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"assets","type":"uint256"}],"name":"RequestRedeem","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"previousAdminRole","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"newAdminRole","type":"bytes32"}],"name":"RoleAdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleGranted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleRevoked","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"oldRatio","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newRatio","type":"uint256"}],"name":"UpdateExpenseRatio","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"oldHarvester","type":"address"},{"indexed":true,"internalType":"address","name":"newHarvester","type":"address"}],"name":"UpdateHarvester","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"oldRatio","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newRatio","type":"uint256"}],"name":"UpdateHarvesterRatio","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"oldThreshold","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newThreshold","type":"uint256"}],"name":"UpdateThreshold","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"oldTreasury","type":"address"},{"indexed":true,"internalType":"address","name":"newTreasury","type":"address"}],"name":"UpdateTreasury","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"receiver","type":"address"},{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"uint256","name":"assets","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"}],"name":"Withdraw","type":"event"},{"inputs":[],"name":"CLAIM_FOR_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DEFAULT_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DOMAIN_SEPARATOR","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"asset","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"base","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"}],"name":"claim","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"receiver","type":"address"}],"name":"claimFor","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"name":"convertToAssets","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"name":"convertToShares","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"}],"name":"deposit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"}],"name":"depositGauge","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"eip712Domain","outputs":[{"internalType":"bytes1","name":"fields","type":"bytes1"},{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"version","type":"string"},{"internalType":"uint256","name":"chainId","type":"uint256"},{"internalType":"address","name":"verifyingContract","type":"address"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"uint256[]","name":"extensions","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"gauge","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getExpenseRatio","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getHarvesterRatio","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleAdmin","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"grantRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"harvest","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"harvester","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRole","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"admin","type":"address"},{"components":[{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"symbol","type":"string"},{"internalType":"uint256","name":"pid","type":"uint256"},{"internalType":"uint256","name":"threshold","type":"uint256"},{"internalType":"address","name":"treasury","type":"address"},{"internalType":"address","name":"harvester","type":"address"}],"internalType":"struct SavingFxUSD.InitializationParameters","name":"params","type":"tuple"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"lockedProxy","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"maxDeposit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"maxMint","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"maxRedeem","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"maxWithdraw","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"}],"name":"mint","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"nav","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"nonces","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"onHarvest","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"permit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"name":"previewDeposit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"name":"previewMint","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"name":"previewRedeem","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"name":"previewWithdraw","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"address","name":"owner","type":"address"}],"name":"redeem","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"callerConfirmation","type":"address"}],"name":"renounceRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"name":"requestRedeem","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"revokeRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalAssets","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"treasury","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint32","name":"_newRatio","type":"uint32"}],"name":"updateExpenseRatio","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_newHarvester","type":"address"}],"name":"updateHarvester","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint32","name":"_newRatio","type":"uint32"}],"name":"updateHarvesterRatio","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"newThreshold","type":"uint256"}],"name":"updateThreshold","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_newTreasury","type":"address"}],"name":"updateTreasury","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"vault","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"address","name":"owner","type":"address"}],"name":"withdraw","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"}]Contract Creation Code
60c0604052348015600e575f80fd5b50604051614029380380614029833981016040819052602b91605b565b6001600160a01b039182166080521660a0526087565b80516001600160a01b03811681146056575f80fd5b919050565b5f8060408385031215606b575f80fd5b6072836041565b9150607e602084016041565b90509250929050565b60805160a051613ee76101425f395f81816106a70152818161082d01528181610a6201528181610c07015281816114bc01528181611d0301528181611d4b01528181611f31015261205901525f818161054d015281816108ab01528181611218015281816113a50152818161149a015281816118b301528181611b9c01528181611d7601528181611dbc01528181611e1301528181611e9401528181611faf01528181612328015281816123a4015261258b0152613ee75ff3fe608060405234801561000f575f80fd5b5060043610610388575f3560e01c80637fff8ffd116101df578063ba08765211610109578063d505accf116100a9578063dd62ed3e11610079578063dd62ed3e146107db578063e75235b8146107ee578063ef8b30f714610756578063fbfa77cf146107f6575f80fd5b8063d505accf1461078f578063d547741f146107a2578063d7d7442f146107b5578063d905777e146107c8575f80fd5b8063c63d75b6116100e4578063c63d75b614610506578063c6e6f59214610756578063c6ffde6914610769578063ce96cb771461077c575f80fd5b8063ba08765214610728578063bf6f5b001461073b578063c1590cd71461074e575f80fd5b8063a217fddf1161017f578063aa2f892d1161014f578063aa2f892d146106dc578063b3d7f6b9146106ef578063b460af9414610702578063b4ba9e1114610715575f80fd5b8063a217fddf14610693578063a69f49351461069a578063a6f19c84146106a2578063a9059cbb146106c9575f80fd5b806391d14854116101ba57806391d148541461063d57806394bf804d1461065057806394d77b751461066357806395d89b411461068b575f80fd5b80637fff8ffd1461060757806384b0196e1461060f5780638fe4e2321461062a575f80fd5b806336568abe116102c05780635001f3b5116102605780636e553f65116102305780636e553f65146105bb57806370a08231146105ce5780637ecebe00146105e15780637f51bb1f146105f4575f80fd5b80635001f3b514610548578063616a53121461056f57806361d027b3146105965780636cb99650146105a8575f80fd5b80634641257d1161029b5780634641257d1461051a5780634a5d843c146105225780634bdaeac1146105355780634cdad506146103df575f80fd5b806336568abe146104c257806338d52e0f146104d5578063402d267d14610506575f80fd5b80631d2ac9431161032b578063248a9ca311610306578063248a9ca31461047a5780632f2ff15d1461048d578063313ce567146104a05780633644e515146104ba575f80fd5b80631d2ac9431461043f5780631e83409a1461045257806323b872dd14610467575f80fd5b806307a2d13a1161036657806307a2d13a146103df578063095ea7b3146103f25780630a28a4771461040557806318160ddd14610418575f80fd5b806301e1d1141461038c57806301ffc9a7146103a757806306fdde03146103ca575b5f80fd5b610394610809565b6040519081526020015b60405180910390f35b6103ba6103b5366004613333565b61092b565b604051901515815260200161039e565b6103d2610961565b60405161039e9190613388565b6103946103ed36600461339a565b610a06565b6103ba6104003660046133d5565b610a11565b61039461041336600461339a565b610a28565b7f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace0254610394565b61039461044d3660046133ff565b610a34565b61046561046036600461342d565b610ae4565b005b6103ba610475366004613448565b610af1565b61039461048836600461339a565b610b16565b61046561049b3660046133ff565b610b36565b6104a8610b58565b60405160ff909116815260200161039e565b610394610b61565b6104656104d03660046133ff565b610b6a565b5f80516020613e92833981519152546001600160a01b03165b6040516001600160a01b03909116815260200161039e565b61039461051436600461342d565b505f1990565b610465610ba2565b610465610530366004613486565b610d5d565b6001546104ee906001600160a01b031681565b6104ee7f000000000000000000000000000000000000000000000000000000000000000081565b6103947f24927c918ee933e498c4f4704c8c8c5997712350624a2ab5df3edca55f9ac03381565b5f546104ee906001600160a01b031681565b6104656105b63660046133d5565b610e04565b6103946105c93660046133ff565b610e46565b6103946105dc36600461342d565b610e69565b6103946105ef36600461342d565b610e99565b61046561060236600461342d565b610ea3565b610394610eb6565b610617610ec7565b60405161039e97969594939291906134a9565b61046561063836600461342d565b610f70565b6103ba61064b3660046133ff565b610f83565b61039461065e3660046133ff565b610fb9565b6104ee61067136600461342d565b60336020525f90815260409020546001600160a01b031681565b6103d2610fd4565b6103945f81565b610394611012565b6104ee7f000000000000000000000000000000000000000000000000000000000000000081565b6103ba6106d73660046133d5565b611023565b6103946106ea36600461339a565b611030565b6103946106fd36600461339a565b61107c565b61039461071036600461353f565b611088565b61046561072336600461357e565b6110de565b61039461073636600461353f565b611112565b610465610749366004613486565b61115f565b6103946111fb565b61039461076436600461339a565b6112aa565b610465610777366004613684565b6112b5565b61039461078a36600461342d565b611531565b61046561079d366004613766565b611544565b6104656107b03660046133ff565b611699565b6104656107c336600461339a565b6116b5565b6103946107d636600461342d565b6116c8565b6103946107e936600461357e565b6116d2565b61039461171b565b6032546104ee906001600160a01b031681565b6032546040516370a0823160e01b81526001600160a01b0391821660048201525f917f000000000000000000000000000000000000000000000000000000000000000016906370a0823190602401602060405180830381865afa158015610872573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061089691906137d7565b6040516370a0823160e01b81523060048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906370a0823190602401602060405180830381865afa1580156108f8573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061091c91906137d7565b6109269190613802565b905090565b5f6001600160e01b03198216637965db0b60e01b148061095b57506301ffc9a760e01b6001600160e01b03198316145b92915050565b60605f5f80516020613e328339815191525b905080600301805461098490613815565b80601f01602080910402602001604051908101604052809291908181526020018280546109b090613815565b80156109fb5780601f106109d2576101008083540402835291602001916109fb565b820191905f5260205f20905b8154815290600101906020018083116109de57829003601f168201915b505050505091505090565b5f61095b825f61172d565b5f33610a1e818585611784565b5060019392505050565b5f61095b826001611791565b5f5f19610a45565b60405180910390fd5b5f610a4f856112aa565b9050610a8c336032546001600160a01b037f00000000000000000000000000000000000000000000000000000000000000008116929116886117df565b610a968482611846565b60408051868152602081018390526001600160a01b0386169133917fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d7910160405180910390a3949350505050565b610aee338261187a565b50565b5f33610afe858285611997565b610b098585856119e1565b60019150505b9392505050565b5f9081525f80516020613e72833981519152602052604090206001015490565b610b3f82610b16565b610b4881611a3e565b610b528383611a48565b50505050565b5f610926611ae9565b5f610926611b18565b6001600160a01b0381163314610b935760405163334bd91960e11b815260040160405180910390fd5b610b9d8282611b21565b505050565b60325f9054906101000a90046001600160a01b03166001600160a01b0316633d18b9126040518163ffffffff1660e01b81526004015f604051808303815f87803b158015610bee575f80fd5b505af1158015610c00573d5f803e3d5ffd5b505050505f7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166330ae4bba6040518163ffffffff1660e01b81526004015f60405180830381865afa158015610c60573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610c87919081019061386e565b6001549091506001600160a01b03165f610c9f611012565b90505f610caa610eb6565b90505f805b8551811015610d3057610cdd868281518110610ccd57610ccd613922565b6020026020010151868686611b9a565b73365accfca291e7d3914637abf1f7635db165bb096001600160a01b0316868281518110610d0d57610d0d613922565b60200260200101516001600160a01b031603610d2857600191505b600101610caf565b5080610d5657610d5673365accfca291e7d3914637abf1f7635db165bb09858585611b9a565b5050505050565b5f610d6781611a3e565b631dcd65008263ffffffff161115610d9257604051633d777e2b60e21b815260040160405180910390fd5b6002545f610da28282601e611cdf565b9050610dbc8263ffffffff808716905f90601e90611ced16565b6002556040805182815263ffffffff861660208201527f4112abbd73890804ec0f3a1fcb9424f04c1f6e5eb2dc909122e6a7232cc2777f91015b60405180910390a150505050565b6001546001600160a01b0316336001600160a01b031614610e385760405163f01134db60e01b815260040160405180910390fd5b610e428282611d01565b5050565b5f5f195f610e53856112aa565b9050610e6133858784611f8c565b949350505050565b5f805f80516020613e328339815191525b6001600160a01b039093165f9081526020939093525050604090205490565b5f61095b826120b9565b5f610ead81611a3e565b610e42826120e1565b6002545f906109269082601e611cdf565b5f60608082808083815f80516020613e528339815191528054909150158015610ef257506001810154155b610f365760405162461bcd60e51b81526020600482015260156024820152741152540dcc4c8e88155b9a5b9a5d1a585b1a5e9959605a1b6044820152606401610a3c565b610f3e612157565b610f46612195565b604080515f80825260208201909252600f60f81b9c939b5091995046985030975095509350915050565b5f610f7a81611a3e565b610e42826121ab565b5f9182525f80516020613e72833981519152602090815260408084206001600160a01b0393909316845291905290205460ff1690565b5f5f195f610fc68561107c565b9050610e6133858388611f8c565b7f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace0480546060915f80516020613e328339815191529161098490613815565b6002545f9061092690601e80611cdf565b5f33610a1e8185856119e1565b5f338161103c826116c8565b90508084111561106557818482604051632e52afbb60e21b8152600401610a3c9392919061384d565b5f61106f85610a06565b9050610e618382876121fc565b5f61095b82600161172d565b5f8061109383611531565b9050808511156110bc57828582604051633fa733bb60e21b8152600401610a3c9392919061384d565b5f6110c686610a28565b90506110d53386868985612480565b95945050505050565b7f24927c918ee933e498c4f4704c8c8c5997712350624a2ab5df3edca55f9ac03361110881611a3e565b610b9d838361187a565b5f8061111d836116c8565b90508085111561114657828582604051632e52afbb60e21b8152600401610a3c9392919061384d565b5f61115086610a06565b90506110d5338686848a612480565b5f61116981611a3e565b6305f5e1008263ffffffff1611156111935760405162bdd18d60e51b815260040160405180910390fd5b6002545f6111a382601e80611cdf565b90506111bd8263ffffffff80871690601e908190611ced16565b6002556040805182815263ffffffff861660208201527f2c3b971a5011a057ee9b96ea2aa1504d93d268e5c9cfdee7581d31435b24435e9101610df6565b5f670de0b6b3a7640000611216670de0b6b3a7640000610a06565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663c1590cd76040518163ffffffff1660e01b8152600401602060405180830381865afa158015611272573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061129691906137d7565b6112a09190613936565b6109269190613961565b5f61095b825f611791565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a008054600160401b810460ff16159067ffffffffffffffff165f811580156112fa5750825b90505f8267ffffffffffffffff1660011480156113165750303b155b905081158015611324575080155b156113425760405163f92ee8a960e01b815260040160405180910390fd5b845467ffffffffffffffff19166001178555831561136c57845460ff60401b1916600160401b1785555b6113746125f7565b61137c6125f7565b6113846125f7565b611395865f01518760200151612601565b85516113a090612613565b6113c97f000000000000000000000000000000000000000000000000000000000000000061263e565b6113db86608001518760a0015161264f565b6113e55f88611a48565b506040868101519051639abbdf4b60e01b8152600481019190915273affe966b27ba3e4ebb8a0ec124c7b7019cc762f890639abbdf4b906024016020604051808303815f875af115801561143b573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061145f9190613974565b603280546001600160a01b0319166001600160a01b0392909216919091179055606086015161148d90612669565b6114e26001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000167f00000000000000000000000000000000000000000000000000000000000000005f196126ee565b831561152857845460ff60401b19168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b50505050505050565b5f61095b61153e83610e69565b5f61172d565b834211156115685760405163313c898160e11b815260048101859052602401610a3c565b5f7f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c98888886115d28c6001600160a01b03165f9081527f5ab42ced628888259c08ac98db1eb0cf702fc1501344311d8b100cd1bfe4bb006020526040902080546001810190915590565b6040805160208101969096526001600160a01b0394851690860152929091166060840152608083015260a082015260c0810186905260e0016040516020818303038152906040528051906020012090505f61162c8261277d565b90505f61163b828787876127a9565b9050896001600160a01b0316816001600160a01b031614611682576040516325c0072360e11b81526001600160a01b0380831660048301528b166024820152604401610a3c565b61168d8a8a8a611784565b50505050505050505050565b6116a282610b16565b6116ab81611a3e565b610b528383611b21565b5f6116bf81611a3e565b610e4282612669565b5f61095b82610e69565b6001600160a01b039182165f9081527f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace016020908152604080832093909416825291909152205490565b6002545f9061092690603c6050611cdf565b5f610b0f611739610809565b611744906001613802565b61174f5f600a613a72565b7f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace025461177b9190613802565b859190856127d5565b610b9d8383836001612822565b5f610b0f6117a082600a613a72565b7f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace02546117cc9190613802565b6117d4610809565b61177b906001613802565b6040516001600160a01b038481166024830152838116604483015260648201839052610b529186918216906323b872dd906084015b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050612905565b6001600160a01b03821661186f5760405163ec442f0560e01b81525f6004820152602401610a3c565b610e425f8383612966565b6001600160a01b038281165f908152603360205260409081902054905183831660248201525f1960448201529116908190631cff79cd907f00000000000000000000000000000000000000000000000000000000000000009060640160408051601f198184030181529181526020820180516001600160e01b03166301e9a69560e41b179052516001600160e01b031960e085901b168152611920929190600401613a80565b5f604051808303815f87803b158015611937575f80fd5b505af1158015611949573d5f803e3d5ffd5b5050604080516001600160a01b038088168252861660208201527f1836092b86c602f5dc00f47313b2873163879c06590285c6c58d63e208ac746693500190505b60405180910390a1505050565b5f6119a284846116d2565b90505f198114610b5257818110156119d357828183604051637dc7a0d960e11b8152600401610a3c9392919061384d565b610b5284848484035f612822565b6001600160a01b038316611a0a57604051634b637e8f60e11b81525f6004820152602401610a3c565b6001600160a01b038216611a335760405163ec442f0560e01b81525f6004820152602401610a3c565b610b9d838383612966565b610aee8133612a8c565b5f5f80516020613e72833981519152611a618484610f83565b611ae0575f848152602082815260408083206001600160a01b03871684529091529020805460ff19166001179055611a963390565b6001600160a01b0316836001600160a01b0316857f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a4600191505061095b565b5f91505061095b565b5f805f80516020613e9283398151915290505f8154611b129190600160a01b900460ff16613aa3565b91505090565b5f610926612ac5565b5f5f80516020613e72833981519152611b3a8484610f83565b15611ae0575f848152602082815260408083206001600160a01b0387168085529252808320805460ff1916905551339287917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a4600191505061095b565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316846001600160a01b03160315610b52576040516370a0823160e01b81523060048201525f906001600160a01b038616906370a0823190602401602060405180830381865afa158015611c18573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611c3c91906137d7565b90508015610d56575f633b9aca00611c548484613936565b611c5e9190613961565b90505f633b9aca00611c708685613936565b611c7a9190613961565b90508015611c9657611c966001600160a01b0388163383612b38565b8115611cb5575f54611cb5906001600160a01b03898116911684612b38565b6115288682611cc48587613abc565b611cce9190613abc565b6001600160a01b038a169190612b38565b6001901b5f190191901c1690565b6001901b5f1901811b1992909216911b1790565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316826001600160a01b031603611d7457603254610e42906001600160a01b037f00000000000000000000000000000000000000000000000000000000000000008116911683612b38565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316826001600160a01b031614611e7f57611de16001600160a01b0383167f0000000000000000000000000000000000000000000000000000000000000000836126ee565b6040516320e8c56560e01b81523060048201526001600160a01b038381166024830152604482018390525f60648301527f000000000000000000000000000000000000000000000000000000000000000016906320e8c565906084016020604051808303815f875af1158015611e59573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611e7d91906137d7565b505b6040516370a0823160e01b81523060048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906370a0823190602401602060405180830381865afa158015611ee1573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611f0591906137d7565b603254604051636e553f6560e01b8152600481018390526001600160a01b0391821660248201529192507f00000000000000000000000000000000000000000000000000000000000000001690636e553f65906044015f604051808303815f87803b158015611f72575f80fd5b505af1158015611f84573d5f803e3d5ffd5b505050505050565b611f9884848484612b69565b6040516370a0823160e01b81523060048201525f907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906370a0823190602401602060405180830381865afa158015611ffc573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061202091906137d7565b905061202a61171b565b8110610d5657603254604051636e553f6560e01b8152600481018390526001600160a01b0391821660248201527f000000000000000000000000000000000000000000000000000000000000000090911690636e553f65906044015f604051808303815f87803b15801561209c575f80fd5b505af11580156120ae573d5f803e3d5ffd5b505050505050505050565b5f807f5ab42ced628888259c08ac98db1eb0cf702fc1501344311d8b100cd1bfe4bb00610e7a565b6001600160a01b0381166121085760405163a7f9319d60e01b815260040160405180910390fd5b5f80546001600160a01b038381166001600160a01b0319831681178455604051919092169283917fd101a15f9e9364a1c0a7c4cc8eb4cd9220094e83353915b0c74e09f72ec73edb9190a35050565b7fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d10280546060915f80516020613e528339815191529161098490613815565b60605f5f80516020613e52833981519152610973565b600180546001600160a01b038381166001600160a01b0319831681179093556040519116919082907fc3ac9d916fede0d1ddffc8ba08d69772bf770989193cda857914cc118de10275905f90a35050565b6122068382612be6565b603254604051632e1a7d4d60e01b8152600481018490526001600160a01b0390911690632e1a7d4d906024015f604051808303815f87803b158015612249575f80fd5b505af115801561225b573d5f803e3d5ffd5b505050506001600160a01b038381165f90815260336020526040902054168061230257604080516001600160a01b038616602082015201604051602081830303815290604052805190602001206040516122b490613326565b8190604051809103905ff59050801580156122d1573d5f803e3d5ffd5b506001600160a01b038581165f90815260336020526040902080546001600160a01b03191691831691909117905590505b60405163a9059cbb60e01b81526001600160a01b038281166004830152602482018590527f0000000000000000000000000000000000000000000000000000000000000000169063a9059cbb906044016020604051808303815f875af115801561236e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906123929190613acf565b50806001600160a01b0316631cff79cd7f0000000000000000000000000000000000000000000000000000000000000000856040516024016123d691815260200190565b60408051601f198184030181529181526020820180516001600160e01b031663aa2f892d60e01b179052516001600160e01b031960e085901b168152612420929190600401613a80565b5f604051808303815f87803b158015612437575f80fd5b505af1158015612449573d5f803e3d5ffd5b505050507f3a4aaf3c8c287a23b905e95af5d9b37807cadef62732e09ef9ce59f5e28474f8848385604051610df69392919061384d565b826001600160a01b0316856001600160a01b0316146124a4576124a4838683611997565b6124ae8382612be6565b826001600160a01b0316846001600160a01b0316866001600160a01b03167ffbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db8585604051612506929190918252602082015260400190565b60405180910390a4603254604051632e1a7d4d60e01b8152600481018490526001600160a01b0390911690632e1a7d4d906024015f604051808303815f87803b158015612551575f80fd5b505af1158015612563573d5f803e3d5ffd5b505060405163a9059cbb60e01b81526001600160a01b038781166004830152602482018690527f000000000000000000000000000000000000000000000000000000000000000016925063a9059cbb91506044016020604051808303815f875af11580156125d3573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611f849190613acf565b6125ff612c1a565b565b612609612c1a565b610e428282612c63565b61261b612c1a565b610aee81604051806040016040528060018152602001603160f81b815250612cb3565b612646612c1a565b610aee81612d12565b612657612c1a565b612660826120e1565b610e42816121ab565b69ffffffffffffffffffff8111156126945760405163a80716eb60e01b815260040160405180910390fd5b6002545f6126a582603c6050611cdf565b90506126b58284603c6050611ced565b60025560408051828152602081018590527fe2f0d2b9bd62fe4d997e442d96308c2084de77174fc94e18e14bf473b030f4dd910161198a565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663095ea7b360e01b17905261273f8482612d82565b610b52576040516001600160a01b0384811660248301525f604483015261277391869182169063095ea7b390606401611814565b610b528482612905565b5f61095b612789611b18565b8360405161190160f01b8152600281019290925260228201526042902090565b5f805f806127b988888888612e1f565b9250925092506127c98282612ee7565b50909695505050505050565b5f806127e2868686612f9f565b90506127ed8361305e565b801561280857505f84806128035761280361394d565b868809115b156110d557612818600182613802565b9695505050505050565b5f80516020613e328339815191526001600160a01b0385166128595760405163e602df0560e01b81525f6004820152602401610a3c565b6001600160a01b03841661288257604051634a1406b160e11b81525f6004820152602401610a3c565b6001600160a01b038086165f90815260018301602090815260408083209388168352929052208390558115610d5657836001600160a01b0316856001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925856040516128f691815260200190565b60405180910390a35050505050565b5f6129196001600160a01b0384168361308a565b905080515f1415801561293d57508080602001905181019061293b9190613acf565b155b15610b9d57604051635274afe760e01b81526001600160a01b0384166004820152602401610a3c565b5f80516020613e328339815191526001600160a01b0384166129a05781816002015f8282546129959190613802565b909155506129fd9050565b6001600160a01b0384165f90815260208290526040902054828110156129df5784818460405163391434e360e21b8152600401610a3c9392919061384d565b6001600160a01b0385165f9081526020839052604090209083900390555b6001600160a01b038316612a1b576002810180548390039055612a39565b6001600160a01b0383165f9081526020829052604090208054830190555b826001600160a01b0316846001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef84604051612a7e91815260200190565b60405180910390a350505050565b612a968282610f83565b610e425760405163e2517d3f60e01b81526001600160a01b038216600482015260248101839052604401610a3c565b5f7f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f612aef613097565b612af76130ff565b60408051602081019490945283019190915260608201524660808201523060a082015260c00160405160208183030381529060405280519060200120905090565b6040516001600160a01b03838116602483015260448201839052610b9d91859182169063a9059cbb90606401611814565b5f80516020613e928339815191528054612b8e906001600160a01b03168630866117df565b612b988483611846565b836001600160a01b0316856001600160a01b03167fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d785856040516128f6929190918252602082015260400190565b6001600160a01b038216612c0f57604051634b637e8f60e11b81525f6004820152602401610a3c565b610e42825f83612966565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0054600160401b900460ff166125ff57604051631afcd79f60e31b815260040160405180910390fd5b612c6b612c1a565b5f80516020613e328339815191527f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace03612ca48482613b32565b5060048101610b528382613b32565b612cbb612c1a565b5f80516020613e528339815191527fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d102612cf48482613b32565b5060038101612d038382613b32565b505f8082556001909101555050565b612d1a612c1a565b5f80516020613e928339815191525f80612d3384613141565b9150915081612d43576012612d45565b805b83546001600160a81b031916600160a01b60ff92909216919091026001600160a01b031916176001600160a01b0394909416939093179091555050565b5f805f846001600160a01b031684604051612d9d9190613bed565b5f604051808303815f865af19150503d805f8114612dd6576040519150601f19603f3d011682016040523d82523d5f602084013e612ddb565b606091505b5091509150818015612e05575080511580612e05575080806020019051810190612e059190613acf565b80156110d55750505050506001600160a01b03163b151590565b5f80807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0841115612e5857505f91506003905082612edd565b604080515f808252602082018084528a905260ff891692820192909252606081018790526080810186905260019060a0016020604051602081039080840390855afa158015612ea9573d5f803e3d5ffd5b5050604051601f1901519150506001600160a01b038116612ed457505f925060019150829050612edd565b92505f91508190505b9450945094915050565b5f826003811115612efa57612efa613c03565b03612f03575050565b6001826003811115612f1757612f17613c03565b03612f355760405163f645eedf60e01b815260040160405180910390fd5b6002826003811115612f4957612f49613c03565b03612f6a5760405163fce698f760e01b815260048101829052602401610a3c565b6003826003811115612f7e57612f7e613c03565b03610e42576040516335e2f38360e21b815260048101829052602401610a3c565b5f838302815f1985870982811083820303915050805f03612fd357838281612fc957612fc961394d565b0492505050610b0f565b808411612ff35760405163227bc15360e01b815260040160405180910390fd5b5f848688095f868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b5f600282600381111561307357613073613c03565b61307d9190613c17565b60ff166001149050919050565b6060610b0f83835f613217565b5f5f80516020613e52833981519152816130af612157565b8051909150156130c757805160209091012092915050565b815480156130d6579392505050565b7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470935050505090565b5f5f80516020613e5283398151915281613117612195565b80519091501561312f57805160209091012092915050565b600182015480156130d6579392505050565b60408051600481526024810182526020810180516001600160e01b031663313ce56760e01b17905290515f918291829182916001600160a01b0387169161318791613bed565b5f60405180830381855afa9150503d805f81146131bf576040519150601f19603f3d011682016040523d82523d5f602084013e6131c4565b606091505b50915091508180156131d857506020815110155b1561320b575f818060200190518101906131f291906137d7565b905060ff8111613209576001969095509350505050565b505b505f9485945092505050565b60608147101561323c5760405163cd78605960e01b8152306004820152602401610a3c565b5f80856001600160a01b031684866040516132579190613bed565b5f6040518083038185875af1925050503d805f8114613291576040519150601f19603f3d011682016040523d82523d5f602084013e613296565b606091505b50915091506128188683836060826132b6576132b1826132fd565b610b0f565b81511580156132cd57506001600160a01b0384163b155b156132f657604051639996b31560e01b81526001600160a01b0385166004820152602401610a3c565b5080610b0f565b80511561330d5780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b6101f980613c3983390190565b5f60208284031215613343575f80fd5b81356001600160e01b031981168114610b0f575f80fd5b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b602081525f610b0f602083018461335a565b5f602082840312156133aa575f80fd5b5035919050565b6001600160a01b0381168114610aee575f80fd5b80356133d0816133b1565b919050565b5f80604083850312156133e6575f80fd5b82356133f1816133b1565b946020939093013593505050565b5f8060408385031215613410575f80fd5b823591506020830135613422816133b1565b809150509250929050565b5f6020828403121561343d575f80fd5b8135610b0f816133b1565b5f805f6060848603121561345a575f80fd5b8335613465816133b1565b92506020840135613475816133b1565b929592945050506040919091013590565b5f60208284031215613496575f80fd5b813563ffffffff81168114610b0f575f80fd5b60ff60f81b8816815260e060208201525f6134c760e083018961335a565b82810360408401526134d9818961335a565b606084018890526001600160a01b038716608085015260a0840186905283810360c0850152845180825260208087019350909101905f5b8181101561352e578351835260209384019390920191600101613510565b50909b9a5050505050505050505050565b5f805f60608486031215613551575f80fd5b833592506020840135613563816133b1565b91506040840135613573816133b1565b809150509250925092565b5f806040838503121561358f575f80fd5b823561359a816133b1565b91506020830135613422816133b1565b634e487b7160e01b5f52604160045260245ffd5b60405160c0810167ffffffffffffffff811182821017156135e1576135e16135aa565b60405290565b604051601f8201601f1916810167ffffffffffffffff81118282101715613610576136106135aa565b604052919050565b5f82601f830112613627575f80fd5b813567ffffffffffffffff811115613641576136416135aa565b613654601f8201601f19166020016135e7565b818152846020838601011115613668575f80fd5b816020850160208301375f918101602001919091529392505050565b5f8060408385031215613695575f80fd5b82356136a0816133b1565b9150602083013567ffffffffffffffff8111156136bb575f80fd5b830160c081860312156136cc575f80fd5b6136d46135be565b813567ffffffffffffffff8111156136ea575f80fd5b6136f687828501613618565b825250602082013567ffffffffffffffff811115613712575f80fd5b61371e87828501613618565b6020830152506040828101359082015260608083013590820152613744608083016133c5565b608082015261375560a083016133c5565b60a082015280925050509250929050565b5f805f805f805f60e0888a03121561377c575f80fd5b8735613787816133b1565b96506020880135613797816133b1565b95506040880135945060608801359350608088013560ff811681146137ba575f80fd5b9699959850939692959460a0840135945060c09093013592915050565b5f602082840312156137e7575f80fd5b5051919050565b634e487b7160e01b5f52601160045260245ffd5b8082018082111561095b5761095b6137ee565b600181811c9082168061382957607f821691505b60208210810361384757634e487b7160e01b5f52602260045260245ffd5b50919050565b6001600160a01b039390931683526020830191909152604082015260600190565b5f6020828403121561387e575f80fd5b815167ffffffffffffffff811115613894575f80fd5b8201601f810184136138a4575f80fd5b805167ffffffffffffffff8111156138be576138be6135aa565b8060051b6138ce602082016135e7565b918252602081840181019290810190878411156138e9575f80fd5b6020850194505b838510156139175784519250613905836133b1565b828252602094850194909101906138f0565b979650505050505050565b634e487b7160e01b5f52603260045260245ffd5b808202811582820484141761095b5761095b6137ee565b634e487b7160e01b5f52601260045260245ffd5b5f8261396f5761396f61394d565b500490565b5f60208284031215613984575f80fd5b8151610b0f816133b1565b6001815b60018411156139ca578085048111156139ae576139ae6137ee565b60018416156139bc57908102905b60019390931c928002613993565b935093915050565b5f826139e05750600161095b565b816139ec57505f61095b565b8160018114613a025760028114613a0c57613a28565b600191505061095b565b60ff841115613a1d57613a1d6137ee565b50506001821b61095b565b5060208310610133831016604e8410600b8410161715613a4b575081810a61095b565b613a575f19848461398f565b805f1904821115613a6a57613a6a6137ee565b029392505050565b5f610b0f60ff8416836139d2565b6001600160a01b03831681526040602082018190525f90610e619083018461335a565b60ff818116838216019081111561095b5761095b6137ee565b8181038181111561095b5761095b6137ee565b5f60208284031215613adf575f80fd5b81518015158114610b0f575f80fd5b601f821115610b9d57805f5260205f20601f840160051c81016020851015613b135750805b601f840160051c820191505b81811015610d56575f8155600101613b1f565b815167ffffffffffffffff811115613b4c57613b4c6135aa565b613b6081613b5a8454613815565b84613aee565b6020601f821160018114613b92575f8315613b7b5750848201515b5f19600385901b1c1916600184901b178455610d56565b5f84815260208120601f198516915b82811015613bc15787850151825560209485019460019092019101613ba1565b5084821015613bde57868401515f19600387901b60f8161c191681555b50505050600190811b01905550565b5f82518060208501845e5f920191825250919050565b634e487b7160e01b5f52602160045260245ffd5b5f60ff831680613c2957613c2961394d565b8060ff8416069150509291505056fe60a0604052348015600e575f80fd5b50336080526080516101cf61002a5f395f604d01526101cf5ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c80631cff79cd1461002d575b5f80fd5b61004061003b3660046100ff565b610042565b005b336001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000161461008b5760405163073658dd60e01b815260040160405180910390fd5b5f836001600160a01b031683836040516100a692919061018a565b5f604051808303815f865af19150503d805f81146100df576040519150601f19603f3d011682016040523d82523d5f602084013e6100e4565b606091505b50509050806100f9576040513d805f833e8082fd5b50505050565b5f805f60408486031215610111575f80fd5b83356001600160a01b0381168114610127575f80fd5b9250602084013567ffffffffffffffff811115610142575f80fd5b8401601f81018613610152575f80fd5b803567ffffffffffffffff811115610168575f80fd5b866020828401011115610179575f80fd5b939660209190910195509293505050565b818382375f910190815291905056fea264697066735822122057a94832f02283c43e3b889fb9a7c55c6fa8c2263b77b41b26eece59ec4a13ad64736f6c634300081a003352c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace00a16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d10002dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b6268000773e532dfede91f04b12a73d3d2acd361424f41f76b4fb79f090161e36b4e00a264697066735822122033cf4d6c6ef28c95467ac9323edfd509a9f7dd9acb5063b1f0ba11a66c40e35f64736f6c634300081a003300000000000000000000000065c9a641afceb9c0e6034e558a319488fa0fa3be000000000000000000000000ed92dde3214c24ae04f5f96927e3be8f8dbc3289
Deployed Bytecode
0x608060405234801561000f575f80fd5b5060043610610388575f3560e01c80637fff8ffd116101df578063ba08765211610109578063d505accf116100a9578063dd62ed3e11610079578063dd62ed3e146107db578063e75235b8146107ee578063ef8b30f714610756578063fbfa77cf146107f6575f80fd5b8063d505accf1461078f578063d547741f146107a2578063d7d7442f146107b5578063d905777e146107c8575f80fd5b8063c63d75b6116100e4578063c63d75b614610506578063c6e6f59214610756578063c6ffde6914610769578063ce96cb771461077c575f80fd5b8063ba08765214610728578063bf6f5b001461073b578063c1590cd71461074e575f80fd5b8063a217fddf1161017f578063aa2f892d1161014f578063aa2f892d146106dc578063b3d7f6b9146106ef578063b460af9414610702578063b4ba9e1114610715575f80fd5b8063a217fddf14610693578063a69f49351461069a578063a6f19c84146106a2578063a9059cbb146106c9575f80fd5b806391d14854116101ba57806391d148541461063d57806394bf804d1461065057806394d77b751461066357806395d89b411461068b575f80fd5b80637fff8ffd1461060757806384b0196e1461060f5780638fe4e2321461062a575f80fd5b806336568abe116102c05780635001f3b5116102605780636e553f65116102305780636e553f65146105bb57806370a08231146105ce5780637ecebe00146105e15780637f51bb1f146105f4575f80fd5b80635001f3b514610548578063616a53121461056f57806361d027b3146105965780636cb99650146105a8575f80fd5b80634641257d1161029b5780634641257d1461051a5780634a5d843c146105225780634bdaeac1146105355780634cdad506146103df575f80fd5b806336568abe146104c257806338d52e0f146104d5578063402d267d14610506575f80fd5b80631d2ac9431161032b578063248a9ca311610306578063248a9ca31461047a5780632f2ff15d1461048d578063313ce567146104a05780633644e515146104ba575f80fd5b80631d2ac9431461043f5780631e83409a1461045257806323b872dd14610467575f80fd5b806307a2d13a1161036657806307a2d13a146103df578063095ea7b3146103f25780630a28a4771461040557806318160ddd14610418575f80fd5b806301e1d1141461038c57806301ffc9a7146103a757806306fdde03146103ca575b5f80fd5b610394610809565b6040519081526020015b60405180910390f35b6103ba6103b5366004613333565b61092b565b604051901515815260200161039e565b6103d2610961565b60405161039e9190613388565b6103946103ed36600461339a565b610a06565b6103ba6104003660046133d5565b610a11565b61039461041336600461339a565b610a28565b7f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace0254610394565b61039461044d3660046133ff565b610a34565b61046561046036600461342d565b610ae4565b005b6103ba610475366004613448565b610af1565b61039461048836600461339a565b610b16565b61046561049b3660046133ff565b610b36565b6104a8610b58565b60405160ff909116815260200161039e565b610394610b61565b6104656104d03660046133ff565b610b6a565b5f80516020613e92833981519152546001600160a01b03165b6040516001600160a01b03909116815260200161039e565b61039461051436600461342d565b505f1990565b610465610ba2565b610465610530366004613486565b610d5d565b6001546104ee906001600160a01b031681565b6104ee7f00000000000000000000000065c9a641afceb9c0e6034e558a319488fa0fa3be81565b6103947f24927c918ee933e498c4f4704c8c8c5997712350624a2ab5df3edca55f9ac03381565b5f546104ee906001600160a01b031681565b6104656105b63660046133d5565b610e04565b6103946105c93660046133ff565b610e46565b6103946105dc36600461342d565b610e69565b6103946105ef36600461342d565b610e99565b61046561060236600461342d565b610ea3565b610394610eb6565b610617610ec7565b60405161039e97969594939291906134a9565b61046561063836600461342d565b610f70565b6103ba61064b3660046133ff565b610f83565b61039461065e3660046133ff565b610fb9565b6104ee61067136600461342d565b60336020525f90815260409020546001600160a01b031681565b6103d2610fd4565b6103945f81565b610394611012565b6104ee7f000000000000000000000000ed92dde3214c24ae04f5f96927e3be8f8dbc328981565b6103ba6106d73660046133d5565b611023565b6103946106ea36600461339a565b611030565b6103946106fd36600461339a565b61107c565b61039461071036600461353f565b611088565b61046561072336600461357e565b6110de565b61039461073636600461353f565b611112565b610465610749366004613486565b61115f565b6103946111fb565b61039461076436600461339a565b6112aa565b610465610777366004613684565b6112b5565b61039461078a36600461342d565b611531565b61046561079d366004613766565b611544565b6104656107b03660046133ff565b611699565b6104656107c336600461339a565b6116b5565b6103946107d636600461342d565b6116c8565b6103946107e936600461357e565b6116d2565b61039461171b565b6032546104ee906001600160a01b031681565b6032546040516370a0823160e01b81526001600160a01b0391821660048201525f917f000000000000000000000000ed92dde3214c24ae04f5f96927e3be8f8dbc328916906370a0823190602401602060405180830381865afa158015610872573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061089691906137d7565b6040516370a0823160e01b81523060048201527f00000000000000000000000065c9a641afceb9c0e6034e558a319488fa0fa3be6001600160a01b0316906370a0823190602401602060405180830381865afa1580156108f8573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061091c91906137d7565b6109269190613802565b905090565b5f6001600160e01b03198216637965db0b60e01b148061095b57506301ffc9a760e01b6001600160e01b03198316145b92915050565b60605f5f80516020613e328339815191525b905080600301805461098490613815565b80601f01602080910402602001604051908101604052809291908181526020018280546109b090613815565b80156109fb5780601f106109d2576101008083540402835291602001916109fb565b820191905f5260205f20905b8154815290600101906020018083116109de57829003601f168201915b505050505091505090565b5f61095b825f61172d565b5f33610a1e818585611784565b5060019392505050565b5f61095b826001611791565b5f5f19610a45565b60405180910390fd5b5f610a4f856112aa565b9050610a8c336032546001600160a01b037f000000000000000000000000ed92dde3214c24ae04f5f96927e3be8f8dbc32898116929116886117df565b610a968482611846565b60408051868152602081018390526001600160a01b0386169133917fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d7910160405180910390a3949350505050565b610aee338261187a565b50565b5f33610afe858285611997565b610b098585856119e1565b60019150505b9392505050565b5f9081525f80516020613e72833981519152602052604090206001015490565b610b3f82610b16565b610b4881611a3e565b610b528383611a48565b50505050565b5f610926611ae9565b5f610926611b18565b6001600160a01b0381163314610b935760405163334bd91960e11b815260040160405180910390fd5b610b9d8282611b21565b505050565b60325f9054906101000a90046001600160a01b03166001600160a01b0316633d18b9126040518163ffffffff1660e01b81526004015f604051808303815f87803b158015610bee575f80fd5b505af1158015610c00573d5f803e3d5ffd5b505050505f7f000000000000000000000000ed92dde3214c24ae04f5f96927e3be8f8dbc32896001600160a01b03166330ae4bba6040518163ffffffff1660e01b81526004015f60405180830381865afa158015610c60573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610c87919081019061386e565b6001549091506001600160a01b03165f610c9f611012565b90505f610caa610eb6565b90505f805b8551811015610d3057610cdd868281518110610ccd57610ccd613922565b6020026020010151868686611b9a565b73365accfca291e7d3914637abf1f7635db165bb096001600160a01b0316868281518110610d0d57610d0d613922565b60200260200101516001600160a01b031603610d2857600191505b600101610caf565b5080610d5657610d5673365accfca291e7d3914637abf1f7635db165bb09858585611b9a565b5050505050565b5f610d6781611a3e565b631dcd65008263ffffffff161115610d9257604051633d777e2b60e21b815260040160405180910390fd5b6002545f610da28282601e611cdf565b9050610dbc8263ffffffff808716905f90601e90611ced16565b6002556040805182815263ffffffff861660208201527f4112abbd73890804ec0f3a1fcb9424f04c1f6e5eb2dc909122e6a7232cc2777f91015b60405180910390a150505050565b6001546001600160a01b0316336001600160a01b031614610e385760405163f01134db60e01b815260040160405180910390fd5b610e428282611d01565b5050565b5f5f195f610e53856112aa565b9050610e6133858784611f8c565b949350505050565b5f805f80516020613e328339815191525b6001600160a01b039093165f9081526020939093525050604090205490565b5f61095b826120b9565b5f610ead81611a3e565b610e42826120e1565b6002545f906109269082601e611cdf565b5f60608082808083815f80516020613e528339815191528054909150158015610ef257506001810154155b610f365760405162461bcd60e51b81526020600482015260156024820152741152540dcc4c8e88155b9a5b9a5d1a585b1a5e9959605a1b6044820152606401610a3c565b610f3e612157565b610f46612195565b604080515f80825260208201909252600f60f81b9c939b5091995046985030975095509350915050565b5f610f7a81611a3e565b610e42826121ab565b5f9182525f80516020613e72833981519152602090815260408084206001600160a01b0393909316845291905290205460ff1690565b5f5f195f610fc68561107c565b9050610e6133858388611f8c565b7f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace0480546060915f80516020613e328339815191529161098490613815565b6002545f9061092690601e80611cdf565b5f33610a1e8185856119e1565b5f338161103c826116c8565b90508084111561106557818482604051632e52afbb60e21b8152600401610a3c9392919061384d565b5f61106f85610a06565b9050610e618382876121fc565b5f61095b82600161172d565b5f8061109383611531565b9050808511156110bc57828582604051633fa733bb60e21b8152600401610a3c9392919061384d565b5f6110c686610a28565b90506110d53386868985612480565b95945050505050565b7f24927c918ee933e498c4f4704c8c8c5997712350624a2ab5df3edca55f9ac03361110881611a3e565b610b9d838361187a565b5f8061111d836116c8565b90508085111561114657828582604051632e52afbb60e21b8152600401610a3c9392919061384d565b5f61115086610a06565b90506110d5338686848a612480565b5f61116981611a3e565b6305f5e1008263ffffffff1611156111935760405162bdd18d60e51b815260040160405180910390fd5b6002545f6111a382601e80611cdf565b90506111bd8263ffffffff80871690601e908190611ced16565b6002556040805182815263ffffffff861660208201527f2c3b971a5011a057ee9b96ea2aa1504d93d268e5c9cfdee7581d31435b24435e9101610df6565b5f670de0b6b3a7640000611216670de0b6b3a7640000610a06565b7f00000000000000000000000065c9a641afceb9c0e6034e558a319488fa0fa3be6001600160a01b031663c1590cd76040518163ffffffff1660e01b8152600401602060405180830381865afa158015611272573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061129691906137d7565b6112a09190613936565b6109269190613961565b5f61095b825f611791565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a008054600160401b810460ff16159067ffffffffffffffff165f811580156112fa5750825b90505f8267ffffffffffffffff1660011480156113165750303b155b905081158015611324575080155b156113425760405163f92ee8a960e01b815260040160405180910390fd5b845467ffffffffffffffff19166001178555831561136c57845460ff60401b1916600160401b1785555b6113746125f7565b61137c6125f7565b6113846125f7565b611395865f01518760200151612601565b85516113a090612613565b6113c97f00000000000000000000000065c9a641afceb9c0e6034e558a319488fa0fa3be61263e565b6113db86608001518760a0015161264f565b6113e55f88611a48565b506040868101519051639abbdf4b60e01b8152600481019190915273affe966b27ba3e4ebb8a0ec124c7b7019cc762f890639abbdf4b906024016020604051808303815f875af115801561143b573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061145f9190613974565b603280546001600160a01b0319166001600160a01b0392909216919091179055606086015161148d90612669565b6114e26001600160a01b037f00000000000000000000000065c9a641afceb9c0e6034e558a319488fa0fa3be167f000000000000000000000000ed92dde3214c24ae04f5f96927e3be8f8dbc32895f196126ee565b831561152857845460ff60401b19168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b50505050505050565b5f61095b61153e83610e69565b5f61172d565b834211156115685760405163313c898160e11b815260048101859052602401610a3c565b5f7f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c98888886115d28c6001600160a01b03165f9081527f5ab42ced628888259c08ac98db1eb0cf702fc1501344311d8b100cd1bfe4bb006020526040902080546001810190915590565b6040805160208101969096526001600160a01b0394851690860152929091166060840152608083015260a082015260c0810186905260e0016040516020818303038152906040528051906020012090505f61162c8261277d565b90505f61163b828787876127a9565b9050896001600160a01b0316816001600160a01b031614611682576040516325c0072360e11b81526001600160a01b0380831660048301528b166024820152604401610a3c565b61168d8a8a8a611784565b50505050505050505050565b6116a282610b16565b6116ab81611a3e565b610b528383611b21565b5f6116bf81611a3e565b610e4282612669565b5f61095b82610e69565b6001600160a01b039182165f9081527f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace016020908152604080832093909416825291909152205490565b6002545f9061092690603c6050611cdf565b5f610b0f611739610809565b611744906001613802565b61174f5f600a613a72565b7f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace025461177b9190613802565b859190856127d5565b610b9d8383836001612822565b5f610b0f6117a082600a613a72565b7f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace02546117cc9190613802565b6117d4610809565b61177b906001613802565b6040516001600160a01b038481166024830152838116604483015260648201839052610b529186918216906323b872dd906084015b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050612905565b6001600160a01b03821661186f5760405163ec442f0560e01b81525f6004820152602401610a3c565b610e425f8383612966565b6001600160a01b038281165f908152603360205260409081902054905183831660248201525f1960448201529116908190631cff79cd907f00000000000000000000000065c9a641afceb9c0e6034e558a319488fa0fa3be9060640160408051601f198184030181529181526020820180516001600160e01b03166301e9a69560e41b179052516001600160e01b031960e085901b168152611920929190600401613a80565b5f604051808303815f87803b158015611937575f80fd5b505af1158015611949573d5f803e3d5ffd5b5050604080516001600160a01b038088168252861660208201527f1836092b86c602f5dc00f47313b2873163879c06590285c6c58d63e208ac746693500190505b60405180910390a1505050565b5f6119a284846116d2565b90505f198114610b5257818110156119d357828183604051637dc7a0d960e11b8152600401610a3c9392919061384d565b610b5284848484035f612822565b6001600160a01b038316611a0a57604051634b637e8f60e11b81525f6004820152602401610a3c565b6001600160a01b038216611a335760405163ec442f0560e01b81525f6004820152602401610a3c565b610b9d838383612966565b610aee8133612a8c565b5f5f80516020613e72833981519152611a618484610f83565b611ae0575f848152602082815260408083206001600160a01b03871684529091529020805460ff19166001179055611a963390565b6001600160a01b0316836001600160a01b0316857f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a4600191505061095b565b5f91505061095b565b5f805f80516020613e9283398151915290505f8154611b129190600160a01b900460ff16613aa3565b91505090565b5f610926612ac5565b5f5f80516020613e72833981519152611b3a8484610f83565b15611ae0575f848152602082815260408083206001600160a01b0387168085529252808320805460ff1916905551339287917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a4600191505061095b565b7f00000000000000000000000065c9a641afceb9c0e6034e558a319488fa0fa3be6001600160a01b0316846001600160a01b03160315610b52576040516370a0823160e01b81523060048201525f906001600160a01b038616906370a0823190602401602060405180830381865afa158015611c18573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611c3c91906137d7565b90508015610d56575f633b9aca00611c548484613936565b611c5e9190613961565b90505f633b9aca00611c708685613936565b611c7a9190613961565b90508015611c9657611c966001600160a01b0388163383612b38565b8115611cb5575f54611cb5906001600160a01b03898116911684612b38565b6115288682611cc48587613abc565b611cce9190613abc565b6001600160a01b038a169190612b38565b6001901b5f190191901c1690565b6001901b5f1901811b1992909216911b1790565b7f000000000000000000000000ed92dde3214c24ae04f5f96927e3be8f8dbc32896001600160a01b0316826001600160a01b031603611d7457603254610e42906001600160a01b037f000000000000000000000000ed92dde3214c24ae04f5f96927e3be8f8dbc32898116911683612b38565b7f00000000000000000000000065c9a641afceb9c0e6034e558a319488fa0fa3be6001600160a01b0316826001600160a01b031614611e7f57611de16001600160a01b0383167f00000000000000000000000065c9a641afceb9c0e6034e558a319488fa0fa3be836126ee565b6040516320e8c56560e01b81523060048201526001600160a01b038381166024830152604482018390525f60648301527f00000000000000000000000065c9a641afceb9c0e6034e558a319488fa0fa3be16906320e8c565906084016020604051808303815f875af1158015611e59573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611e7d91906137d7565b505b6040516370a0823160e01b81523060048201527f00000000000000000000000065c9a641afceb9c0e6034e558a319488fa0fa3be6001600160a01b0316906370a0823190602401602060405180830381865afa158015611ee1573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611f0591906137d7565b603254604051636e553f6560e01b8152600481018390526001600160a01b0391821660248201529192507f000000000000000000000000ed92dde3214c24ae04f5f96927e3be8f8dbc32891690636e553f65906044015f604051808303815f87803b158015611f72575f80fd5b505af1158015611f84573d5f803e3d5ffd5b505050505050565b611f9884848484612b69565b6040516370a0823160e01b81523060048201525f907f00000000000000000000000065c9a641afceb9c0e6034e558a319488fa0fa3be6001600160a01b0316906370a0823190602401602060405180830381865afa158015611ffc573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061202091906137d7565b905061202a61171b565b8110610d5657603254604051636e553f6560e01b8152600481018390526001600160a01b0391821660248201527f000000000000000000000000ed92dde3214c24ae04f5f96927e3be8f8dbc328990911690636e553f65906044015f604051808303815f87803b15801561209c575f80fd5b505af11580156120ae573d5f803e3d5ffd5b505050505050505050565b5f807f5ab42ced628888259c08ac98db1eb0cf702fc1501344311d8b100cd1bfe4bb00610e7a565b6001600160a01b0381166121085760405163a7f9319d60e01b815260040160405180910390fd5b5f80546001600160a01b038381166001600160a01b0319831681178455604051919092169283917fd101a15f9e9364a1c0a7c4cc8eb4cd9220094e83353915b0c74e09f72ec73edb9190a35050565b7fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d10280546060915f80516020613e528339815191529161098490613815565b60605f5f80516020613e52833981519152610973565b600180546001600160a01b038381166001600160a01b0319831681179093556040519116919082907fc3ac9d916fede0d1ddffc8ba08d69772bf770989193cda857914cc118de10275905f90a35050565b6122068382612be6565b603254604051632e1a7d4d60e01b8152600481018490526001600160a01b0390911690632e1a7d4d906024015f604051808303815f87803b158015612249575f80fd5b505af115801561225b573d5f803e3d5ffd5b505050506001600160a01b038381165f90815260336020526040902054168061230257604080516001600160a01b038616602082015201604051602081830303815290604052805190602001206040516122b490613326565b8190604051809103905ff59050801580156122d1573d5f803e3d5ffd5b506001600160a01b038581165f90815260336020526040902080546001600160a01b03191691831691909117905590505b60405163a9059cbb60e01b81526001600160a01b038281166004830152602482018590527f00000000000000000000000065c9a641afceb9c0e6034e558a319488fa0fa3be169063a9059cbb906044016020604051808303815f875af115801561236e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906123929190613acf565b50806001600160a01b0316631cff79cd7f00000000000000000000000065c9a641afceb9c0e6034e558a319488fa0fa3be856040516024016123d691815260200190565b60408051601f198184030181529181526020820180516001600160e01b031663aa2f892d60e01b179052516001600160e01b031960e085901b168152612420929190600401613a80565b5f604051808303815f87803b158015612437575f80fd5b505af1158015612449573d5f803e3d5ffd5b505050507f3a4aaf3c8c287a23b905e95af5d9b37807cadef62732e09ef9ce59f5e28474f8848385604051610df69392919061384d565b826001600160a01b0316856001600160a01b0316146124a4576124a4838683611997565b6124ae8382612be6565b826001600160a01b0316846001600160a01b0316866001600160a01b03167ffbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db8585604051612506929190918252602082015260400190565b60405180910390a4603254604051632e1a7d4d60e01b8152600481018490526001600160a01b0390911690632e1a7d4d906024015f604051808303815f87803b158015612551575f80fd5b505af1158015612563573d5f803e3d5ffd5b505060405163a9059cbb60e01b81526001600160a01b038781166004830152602482018690527f00000000000000000000000065c9a641afceb9c0e6034e558a319488fa0fa3be16925063a9059cbb91506044016020604051808303815f875af11580156125d3573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611f849190613acf565b6125ff612c1a565b565b612609612c1a565b610e428282612c63565b61261b612c1a565b610aee81604051806040016040528060018152602001603160f81b815250612cb3565b612646612c1a565b610aee81612d12565b612657612c1a565b612660826120e1565b610e42816121ab565b69ffffffffffffffffffff8111156126945760405163a80716eb60e01b815260040160405180910390fd5b6002545f6126a582603c6050611cdf565b90506126b58284603c6050611ced565b60025560408051828152602081018590527fe2f0d2b9bd62fe4d997e442d96308c2084de77174fc94e18e14bf473b030f4dd910161198a565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663095ea7b360e01b17905261273f8482612d82565b610b52576040516001600160a01b0384811660248301525f604483015261277391869182169063095ea7b390606401611814565b610b528482612905565b5f61095b612789611b18565b8360405161190160f01b8152600281019290925260228201526042902090565b5f805f806127b988888888612e1f565b9250925092506127c98282612ee7565b50909695505050505050565b5f806127e2868686612f9f565b90506127ed8361305e565b801561280857505f84806128035761280361394d565b868809115b156110d557612818600182613802565b9695505050505050565b5f80516020613e328339815191526001600160a01b0385166128595760405163e602df0560e01b81525f6004820152602401610a3c565b6001600160a01b03841661288257604051634a1406b160e11b81525f6004820152602401610a3c565b6001600160a01b038086165f90815260018301602090815260408083209388168352929052208390558115610d5657836001600160a01b0316856001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925856040516128f691815260200190565b60405180910390a35050505050565b5f6129196001600160a01b0384168361308a565b905080515f1415801561293d57508080602001905181019061293b9190613acf565b155b15610b9d57604051635274afe760e01b81526001600160a01b0384166004820152602401610a3c565b5f80516020613e328339815191526001600160a01b0384166129a05781816002015f8282546129959190613802565b909155506129fd9050565b6001600160a01b0384165f90815260208290526040902054828110156129df5784818460405163391434e360e21b8152600401610a3c9392919061384d565b6001600160a01b0385165f9081526020839052604090209083900390555b6001600160a01b038316612a1b576002810180548390039055612a39565b6001600160a01b0383165f9081526020829052604090208054830190555b826001600160a01b0316846001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef84604051612a7e91815260200190565b60405180910390a350505050565b612a968282610f83565b610e425760405163e2517d3f60e01b81526001600160a01b038216600482015260248101839052604401610a3c565b5f7f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f612aef613097565b612af76130ff565b60408051602081019490945283019190915260608201524660808201523060a082015260c00160405160208183030381529060405280519060200120905090565b6040516001600160a01b03838116602483015260448201839052610b9d91859182169063a9059cbb90606401611814565b5f80516020613e928339815191528054612b8e906001600160a01b03168630866117df565b612b988483611846565b836001600160a01b0316856001600160a01b03167fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d785856040516128f6929190918252602082015260400190565b6001600160a01b038216612c0f57604051634b637e8f60e11b81525f6004820152602401610a3c565b610e42825f83612966565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0054600160401b900460ff166125ff57604051631afcd79f60e31b815260040160405180910390fd5b612c6b612c1a565b5f80516020613e328339815191527f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace03612ca48482613b32565b5060048101610b528382613b32565b612cbb612c1a565b5f80516020613e528339815191527fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d102612cf48482613b32565b5060038101612d038382613b32565b505f8082556001909101555050565b612d1a612c1a565b5f80516020613e928339815191525f80612d3384613141565b9150915081612d43576012612d45565b805b83546001600160a81b031916600160a01b60ff92909216919091026001600160a01b031916176001600160a01b0394909416939093179091555050565b5f805f846001600160a01b031684604051612d9d9190613bed565b5f604051808303815f865af19150503d805f8114612dd6576040519150601f19603f3d011682016040523d82523d5f602084013e612ddb565b606091505b5091509150818015612e05575080511580612e05575080806020019051810190612e059190613acf565b80156110d55750505050506001600160a01b03163b151590565b5f80807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0841115612e5857505f91506003905082612edd565b604080515f808252602082018084528a905260ff891692820192909252606081018790526080810186905260019060a0016020604051602081039080840390855afa158015612ea9573d5f803e3d5ffd5b5050604051601f1901519150506001600160a01b038116612ed457505f925060019150829050612edd565b92505f91508190505b9450945094915050565b5f826003811115612efa57612efa613c03565b03612f03575050565b6001826003811115612f1757612f17613c03565b03612f355760405163f645eedf60e01b815260040160405180910390fd5b6002826003811115612f4957612f49613c03565b03612f6a5760405163fce698f760e01b815260048101829052602401610a3c565b6003826003811115612f7e57612f7e613c03565b03610e42576040516335e2f38360e21b815260048101829052602401610a3c565b5f838302815f1985870982811083820303915050805f03612fd357838281612fc957612fc961394d565b0492505050610b0f565b808411612ff35760405163227bc15360e01b815260040160405180910390fd5b5f848688095f868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b5f600282600381111561307357613073613c03565b61307d9190613c17565b60ff166001149050919050565b6060610b0f83835f613217565b5f5f80516020613e52833981519152816130af612157565b8051909150156130c757805160209091012092915050565b815480156130d6579392505050565b7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470935050505090565b5f5f80516020613e5283398151915281613117612195565b80519091501561312f57805160209091012092915050565b600182015480156130d6579392505050565b60408051600481526024810182526020810180516001600160e01b031663313ce56760e01b17905290515f918291829182916001600160a01b0387169161318791613bed565b5f60405180830381855afa9150503d805f81146131bf576040519150601f19603f3d011682016040523d82523d5f602084013e6131c4565b606091505b50915091508180156131d857506020815110155b1561320b575f818060200190518101906131f291906137d7565b905060ff8111613209576001969095509350505050565b505b505f9485945092505050565b60608147101561323c5760405163cd78605960e01b8152306004820152602401610a3c565b5f80856001600160a01b031684866040516132579190613bed565b5f6040518083038185875af1925050503d805f8114613291576040519150601f19603f3d011682016040523d82523d5f602084013e613296565b606091505b50915091506128188683836060826132b6576132b1826132fd565b610b0f565b81511580156132cd57506001600160a01b0384163b155b156132f657604051639996b31560e01b81526001600160a01b0385166004820152602401610a3c565b5080610b0f565b80511561330d5780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b6101f980613c3983390190565b5f60208284031215613343575f80fd5b81356001600160e01b031981168114610b0f575f80fd5b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b602081525f610b0f602083018461335a565b5f602082840312156133aa575f80fd5b5035919050565b6001600160a01b0381168114610aee575f80fd5b80356133d0816133b1565b919050565b5f80604083850312156133e6575f80fd5b82356133f1816133b1565b946020939093013593505050565b5f8060408385031215613410575f80fd5b823591506020830135613422816133b1565b809150509250929050565b5f6020828403121561343d575f80fd5b8135610b0f816133b1565b5f805f6060848603121561345a575f80fd5b8335613465816133b1565b92506020840135613475816133b1565b929592945050506040919091013590565b5f60208284031215613496575f80fd5b813563ffffffff81168114610b0f575f80fd5b60ff60f81b8816815260e060208201525f6134c760e083018961335a565b82810360408401526134d9818961335a565b606084018890526001600160a01b038716608085015260a0840186905283810360c0850152845180825260208087019350909101905f5b8181101561352e578351835260209384019390920191600101613510565b50909b9a5050505050505050505050565b5f805f60608486031215613551575f80fd5b833592506020840135613563816133b1565b91506040840135613573816133b1565b809150509250925092565b5f806040838503121561358f575f80fd5b823561359a816133b1565b91506020830135613422816133b1565b634e487b7160e01b5f52604160045260245ffd5b60405160c0810167ffffffffffffffff811182821017156135e1576135e16135aa565b60405290565b604051601f8201601f1916810167ffffffffffffffff81118282101715613610576136106135aa565b604052919050565b5f82601f830112613627575f80fd5b813567ffffffffffffffff811115613641576136416135aa565b613654601f8201601f19166020016135e7565b818152846020838601011115613668575f80fd5b816020850160208301375f918101602001919091529392505050565b5f8060408385031215613695575f80fd5b82356136a0816133b1565b9150602083013567ffffffffffffffff8111156136bb575f80fd5b830160c081860312156136cc575f80fd5b6136d46135be565b813567ffffffffffffffff8111156136ea575f80fd5b6136f687828501613618565b825250602082013567ffffffffffffffff811115613712575f80fd5b61371e87828501613618565b6020830152506040828101359082015260608083013590820152613744608083016133c5565b608082015261375560a083016133c5565b60a082015280925050509250929050565b5f805f805f805f60e0888a03121561377c575f80fd5b8735613787816133b1565b96506020880135613797816133b1565b95506040880135945060608801359350608088013560ff811681146137ba575f80fd5b9699959850939692959460a0840135945060c09093013592915050565b5f602082840312156137e7575f80fd5b5051919050565b634e487b7160e01b5f52601160045260245ffd5b8082018082111561095b5761095b6137ee565b600181811c9082168061382957607f821691505b60208210810361384757634e487b7160e01b5f52602260045260245ffd5b50919050565b6001600160a01b039390931683526020830191909152604082015260600190565b5f6020828403121561387e575f80fd5b815167ffffffffffffffff811115613894575f80fd5b8201601f810184136138a4575f80fd5b805167ffffffffffffffff8111156138be576138be6135aa565b8060051b6138ce602082016135e7565b918252602081840181019290810190878411156138e9575f80fd5b6020850194505b838510156139175784519250613905836133b1565b828252602094850194909101906138f0565b979650505050505050565b634e487b7160e01b5f52603260045260245ffd5b808202811582820484141761095b5761095b6137ee565b634e487b7160e01b5f52601260045260245ffd5b5f8261396f5761396f61394d565b500490565b5f60208284031215613984575f80fd5b8151610b0f816133b1565b6001815b60018411156139ca578085048111156139ae576139ae6137ee565b60018416156139bc57908102905b60019390931c928002613993565b935093915050565b5f826139e05750600161095b565b816139ec57505f61095b565b8160018114613a025760028114613a0c57613a28565b600191505061095b565b60ff841115613a1d57613a1d6137ee565b50506001821b61095b565b5060208310610133831016604e8410600b8410161715613a4b575081810a61095b565b613a575f19848461398f565b805f1904821115613a6a57613a6a6137ee565b029392505050565b5f610b0f60ff8416836139d2565b6001600160a01b03831681526040602082018190525f90610e619083018461335a565b60ff818116838216019081111561095b5761095b6137ee565b8181038181111561095b5761095b6137ee565b5f60208284031215613adf575f80fd5b81518015158114610b0f575f80fd5b601f821115610b9d57805f5260205f20601f840160051c81016020851015613b135750805b601f840160051c820191505b81811015610d56575f8155600101613b1f565b815167ffffffffffffffff811115613b4c57613b4c6135aa565b613b6081613b5a8454613815565b84613aee565b6020601f821160018114613b92575f8315613b7b5750848201515b5f19600385901b1c1916600184901b178455610d56565b5f84815260208120601f198516915b82811015613bc15787850151825560209485019460019092019101613ba1565b5084821015613bde57868401515f19600387901b60f8161c191681555b50505050600190811b01905550565b5f82518060208501845e5f920191825250919050565b634e487b7160e01b5f52602160045260245ffd5b5f60ff831680613c2957613c2961394d565b8060ff8416069150509291505056fe60a0604052348015600e575f80fd5b50336080526080516101cf61002a5f395f604d01526101cf5ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c80631cff79cd1461002d575b5f80fd5b61004061003b3660046100ff565b610042565b005b336001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000161461008b5760405163073658dd60e01b815260040160405180910390fd5b5f836001600160a01b031683836040516100a692919061018a565b5f604051808303815f865af19150503d805f81146100df576040519150601f19603f3d011682016040523d82523d5f602084013e6100e4565b606091505b50509050806100f9576040513d805f833e8082fd5b50505050565b5f805f60408486031215610111575f80fd5b83356001600160a01b0381168114610127575f80fd5b9250602084013567ffffffffffffffff811115610142575f80fd5b8401601f81018613610152575f80fd5b803567ffffffffffffffff811115610168575f80fd5b866020828401011115610179575f80fd5b939660209190910195509293505050565b818382375f910190815291905056fea264697066735822122057a94832f02283c43e3b889fb9a7c55c6fa8c2263b77b41b26eece59ec4a13ad64736f6c634300081a003352c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace00a16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d10002dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b6268000773e532dfede91f04b12a73d3d2acd361424f41f76b4fb79f090161e36b4e00a264697066735822122033cf4d6c6ef28c95467ac9323edfd509a9f7dd9acb5063b1f0ba11a66c40e35f64736f6c634300081a0033
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
00000000000000000000000065c9a641afceb9c0e6034e558a319488fa0fa3be000000000000000000000000ed92dde3214c24ae04f5f96927e3be8f8dbc3289
-----Decoded View---------------
Arg [0] : _base (address): 0x65C9A641afCEB9C0E6034e558A319488FA0FA3be
Arg [1] : _gauge (address): 0xEd92dDe3214c24Ae04F5f96927E3bE8f8DbC3289
-----Encoded View---------------
2 Constructor Arguments found :
Arg [0] : 00000000000000000000000065c9a641afceb9c0e6034e558a319488fa0fa3be
Arg [1] : 000000000000000000000000ed92dde3214c24ae04f5f96927e3be8f8dbc3289
Loading...
Loading
Loading...
Loading
Multichain Portfolio | 36 Chains
| Chain | Token | Portfolio % | Price | Amount | Value |
|---|
Loading...
Loading
Loading...
Loading
Loading...
Loading
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.