S Price: $0.068016 (-2.39%)
Gas: 55 Gwei

Contract

0x5E8352729ebD1Ea860836d6B3f59eaf286488D15

Overview

S Balance

Sonic LogoSonic LogoSonic Logo0 S

S Value

$0.00

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
Block
From
To
Issue419689272025-08-07 6:50:49172 days ago1754549449IN
dTRINITY: Issuer
0 S0.0092505955.01
Issue419245182025-08-06 22:43:46172 days ago1754520226IN
dTRINITY: Issuer
0 S0.0086661655.01
Issue418472912025-08-06 9:01:39172 days ago1754470899IN
dTRINITY: Issuer
0 S0.0095132655.01
Issue415496172025-08-04 2:37:02175 days ago1754275022IN
dTRINITY: Issuer
0 S0.0074281655.01
Issue415495462025-08-04 2:36:27175 days ago1754274987IN
dTRINITY: Issuer
0 S0.0089851655.01
Issue415493702025-08-04 2:34:30175 days ago1754274870IN
dTRINITY: Issuer
0 S0.0080738155.01
Issue415492002025-08-04 2:32:25175 days ago1754274745IN
dTRINITY: Issuer
0 S0.0083551355.01
Issue415491312025-08-04 2:31:36175 days ago1754274696IN
dTRINITY: Issuer
0 S0.0096044155.01
Issue415485542025-08-04 2:24:37175 days ago1754274277IN
dTRINITY: Issuer
0 S0.0071443655.01
Issue415485002025-08-04 2:24:06175 days ago1754274246IN
dTRINITY: Issuer
0 S0.0084021155.01
Issue414555702025-08-03 7:14:52176 days ago1754205292IN
dTRINITY: Issuer
0 S0.0082597555.01
Issue414554062025-08-03 7:13:10176 days ago1754205190IN
dTRINITY: Issuer
0 S0.0082597555.01
Issue414550372025-08-03 7:09:52176 days ago1754204992IN
dTRINITY: Issuer
0 S0.0086228455.02
Issue414548732025-08-03 7:08:12176 days ago1754204892IN
dTRINITY: Issuer
0 S0.0087612558.35
Issue413347352025-08-02 9:54:51176 days ago1754128491IN
dTRINITY: Issuer
0 S0.0089272155
Issue412604452025-08-01 20:38:00177 days ago1754080680IN
dTRINITY: Issuer
0 S0.0084567150.0001
Issue411854642025-08-01 10:21:33177 days ago1754043693IN
dTRINITY: Issuer
0 S0.008987255.01
Issue411850322025-08-01 10:17:19177 days ago1754043439IN
dTRINITY: Issuer
0 S0.0089888355.02
Issue411178162025-08-01 0:33:28178 days ago1754008408IN
dTRINITY: Issuer
0 S0.008404255.01
Issue410618112025-07-31 16:45:29178 days ago1753980329IN
dTRINITY: Issuer
0 S0.0086668255.01
Issue410146172025-07-31 10:18:39178 days ago1753957119IN
dTRINITY: Issuer
0 S0.0088760155
Issue410136692025-07-31 10:09:28178 days ago1753956568IN
dTRINITY: Issuer
0 S0.0096040455
Issue410073962025-07-31 9:15:47178 days ago1753953347IN
dTRINITY: Issuer
0 S0.0107666460
Issue409983532025-07-31 7:41:07179 days ago1753947667IN
dTRINITY: Issuer
0 S0.007995755.01
Issue409939302025-07-31 6:58:32179 days ago1753945112IN
dTRINITY: Issuer
0 S0.007995755.01
View all transactions

View more zero value Internal Transactions in Advanced View mode

Advanced mode:
Cross-Chain Transactions
Loading...
Loading

Similar Match Source Code
This contract matches the deployed Bytecode of the Source Code for Contract 0x3b8c68a3...8F7Cb51f8
The constructor portion of the code might be different and could alter the actual behaviour of the contract

Contract Name:
Issuer

Compiler Version
v0.8.20+commit.a1b79de6

Optimization Enabled:
Yes with 200 runs

Other Settings:
paris EvmVersion, MIT license

Contract Source Code (Solidity Standard Json-Input format)

// SPDX-License-Identifier: MIT
/* ———————————————————————————————————————————————————————————————————————————————— *
 *    _____     ______   ______     __     __   __     __     ______   __  __       *
 *   /\  __-.  /\__  _\ /\  == \   /\ \   /\ "-.\ \   /\ \   /\__  _\ /\ \_\ \      *
 *   \ \ \/\ \ \/_/\ \/ \ \  __<   \ \ \  \ \ \-.  \  \ \ \  \/_/\ \/ \ \____ \     *
 *    \ \____-    \ \_\  \ \_\ \_\  \ \_\  \ \_\\"\_\  \ \_\    \ \_\  \/\_____\    *
 *     \/____/     \/_/   \/_/ /_/   \/_/   \/_/ \/_/   \/_/     \/_/   \/_____/    *
 *                                                                                  *
 * ————————————————————————————————— dtrinity.org ————————————————————————————————— *
 *                                                                                  *
 *                                         ▲                                        *
 *                                        ▲ ▲                                       *
 *                                                                                  *
 * ———————————————————————————————————————————————————————————————————————————————— *
 * dTRINITY Protocol: https://github.com/dtrinity                                   *
 * ———————————————————————————————————————————————————————————————————————————————— */

pragma solidity ^0.8.20;

import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";

import "contracts/common/IAaveOracle.sol";
import "contracts/common/IMintableERC20.sol";
import "./CollateralVault.sol";
import "./AmoManager.sol";
import "./OracleAware.sol";

/**
 * @title Issuer
 * @notice Contract responsible for issuing dStable tokens
 */
contract Issuer is AccessControl, OracleAware {
    using SafeERC20 for IERC20Metadata;

    /* Core state */

    IMintableERC20 public dstable;
    uint8 public immutable dstableDecimals;
    CollateralVault public collateralVault;
    AmoManager public amoManager;

    uint256 public immutable BASE_UNIT;

    /* Events */

    event CollateralVaultSet(address indexed collateralVault);
    event AmoManagerSet(address indexed amoManager);

    /* Roles */

    bytes32 public constant AMO_MANAGER_ROLE = keccak256("AMO_MANAGER_ROLE");
    bytes32 public constant INCENTIVES_MANAGER_ROLE =
        keccak256("INCENTIVES_MANAGER_ROLE");

    /* Errors */

    error SlippageTooHigh(uint256 minDStable, uint256 dstableAmount);
    error IssuanceSurpassesExcessCollateral(
        uint256 collateralInDstable,
        uint256 circulatingDstable
    );
    error MintingToAmoShouldNotIncreaseSupply(
        uint256 circulatingDstableBefore,
        uint256 circulatingDstableAfter
    );

    /**
     * @notice Initializes the Issuer contract with core dependencies
     * @param _collateralVault The address of the collateral vault
     * @param _dstable The address of the dStable stablecoin
     * @param oracle The address of the price oracle
     * @param _amoManager The address of the AMO Manager
     */
    constructor(
        address _collateralVault,
        address _dstable,
        IPriceOracleGetter oracle,
        address _amoManager
    ) OracleAware(oracle, oracle.BASE_CURRENCY_UNIT()) {
        collateralVault = CollateralVault(_collateralVault);
        dstable = IMintableERC20(_dstable);
        dstableDecimals = dstable.decimals();
        amoManager = AmoManager(_amoManager);

        BASE_UNIT = oracle.BASE_CURRENCY_UNIT();

        _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
        grantRole(AMO_MANAGER_ROLE, msg.sender);
        grantRole(INCENTIVES_MANAGER_ROLE, msg.sender);
    }

    /* Issuer */

    /**
     * @notice Issues dStable tokens in exchange for collateral from the caller
     * @param collateralAmount The amount of collateral to deposit
     * @param collateralAsset The address of the collateral asset
     * @param minDStable The minimum amount of dStable to receive, used for slippage protection
     */
    function issue(
        uint256 collateralAmount,
        address collateralAsset,
        uint256 minDStable
    ) external {
        uint8 collateralDecimals = IERC20Metadata(collateralAsset).decimals();
        uint256 baseValue = (oracle.getAssetPrice(collateralAsset) *
            collateralAmount) / (10 ** collateralDecimals);
        uint256 dstableAmount = baseValueToDstableAmount(baseValue);
        if (dstableAmount < minDStable) {
            revert SlippageTooHigh(minDStable, dstableAmount);
        }

        // Transfer collateral directly to vault
        IERC20Metadata(collateralAsset).safeTransferFrom(
            msg.sender,
            address(collateralVault),
            collateralAmount
        );

        dstable.mint(msg.sender, dstableAmount);
    }

    /**
     * @notice Issues dStable tokens using excess collateral in the system
     * @param receiver The address to receive the minted dStable tokens
     * @param dstableAmount The amount of dStable to mint
     */
    function issueUsingExcessCollateral(
        address receiver,
        uint256 dstableAmount
    ) external onlyRole(INCENTIVES_MANAGER_ROLE) {
        dstable.mint(receiver, dstableAmount);

        // We don't use the buffer value here because we only mint up to the excess collateral
        uint256 _circulatingDstable = circulatingDstable();
        uint256 _collateralInDstable = collateralInDstable();
        if (_collateralInDstable < _circulatingDstable) {
            revert IssuanceSurpassesExcessCollateral(
                _collateralInDstable,
                _circulatingDstable
            );
        }
    }

    /**
     * @notice Increases the AMO supply by minting new dStable tokens
     * @param dstableAmount The amount of dStable to mint and send to the AMO Manager
     */
    function increaseAmoSupply(
        uint256 dstableAmount
    ) external onlyRole(AMO_MANAGER_ROLE) {
        uint256 _circulatingDstableBefore = circulatingDstable();

        dstable.mint(address(amoManager), dstableAmount);

        uint256 _circulatingDstableAfter = circulatingDstable();

        // Sanity check that we are sending to the active AMO Manager
        if (_circulatingDstableAfter != _circulatingDstableBefore) {
            revert MintingToAmoShouldNotIncreaseSupply(
                _circulatingDstableBefore,
                _circulatingDstableAfter
            );
        }
    }

    /**
     * @notice Calculates the circulating supply of dStable tokens
     * @return The amount of dStable tokens that are not held by the AMO Manager
     */
    function circulatingDstable() public view returns (uint256) {
        uint256 totalDstable = dstable.totalSupply();
        uint256 amoDstable = amoManager.totalAmoSupply();
        return totalDstable - amoDstable;
    }

    /**
     * @notice Calculates the collateral value in dStable tokens
     * @return The amount of dStable tokens equivalent to the collateral value
     */
    function collateralInDstable() public view returns (uint256) {
        uint256 _collateralInBase = collateralVault.totalValue();
        return baseValueToDstableAmount(_collateralInBase);
    }

    /**
     * @notice Converts a base value to an equivalent amount of dStable tokens
     * @param baseValue The amount of base value to convert
     * @return The equivalent amount of dStable tokens
     */
    function baseValueToDstableAmount(
        uint256 baseValue
    ) public view returns (uint256) {
        return (baseValue * (10 ** dstableDecimals)) / BASE_UNIT;
    }

    /* Admin */

    /**
     * @notice Sets the AMO Manager address
     * @param _amoManager The address of the AMO Manager
     */
    function setAmoManager(
        address _amoManager
    ) external onlyRole(DEFAULT_ADMIN_ROLE) {
        amoManager = AmoManager(_amoManager);
        grantRole(AMO_MANAGER_ROLE, _amoManager);
        emit AmoManagerSet(_amoManager);
    }

    /**
     * @notice Sets the collateral vault address
     * @param _collateralVault The address of the collateral vault
     */
    function setCollateralVault(
        address _collateralVault
    ) external onlyRole(DEFAULT_ADMIN_ROLE) {
        collateralVault = CollateralVault(_collateralVault);
        emit CollateralVaultSet(_collateralVault);
    }
}

// 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.1.0) (access/IAccessControl.sol)

pragma solidity ^0.8.20;

/**
 * @dev External interface of AccessControl declared to support ERC-165 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. This account bears the admin role (for the granted role).
     * Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
     */
    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.1.0) (interfaces/IERC1363.sol)

pragma solidity ^0.8.20;

import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

File 5 of 23 : IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)

pragma solidity ^0.8.20;

import {IERC165} from "../utils/introspection/IERC165.sol";

File 6 of 23 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../token/ERC20/IERC20.sol";

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
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.1.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 ERC-20 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.2.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 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 {
    /**
     * @dev An operation with an ERC-20 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.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    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.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    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.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    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 Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            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 {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            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 silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (utils/Address.sol)

pragma solidity ^0.8.20;

import {Errors} from "./Errors.sol";

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @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 Errors.InsufficientBalance(address(this).balance, amount);
        }

        (bool success, bytes memory returndata) = recipient.call{value: amount}("");
        if (!success) {
            _revert(returndata);
        }
    }

    /**
     * @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
     * {Errors.FailedCall} 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 Errors.InsufficientBalance(address(this).balance, value);
        }
        (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 {Errors.FailedCall}) 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 {Errors.FailedCall} 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 {Errors.FailedCall}.
     */
    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
            assembly ("memory-safe") {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert Errors.FailedCall();
        }
    }
}

// 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;
    }
}

File 12 of 23 : Errors.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)

pragma solidity ^0.8.20;

/**
 * @dev Collection of common custom errors used in multiple contracts
 *
 * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
 * It is recommended to avoid relying on the error API for critical functionality.
 *
 * _Available since v5.1._
 */
library Errors {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error InsufficientBalance(uint256 balance, uint256 needed);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedCall();

    /**
     * @dev The deployment failed.
     */
    error FailedDeployment();

    /**
     * @dev A necessary precompile is missing.
     */
    error MissingPrecompile(address);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;

/**
 * @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 EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * 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 ReentrancyGuard {
    // 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;

    uint256 private _status;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    constructor() {
        _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 {
        // 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 {
        // 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) {
        return _status == ENTERED;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.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 ERC-165 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.1.0) (utils/introspection/IERC165.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * 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[ERC 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);
}

File 16 of 23 : EnumerableMap.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/structs/EnumerableMap.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableMap.js.

pragma solidity ^0.8.20;

import {EnumerableSet} from "./EnumerableSet.sol";

/**
 * @dev Library for managing an enumerable variant of Solidity's
 * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
 * type.
 *
 * Maps have the following properties:
 *
 * - Entries are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Entries are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using EnumerableMap for EnumerableMap.UintToAddressMap;
 *
 *     // Declare a set state variable
 *     EnumerableMap.UintToAddressMap private myMap;
 * }
 * ```
 *
 * The following map types are supported:
 *
 * - `uint256 -> address` (`UintToAddressMap`) since v3.0.0
 * - `address -> uint256` (`AddressToUintMap`) since v4.6.0
 * - `bytes32 -> bytes32` (`Bytes32ToBytes32Map`) since v4.6.0
 * - `uint256 -> uint256` (`UintToUintMap`) since v4.7.0
 * - `bytes32 -> uint256` (`Bytes32ToUintMap`) since v4.7.0
 * - `uint256 -> bytes32` (`UintToBytes32Map`) since v5.1.0
 * - `address -> address` (`AddressToAddressMap`) since v5.1.0
 * - `address -> bytes32` (`AddressToBytes32Map`) since v5.1.0
 * - `bytes32 -> address` (`Bytes32ToAddressMap`) since v5.1.0
 *
 * [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 EnumerableMap, you can either remove all elements one by one or create a fresh instance using an
 * array of EnumerableMap.
 * ====
 */
library EnumerableMap {
    using EnumerableSet for EnumerableSet.Bytes32Set;

    // To implement this library for multiple types with as little code repetition as possible, we write it in
    // terms of a generic Map type with bytes32 keys and values. The Map implementation uses private functions,
    // and user-facing implementations such as `UintToAddressMap` are just wrappers around the underlying Map.
    // This means that we can only create new EnumerableMaps for types that fit in bytes32.

    /**
     * @dev Query for a nonexistent map key.
     */
    error EnumerableMapNonexistentKey(bytes32 key);

    struct Bytes32ToBytes32Map {
        // Storage of keys
        EnumerableSet.Bytes32Set _keys;
        mapping(bytes32 key => bytes32) _values;
    }

    /**
     * @dev Adds a key-value pair to a map, or updates the value for an existing
     * key. O(1).
     *
     * Returns true if the key was added to the map, that is if it was not
     * already present.
     */
    function set(Bytes32ToBytes32Map storage map, bytes32 key, bytes32 value) internal returns (bool) {
        map._values[key] = value;
        return map._keys.add(key);
    }

    /**
     * @dev Removes a key-value pair from a map. O(1).
     *
     * Returns true if the key was removed from the map, that is if it was present.
     */
    function remove(Bytes32ToBytes32Map storage map, bytes32 key) internal returns (bool) {
        delete map._values[key];
        return map._keys.remove(key);
    }

    /**
     * @dev Returns true if the key is in the map. O(1).
     */
    function contains(Bytes32ToBytes32Map storage map, bytes32 key) internal view returns (bool) {
        return map._keys.contains(key);
    }

    /**
     * @dev Returns the number of key-value pairs in the map. O(1).
     */
    function length(Bytes32ToBytes32Map storage map) internal view returns (uint256) {
        return map._keys.length();
    }

    /**
     * @dev Returns the key-value pair stored at position `index` in the map. O(1).
     *
     * Note that there are no guarantees on the ordering of entries inside the
     * array, and it may change when more entries are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(Bytes32ToBytes32Map storage map, uint256 index) internal view returns (bytes32 key, bytes32 value) {
        bytes32 atKey = map._keys.at(index);
        return (atKey, map._values[atKey]);
    }

    /**
     * @dev Tries to returns the value associated with `key`. O(1).
     * Does not revert if `key` is not in the map.
     */
    function tryGet(Bytes32ToBytes32Map storage map, bytes32 key) internal view returns (bool exists, bytes32 value) {
        bytes32 val = map._values[key];
        if (val == bytes32(0)) {
            return (contains(map, key), bytes32(0));
        } else {
            return (true, val);
        }
    }

    /**
     * @dev Returns the value associated with `key`. O(1).
     *
     * Requirements:
     *
     * - `key` must be in the map.
     */
    function get(Bytes32ToBytes32Map storage map, bytes32 key) internal view returns (bytes32) {
        bytes32 value = map._values[key];
        if (value == 0 && !contains(map, key)) {
            revert EnumerableMapNonexistentKey(key);
        }
        return value;
    }

    /**
     * @dev Return the an array containing all the keys
     *
     * 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 map grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function keys(Bytes32ToBytes32Map storage map) internal view returns (bytes32[] memory) {
        return map._keys.values();
    }

    // UintToUintMap

    struct UintToUintMap {
        Bytes32ToBytes32Map _inner;
    }

    /**
     * @dev Adds a key-value pair to a map, or updates the value for an existing
     * key. O(1).
     *
     * Returns true if the key was added to the map, that is if it was not
     * already present.
     */
    function set(UintToUintMap storage map, uint256 key, uint256 value) internal returns (bool) {
        return set(map._inner, bytes32(key), bytes32(value));
    }

    /**
     * @dev Removes a value from a map. O(1).
     *
     * Returns true if the key was removed from the map, that is if it was present.
     */
    function remove(UintToUintMap storage map, uint256 key) internal returns (bool) {
        return remove(map._inner, bytes32(key));
    }

    /**
     * @dev Returns true if the key is in the map. O(1).
     */
    function contains(UintToUintMap storage map, uint256 key) internal view returns (bool) {
        return contains(map._inner, bytes32(key));
    }

    /**
     * @dev Returns the number of elements in the map. O(1).
     */
    function length(UintToUintMap storage map) internal view returns (uint256) {
        return length(map._inner);
    }

    /**
     * @dev Returns the element stored at position `index` in the map. 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(UintToUintMap storage map, uint256 index) internal view returns (uint256 key, uint256 value) {
        (bytes32 atKey, bytes32 val) = at(map._inner, index);
        return (uint256(atKey), uint256(val));
    }

    /**
     * @dev Tries to returns the value associated with `key`. O(1).
     * Does not revert if `key` is not in the map.
     */
    function tryGet(UintToUintMap storage map, uint256 key) internal view returns (bool exists, uint256 value) {
        (bool success, bytes32 val) = tryGet(map._inner, bytes32(key));
        return (success, uint256(val));
    }

    /**
     * @dev Returns the value associated with `key`. O(1).
     *
     * Requirements:
     *
     * - `key` must be in the map.
     */
    function get(UintToUintMap storage map, uint256 key) internal view returns (uint256) {
        return uint256(get(map._inner, bytes32(key)));
    }

    /**
     * @dev Return the an array containing all the keys
     *
     * 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 map grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function keys(UintToUintMap storage map) internal view returns (uint256[] memory) {
        bytes32[] memory store = keys(map._inner);
        uint256[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    // UintToAddressMap

    struct UintToAddressMap {
        Bytes32ToBytes32Map _inner;
    }

    /**
     * @dev Adds a key-value pair to a map, or updates the value for an existing
     * key. O(1).
     *
     * Returns true if the key was added to the map, that is if it was not
     * already present.
     */
    function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
        return set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a map. O(1).
     *
     * Returns true if the key was removed from the map, that is if it was present.
     */
    function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
        return remove(map._inner, bytes32(key));
    }

    /**
     * @dev Returns true if the key is in the map. O(1).
     */
    function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
        return contains(map._inner, bytes32(key));
    }

    /**
     * @dev Returns the number of elements in the map. O(1).
     */
    function length(UintToAddressMap storage map) internal view returns (uint256) {
        return length(map._inner);
    }

    /**
     * @dev Returns the element stored at position `index` in the map. 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(UintToAddressMap storage map, uint256 index) internal view returns (uint256 key, address value) {
        (bytes32 atKey, bytes32 val) = at(map._inner, index);
        return (uint256(atKey), address(uint160(uint256(val))));
    }

    /**
     * @dev Tries to returns the value associated with `key`. O(1).
     * Does not revert if `key` is not in the map.
     */
    function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool exists, address value) {
        (bool success, bytes32 val) = tryGet(map._inner, bytes32(key));
        return (success, address(uint160(uint256(val))));
    }

    /**
     * @dev Returns the value associated with `key`. O(1).
     *
     * Requirements:
     *
     * - `key` must be in the map.
     */
    function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
        return address(uint160(uint256(get(map._inner, bytes32(key)))));
    }

    /**
     * @dev Return the an array containing all the keys
     *
     * 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 map grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function keys(UintToAddressMap storage map) internal view returns (uint256[] memory) {
        bytes32[] memory store = keys(map._inner);
        uint256[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    // UintToBytes32Map

    struct UintToBytes32Map {
        Bytes32ToBytes32Map _inner;
    }

    /**
     * @dev Adds a key-value pair to a map, or updates the value for an existing
     * key. O(1).
     *
     * Returns true if the key was added to the map, that is if it was not
     * already present.
     */
    function set(UintToBytes32Map storage map, uint256 key, bytes32 value) internal returns (bool) {
        return set(map._inner, bytes32(key), value);
    }

    /**
     * @dev Removes a value from a map. O(1).
     *
     * Returns true if the key was removed from the map, that is if it was present.
     */
    function remove(UintToBytes32Map storage map, uint256 key) internal returns (bool) {
        return remove(map._inner, bytes32(key));
    }

    /**
     * @dev Returns true if the key is in the map. O(1).
     */
    function contains(UintToBytes32Map storage map, uint256 key) internal view returns (bool) {
        return contains(map._inner, bytes32(key));
    }

    /**
     * @dev Returns the number of elements in the map. O(1).
     */
    function length(UintToBytes32Map storage map) internal view returns (uint256) {
        return length(map._inner);
    }

    /**
     * @dev Returns the element stored at position `index` in the map. 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(UintToBytes32Map storage map, uint256 index) internal view returns (uint256 key, bytes32 value) {
        (bytes32 atKey, bytes32 val) = at(map._inner, index);
        return (uint256(atKey), val);
    }

    /**
     * @dev Tries to returns the value associated with `key`. O(1).
     * Does not revert if `key` is not in the map.
     */
    function tryGet(UintToBytes32Map storage map, uint256 key) internal view returns (bool exists, bytes32 value) {
        (bool success, bytes32 val) = tryGet(map._inner, bytes32(key));
        return (success, val);
    }

    /**
     * @dev Returns the value associated with `key`. O(1).
     *
     * Requirements:
     *
     * - `key` must be in the map.
     */
    function get(UintToBytes32Map storage map, uint256 key) internal view returns (bytes32) {
        return get(map._inner, bytes32(key));
    }

    /**
     * @dev Return the an array containing all the keys
     *
     * 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 map grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function keys(UintToBytes32Map storage map) internal view returns (uint256[] memory) {
        bytes32[] memory store = keys(map._inner);
        uint256[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    // AddressToUintMap

    struct AddressToUintMap {
        Bytes32ToBytes32Map _inner;
    }

    /**
     * @dev Adds a key-value pair to a map, or updates the value for an existing
     * key. O(1).
     *
     * Returns true if the key was added to the map, that is if it was not
     * already present.
     */
    function set(AddressToUintMap storage map, address key, uint256 value) internal returns (bool) {
        return set(map._inner, bytes32(uint256(uint160(key))), bytes32(value));
    }

    /**
     * @dev Removes a value from a map. O(1).
     *
     * Returns true if the key was removed from the map, that is if it was present.
     */
    function remove(AddressToUintMap storage map, address key) internal returns (bool) {
        return remove(map._inner, bytes32(uint256(uint160(key))));
    }

    /**
     * @dev Returns true if the key is in the map. O(1).
     */
    function contains(AddressToUintMap storage map, address key) internal view returns (bool) {
        return contains(map._inner, bytes32(uint256(uint160(key))));
    }

    /**
     * @dev Returns the number of elements in the map. O(1).
     */
    function length(AddressToUintMap storage map) internal view returns (uint256) {
        return length(map._inner);
    }

    /**
     * @dev Returns the element stored at position `index` in the map. 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(AddressToUintMap storage map, uint256 index) internal view returns (address key, uint256 value) {
        (bytes32 atKey, bytes32 val) = at(map._inner, index);
        return (address(uint160(uint256(atKey))), uint256(val));
    }

    /**
     * @dev Tries to returns the value associated with `key`. O(1).
     * Does not revert if `key` is not in the map.
     */
    function tryGet(AddressToUintMap storage map, address key) internal view returns (bool exists, uint256 value) {
        (bool success, bytes32 val) = tryGet(map._inner, bytes32(uint256(uint160(key))));
        return (success, uint256(val));
    }

    /**
     * @dev Returns the value associated with `key`. O(1).
     *
     * Requirements:
     *
     * - `key` must be in the map.
     */
    function get(AddressToUintMap storage map, address key) internal view returns (uint256) {
        return uint256(get(map._inner, bytes32(uint256(uint160(key)))));
    }

    /**
     * @dev Return the an array containing all the keys
     *
     * 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 map grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function keys(AddressToUintMap storage map) internal view returns (address[] memory) {
        bytes32[] memory store = keys(map._inner);
        address[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    // AddressToAddressMap

    struct AddressToAddressMap {
        Bytes32ToBytes32Map _inner;
    }

    /**
     * @dev Adds a key-value pair to a map, or updates the value for an existing
     * key. O(1).
     *
     * Returns true if the key was added to the map, that is if it was not
     * already present.
     */
    function set(AddressToAddressMap storage map, address key, address value) internal returns (bool) {
        return set(map._inner, bytes32(uint256(uint160(key))), bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a map. O(1).
     *
     * Returns true if the key was removed from the map, that is if it was present.
     */
    function remove(AddressToAddressMap storage map, address key) internal returns (bool) {
        return remove(map._inner, bytes32(uint256(uint160(key))));
    }

    /**
     * @dev Returns true if the key is in the map. O(1).
     */
    function contains(AddressToAddressMap storage map, address key) internal view returns (bool) {
        return contains(map._inner, bytes32(uint256(uint160(key))));
    }

    /**
     * @dev Returns the number of elements in the map. O(1).
     */
    function length(AddressToAddressMap storage map) internal view returns (uint256) {
        return length(map._inner);
    }

    /**
     * @dev Returns the element stored at position `index` in the map. 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(AddressToAddressMap storage map, uint256 index) internal view returns (address key, address value) {
        (bytes32 atKey, bytes32 val) = at(map._inner, index);
        return (address(uint160(uint256(atKey))), address(uint160(uint256(val))));
    }

    /**
     * @dev Tries to returns the value associated with `key`. O(1).
     * Does not revert if `key` is not in the map.
     */
    function tryGet(AddressToAddressMap storage map, address key) internal view returns (bool exists, address value) {
        (bool success, bytes32 val) = tryGet(map._inner, bytes32(uint256(uint160(key))));
        return (success, address(uint160(uint256(val))));
    }

    /**
     * @dev Returns the value associated with `key`. O(1).
     *
     * Requirements:
     *
     * - `key` must be in the map.
     */
    function get(AddressToAddressMap storage map, address key) internal view returns (address) {
        return address(uint160(uint256(get(map._inner, bytes32(uint256(uint160(key)))))));
    }

    /**
     * @dev Return the an array containing all the keys
     *
     * 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 map grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function keys(AddressToAddressMap storage map) internal view returns (address[] memory) {
        bytes32[] memory store = keys(map._inner);
        address[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    // AddressToBytes32Map

    struct AddressToBytes32Map {
        Bytes32ToBytes32Map _inner;
    }

    /**
     * @dev Adds a key-value pair to a map, or updates the value for an existing
     * key. O(1).
     *
     * Returns true if the key was added to the map, that is if it was not
     * already present.
     */
    function set(AddressToBytes32Map storage map, address key, bytes32 value) internal returns (bool) {
        return set(map._inner, bytes32(uint256(uint160(key))), value);
    }

    /**
     * @dev Removes a value from a map. O(1).
     *
     * Returns true if the key was removed from the map, that is if it was present.
     */
    function remove(AddressToBytes32Map storage map, address key) internal returns (bool) {
        return remove(map._inner, bytes32(uint256(uint160(key))));
    }

    /**
     * @dev Returns true if the key is in the map. O(1).
     */
    function contains(AddressToBytes32Map storage map, address key) internal view returns (bool) {
        return contains(map._inner, bytes32(uint256(uint160(key))));
    }

    /**
     * @dev Returns the number of elements in the map. O(1).
     */
    function length(AddressToBytes32Map storage map) internal view returns (uint256) {
        return length(map._inner);
    }

    /**
     * @dev Returns the element stored at position `index` in the map. 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(AddressToBytes32Map storage map, uint256 index) internal view returns (address key, bytes32 value) {
        (bytes32 atKey, bytes32 val) = at(map._inner, index);
        return (address(uint160(uint256(atKey))), val);
    }

    /**
     * @dev Tries to returns the value associated with `key`. O(1).
     * Does not revert if `key` is not in the map.
     */
    function tryGet(AddressToBytes32Map storage map, address key) internal view returns (bool exists, bytes32 value) {
        (bool success, bytes32 val) = tryGet(map._inner, bytes32(uint256(uint160(key))));
        return (success, val);
    }

    /**
     * @dev Returns the value associated with `key`. O(1).
     *
     * Requirements:
     *
     * - `key` must be in the map.
     */
    function get(AddressToBytes32Map storage map, address key) internal view returns (bytes32) {
        return get(map._inner, bytes32(uint256(uint160(key))));
    }

    /**
     * @dev Return the an array containing all the keys
     *
     * 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 map grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function keys(AddressToBytes32Map storage map) internal view returns (address[] memory) {
        bytes32[] memory store = keys(map._inner);
        address[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    // Bytes32ToUintMap

    struct Bytes32ToUintMap {
        Bytes32ToBytes32Map _inner;
    }

    /**
     * @dev Adds a key-value pair to a map, or updates the value for an existing
     * key. O(1).
     *
     * Returns true if the key was added to the map, that is if it was not
     * already present.
     */
    function set(Bytes32ToUintMap storage map, bytes32 key, uint256 value) internal returns (bool) {
        return set(map._inner, key, bytes32(value));
    }

    /**
     * @dev Removes a value from a map. O(1).
     *
     * Returns true if the key was removed from the map, that is if it was present.
     */
    function remove(Bytes32ToUintMap storage map, bytes32 key) internal returns (bool) {
        return remove(map._inner, key);
    }

    /**
     * @dev Returns true if the key is in the map. O(1).
     */
    function contains(Bytes32ToUintMap storage map, bytes32 key) internal view returns (bool) {
        return contains(map._inner, key);
    }

    /**
     * @dev Returns the number of elements in the map. O(1).
     */
    function length(Bytes32ToUintMap storage map) internal view returns (uint256) {
        return length(map._inner);
    }

    /**
     * @dev Returns the element stored at position `index` in the map. 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(Bytes32ToUintMap storage map, uint256 index) internal view returns (bytes32 key, uint256 value) {
        (bytes32 atKey, bytes32 val) = at(map._inner, index);
        return (atKey, uint256(val));
    }

    /**
     * @dev Tries to returns the value associated with `key`. O(1).
     * Does not revert if `key` is not in the map.
     */
    function tryGet(Bytes32ToUintMap storage map, bytes32 key) internal view returns (bool exists, uint256 value) {
        (bool success, bytes32 val) = tryGet(map._inner, key);
        return (success, uint256(val));
    }

    /**
     * @dev Returns the value associated with `key`. O(1).
     *
     * Requirements:
     *
     * - `key` must be in the map.
     */
    function get(Bytes32ToUintMap storage map, bytes32 key) internal view returns (uint256) {
        return uint256(get(map._inner, key));
    }

    /**
     * @dev Return the an array containing all the keys
     *
     * 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 map grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function keys(Bytes32ToUintMap storage map) internal view returns (bytes32[] memory) {
        bytes32[] memory store = keys(map._inner);
        bytes32[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    // Bytes32ToAddressMap

    struct Bytes32ToAddressMap {
        Bytes32ToBytes32Map _inner;
    }

    /**
     * @dev Adds a key-value pair to a map, or updates the value for an existing
     * key. O(1).
     *
     * Returns true if the key was added to the map, that is if it was not
     * already present.
     */
    function set(Bytes32ToAddressMap storage map, bytes32 key, address value) internal returns (bool) {
        return set(map._inner, key, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a map. O(1).
     *
     * Returns true if the key was removed from the map, that is if it was present.
     */
    function remove(Bytes32ToAddressMap storage map, bytes32 key) internal returns (bool) {
        return remove(map._inner, key);
    }

    /**
     * @dev Returns true if the key is in the map. O(1).
     */
    function contains(Bytes32ToAddressMap storage map, bytes32 key) internal view returns (bool) {
        return contains(map._inner, key);
    }

    /**
     * @dev Returns the number of elements in the map. O(1).
     */
    function length(Bytes32ToAddressMap storage map) internal view returns (uint256) {
        return length(map._inner);
    }

    /**
     * @dev Returns the element stored at position `index` in the map. 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(Bytes32ToAddressMap storage map, uint256 index) internal view returns (bytes32 key, address value) {
        (bytes32 atKey, bytes32 val) = at(map._inner, index);
        return (atKey, address(uint160(uint256(val))));
    }

    /**
     * @dev Tries to returns the value associated with `key`. O(1).
     * Does not revert if `key` is not in the map.
     */
    function tryGet(Bytes32ToAddressMap storage map, bytes32 key) internal view returns (bool exists, address value) {
        (bool success, bytes32 val) = tryGet(map._inner, key);
        return (success, address(uint160(uint256(val))));
    }

    /**
     * @dev Returns the value associated with `key`. O(1).
     *
     * Requirements:
     *
     * - `key` must be in the map.
     */
    function get(Bytes32ToAddressMap storage map, bytes32 key) internal view returns (address) {
        return address(uint160(uint256(get(map._inner, key))));
    }

    /**
     * @dev Return the an array containing all the keys
     *
     * 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 map grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function keys(Bytes32ToAddressMap storage map) internal view returns (bytes32[] memory) {
        bytes32[] memory store = keys(map._inner);
        bytes32[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.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;

        assembly ("memory-safe") {
            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;

        assembly ("memory-safe") {
            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;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }
}

// SPDX-License-Identifier: AGPL-3.0
/* ———————————————————————————————————————————————————————————————————————————————— *
 *    _____     ______   ______     __     __   __     __     ______   __  __       *
 *   /\  __-.  /\__  _\ /\  == \   /\ \   /\ "-.\ \   /\ \   /\__  _\ /\ \_\ \      *
 *   \ \ \/\ \ \/_/\ \/ \ \  __<   \ \ \  \ \ \-.  \  \ \ \  \/_/\ \/ \ \____ \     *
 *    \ \____-    \ \_\  \ \_\ \_\  \ \_\  \ \_\\"\_\  \ \_\    \ \_\  \/\_____\    *
 *     \/____/     \/_/   \/_/ /_/   \/_/   \/_/ \/_/   \/_/     \/_/   \/_____/    *
 *                                                                                  *
 * ————————————————————————————————— dtrinity.org ————————————————————————————————— *
 *                                                                                  *
 *                                         ▲                                        *
 *                                        ▲ ▲                                       *
 *                                                                                  *
 * ———————————————————————————————————————————————————————————————————————————————— *
 * dTRINITY Protocol: https://github.com/dtrinity                                   *
 * ———————————————————————————————————————————————————————————————————————————————— */

pragma solidity ^0.8.20;

/**
 * @title IPriceOracleGetter
 * @author Aave
 * @notice Interface for the Aave price oracle.
 */
interface IPriceOracleGetter {
    /**
     * @notice Returns the base currency address
     * @dev Address 0x0 is reserved for USD as base currency.
     * @return Returns the base currency address.
     */
    function BASE_CURRENCY() external view returns (address);

    /**
     * @notice Returns the base currency unit
     * @dev 1 ether for ETH, 1e8 for USD.
     * @return Returns the base currency unit.
     */
    function BASE_CURRENCY_UNIT() external view returns (uint256);

    /**
     * @notice Returns the asset price in the base currency
     * @param asset The address of the asset
     * @return The price of the asset
     */
    function getAssetPrice(address asset) external view returns (uint256);
}

// SPDX-License-Identifier: Unlicense
/* ———————————————————————————————————————————————————————————————————————————————— *
 *    _____     ______   ______     __     __   __     __     ______   __  __       *
 *   /\  __-.  /\__  _\ /\  == \   /\ \   /\ "-.\ \   /\ \   /\__  _\ /\ \_\ \      *
 *   \ \ \/\ \ \/_/\ \/ \ \  __<   \ \ \  \ \ \-.  \  \ \ \  \/_/\ \/ \ \____ \     *
 *    \ \____-    \ \_\  \ \_\ \_\  \ \_\  \ \_\\"\_\  \ \_\    \ \_\  \/\_____\    *
 *     \/____/     \/_/   \/_/ /_/   \/_/   \/_/ \/_/   \/_/     \/_/   \/_____/    *
 *                                                                                  *
 * ————————————————————————————————— dtrinity.org ————————————————————————————————— *
 *                                                                                  *
 *                                         ▲                                        *
 *                                        ▲ ▲                                       *
 *                                                                                  *
 * ———————————————————————————————————————————————————————————————————————————————— *
 * dTRINITY Protocol: https://github.com/dtrinity                                   *
 * ———————————————————————————————————————————————————————————————————————————————— */

pragma solidity ^0.8.20;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

interface IMintableERC20 is IERC20 {
    function mint(address to, uint256 amount) external;

    function burn(uint256 amount) external;

    function burnFrom(address account, uint256 amount) external;

    function decimals() external view returns (uint8);
}

// SPDX-License-Identifier: MIT
/* ———————————————————————————————————————————————————————————————————————————————— *
 *    _____     ______   ______     __     __   __     __     ______   __  __       *
 *   /\  __-.  /\__  _\ /\  == \   /\ \   /\ "-.\ \   /\ \   /\__  _\ /\ \_\ \      *
 *   \ \ \/\ \ \/_/\ \/ \ \  __<   \ \ \  \ \ \-.  \  \ \ \  \/_/\ \/ \ \____ \     *
 *    \ \____-    \ \_\  \ \_\ \_\  \ \_\  \ \_\\"\_\  \ \_\    \ \_\  \/\_____\    *
 *     \/____/     \/_/   \/_/ /_/   \/_/   \/_/ \/_/   \/_/     \/_/   \/_____/    *
 *                                                                                  *
 * ————————————————————————————————— dtrinity.org ————————————————————————————————— *
 *                                                                                  *
 *                                         ▲                                        *
 *                                        ▲ ▲                                       *
 *                                                                                  *
 * ———————————————————————————————————————————————————————————————————————————————— *
 * dTRINITY Protocol: https://github.com/dtrinity                                   *
 * ———————————————————————————————————————————————————————————————————————————————— */

pragma solidity ^0.8.20;

import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableMap.sol";
import "contracts/common/IMintableERC20.sol";
import "./AmoVault.sol";

/**
 * @title AmoManager
 * @dev Manages AMOs for dStable
 * Handles allocation, deallocation, collateral management, and profit management for AMO vaults.
 */
contract AmoManager is AccessControl, OracleAware {
    using EnumerableMap for EnumerableMap.AddressToUintMap;

    /* Core state */

    EnumerableMap.AddressToUintMap private _amoVaults;
    uint256 public totalAllocated;
    IMintableERC20 public dstable;
    CollateralVault public collateralHolderVault;

    uint256 public immutable BASE_UNIT;

    /* Events */

    event AmoVaultSet(address indexed amoVault, bool isActive);
    event AmoAllocated(address indexed amoVault, uint256 dstableAmount);
    event AmoDeallocated(address indexed amoVault, uint256 dstableAmount);
    event ProfitsWithdrawn(address indexed amoVault, uint256 amount);

    /* Roles */

    bytes32 public constant AMO_ALLOCATOR_ROLE =
        keccak256("AMO_ALLOCATOR_ROLE");
    bytes32 public constant FEE_COLLECTOR_ROLE =
        keccak256("FEE_COLLECTOR_ROLE");

    /* Errors */

    error InactiveAmoVault(address amoVault);
    error AmoSupplyInvariantViolation(
        uint256 startingSupply,
        uint256 endingSupply
    );
    error AmoVaultAlreadyEnabled(address amoVault);
    error CannotTransferDStable();
    error InsufficientProfits(
        uint256 takeProfitValueInBase,
        int256 availableProfitInBase
    );

    /**
     * @notice Initializes the AmoManager contract.
     * @param _dstable The address of the dStable stablecoin.
     * @param _collateralHolderVault The address of the collateral holder vault.
     * @param _oracle The oracle for price feeds.
     */
    constructor(
        address _dstable,
        address _collateralHolderVault,
        IPriceOracleGetter _oracle
    ) OracleAware(_oracle, _oracle.BASE_CURRENCY_UNIT()) {
        dstable = IMintableERC20(_dstable);
        collateralHolderVault = CollateralVault(_collateralHolderVault);

        BASE_UNIT = oracle.BASE_CURRENCY_UNIT();

        _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
        grantRole(AMO_ALLOCATOR_ROLE, msg.sender);
        grantRole(FEE_COLLECTOR_ROLE, msg.sender);
    }

    /* AMO */

    /**
     * @notice Allocates AMO tokens to an AMO vault.
     * @param amoVault The address of the AMO vault.
     * @param dstableAmount The amount of dStable to allocate.
     */
    function allocateAmo(
        address amoVault,
        uint256 dstableAmount
    ) public onlyRole(AMO_ALLOCATOR_ROLE) {
        uint256 startingAmoSupply = totalAmoSupply();

        // Make sure the vault is active
        if (!isAmoActive(amoVault)) {
            revert InactiveAmoVault(amoVault);
        }

        // Update the allocation for this vault
        (, uint256 currentAllocation) = _amoVaults.tryGet(amoVault);
        _amoVaults.set(amoVault, currentAllocation + dstableAmount);

        // Make the deposit
        totalAllocated += dstableAmount;
        dstable.transfer(amoVault, dstableAmount);

        // Check invariants
        uint256 endingAmoSupply = totalAmoSupply();
        if (endingAmoSupply != startingAmoSupply) {
            revert AmoSupplyInvariantViolation(
                startingAmoSupply,
                endingAmoSupply
            );
        }

        emit AmoAllocated(amoVault, dstableAmount);
    }

    /**
     * @notice Deallocates AMO tokens from an AMO vault.
     * @param amoVault The address of the AMO vault.
     * @param dstableAmount The amount of dStable to deallocate.
     */
    function deallocateAmo(
        address amoVault,
        uint256 dstableAmount
    ) public onlyRole(AMO_ALLOCATOR_ROLE) {
        uint256 startingAmoSupply = totalAmoSupply();

        // We don't require that the vault is active or has allocation, since we want to allow withdrawing from inactive vaults

        // If the vault is still active, make sure it has enough allocation and decrease it
        (, uint256 currentAllocation) = _amoVaults.tryGet(amoVault);
        if (currentAllocation > 0) {
            // Update the allocation for this vault
            _amoVaults.set(amoVault, currentAllocation - dstableAmount);
        }

        // Make the withdrawal
        totalAllocated -= dstableAmount;
        dstable.transferFrom(amoVault, address(this), dstableAmount);

        // Check invariants
        uint256 endingAmoSupply = totalAmoSupply();
        if (endingAmoSupply != startingAmoSupply) {
            revert AmoSupplyInvariantViolation(
                startingAmoSupply,
                endingAmoSupply
            );
        }

        emit AmoDeallocated(amoVault, dstableAmount);
    }

    /**
     * @notice Returns the total AMO supply.
     * @return The total AMO supply.
     */
    function totalAmoSupply() public view returns (uint256) {
        uint256 freeBalance = dstable.balanceOf(address(this));
        return freeBalance + totalAllocated;
    }

    /**
     * @notice Decreases the AMO supply by burning dStable.
     * @param dstableAmount The amount of dStable to burn.
     */
    function decreaseAmoSupply(
        uint256 dstableAmount
    ) public onlyRole(AMO_ALLOCATOR_ROLE) {
        dstable.burn(dstableAmount);
    }

    /**
     * @notice Checks if an AMO vault is active.
     * @param amoVault The address of the AMO vault to check.
     * @return True if the AMO vault is active, false otherwise.
     */
    function isAmoActive(address amoVault) public view returns (bool) {
        return _amoVaults.contains(amoVault);
    }

    /**
     * @notice Returns the allocation for a specific AMO vault.
     * @param amoVault The address of the AMO vault.
     * @return The current allocation for the vault.
     */
    function amoVaultAllocation(
        address amoVault
    ) public view returns (uint256) {
        (bool exists, uint256 allocation) = _amoVaults.tryGet(amoVault);
        return exists ? allocation : 0;
    }

    /**
     * @notice Returns the list of all AMO vaults.
     * @return The list of AMO vault addresses.
     */
    function amoVaults() public view returns (address[] memory) {
        return _amoVaults.keys();
    }

    /**
     * @notice Enables an AMO vault.
     * @param amoVault The address of the AMO vault.
     */
    function enableAmoVault(
        address amoVault
    ) public onlyRole(DEFAULT_ADMIN_ROLE) {
        if (_amoVaults.contains(amoVault)) {
            revert AmoVaultAlreadyEnabled(amoVault);
        }
        _amoVaults.set(amoVault, 0);
        emit AmoVaultSet(amoVault, true);
    }

    /**
     * @notice Disables an AMO vault.
     * @param amoVault The address of the AMO vault.
     */
    function disableAmoVault(
        address amoVault
    ) public onlyRole(DEFAULT_ADMIN_ROLE) {
        if (!_amoVaults.contains(amoVault)) {
            revert InactiveAmoVault(amoVault);
        }
        _amoVaults.remove(amoVault);
        emit AmoVaultSet(amoVault, false);
    }

    /* Collateral Management */

    /**
     * @notice Returns the total collateral value of all active AMO vaults.
     * @return The total collateral value in base value.
     */
    function totalCollateralValue() public view returns (uint256) {
        uint256 totalBaseValue = 0;
        for (uint256 i = 0; i < _amoVaults.length(); i++) {
            (address vaultAddress, ) = _amoVaults.at(i);
            if (isAmoActive(vaultAddress)) {
                totalBaseValue += AmoVault(vaultAddress).totalCollateralValue();
            }
        }
        return totalBaseValue;
    }

    /**
     * @notice Transfers collateral from an AMO vault to the holding vault.
     * @param amoVault The address of the AMO vault.
     * @param token The address of the collateral token to transfer.
     * @param amount The amount of collateral to transfer.
     */
    function transferFromAmoVaultToHoldingVault(
        address amoVault,
        address token,
        uint256 amount
    ) public onlyRole(AMO_ALLOCATOR_ROLE) {
        if (token == address(dstable)) {
            revert CannotTransferDStable();
        }

        // Update allocation
        // A note on why we modify AMO allocation when we withdraw collateral:
        // 1. When dStable AMO enters the AMO vault, the dStable is initially unbacked
        // 2. Over time the AMO vault accrues collateral in exchange for distributing dStable
        // 3. We may be able to make better use of that collateral in a different collateral vault
        // 4. So we transfer the collateral out of the AMO vault, but at that point the dStable that
        //    converted to that collateral is now free-floating and fully backed
        // 5. Thus we decrement the AMO allocation to reflect the fact that the dStable is no longer
        //    unbacked, but is actually fully backed and circulating
        uint256 collateralBaseValue = collateralHolderVault
            .assetValueFromAmount(amount, token);
        uint256 collateralInDstable = baseValueToDstableAmount(
            collateralBaseValue
        );
        (, uint256 currentAllocation) = _amoVaults.tryGet(amoVault);

        // Prevent underflow by only deducting what's available
        uint256 adjustmentAmount = collateralInDstable;
        if (collateralInDstable > currentAllocation) {
            adjustmentAmount = currentAllocation;
        }

        _amoVaults.set(amoVault, currentAllocation - adjustmentAmount);
        totalAllocated -= adjustmentAmount;

        // Transfer the collateral
        AmoVault(amoVault).withdrawTo(
            address(collateralHolderVault),
            amount,
            token
        );
    }

    /**
     * @notice Transfers collateral from the holding vault to an AMO vault.
     * @param amoVault The address of the AMO vault.
     * @param token The address of the collateral token to transfer.
     * @param amount The amount of collateral to transfer.
     */
    function transferFromHoldingVaultToAmoVault(
        address amoVault,
        address token,
        uint256 amount
    ) public onlyRole(AMO_ALLOCATOR_ROLE) {
        if (token == address(dstable)) {
            revert CannotTransferDStable();
        }
        if (!_amoVaults.contains(amoVault)) {
            revert InactiveAmoVault(amoVault);
        }

        // Update allocation
        // A note on why we modify AMO allocation when we deposit collateral:
        // 1. When we deposit collateral, it can be used to buy back dStable
        // 2. When we buy back dStable, the dStable is now unbacked (a redemption)
        // 3. Thus any collateral deposited to an AMO vault can create unbacked dStable,
        //    which means the AMO allocation for that vault must be increased to reflect this
        uint256 collateralBaseValue = collateralHolderVault
            .assetValueFromAmount(amount, token);
        uint256 collateralInDstable = baseValueToDstableAmount(
            collateralBaseValue
        );
        (, uint256 currentAllocation) = _amoVaults.tryGet(amoVault);
        _amoVaults.set(amoVault, currentAllocation + collateralInDstable);
        totalAllocated += collateralInDstable;

        // Transfer the collateral
        collateralHolderVault.withdrawTo(amoVault, amount, token);
    }

    /* Profit Management */

    /**
     * @notice Returns the available profit for a specific vault in base value (e.g., the underlying).
     * @param vaultAddress The address of the AMO vault to check.
     * @return The available profit in base (can be negative).
     */
    function availableVaultProfitsInBase(
        address vaultAddress
    ) public view returns (int256) {
        uint256 totalVaultValueInBase = AmoVault(vaultAddress).totalValue();
        uint256 allocatedDstable = amoVaultAllocation(vaultAddress);
        uint256 allocatedValueInBase = dstableAmountToBaseValue(
            allocatedDstable
        );

        return int256(totalVaultValueInBase) - int256(allocatedValueInBase);
    }

    /**
     * @notice Withdraws profits from an AMO vault to a recipient.
     * @param amoVault The AMO vault from which to withdraw profits.
     * @param recipient The address to receive the profits.
     * @param takeProfitToken The collateral token to withdraw.
     * @param takeProfitAmount The amount of collateral to withdraw.
     * @return takeProfitValueInBase The value of the withdrawn profits in base.
     */
    function withdrawProfits(
        AmoVault amoVault,
        address recipient,
        address takeProfitToken,
        uint256 takeProfitAmount
    )
        public
        onlyRole(FEE_COLLECTOR_ROLE)
        returns (uint256 takeProfitValueInBase)
    {
        // Leave open the possibility of withdrawing profits from inactive vaults

        takeProfitValueInBase = amoVault.assetValueFromAmount(
            takeProfitAmount,
            takeProfitToken
        );

        int256 _availableProfitInBase = availableVaultProfitsInBase(
            address(amoVault)
        );

        // Make sure we are withdrawing less than the available profit
        if (
            _availableProfitInBase <= 0 ||
            int256(takeProfitValueInBase) > _availableProfitInBase
        ) {
            revert InsufficientProfits(
                takeProfitValueInBase,
                _availableProfitInBase
            );
        }

        // Withdraw profits from the vault
        amoVault.withdrawTo(recipient, takeProfitAmount, takeProfitToken);

        emit ProfitsWithdrawn(address(amoVault), takeProfitValueInBase);

        return takeProfitValueInBase;
    }

    /**
     * @notice Returns the total available profit across all AMO vaults in base.
     * @return The total available profit in base.
     */
    function availableProfitInBase() public view returns (int256) {
        int256 totalProfit = 0;

        // Iterate through all AMO vaults
        for (uint256 i = 0; i < _amoVaults.length(); i++) {
            (address vaultAddress, ) = _amoVaults.at(i);

            if (isAmoActive(vaultAddress)) {
                totalProfit += availableVaultProfitsInBase(vaultAddress);
            }
        }

        return totalProfit;
    }

    /* Utility */

    /**
     * @notice Converts a base value to an equivalent amount of dStable tokens.
     * @param baseValue The amount of base value to convert.
     * @return The equivalent amount of dStable tokens.
     */
    function baseValueToDstableAmount(
        uint256 baseValue
    ) public view returns (uint256) {
        uint8 dstableDecimals = dstable.decimals();
        return
            (baseValue * (10 ** dstableDecimals)) /
            (oracle.getAssetPrice(address(dstable)));
    }

    /**
     * @notice Converts an amount of dStable tokens to an equivalent base value.
     * @param dstableAmount The amount of dStable tokens to convert.
     * @return The equivalent amount of base value.
     */
    function dstableAmountToBaseValue(
        uint256 dstableAmount
    ) public view returns (uint256) {
        uint8 dstableDecimals = dstable.decimals();
        return
            (dstableAmount * oracle.getAssetPrice(address(dstable))) /
            (10 ** dstableDecimals);
    }

    /* Admin */

    /**
     * @notice Sets the collateral vault address
     * @param _collateralVault The address of the new collateral vault
     */
    function setCollateralVault(
        address _collateralVault
    ) external onlyRole(DEFAULT_ADMIN_ROLE) {
        collateralHolderVault = CollateralVault(_collateralVault);
    }
}

/**
 * @title ICollateralSum
 * @dev Interface for contracts that can provide total collateral value.
 */
interface ICollateralSum {
    /**
     * @notice Returns the total collateral value of the implementing contract.
     * @return The total collateral value in base value.
     */
    function totalCollateralValue() external view returns (uint256);
}

// SPDX-License-Identifier: MIT
/* ———————————————————————————————————————————————————————————————————————————————— *
 *    _____     ______   ______     __     __   __     __     ______   __  __       *
 *   /\  __-.  /\__  _\ /\  == \   /\ \   /\ "-.\ \   /\ \   /\__  _\ /\ \_\ \      *
 *   \ \ \/\ \ \/_/\ \/ \ \  __<   \ \ \  \ \ \-.  \  \ \ \  \/_/\ \/ \ \____ \     *
 *    \ \____-    \ \_\  \ \_\ \_\  \ \_\  \ \_\\"\_\  \ \_\    \ \_\  \/\_____\    *
 *     \/____/     \/_/   \/_/ /_/   \/_/   \/_/ \/_/   \/_/     \/_/   \/_____/    *
 *                                                                                  *
 * ————————————————————————————————— dtrinity.org ————————————————————————————————— *
 *                                                                                  *
 *                                         ▲                                        *
 *                                        ▲ ▲                                       *
 *                                                                                  *
 * ———————————————————————————————————————————————————————————————————————————————— *
 * dTRINITY Protocol: https://github.com/dtrinity                                   *
 * ———————————————————————————————————————————————————————————————————————————————— */

pragma solidity ^0.8.20;

import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "contracts/common/IMintableERC20.sol";
import "./AmoManager.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "contracts/dstable/CollateralVault.sol";

interface IRecoverable {
    function recoverERC20(address token, address to, uint256 amount) external;

    function recoverETH(address to, uint256 amount) external;
}

/**
 * @title AmoVault
 * @notice Base contract for AMO (Algorithmic Market Operations) vaults that manage dStable and collateral assets
 */
abstract contract AmoVault is CollateralVault, IRecoverable, ReentrancyGuard {
    using SafeERC20 for IERC20;
    using Address for address payable;

    /* Core state */

    IMintableERC20 public immutable dstable;
    uint8 public immutable dstableDecimals;
    AmoManager public amoManager;

    /* Roles */

    bytes32 public constant RECOVERER_ROLE = keccak256("RECOVERER_ROLE");

    /* Errors */

    error CannotRecoverVaultToken(address token);
    error InvalidAmoManager();

    constructor(
        address _dstable,
        address _amoManager,
        address _admin,
        address _collateralWithdrawer,
        address _recoverer,
        IPriceOracleGetter _oracle
    ) CollateralVault(_oracle) {
        dstable = IMintableERC20(_dstable);
        dstableDecimals = IERC20Metadata(_dstable).decimals();
        amoManager = AmoManager(_amoManager);
        _grantRole(DEFAULT_ADMIN_ROLE, _admin);
        grantRole(COLLATERAL_WITHDRAWER_ROLE, _collateralWithdrawer);
        grantRole(RECOVERER_ROLE, _recoverer);
        approveAmoManager();
    }

    /**
     * @notice Approves the AmoManager to spend dStable on behalf of this contract
     * @dev Only callable by the contract owner or an account with the DEFAULT_ADMIN_ROLE
     */
    function approveAmoManager() public onlyRole(DEFAULT_ADMIN_ROLE) {
        dstable.approve(address(amoManager), type(uint256).max);
    }

    /**
     * @notice Sets a new AmoManager address
     * @param _newAmoManager The address of the new AmoManager
     * @dev Only callable by an account with the DEFAULT_ADMIN_ROLE
     */
    function setAmoManager(
        address _newAmoManager
    ) external onlyRole(DEFAULT_ADMIN_ROLE) {
        if (_newAmoManager == address(0)) revert InvalidAmoManager();

        // Reset allowance for old AMO manager
        dstable.approve(address(amoManager), 0);

        // Set new AMO manager
        amoManager = AmoManager(_newAmoManager);

        // Approve new AMO manager
        approveAmoManager();
    }

    /* Recovery */

    /**
     * @notice Recovers ERC20 tokens accidentally sent to the contract
     * @param token The address of the token to recover
     * @param to The address to send the tokens to
     * @param amount The amount of tokens to recover
     */
    function recoverERC20(
        address token,
        address to,
        uint256 amount
    ) external onlyRole(RECOVERER_ROLE) nonReentrant {
        if (token == address(dstable) || isCollateralSupported(token)) {
            revert CannotRecoverVaultToken(token);
        }
        IERC20(token).safeTransfer(to, amount);
    }

    /**
     * @notice Recovers ETH accidentally sent to the contract
     * @param to The address to send the ETH to
     * @param amount The amount of ETH to recover
     */
    function recoverETH(
        address to,
        uint256 amount
    ) external onlyRole(RECOVERER_ROLE) {
        payable(to).sendValue(amount);
    }

    /* Virtual functions */

    /**
     * @notice Calculates the total value of non-dStable collateral assets in the vault
     * @return The total value of collateral assets denominated in the base currency
     * @dev Must be implemented by derived contracts
     */
    function totalCollateralValue() public view virtual returns (uint256);

    /**
     * @notice Calculates the total value of dStable holdings in the vault
     * @return The total value of dStable holdings denominated in the base currency
     * @dev Must be implemented by derived contracts
     */
    function totalDstableValue() public view virtual returns (uint256);
}

// SPDX-License-Identifier: MIT
/* ———————————————————————————————————————————————————————————————————————————————— *
 *    _____     ______   ______     __     __   __     __     ______   __  __       *
 *   /\  __-.  /\__  _\ /\  == \   /\ \   /\ "-.\ \   /\ \   /\__  _\ /\ \_\ \      *
 *   \ \ \/\ \ \/_/\ \/ \ \  __<   \ \ \  \ \ \-.  \  \ \ \  \/_/\ \/ \ \____ \     *
 *    \ \____-    \ \_\  \ \_\ \_\  \ \_\  \ \_\\"\_\  \ \_\    \ \_\  \/\_____\    *
 *     \/____/     \/_/   \/_/ /_/   \/_/   \/_/ \/_/   \/_/     \/_/   \/_____/    *
 *                                                                                  *
 * ————————————————————————————————— dtrinity.org ————————————————————————————————— *
 *                                                                                  *
 *                                         ▲                                        *
 *                                        ▲ ▲                                       *
 *                                                                                  *
 * ———————————————————————————————————————————————————————————————————————————————— *
 * dTRINITY Protocol: https://github.com/dtrinity                                   *
 * ———————————————————————————————————————————————————————————————————————————————— */

pragma solidity ^0.8.20;

import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";

import "contracts/common/IAaveOracle.sol";
import "./OracleAware.sol";

/**
 * @title CollateralVault
 * @notice Abstract contract for any contract that manages collateral assets
\ */
abstract contract CollateralVault is AccessControl, OracleAware {
    using SafeERC20 for IERC20Metadata;
    using EnumerableSet for EnumerableSet.AddressSet;

    /* Core state */

    EnumerableSet.AddressSet internal _supportedCollaterals;

    /* Events */

    event CollateralAllowed(address indexed collateralAsset);
    event CollateralDisallowed(address indexed collateralAsset);

    /* Roles */

    bytes32 public constant COLLATERAL_MANAGER_ROLE =
        keccak256("COLLATERAL_MANAGER_ROLE");
    bytes32 public constant COLLATERAL_STRATEGY_ROLE =
        keccak256("COLLATERAL_STRATEGY_ROLE");
    bytes32 public constant COLLATERAL_WITHDRAWER_ROLE =
        keccak256("COLLATERAL_WITHDRAWER_ROLE");

    /* Errors */
    error UnsupportedCollateral(address collateralAsset);
    error CollateralAlreadyAllowed(address collateralAsset);
    error NoOracleSupport(address collateralAsset);
    error FailedToAddCollateral(address collateralAsset);
    error CollateralNotSupported(address collateralAsset);
    error MustSupportAtLeastOneCollateral();
    error FailedToRemoveCollateral(address collateralAsset);

    /**
     * @notice Initializes the vault with an oracle and sets up initial roles
     * @dev Grants all roles to the contract deployer initially
     * @param oracle The price oracle to use for collateral valuation
     */
    constructor(
        IPriceOracleGetter oracle
    ) OracleAware(oracle, oracle.BASE_CURRENCY_UNIT()) {
        _grantRole(DEFAULT_ADMIN_ROLE, msg.sender); // This is the super admin
        grantRole(COLLATERAL_MANAGER_ROLE, msg.sender);
        grantRole(COLLATERAL_WITHDRAWER_ROLE, msg.sender);
        grantRole(COLLATERAL_STRATEGY_ROLE, msg.sender);
    }

    /* Deposit */

    /**
     * @notice Deposit collateral into the vault
     * @param collateralAmount The amount of collateral to deposit
     * @param collateralAsset The address of the collateral asset
     */
    function deposit(uint256 collateralAmount, address collateralAsset) public {
        if (!_supportedCollaterals.contains(collateralAsset)) {
            revert UnsupportedCollateral(collateralAsset);
        }

        IERC20Metadata(collateralAsset).safeTransferFrom(
            msg.sender,
            address(this),
            collateralAmount
        );
    }

    /* Withdrawal */

    /**
     * @notice Withdraws collateral from the vault
     * @param collateralAmount The amount of collateral to withdraw
     * @param collateralAsset The address of the collateral asset
     */
    function withdraw(
        uint256 collateralAmount,
        address collateralAsset
    ) public onlyRole(COLLATERAL_WITHDRAWER_ROLE) {
        return _withdraw(msg.sender, collateralAmount, collateralAsset);
    }

    /**
     * @notice Withdraws collateral from the vault to a specific address
     * @param recipient The address receiving the collateral
     * @param collateralAmount The amount of collateral to withdraw
     * @param collateralAsset The address of the collateral asset
     */
    function withdrawTo(
        address recipient,
        uint256 collateralAmount,
        address collateralAsset
    ) public onlyRole(COLLATERAL_WITHDRAWER_ROLE) {
        return _withdraw(recipient, collateralAmount, collateralAsset);
    }

    /**
     * @notice Internal function to withdraw collateral from the vault
     * @param withdrawer The address withdrawing the collateral
     * @param collateralAmount The amount of collateral to withdraw
     * @param collateralAsset The address of the collateral asset
     */
    function _withdraw(
        address withdrawer,
        uint256 collateralAmount,
        address collateralAsset
    ) internal {
        IERC20Metadata(collateralAsset).safeTransfer(
            withdrawer,
            collateralAmount
        );
    }

    /* Collateral Info */

    /**
     * @notice Calculates the total value of all assets in the vault
     * @return baseValue The total value of all assets in base
     */
    function totalValue() public view virtual returns (uint256 baseValue);

    /**
     * @notice Calculates the base value of a given amount of an asset
     * @param assetAmount The amount of the asset
     * @param asset The address of the asset
     * @return baseValue The base value of the asset
     */
    function assetValueFromAmount(
        uint256 assetAmount,
        address asset
    ) public view returns (uint256 baseValue) {
        uint256 assetPrice = oracle.getAssetPrice(asset);
        uint8 assetDecimals = IERC20Metadata(asset).decimals();
        return (assetPrice * assetAmount) / (10 ** assetDecimals);
    }

    /**
     * @notice Calculates the amount of an asset that corresponds to a given base value
     * @param baseValue The base value
     * @param asset The address of the asset
     * @return assetAmount The amount of the asset
     */
    function assetAmountFromValue(
        uint256 baseValue,
        address asset
    ) public view returns (uint256 assetAmount) {
        uint256 assetPrice = oracle.getAssetPrice(asset);
        uint8 assetDecimals = IERC20Metadata(asset).decimals();
        return (baseValue * (10 ** assetDecimals)) / assetPrice;
    }

    /* Collateral management */

    /**
     * @notice Allows a new collateral asset
     * @param collateralAsset The address of the collateral asset
     */
    function allowCollateral(
        address collateralAsset
    ) public onlyRole(COLLATERAL_MANAGER_ROLE) {
        if (_supportedCollaterals.contains(collateralAsset)) {
            revert CollateralAlreadyAllowed(collateralAsset);
        }
        if (oracle.getAssetPrice(collateralAsset) == 0) {
            revert NoOracleSupport(collateralAsset);
        }
        if (!_supportedCollaterals.add(collateralAsset)) {
            revert FailedToAddCollateral(collateralAsset);
        }
        emit CollateralAllowed(collateralAsset);
    }

    /**
     * @notice Disallows a previously supported collateral asset
     * @dev Requires at least one collateral asset to remain supported
     * @param collateralAsset The address of the collateral asset to disallow
     */
    function disallowCollateral(
        address collateralAsset
    ) public onlyRole(COLLATERAL_MANAGER_ROLE) {
        if (!_supportedCollaterals.contains(collateralAsset)) {
            revert CollateralNotSupported(collateralAsset);
        }
        if (_supportedCollaterals.length() <= 1) {
            revert MustSupportAtLeastOneCollateral();
        }
        if (!_supportedCollaterals.remove(collateralAsset)) {
            revert FailedToRemoveCollateral(collateralAsset);
        }

        emit CollateralDisallowed(collateralAsset);
    }

    /**
     * @notice Checks if a given asset is supported as collateral
     * @param collateralAsset The address of the collateral asset to check
     * @return bool True if the asset is supported, false otherwise
     */
    function isCollateralSupported(
        address collateralAsset
    ) public view returns (bool) {
        return _supportedCollaterals.contains(collateralAsset);
    }

    /**
     * @notice Returns a list of all supported collateral assets
     * @return address[] Array of collateral asset addresses
     */
    function listCollateral() public view returns (address[] memory) {
        return _supportedCollaterals.values();
    }

    /**
     * @notice Calculates the total base value of all supported collateral assets in the vault
     * @dev Iterates through all supported collaterals and sums their base values
     * @return uint256 The total value in base
     */
    function _totalValueOfSupportedCollaterals()
        internal
        view
        returns (uint256)
    {
        uint256 totalBaseValue = 0;
        for (uint256 i = 0; i < _supportedCollaterals.length(); i++) {
            address collateral = _supportedCollaterals.at(i);
            uint256 collateralPrice = oracle.getAssetPrice(collateral);
            uint8 collateralDecimals = IERC20Metadata(collateral).decimals();
            uint256 collateralValue = (collateralPrice *
                IERC20Metadata(collateral).balanceOf(address(this))) /
                (10 ** collateralDecimals);
            totalBaseValue += collateralValue;
        }
        return totalBaseValue;
    }
}

// SPDX-License-Identifier: MIT
/* ———————————————————————————————————————————————————————————————————————————————— *
 *    _____     ______   ______     __     __   __     __     ______   __  __       *
 *   /\  __-.  /\__  _\ /\  == \   /\ \   /\ "-.\ \   /\ \   /\__  _\ /\ \_\ \      *
 *   \ \ \/\ \ \/_/\ \/ \ \  __<   \ \ \  \ \ \-.  \  \ \ \  \/_/\ \/ \ \____ \     *
 *    \ \____-    \ \_\  \ \_\ \_\  \ \_\  \ \_\\"\_\  \ \_\    \ \_\  \/\_____\    *
 *     \/____/     \/_/   \/_/ /_/   \/_/   \/_/ \/_/   \/_/     \/_/   \/_____/    *
 *                                                                                  *
 * ————————————————————————————————— dtrinity.org ————————————————————————————————— *
 *                                                                                  *
 *                                         ▲                                        *
 *                                        ▲ ▲                                       *
 *                                                                                  *
 * ———————————————————————————————————————————————————————————————————————————————— *
 * dTRINITY Protocol: https://github.com/dtrinity                                   *
 * ———————————————————————————————————————————————————————————————————————————————— */

pragma solidity ^0.8.20;

import "@openzeppelin/contracts/access/AccessControl.sol";
import "contracts/common/IAaveOracle.sol";

/**
 * @title OracleAware
 * @notice Abstract contract that provides oracle functionality to other contracts
 */
abstract contract OracleAware is AccessControl {
    /* Core state */

    IPriceOracleGetter public oracle;
    uint256 public baseCurrencyUnit;

    /* Events */

    event OracleSet(address indexed newOracle);

    /* Errors */

    error IncorrectBaseCurrencyUnit(uint256 baseCurrencyUnit);

    /**
     * @notice Initializes the contract with an oracle and base currency unit
     * @param initialOracle The initial oracle to use for price feeds
     * @param _baseCurrencyUnit The base currency unit for price calculations
     * @dev Sets up the initial oracle and base currency unit values
     */
    constructor(IPriceOracleGetter initialOracle, uint256 _baseCurrencyUnit) {
        oracle = initialOracle;
        baseCurrencyUnit = _baseCurrencyUnit;

        _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
    }

    /**
     * @notice Sets the oracle to use for collateral valuation
     * @param newOracle The new oracle to use
     */
    function setOracle(
        IPriceOracleGetter newOracle
    ) public onlyRole(DEFAULT_ADMIN_ROLE) {
        if (newOracle.BASE_CURRENCY_UNIT() != baseCurrencyUnit) {
            revert IncorrectBaseCurrencyUnit(baseCurrencyUnit);
        }

        oracle = newOracle;

        emit OracleSet(address(newOracle));
    }

    /**
     * @notice Updates the base currency unit used for price calculations
     * @param _newBaseCurrencyUnit The new base currency unit to set
     * @dev Only used if the oracle's base currency unit changes
     */
    function setBaseCurrencyUnit(
        uint256 _newBaseCurrencyUnit
    ) public onlyRole(DEFAULT_ADMIN_ROLE) {
        baseCurrencyUnit = _newBaseCurrencyUnit;
    }
}

Settings
{
  "evmVersion": "paris",
  "libraries": {},
  "metadata": {
    "bytecodeHash": "ipfs",
    "useLiteralContent": true
  },
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "remappings": [],
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  }
}

Contract Security Audit

Contract ABI

API
[{"inputs":[{"internalType":"address","name":"_collateralVault","type":"address"},{"internalType":"address","name":"_dstable","type":"address"},{"internalType":"contract IPriceOracleGetter","name":"oracle","type":"address"},{"internalType":"address","name":"_amoManager","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":"uint256","name":"baseCurrencyUnit","type":"uint256"}],"name":"IncorrectBaseCurrencyUnit","type":"error"},{"inputs":[{"internalType":"uint256","name":"collateralInDstable","type":"uint256"},{"internalType":"uint256","name":"circulatingDstable","type":"uint256"}],"name":"IssuanceSurpassesExcessCollateral","type":"error"},{"inputs":[{"internalType":"uint256","name":"circulatingDstableBefore","type":"uint256"},{"internalType":"uint256","name":"circulatingDstableAfter","type":"uint256"}],"name":"MintingToAmoShouldNotIncreaseSupply","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[{"internalType":"uint256","name":"minDStable","type":"uint256"},{"internalType":"uint256","name":"dstableAmount","type":"uint256"}],"name":"SlippageTooHigh","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"amoManager","type":"address"}],"name":"AmoManagerSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"collateralVault","type":"address"}],"name":"CollateralVaultSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"newOracle","type":"address"}],"name":"OracleSet","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"},{"inputs":[],"name":"AMO_MANAGER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"BASE_UNIT","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DEFAULT_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"INCENTIVES_MANAGER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"amoManager","outputs":[{"internalType":"contract AmoManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"baseCurrencyUnit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"baseValue","type":"uint256"}],"name":"baseValueToDstableAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"circulatingDstable","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"collateralInDstable","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"collateralVault","outputs":[{"internalType":"contract CollateralVault","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"dstable","outputs":[{"internalType":"contract IMintableERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"dstableDecimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleAdmin","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"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":[{"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":"uint256","name":"dstableAmount","type":"uint256"}],"name":"increaseAmoSupply","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"collateralAmount","type":"uint256"},{"internalType":"address","name":"collateralAsset","type":"address"},{"internalType":"uint256","name":"minDStable","type":"uint256"}],"name":"issue","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"dstableAmount","type":"uint256"}],"name":"issueUsingExcessCollateral","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"oracle","outputs":[{"internalType":"contract IPriceOracleGetter","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"callerConfirmation","type":"address"}],"name":"renounceRole","outputs":[],"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":"address","name":"_amoManager","type":"address"}],"name":"setAmoManager","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_newBaseCurrencyUnit","type":"uint256"}],"name":"setBaseCurrencyUnit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_collateralVault","type":"address"}],"name":"setCollateralVault","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract IPriceOracleGetter","name":"newOracle","type":"address"}],"name":"setOracle","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"}]

0x60c06040523480156200001157600080fd5b5060405162001590380380620015908339810160408190526200003491620003b8565b81826001600160a01b0316638c89b64f6040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000074573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906200009a919062000420565b600180546001600160a01b0319166001600160a01b0384161790556002819055620000c760003362000259565b5050600480546001600160a01b038088166001600160a01b0319928316178355600380549188169190921681179091556040805163313ce56760e01b8152905191935063313ce56792818101926020929091908290030181865afa15801562000134573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906200015a91906200043a565b60ff16608052600580546001600160a01b0319166001600160a01b038381169190911790915560408051638c89b64f60e01b8152905191841691638c89b64f916004808201926020929091908290030181865afa158015620001c0573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620001e6919062000420565b60a052620001f660003362000259565b50620002237fbc4aa291e35c786eceb374be398429586e466107044903c4dff7a8687a5300703362000308565b6200024f7f5e1c59076ed40a2f2d7578e32a78795e357500600174cc5627a8953d155117223362000308565b5050505062000466565b6000828152602081815260408083206001600160a01b038516845290915281205460ff16620002fe576000838152602081815260408083206001600160a01b03861684529091529020805460ff19166001179055620002b53390565b6001600160a01b0316826001600160a01b0316847f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a450600162000302565b5060005b92915050565b600082815260208190526040902060010154620003258162000337565b62000331838362000259565b50505050565b62000343813362000346565b50565b6000828152602081815260408083206001600160a01b038516845290915290205460ff166200039e5760405163e2517d3f60e01b81526001600160a01b03821660048201526024810183905260440160405180910390fd5b5050565b6001600160a01b03811681146200034357600080fd5b60008060008060808587031215620003cf57600080fd5b8451620003dc81620003a2565b6020860151909450620003ef81620003a2565b60408601519093506200040281620003a2565b60608601519092506200041581620003a2565b939692955090935050565b6000602082840312156200043357600080fd5b5051919050565b6000602082840312156200044d57600080fd5b815160ff811681146200045f57600080fd5b9392505050565b60805160a0516110f66200049a600039600081816101eb0152610ad501526000818161024b0152610af901526110f66000f3fe608060405234801561001057600080fd5b506004361061018e5760003560e01c806368a806c4116100de5780639d4cc8d311610097578063d54bc55e11610071578063d54bc55e146103c3578063e797c589146103d6578063f3bddde1146103e9578063f817f7d0146103f257600080fd5b80639d4cc8d314610395578063a217fddf146103a8578063d547741f146103b057600080fd5b806368a806c41461030f5780637adbf973146103225780637dc0d1d01461033557806391d148541461034857806397fe30ef1461035b5780639866f3201461036e57600080fd5b80632abcdf681161014b57806336568abe1161012557806336568abe146102af5780633ffa884c146102c25780634a0bbabb146102d55780635b8862dc146102e857600080fd5b80632abcdf681461027f5780632f2ff15d1461029457806330975247146102a757600080fd5b806301ffc9a7146101935780630bece79c146101bb5780630e962f00146101e657806311c71b3b1461021b578063248a9ca3146102235780632666391114610246575b600080fd5b6101a66101a1366004610e1f565b610405565b60405190151581526020015b60405180910390f35b6004546101ce906001600160a01b031681565b6040516001600160a01b0390911681526020016101b2565b61020d7f000000000000000000000000000000000000000000000000000000000000000081565b6040519081526020016101b2565b61020d61043c565b61020d610231366004610e50565b60009081526020819052604090206001015490565b61026d7f000000000000000000000000000000000000000000000000000000000000000081565b60405160ff90911681526020016101b2565b61029261028d366004610e50565b610544565b005b6102926102a2366004610e7e565b610623565b61020d610648565b6102926102bd366004610e7e565b6106c6565b6102926102d0366004610eae565b6106fe565b6102926102e3366004610e50565b6108b5565b61020d7fbc4aa291e35c786eceb374be398429586e466107044903c4dff7a8687a53007081565b61029261031d366004610ee6565b6108c6565b610292610330366004610ee6565b61091c565b6001546101ce906001600160a01b031681565b6101a6610356366004610e7e565b6109fb565b6003546101ce906001600160a01b031681565b61020d7f5e1c59076ed40a2f2d7578e32a78795e357500600174cc5627a8953d1551172281565b6102926103a3366004610ee6565b610a24565b61020d600081565b6102926103be366004610e7e565b610aac565b61020d6103d1366004610e50565b610ad1565b6102926103e4366004610f03565b610b33565b61020d60025481565b6005546101ce906001600160a01b031681565b60006001600160e01b03198216637965db0b60e01b148061043657506301ffc9a760e01b6001600160e01b03198316145b92915050565b600080600360009054906101000a90046001600160a01b03166001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610492573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104b69190610f2f565b90506000600560009054906101000a90046001600160a01b03166001600160a01b031663773df1516040518163ffffffff1660e01b8152600401602060405180830381865afa15801561050d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105319190610f2f565b905061053d8183610f5e565b9250505090565b7fbc4aa291e35c786eceb374be398429586e466107044903c4dff7a8687a53007061056e81610c0d565b600061057861043c565b6003546005546040516340c10f1960e01b81526001600160a01b0391821660048201526024810187905292935016906340c10f1990604401600060405180830381600087803b1580156105ca57600080fd5b505af11580156105de573d6000803e3d6000fd5b5050505060006105ec61043c565b905081811461061d5760405163353d06cf60e21b815260048101839052602481018290526044015b60405180910390fd5b50505050565b60008281526020819052604090206001015461063e81610c0d565b61061d8383610c1a565b60048054604080516306a61f7560e51b8152905160009384936001600160a01b03169263d4c3eea092818301926020928290030181865afa158015610691573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106b59190610f2f565b90506106c081610ad1565b91505090565b6001600160a01b03811633146106ef5760405163334bd91960e11b815260040160405180910390fd5b6106f98282610cac565b505050565b6000826001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa15801561073e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107629190610f71565b9050600061077182600a611078565b60015460405163b3596f0760e01b81526001600160a01b0387811660048301528892169063b3596f0790602401602060405180830381865afa1580156107bb573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107df9190610f2f565b6107e99190611087565b6107f3919061109e565b9050600061080082610ad1565b90508381101561082d57604051633b5d56ed60e11b81526004810185905260248101829052604401610614565b600454610849906001600160a01b038781169133911689610d17565b6003546040516340c10f1960e01b8152336004820152602481018390526001600160a01b03909116906340c10f1990604401600060405180830381600087803b15801561089557600080fd5b505af11580156108a9573d6000803e3d6000fd5b50505050505050505050565b60006108c081610c0d565b50600255565b60006108d181610c0d565b600480546001600160a01b0319166001600160a01b0384169081179091556040517fc92ec24b34ad9d3aa14cd5be87b888d7790d40903da5f44c6367b2fb6cdb208390600090a25050565b600061092781610c0d565b600254826001600160a01b0316638c89b64f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610968573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061098c9190610f2f565b146109b057600254604051639b6812b960e01b815260040161061491815260200190565b600180546001600160a01b0319166001600160a01b0384169081179091556040517f3f32684a32a11dabdbb8c0177de80aa3ae36a004d75210335b49e544e48cd0aa90600090a25050565b6000918252602082815260408084206001600160a01b0393909316845291905290205460ff1690565b6000610a2f81610c0d565b600580546001600160a01b0319166001600160a01b038416179055610a747fbc4aa291e35c786eceb374be398429586e466107044903c4dff7a8687a53007083610623565b6040516001600160a01b038316907fc1ed2a2e76938d5535836b1406331936bd2440c622b1314c8459f98a5065577b90600090a25050565b600082815260208190526040902060010154610ac781610c0d565b61061d8383610cac565b60007f0000000000000000000000000000000000000000000000000000000000000000610b1f7f0000000000000000000000000000000000000000000000000000000000000000600a611078565b610b299084611087565b610436919061109e565b7f5e1c59076ed40a2f2d7578e32a78795e357500600174cc5627a8953d15511722610b5d81610c0d565b6003546040516340c10f1960e01b81526001600160a01b03858116600483015260248201859052909116906340c10f1990604401600060405180830381600087803b158015610bab57600080fd5b505af1158015610bbf573d6000803e3d6000fd5b505050506000610bcd61043c565b90506000610bd9610648565b905081811015610c06576040516379f1a2a760e01b81526004810182905260248101839052604401610614565b5050505050565b610c178133610d71565b50565b6000610c2683836109fb565b610ca4576000838152602081815260408083206001600160a01b03861684529091529020805460ff19166001179055610c5c3390565b6001600160a01b0316826001600160a01b0316847f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a4506001610436565b506000610436565b6000610cb883836109fb565b15610ca4576000838152602081815260408083206001600160a01b0386168085529252808320805460ff1916905551339286917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a4506001610436565b604080516001600160a01b0385811660248301528416604482015260648082018490528251808303909101815260849091019091526020810180516001600160e01b03166323b872dd60e01b17905261061d908590610dae565b610d7b82826109fb565b610daa5760405163e2517d3f60e01b81526001600160a01b038216600482015260248101839052604401610614565b5050565b600080602060008451602086016000885af180610dd1576040513d6000823e3d81fd5b50506000513d91508115610de9578060011415610df6565b6001600160a01b0384163b155b1561061d57604051635274afe760e01b81526001600160a01b0385166004820152602401610614565b600060208284031215610e3157600080fd5b81356001600160e01b031981168114610e4957600080fd5b9392505050565b600060208284031215610e6257600080fd5b5035919050565b6001600160a01b0381168114610c1757600080fd5b60008060408385031215610e9157600080fd5b823591506020830135610ea381610e69565b809150509250929050565b600080600060608486031215610ec357600080fd5b833592506020840135610ed581610e69565b929592945050506040919091013590565b600060208284031215610ef857600080fd5b8135610e4981610e69565b60008060408385031215610f1657600080fd5b8235610f2181610e69565b946020939093013593505050565b600060208284031215610f4157600080fd5b5051919050565b634e487b7160e01b600052601160045260246000fd5b8181038181111561043657610436610f48565b600060208284031215610f8357600080fd5b815160ff81168114610e4957600080fd5b600181815b80851115610fcf578160001904821115610fb557610fb5610f48565b80851615610fc257918102915b93841c9390800290610f99565b509250929050565b600082610fe657506001610436565b81610ff357506000610436565b816001811461100957600281146110135761102f565b6001915050610436565b60ff84111561102457611024610f48565b50506001821b610436565b5060208310610133831016604e8410600b8410161715611052575081810a610436565b61105c8383610f94565b806000190482111561107057611070610f48565b029392505050565b6000610e4960ff841683610fd7565b808202811582820484141761043657610436610f48565b6000826110bb57634e487b7160e01b600052601260045260246000fd5b50049056fea264697066735822122076984262299da1f60137cc443c88029979c18dbc76162639506e1c1cb0bedfa964736f6c63430008140033000000000000000000000000d6bbab428240c6a4e093e13802f2eca3e9f0de7d00000000000000000000000053a6abb52b2f968fa80df6a894e4f1b1020da9750000000000000000000000001295a55d482257ecd66ba8846eab6849712c3a9c0000000000000000000000000346e3770fba1fa6b041aae9b7fd5070bd46973c

Deployed Bytecode

0x608060405234801561001057600080fd5b506004361061018e5760003560e01c806368a806c4116100de5780639d4cc8d311610097578063d54bc55e11610071578063d54bc55e146103c3578063e797c589146103d6578063f3bddde1146103e9578063f817f7d0146103f257600080fd5b80639d4cc8d314610395578063a217fddf146103a8578063d547741f146103b057600080fd5b806368a806c41461030f5780637adbf973146103225780637dc0d1d01461033557806391d148541461034857806397fe30ef1461035b5780639866f3201461036e57600080fd5b80632abcdf681161014b57806336568abe1161012557806336568abe146102af5780633ffa884c146102c25780634a0bbabb146102d55780635b8862dc146102e857600080fd5b80632abcdf681461027f5780632f2ff15d1461029457806330975247146102a757600080fd5b806301ffc9a7146101935780630bece79c146101bb5780630e962f00146101e657806311c71b3b1461021b578063248a9ca3146102235780632666391114610246575b600080fd5b6101a66101a1366004610e1f565b610405565b60405190151581526020015b60405180910390f35b6004546101ce906001600160a01b031681565b6040516001600160a01b0390911681526020016101b2565b61020d7f0000000000000000000000000000000000000000000000000de0b6b3a764000081565b6040519081526020016101b2565b61020d61043c565b61020d610231366004610e50565b60009081526020819052604090206001015490565b61026d7f000000000000000000000000000000000000000000000000000000000000001281565b60405160ff90911681526020016101b2565b61029261028d366004610e50565b610544565b005b6102926102a2366004610e7e565b610623565b61020d610648565b6102926102bd366004610e7e565b6106c6565b6102926102d0366004610eae565b6106fe565b6102926102e3366004610e50565b6108b5565b61020d7fbc4aa291e35c786eceb374be398429586e466107044903c4dff7a8687a53007081565b61029261031d366004610ee6565b6108c6565b610292610330366004610ee6565b61091c565b6001546101ce906001600160a01b031681565b6101a6610356366004610e7e565b6109fb565b6003546101ce906001600160a01b031681565b61020d7f5e1c59076ed40a2f2d7578e32a78795e357500600174cc5627a8953d1551172281565b6102926103a3366004610ee6565b610a24565b61020d600081565b6102926103be366004610e7e565b610aac565b61020d6103d1366004610e50565b610ad1565b6102926103e4366004610f03565b610b33565b61020d60025481565b6005546101ce906001600160a01b031681565b60006001600160e01b03198216637965db0b60e01b148061043657506301ffc9a760e01b6001600160e01b03198316145b92915050565b600080600360009054906101000a90046001600160a01b03166001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610492573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104b69190610f2f565b90506000600560009054906101000a90046001600160a01b03166001600160a01b031663773df1516040518163ffffffff1660e01b8152600401602060405180830381865afa15801561050d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105319190610f2f565b905061053d8183610f5e565b9250505090565b7fbc4aa291e35c786eceb374be398429586e466107044903c4dff7a8687a53007061056e81610c0d565b600061057861043c565b6003546005546040516340c10f1960e01b81526001600160a01b0391821660048201526024810187905292935016906340c10f1990604401600060405180830381600087803b1580156105ca57600080fd5b505af11580156105de573d6000803e3d6000fd5b5050505060006105ec61043c565b905081811461061d5760405163353d06cf60e21b815260048101839052602481018290526044015b60405180910390fd5b50505050565b60008281526020819052604090206001015461063e81610c0d565b61061d8383610c1a565b60048054604080516306a61f7560e51b8152905160009384936001600160a01b03169263d4c3eea092818301926020928290030181865afa158015610691573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106b59190610f2f565b90506106c081610ad1565b91505090565b6001600160a01b03811633146106ef5760405163334bd91960e11b815260040160405180910390fd5b6106f98282610cac565b505050565b6000826001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa15801561073e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107629190610f71565b9050600061077182600a611078565b60015460405163b3596f0760e01b81526001600160a01b0387811660048301528892169063b3596f0790602401602060405180830381865afa1580156107bb573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107df9190610f2f565b6107e99190611087565b6107f3919061109e565b9050600061080082610ad1565b90508381101561082d57604051633b5d56ed60e11b81526004810185905260248101829052604401610614565b600454610849906001600160a01b038781169133911689610d17565b6003546040516340c10f1960e01b8152336004820152602481018390526001600160a01b03909116906340c10f1990604401600060405180830381600087803b15801561089557600080fd5b505af11580156108a9573d6000803e3d6000fd5b50505050505050505050565b60006108c081610c0d565b50600255565b60006108d181610c0d565b600480546001600160a01b0319166001600160a01b0384169081179091556040517fc92ec24b34ad9d3aa14cd5be87b888d7790d40903da5f44c6367b2fb6cdb208390600090a25050565b600061092781610c0d565b600254826001600160a01b0316638c89b64f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610968573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061098c9190610f2f565b146109b057600254604051639b6812b960e01b815260040161061491815260200190565b600180546001600160a01b0319166001600160a01b0384169081179091556040517f3f32684a32a11dabdbb8c0177de80aa3ae36a004d75210335b49e544e48cd0aa90600090a25050565b6000918252602082815260408084206001600160a01b0393909316845291905290205460ff1690565b6000610a2f81610c0d565b600580546001600160a01b0319166001600160a01b038416179055610a747fbc4aa291e35c786eceb374be398429586e466107044903c4dff7a8687a53007083610623565b6040516001600160a01b038316907fc1ed2a2e76938d5535836b1406331936bd2440c622b1314c8459f98a5065577b90600090a25050565b600082815260208190526040902060010154610ac781610c0d565b61061d8383610cac565b60007f0000000000000000000000000000000000000000000000000de0b6b3a7640000610b1f7f0000000000000000000000000000000000000000000000000000000000000012600a611078565b610b299084611087565b610436919061109e565b7f5e1c59076ed40a2f2d7578e32a78795e357500600174cc5627a8953d15511722610b5d81610c0d565b6003546040516340c10f1960e01b81526001600160a01b03858116600483015260248201859052909116906340c10f1990604401600060405180830381600087803b158015610bab57600080fd5b505af1158015610bbf573d6000803e3d6000fd5b505050506000610bcd61043c565b90506000610bd9610648565b905081811015610c06576040516379f1a2a760e01b81526004810182905260248101839052604401610614565b5050505050565b610c178133610d71565b50565b6000610c2683836109fb565b610ca4576000838152602081815260408083206001600160a01b03861684529091529020805460ff19166001179055610c5c3390565b6001600160a01b0316826001600160a01b0316847f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a4506001610436565b506000610436565b6000610cb883836109fb565b15610ca4576000838152602081815260408083206001600160a01b0386168085529252808320805460ff1916905551339286917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a4506001610436565b604080516001600160a01b0385811660248301528416604482015260648082018490528251808303909101815260849091019091526020810180516001600160e01b03166323b872dd60e01b17905261061d908590610dae565b610d7b82826109fb565b610daa5760405163e2517d3f60e01b81526001600160a01b038216600482015260248101839052604401610614565b5050565b600080602060008451602086016000885af180610dd1576040513d6000823e3d81fd5b50506000513d91508115610de9578060011415610df6565b6001600160a01b0384163b155b1561061d57604051635274afe760e01b81526001600160a01b0385166004820152602401610614565b600060208284031215610e3157600080fd5b81356001600160e01b031981168114610e4957600080fd5b9392505050565b600060208284031215610e6257600080fd5b5035919050565b6001600160a01b0381168114610c1757600080fd5b60008060408385031215610e9157600080fd5b823591506020830135610ea381610e69565b809150509250929050565b600080600060608486031215610ec357600080fd5b833592506020840135610ed581610e69565b929592945050506040919091013590565b600060208284031215610ef857600080fd5b8135610e4981610e69565b60008060408385031215610f1657600080fd5b8235610f2181610e69565b946020939093013593505050565b600060208284031215610f4157600080fd5b5051919050565b634e487b7160e01b600052601160045260246000fd5b8181038181111561043657610436610f48565b600060208284031215610f8357600080fd5b815160ff81168114610e4957600080fd5b600181815b80851115610fcf578160001904821115610fb557610fb5610f48565b80851615610fc257918102915b93841c9390800290610f99565b509250929050565b600082610fe657506001610436565b81610ff357506000610436565b816001811461100957600281146110135761102f565b6001915050610436565b60ff84111561102457611024610f48565b50506001821b610436565b5060208310610133831016604e8410600b8410161715611052575081810a610436565b61105c8383610f94565b806000190482111561107057611070610f48565b029392505050565b6000610e4960ff841683610fd7565b808202811582820484141761043657610436610f48565b6000826110bb57634e487b7160e01b600052601260045260246000fd5b50049056fea264697066735822122076984262299da1f60137cc443c88029979c18dbc76162639506e1c1cb0bedfa964736f6c63430008140033

Block Transaction Gas Used Reward
view all blocks ##produced##

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading
Loading...
Loading

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
Loading...
Loading
[ Download: CSV Export  ]

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.