ETH Price: $1,926.27 (-3.13%)
 

Overview

ETH Balance

0 ETH

Eth Value

$0.00

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To
Grant Role241128132025-12-28 18:06:1160 days ago1766945171IN
0x253d0C04...036E032A9
0 ETH0.000001440.0280298
Grant Role241111012025-12-28 12:22:3561 days ago1766924555IN
0x253d0C04...036E032A9
0 ETH0.00000150.02914617
Grant Role241111002025-12-28 12:22:2361 days ago1766924543IN
0x253d0C04...036E032A9
0 ETH0.00000150.02909366
Grant Role241110992025-12-28 12:22:1161 days ago1766924531IN
0x253d0C04...036E032A9
0 ETH0.000001550.03006574
Grant Role241110982025-12-28 12:21:5961 days ago1766924519IN
0x253d0C04...036E032A9
0 ETH0.000001370.02659866
Grant Role241110972025-12-28 12:21:4761 days ago1766924507IN
0x253d0C04...036E032A9
0 ETH0.00000140.02721481
Grant Role241110882025-12-28 12:19:5961 days ago1766924399IN
0x253d0C04...036E032A9
0 ETH0.000000850.02913286
Grant Role241109632025-12-28 11:54:5961 days ago1766922899IN
0x253d0C04...036E032A9
0 ETH0.000001640.03181555
Grant Role241109622025-12-28 11:54:4761 days ago1766922887IN
0x253d0C04...036E032A9
0 ETH0.00000150.02915988
Grant Role241109602025-12-28 11:54:2361 days ago1766922863IN
0x253d0C04...036E032A9
0 ETH0.000001430.02782699
Initialize241108402025-12-28 11:30:2361 days ago1766921423IN
0x253d0C04...036E032A9
0 ETH0.000001980.02783157

View more zero value Internal Transactions in Advanced View mode

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

Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
ProtocolTreasury

Compiler Version
v0.8.26+commit.8a97fa7a

Optimization Enabled:
Yes with 200 runs

Other Settings:
cancun EvmVersion
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.26;

import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

import { IHarvesterCallback } from "./interfaces/IHarvesterCallback.sol";

import { PermissionedSwap } from "../common/utils/PermissionedSwap.sol";
import { PegKeeper } from "../core/PegKeeper.sol";

contract ProtocolTreasury is PermissionedSwap {
  using SafeERC20 for IERC20;

  /**********
   * Errors *
   **********/

  /// @dev Thrown when the multicall fails.
  error ErrorMulticallFailed();

  /*************
   * Constants *
   *************/

  /// @notice The role for permissioned multicall.
  bytes32 public constant MULTICALL_ROLE = keccak256("MULTICALL_ROLE");

  /// @notice The role for permissioned batch transfer.
  bytes32 public constant BATCH_TRANSFER_ROLE = keccak256("BATCH_TRANSFER_ROLE");

  /// @notice The role for permissioned token receiver.
  bytes32 public constant TOKEN_RECEIVER_ROLE = keccak256("TOKEN_RECEIVER_ROLE");

  /// @notice The role for permissioned peg keeper.
  bytes32 public constant PEG_KEEPER_ROLE = keccak256("PEG_KEEPER_ROLE");

  /// @notice The role for buyback.
  bytes32 public constant BUYBACK_ROLE = keccak256("BUYBACK_ROLE");

  /// @notice The role for stabilize.
  bytes32 public constant STABILIZE_ROLE = keccak256("STABILIZE_ROLE");

  /***************
   * Constructor *
   ***************/

  function initialize(address _admin) external initializer {
    __Context_init();
    __ERC165_init();
    __AccessControl_init();

    _grantRole(DEFAULT_ADMIN_ROLE, _admin);
  }

  /****************************
   * Public Mutated Functions *
   ****************************/

  /// @notice Multicall function to call multiple functions in a single transaction.
  /// @param targets The addresses of the contracts to call.
  /// @param data The data to call the functions with.
  function multicall(address[] calldata targets, bytes[] calldata data) external onlyRole(MULTICALL_ROLE) {
    for (uint256 i = 0; i < targets.length; i++) {
      (bool success, ) = targets[i].call(data[i]);
      if (!success) revert ErrorMulticallFailed();
    }
  }

  /// @notice Batch transfer tokens to the receiver.
  /// @param token The address of the token to transfer.
  /// @param receivers The addresses of the receivers to transfer.
  /// @param amounts The amounts of the tokens to transfer.
  function batchTransfer(
    address token,
    address[] calldata receivers,
    uint256[] calldata amounts
  ) external onlyRole(BATCH_TRANSFER_ROLE) {
    for (uint256 i = 0; i < receivers.length; i++) {
      _checkRole(TOKEN_RECEIVER_ROLE, receivers[i]);
      IERC20(token).safeTransfer(receivers[i], amounts[i]);
    }
  }

  /// @notice Buyback fxUSD with stable reserve in FxUSDSave.
  /// @param pegKeeper The address of peg keeper.
  /// @param amountIn The amount of stable token to use.
  /// @param data The hook data to `onSwap`.
  /// @return amountOut The amount of fxUSD swapped.
  /// @return bonus The amount of bonus fxUSD.
  function buyback(
    address pegKeeper,
    uint256 amountIn,
    bytes calldata data
  ) external onlyRole(BUYBACK_ROLE) returns (uint256 amountOut, uint256 bonus) {
    (amountOut, bonus) = PegKeeper(pegKeeper).buyback(amountIn, data);
  }

  /// @notice Stabilize the fxUSD price in curve pool.
  /// @param pegKeeper The address of peg keeper.
  /// @param srcToken The address of source token (fxUSD or stable token).
  /// @param amountIn The amount of source token to use.
  /// @param data The hook data to `onSwap`.
  /// @return amountOut The amount of target token swapped.
  /// @return bonus The amount of bonus token.
  function stabilize(
    address pegKeeper,
    address srcToken,
    uint256 amountIn,
    bytes calldata data
  ) external onlyRole(STABILIZE_ROLE) returns (uint256 amountOut, uint256 bonus) {
    (amountOut, bonus) = PegKeeper(pegKeeper).stabilize(srcToken, amountIn, data);
  }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/AccessControl.sol)

pragma solidity ^0.8.20;

import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {ERC165Upgradeable} from "../utils/introspection/ERC165Upgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```solidity
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```solidity
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
 * to enforce additional security measures for this role.
 */
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControl, ERC165Upgradeable {
    struct RoleData {
        mapping(address account => bool) hasRole;
        bytes32 adminRole;
    }

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;


    /// @custom:storage-location erc7201:openzeppelin.storage.AccessControl
    struct AccessControlStorage {
        mapping(bytes32 role => RoleData) _roles;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControl")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800;

    function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) {
        assembly {
            $.slot := AccessControlStorageLocation
        }
    }

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with an {AccessControlUnauthorizedAccount} error including the required role.
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

    function __AccessControl_init() internal onlyInitializing {
    }

    function __AccessControl_init_unchained() internal onlyInitializing {
    }
    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual returns (bool) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        return $._roles[role].hasRole[account];
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
     * is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
     * is missing `role`.
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert AccessControlUnauthorizedAccount(account, role);
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        return $._roles[role].adminRole;
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleGranted} event.
     */
    function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleRevoked} event.
     */
    function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _revokeRole(role, account);
    }

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address callerConfirmation) public virtual {
        if (callerConfirmation != _msgSender()) {
            revert AccessControlBadConfirmation();
        }

        _revokeRole(role, callerConfirmation);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        AccessControlStorage storage $ = _getAccessControlStorage();
        bytes32 previousAdminRole = getRoleAdmin(role);
        $._roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        if (!hasRole(role, account)) {
            $._roles[role].hasRole[account] = true;
            emit RoleGranted(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Attempts to revoke `role` from `account` and returns a boolean indicating if `role` was revoked.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        if (hasRole(role, account)) {
            $._roles[role].hasRole[account] = false;
            emit RoleRevoked(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Storage of the initializable contract.
     *
     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
     * when using with upgradeable contracts.
     *
     * @custom:storage-location erc7201:openzeppelin.storage.Initializable
     */
    struct InitializableStorage {
        /**
         * @dev Indicates that the contract has been initialized.
         */
        uint64 _initialized;
        /**
         * @dev Indicates that the contract is in the process of being initialized.
         */
        bool _initializing;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;

    /**
     * @dev The contract is already initialized.
     */
    error InvalidInitialization();

    /**
     * @dev The contract is not initializing.
     */
    error NotInitializing();

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint64 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
     * production.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        // Cache values to avoid duplicated sloads
        bool isTopLevelCall = !$._initializing;
        uint64 initialized = $._initialized;

        // Allowed calls:
        // - initialSetup: the contract is not in the initializing state and no previous version was
        //                 initialized
        // - construction: the contract is initialized at version 1 (no reinitialization) and the
        //                 current contract is just being deployed
        bool initialSetup = initialized == 0 && isTopLevelCall;
        bool construction = initialized == 1 && address(this).code.length == 0;

        if (!initialSetup && !construction) {
            revert InvalidInitialization();
        }
        $._initialized = 1;
        if (isTopLevelCall) {
            $._initializing = true;
        }
        _;
        if (isTopLevelCall) {
            $._initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint64 version) {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing || $._initialized >= version) {
            revert InvalidInitialization();
        }
        $._initialized = version;
        $._initializing = true;
        _;
        $._initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        _checkInitializing();
        _;
    }

    /**
     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
     */
    function _checkInitializing() internal view virtual {
        if (!_isInitializing()) {
            revert NotInitializing();
        }
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing) {
            revert InvalidInitialization();
        }
        if ($._initialized != type(uint64).max) {
            $._initialized = type(uint64).max;
            emit Initialized(type(uint64).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint64) {
        return _getInitializableStorage()._initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _getInitializableStorage()._initializing;
    }

    /**
     * @dev Pointer to storage slot. Allows integrators to override it with a custom storage location.
     *
     * NOTE: Consider following the ERC-7201 formula to derive storage locations.
     */
    function _initializableStorageSlot() internal pure virtual returns (bytes32) {
        return INITIALIZABLE_STORAGE;
    }

    /**
     * @dev Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        bytes32 slot = _initializableStorageSlot();
        assembly {
            $.slot := slot
        }
    }
}

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

pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract ContextUpgradeable is Initializable {
    function __Context_init() internal onlyInitializing {
    }

    function __Context_init_unchained() internal onlyInitializing {
    }
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/ERC165.sol)

pragma solidity ^0.8.20;

import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement 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 ERC165Upgradeable is Initializable, IERC165 {
    function __ERC165_init() internal onlyInitializing {
    }

    function __ERC165_init_unchained() internal onlyInitializing {
    }
    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/IAccessControl.sol)

pragma solidity >=0.8.4;

/**
 * @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 to signal 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.4.0) (interfaces/IERC1363.sol)

pragma solidity >=0.6.2;

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 8 of 20 : IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)

pragma solidity >=0.4.16;

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

File 9 of 20 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)

pragma solidity >=0.4.16;

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

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

pragma solidity >=0.4.16;

/**
 * @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.3.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 Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(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.4.0) (utils/introspection/IERC165.sol)

pragma solidity >=0.4.16;

/**
 * @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);
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import { AccessControlUpgradeable } from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

// solhint-disable avoid-low-level-calls
// solhint-disable no-inline-assembly

abstract contract PermissionedSwap is AccessControlUpgradeable {
  using SafeERC20 for IERC20;

  /**********
   * Errors *
   **********/

  /// @dev Thrown when the amount of output token is not enough.
  error InsufficientOutputToken();

  /*************
   * Constants *
   *************/

  /// @notice The role for permissioned trader.
  bytes32 public constant PERMISSIONED_TRADER_ROLE = keccak256("PERMISSIONED_TRADER_ROLE");

  /// @notice The role for permissioned trading router.
  bytes32 public constant PERMISSIONED_ROUTER_ROLE = keccak256("PERMISSIONED_ROUTER_ROLE");

  /***********
   * Structs *
   ***********/

  /// @notice The struct for trading parameters.
  ///
  /// @param router The address of trading router.
  /// @param data The calldata passing to the router contract.
  /// @param minOut The minimum amount of output token should receive.
  struct TradingParameter {
    address router;
    bytes data;
    uint256 minOut;
  }

  /*************
   * Variables *
   *************/

  /// @dev reserved slots.
  uint256[50] private __gap;

  /****************************
   * Public Mutated Functions *
   ****************************/

  /// @notice Swap token with permissioned router.
  /// @param srcToken The address of source token.
  /// @param dstToken The address of destination token.
  /// @param amountIn The amount of input token.
  /// @param params The token converting parameters.
  /// @return amountOut The amount of output token received.
  function swap(
    address srcToken,
    address dstToken,
    uint256 amountIn,
    TradingParameter memory params
  ) external returns (uint256 amountOut) {
    amountOut = _doTrade(srcToken, dstToken, amountIn, params);
  }

  /************************
   * Restricted Functions *
   ************************/

  /// @notice Withdraw base token to someone else.
  /// @dev This should be only used when we are retiring this contract.
  /// @param baseToken The address of base token.
  function withdraw(address baseToken, address recipient) external onlyRole(DEFAULT_ADMIN_ROLE) {
    uint256 amountIn = IERC20(baseToken).balanceOf(address(this));
    IERC20(baseToken).safeTransfer(recipient, amountIn);
  }

  /**********************
   * Internal Functions *
   **********************/

  /// @dev Internal function to convert token with routes.
  /// @param srcToken The address of source token.
  /// @param dstToken The address of destination token.
  /// @param amountIn The amount of input token.
  /// @param params The token converting parameters.
  /// @return amountOut The amount of output token received.
  function _doTrade(
    address srcToken,
    address dstToken,
    uint256 amountIn,
    TradingParameter memory params
  ) internal virtual onlyRole(PERMISSIONED_TRADER_ROLE) returns (uint256 amountOut) {
    if (srcToken == dstToken) return amountIn;

    // router should be permissioned
    _checkRole(PERMISSIONED_ROUTER_ROLE, params.router);

    // approve to router
    IERC20(srcToken).forceApprove(params.router, amountIn);

    // do trading
    amountOut = IERC20(dstToken).balanceOf(address(this));
    (bool success, ) = params.router.call(params.data);
    if (!success) {
      // below lines will propagate inner error up
      assembly {
        let ptr := mload(0x40)
        let size := returndatasize()
        returndatacopy(ptr, 0, size)
        revert(ptr, size)
      }
    }

    amountOut = IERC20(dstToken).balanceOf(address(this)) - amountOut;
    if (amountOut < params.minOut) {
      revert InsufficientOutputToken();
    }
  }
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.26;

import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

import { AccessControlUpgradeable } from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";

import { IMultiPathConverter } from "../helpers/interfaces/IMultiPathConverter.sol";
import { ICurveStableSwapNG } from "../interfaces/Curve/ICurveStableSwapNG.sol";
import { IFxUSDRegeneracy } from "../interfaces/IFxUSDRegeneracy.sol";
import { IPegKeeper } from "../interfaces/IPegKeeper.sol";
import { IFxUSDBasePool } from "../interfaces/IFxUSDBasePool.sol";

contract PegKeeper is AccessControlUpgradeable, IPegKeeper {
  using SafeERC20 for IERC20;

  /**********
   * Errors *
   **********/

  error ErrorNotInCallbackContext();

  error ErrorZeroAddress();

  error ErrorInsufficientOutput();

  /*************
   * Constants *
   *************/

  /// @dev The precision used to compute nav.
  uint256 private constant PRECISION = 1e18;

  /// @notice The role for buyback.
  bytes32 public constant BUYBACK_ROLE = keccak256("BUYBACK_ROLE");

  /// @notice The role for stabilize.
  bytes32 public constant STABILIZE_ROLE = keccak256("STABILIZE_ROLE");

  /// @dev contexts for buyback and stabilize callback
  uint8 private constant CONTEXT_NO_CONTEXT = 1;
  uint8 private constant CONTEXT_BUYBACK = 2;
  uint8 private constant CONTEXT_STABILIZE = 3;

  /***********************
   * Immutable Variables *
   ***********************/

  /// @notice The address of fxUSD.
  address public immutable fxUSD;

  /// @notice The address of stable token.
  address public immutable stable;

  /// @notice The address of FxUSDBasePool.
  address public immutable fxBASE;

  /*********************
   * Storage Variables *
   *********************/

  /// @dev The context for buyback and stabilize callback.
  uint8 private context;

  /// @notice The address of MultiPathConverter.
  address public converter;

  /// @notice The curve pool for stable and fxUSD
  address public curvePool;

  /// @notice The fxUSD depeg price threshold.
  uint256 public priceThreshold;

  /*************
   * Modifiers *
   *************/

  modifier setContext(uint8 c) {
    context = c;
    _;
    context = CONTEXT_NO_CONTEXT;
  }

  /***************
   * Constructor *
   ***************/

  constructor(address _fxBASE) {
    fxBASE = _fxBASE;
    fxUSD = IFxUSDBasePool(_fxBASE).yieldToken();
    stable = IFxUSDBasePool(_fxBASE).stableToken();
  }

  function initialize(address admin, address _converter, address _curvePool) external initializer {
    __Context_init();
    __ERC165_init();
    __AccessControl_init();

    _grantRole(DEFAULT_ADMIN_ROLE, admin);

    _updateConverter(_converter);
    _updateCurvePool(_curvePool);
    _updatePriceThreshold(995000000000000000); // 0.995

    context = CONTEXT_NO_CONTEXT;
  }

  /*************************
   * Public View Functions *
   *************************/

  /// @inheritdoc IPegKeeper
  function isBorrowAllowed() external view returns (bool) {
    return _getFxUSDEmaPrice() >= priceThreshold;
  }

  /// @inheritdoc IPegKeeper
  function isFundingEnabled() external view returns (bool) {
    return _getFxUSDEmaPrice() < priceThreshold;
  }

  /// @inheritdoc IPegKeeper
  function isRedeemAllowed() external view returns (bool) {
    return _getFxUSDEmaPrice() < priceThreshold;
  }

  /// @inheritdoc IPegKeeper
  function getFxUSDPrice() external view returns (uint256) {
    return _getFxUSDEmaPrice();
  }

  /****************************
   * Public Mutated Functions *
   ****************************/

  /// @inheritdoc IPegKeeper
  function buyback(
    uint256 amountIn,
    bytes calldata data
  ) external onlyRole(BUYBACK_ROLE) setContext(CONTEXT_BUYBACK) returns (uint256 amountOut, uint256 bonus) {
    (amountOut, bonus) = IFxUSDRegeneracy(fxUSD).buyback(amountIn, _msgSender(), data);
  }

  /// @inheritdoc IPegKeeper
  function stabilize(
    address srcToken,
    uint256 amountIn,
    bytes calldata data
  ) external onlyRole(STABILIZE_ROLE) setContext(CONTEXT_STABILIZE) returns (uint256 amountOut, uint256 bonus) {
    (amountOut, bonus) = IFxUSDBasePool(fxBASE).arbitrage(srcToken, amountIn, _msgSender(), data);
  }

  /// @inheritdoc IPegKeeper
  /// @dev This function will be called in `buyback`, `stabilize`.
  function onSwap(
    address srcToken,
    address targetToken,
    uint256 amountIn,
    bytes calldata data
  ) external returns (uint256 amountOut) {
    // check callback validity
    if (context == CONTEXT_NO_CONTEXT) revert ErrorNotInCallbackContext();

    amountOut = _doSwap(srcToken, amountIn, data);
    IERC20(targetToken).safeTransfer(_msgSender(), amountOut);
  }

  /************************
   * Restricted Functions *
   ************************/

  /// @notice Update the address of converter.
  /// @param newConverter The address of converter.
  function updateConverter(address newConverter) external onlyRole(DEFAULT_ADMIN_ROLE) {
    _updateConverter(newConverter);
  }

  /// @notice Update the address of curve pool.
  /// @param newPool The address of curve pool.
  function updateCurvePool(address newPool) external onlyRole(DEFAULT_ADMIN_ROLE) {
    _updateCurvePool(newPool);
  }

  /// @notice Update the value of depeg price threshold.
  /// @param newThreshold The value of new price threshold.
  function updatePriceThreshold(uint256 newThreshold) external onlyRole(DEFAULT_ADMIN_ROLE) {
    _updatePriceThreshold(newThreshold);
  }

  /**********************
   * Internal Functions *
   **********************/

  /// @dev Internal function to update the address of converter.
  /// @param newConverter The address of converter.
  function _updateConverter(address newConverter) internal {
    if (newConverter == address(0)) revert ErrorZeroAddress();

    address oldConverter = converter;
    converter = newConverter;

    emit UpdateConverter(oldConverter, newConverter);
  }

  /// @dev Internal function to update the address of curve pool.
  /// @param newPool The address of curve pool.
  function _updateCurvePool(address newPool) internal {
    if (newPool == address(0)) revert ErrorZeroAddress();

    address oldPool = curvePool;
    curvePool = newPool;

    emit UpdateCurvePool(oldPool, newPool);
  }

  /// @dev Internal function to update the value of depeg price threshold.
  /// @param newThreshold The value of new price threshold.
  function _updatePriceThreshold(uint256 newThreshold) internal {
    uint256 oldThreshold = priceThreshold;
    priceThreshold = newThreshold;

    emit UpdatePriceThreshold(oldThreshold, newThreshold);
  }

  /// @dev Internal function to do swap.
  /// @param srcToken The address of source token.
  /// @param amountIn The amount of token to use.
  /// @param data The callback data.
  /// @return amountOut The amount of token swapped.
  function _doSwap(address srcToken, uint256 amountIn, bytes calldata data) internal returns (uint256 amountOut) {
    IERC20(srcToken).forceApprove(converter, amountIn);

    (uint256 minOut, uint256 encoding, uint256[] memory routes) = abi.decode(data, (uint256, uint256, uint256[]));
    amountOut = IMultiPathConverter(converter).convert(srcToken, amountIn, encoding, routes);
    if (amountOut < minOut) revert ErrorInsufficientOutput();
  }

  /// @dev Internal function to get curve ema price for fxUSD.
  /// @return price The value of ema price, multiplied by 1e18.
  function _getFxUSDEmaPrice() internal view returns (uint256 price) {
    address cachedCurvePool = curvePool; // gas saving
    address firstCoin = ICurveStableSwapNG(cachedCurvePool).coins(0);
    price = ICurveStableSwapNG(cachedCurvePool).price_oracle(0);
    if (firstCoin == fxUSD) {
      price = (PRECISION * PRECISION) / price;
    }
  }
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface IHarvesterCallback {
  /// @notice Hook function to handle harvested rewards.
  /// @param token The address of token.
  /// @param amount The amount of tokens.
  function onHarvest(address token, uint256 amount) external;
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface IMultiPathConverter {
  function queryConvert(
    uint256 _amount,
    uint256 _encoding,
    uint256[] calldata _routes
  ) external returns (uint256 amountOut);

  function convert(
    address _tokenIn,
    uint256 _amount,
    uint256 _encoding,
    uint256[] calldata _routes
  ) external payable returns (uint256 amountOut);
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface ICurveStableSwapNG {
  /*************************
   * Public View Functions *
   *************************/

  function coins(uint256 index) external view returns (address);

  function last_price(uint256 index) external view returns (uint256);

  function ema_price(uint256 index) external view returns (uint256);

  /// @notice Returns the AMM State price of token
  /// @dev if i = 0, it will return the state price of coin[1].
  /// @param i index of state price (0 for coin[1], 1 for coin[2], ...)
  /// @return uint256 The state price quoted by the AMM for coin[i+1]
  function get_p(uint256 i) external view returns (uint256);

  function price_oracle(uint256 index) external view returns (uint256);

  function D_oracle() external view returns (uint256);

  function A() external view returns (uint256);

  function A_precise() external view returns (uint256);

  /// @notice Calculate the current input dx given output dy
  /// @dev Index values can be found via the `coins` public getter method
  /// @param i Index value for the coin to send
  /// @param j Index value of the coin to receive
  /// @param dy Amount of `j` being received after exchange
  /// @return Amount of `i` predicted
  function get_dx(
    int128 i,
    int128 j,
    uint256 dy
  ) external view returns (uint256);

  /// @notice Calculate the current output dy given input dx
  /// @dev Index values can be found via the `coins` public getter method
  /// @param i Index value for the coin to send
  /// @param j Index value of the coin to receive
  /// @param dx Amount of `i` being exchanged
  /// @return Amount of `j` predicted
  function get_dy(
    int128 i,
    int128 j,
    uint256 dx
  ) external view returns (uint256);

  /// @notice Calculate the amount received when withdrawing a single coin
  /// @param burn_amount Amount of LP tokens to burn in the withdrawal
  /// @param i Index value of the coin to withdraw
  /// @return Amount of coin received
  function calc_withdraw_one_coin(uint256 burn_amount, int128 i) external view returns (uint256);

  /// @notice The current virtual price of the pool LP token
  /// @dev Useful for calculating profits.
  ///      The method may be vulnerable to donation-style attacks if implementation
  ///      contains rebasing tokens. For integrators, caution is advised.
  /// @return LP token virtual price normalized to 1e18
  function get_virtual_price() external view returns (uint256);

  /// @notice Calculate addition or reduction in token supply from a deposit or withdrawal
  /// @param amounts Amount of each coin being deposited
  /// @param is_deposit set True for deposits, False for withdrawals
  /// @return Expected amount of LP tokens received
  function calc_token_amount(uint256[] calldata amounts, bool is_deposit) external view returns (uint256);

  /// @notice Get the current balance of a coin within the
  ///         pool, less the accrued admin fees
  /// @param i Index value for the coin to query balance of
  /// @return Token balance
  function balances(uint256 i) external view returns (uint256);

  function get_balances() external view returns (uint256[] memory);

  function stored_rates() external view returns (uint256[] memory);

  /// @notice Return the fee for swapping between `i` and `j`
  /// @param i Index value for the coin to send
  /// @param j Index value of the coin to receive
  /// @return Swap fee expressed as an integer with 1e10 precision
  function dynamic_fee(int128 i, int128 j) external view returns (uint256);

  /****************************
   * Public Mutated Functions *
   ****************************/

  /// @notice Perform an exchange between two coins
  /// @dev Index values can be found via the `coins` public getter method
  /// @param i Index value for the coin to send
  /// @param j Index value of the coin to receive
  /// @param dx Amount of `i` being exchanged
  /// @param min_dy Minimum amount of `j` to receive
  /// @return Actual amount of `j` received
  function exchange(
    int128 i,
    int128 j,
    uint256 dx,
    uint256 min_dy
  ) external returns (uint256);

  /// @notice Perform an exchange between two coins
  /// @dev Index values can be found via the `coins` public getter method
  /// @param i Index value for the coin to send
  /// @param j Index value of the coin to receive
  /// @param dx Amount of `i` being exchanged
  /// @param min_dy Minimum amount of `j` to receive
  /// @param receiver Address that receives `j`
  /// @return Actual amount of `j` received
  function exchange(
    int128 i,
    int128 j,
    uint256 dx,
    uint256 min_dy,
    address receiver
  ) external returns (uint256);

  /// @notice Perform an exchange between two coins without transferring token in
  /// @dev The contract swaps tokens based on a change in balance of coin[i]. The
  ///      dx = ERC20(coin[i]).balanceOf(self) - self.stored_balances[i]. Users of
  ///      this method are dex aggregators, arbitrageurs, or other users who do not
  ///      wish to grant approvals to the contract: they would instead send tokens
  ///      directly to the contract and call `exchange_received`.
  ///      Note: This is disabled if pool contains rebasing tokens.
  /// @param i Index value for the coin to send
  /// @param j Index value of the coin to receive
  /// @param dx Amount of `i` being exchanged
  /// @param min_dy Minimum amount of `j` to receive
  /// @return Actual amount of `j` received
  function exchange_received(
    int128 i,
    int128 j,
    uint256 dx,
    uint256 min_dy
  ) external returns (uint256);

  /// @notice Perform an exchange between two coins without transferring token in
  /// @dev The contract swaps tokens based on a change in balance of coin[i]. The
  ///      dx = ERC20(coin[i]).balanceOf(self) - self.stored_balances[i]. Users of
  ///      this method are dex aggregators, arbitrageurs, or other users who do not
  ///      wish to grant approvals to the contract: they would instead send tokens
  ///      directly to the contract and call `exchange_received`.
  ///      Note: This is disabled if pool contains rebasing tokens.
  /// @param i Index value for the coin to send
  /// @param j Index value of the coin to receive
  /// @param dx Amount of `i` being exchanged
  /// @param min_dy Minimum amount of `j` to receive
  /// @param receiver Address that receives `j`
  /// @return Actual amount of `j` received
  function exchange_received(
    int128 i,
    int128 j,
    uint256 dx,
    uint256 min_dy,
    address receiver
  ) external returns (uint256);

  /// @notice Deposit coins into the pool
  /// @param amounts List of amounts of coins to deposit
  /// @param min_mint_amount Minimum amount of LP tokens to mint from the deposit
  /// @return Amount of LP tokens received by depositing
  function add_liquidity(uint256[] calldata amounts, uint256 min_mint_amount) external returns (uint256);

  /// @notice Deposit coins into the pool
  /// @param amounts List of amounts of coins to deposit
  /// @param min_mint_amount Minimum amount of LP tokens to mint from the deposit
  /// @param receiver Address that owns the minted LP tokens
  /// @return Amount of LP tokens received by depositing
  function add_liquidity(
    uint256[] calldata amounts,
    uint256 min_mint_amount,
    address receiver
  ) external returns (uint256);

  /// @notice Withdraw a single coin from the pool
  /// @param burn_amount Amount of LP tokens to burn in the withdrawal
  /// @param i Index value of the coin to withdraw
  /// @param min_received Minimum amount of coin to receive
  /// @return Amount of coin received
  function remove_liquidity_one_coin(
    uint256 burn_amount,
    int128 i,
    uint256 min_received
  ) external returns (uint256);

  /// @notice Withdraw a single coin from the pool
  /// @param burn_amount Amount of LP tokens to burn in the withdrawal
  /// @param i Index value of the coin to withdraw
  /// @param min_received Minimum amount of coin to receive
  /// @param receiver Address that receives the withdrawn coins
  /// @return Amount of coin received
  function remove_liquidity_one_coin(
    uint256 burn_amount,
    int128 i,
    uint256 min_received,
    address receiver
  ) external returns (uint256);

  /// @notice Withdraw coins from the pool in an imbalanced amount
  /// @param amounts List of amounts of underlying coins to withdraw
  /// @param max_burn_amount Maximum amount of LP token to burn in the withdrawal
  /// @return Actual amount of the LP token burned in the withdrawal
  function remove_liquidity_imbalance(uint256[] calldata amounts, uint256 max_burn_amount) external returns (uint256);

  /// @notice Withdraw coins from the pool in an imbalanced amount
  /// @param amounts List of amounts of underlying coins to withdraw
  /// @param max_burn_amount Maximum amount of LP token to burn in the withdrawal
  /// @param receiver Address that receives the withdrawn coins
  /// @return Actual amount of the LP token burned in the withdrawal
  function remove_liquidity_imbalance(
    uint256[] calldata amounts,
    uint256 max_burn_amount,
    address receiver
  ) external returns (uint256);

  /// @notice Withdraw coins from the pool
  /// @dev Withdrawal amounts are based on current deposit ratios
  /// @param burn_amount Quantity of LP tokens to burn in the withdrawal
  /// @param min_amounts Minimum amounts of underlying coins to receive
  /// @return List of amounts of coins that were withdrawn
  function remove_liquidity(uint256 burn_amount, uint256[] calldata min_amounts) external returns (uint256[] memory);

  /// @notice Withdraw coins from the pool
  /// @dev Withdrawal amounts are based on current deposit ratios
  /// @param burn_amount Quantity of LP tokens to burn in the withdrawal
  /// @param min_amounts Minimum amounts of underlying coins to receive
  /// @param receiver Address that receives the withdrawn coins
  /// @return List of amounts of coins that were withdrawn
  function remove_liquidity(
    uint256 burn_amount,
    uint256[] calldata min_amounts,
    address receiver
  ) external returns (uint256[] memory);

  /// @notice Withdraw coins from the pool
  /// @dev Withdrawal amounts are based on current deposit ratios
  /// @param burn_amount Quantity of LP tokens to burn in the withdrawal
  /// @param min_amounts Minimum amounts of underlying coins to receive
  /// @param receiver Address that receives the withdrawn coins
  /// @return List of amounts of coins that were withdrawn
  function remove_liquidity(
    uint256 burn_amount,
    uint256[] calldata min_amounts,
    address receiver,
    bool claim_admin_fees
  ) external returns (uint256[] memory);

  /// @notice Claim admin fees. Callable by anyone.
  function withdraw_admin_fees() external;
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface IFxUSDBasePool {
  /**********
   * Events *
   **********/

  /// @notice Emitted when the stable depeg price is updated.
  /// @param oldPrice The value of previous depeg price, multiplied by 1e18.
  /// @param newPrice The value of current depeg price, multiplied by 1e18.
  event UpdateStableDepegPrice(uint256 oldPrice, uint256 newPrice);

  /// @notice Emitted when the redeem cool down period is updated.
  /// @param oldPeriod The value of previous redeem cool down period.
  /// @param newPeriod The value of current redeem cool down period.
  event UpdateRedeemCoolDownPeriod(uint256 oldPeriod, uint256 newPeriod);

  /// @notice Emitted when the instant redeem fee ratio is updated.
  /// @param oldRatio The value of previous instant redeem fee ratio, multiplied by 1e18.
  /// @param newRatio The value of current instant redeem fee ratio, multiplied by 1e18.
  event UpdateInstantRedeemFeeRatio(uint256 oldRatio, uint256 newRatio);

  /// @notice Emitted when deposit tokens.
  /// @param caller The address of caller.
  /// @param receiver The address of pool share recipient.
  /// @param tokenIn The address of input token.
  /// @param amountDeposited The amount of input tokens.
  /// @param amountSharesOut The amount of pool shares minted.
  event Deposit(
    address indexed caller,
    address indexed receiver,
    address indexed tokenIn,
    uint256 amountDeposited,
    uint256 amountSharesOut
  );
  
  /// @notice Emitted when users request redeem.
  /// @param caller The address of caller.
  /// @param shares The amount of shares to redeem.
  /// @param unlockAt The timestamp when this share can be redeemed.
  event RequestRedeem(address indexed caller, uint256 shares, uint256 unlockAt);

  /// @notice Emitted when redeem pool shares.
  /// @param caller The address of caller.
  /// @param receiver The address of pool share recipient.
  /// @param amountSharesToRedeem The amount of pool shares burned.
  /// @param amountYieldTokenOut The amount of yield tokens redeemed.
  /// @param amountStableTokenOut The amount of stable tokens redeemed.
  event Redeem(
    address indexed caller,
    address indexed receiver,
    uint256 amountSharesToRedeem,
    uint256 amountYieldTokenOut,
    uint256 amountStableTokenOut
  );

  /// @notice Emitted when instant redeem pool shares.
  /// @param caller The address of caller.
  /// @param receiver The address of pool share recipient.
  /// @param amountSharesToRedeem The amount of pool shares burned.
  /// @param amountYieldTokenOut The amount of yield tokens redeemed.
  /// @param amountStableTokenOut The amount of stable tokens redeemed.
  event InstantRedeem(
    address indexed caller,
    address indexed receiver,
    uint256 amountSharesToRedeem,
    uint256 amountYieldTokenOut,
    uint256 amountStableTokenOut
  );

  /// @notice Emitted when rebalance or liquidate.
  /// @param caller The address of caller.
  /// @param tokenIn The address of input token.
  /// @param amountTokenIn The amount of input token used.
  /// @param amountCollateral The amount of collateral token rebalanced.
  /// @param amountYieldToken The amount of yield token used.
  /// @param amountStableToken The amount of stable token used.
  event Rebalance(
    address indexed caller,
    address indexed tokenIn,
    uint256 amountTokenIn,
    uint256 amountCollateral,
    uint256 amountYieldToken,
    uint256 amountStableToken
  );

  /// @notice Emitted when arbitrage in curve pool.
  /// @param caller The address of caller.
  /// @param tokenIn The address of input token.
  /// @param amountIn The amount of input token used.
  /// @param amountOut The amount of output token swapped.
  /// @param bonusOut The amount of bonus token.
  event Arbitrage(
    address indexed caller,
    address indexed tokenIn,
    uint256 amountIn,
    uint256 amountOut,
    uint256 bonusOut
  );

  /*************************
   * Public View Functions *
   *************************/

  /// @notice The address of yield token.
  function yieldToken() external view returns (address);

  /// @notice The address of stable token.
  function stableToken() external view returns (address);

  /// @notice The total amount of yield token managed in this contract
  function totalYieldToken() external view returns (uint256);

  /// @notice The total amount of stable token managed in this contract
  function totalStableToken() external view returns (uint256);

  /// @notice The net asset value, multiplied by 1e18.
  function nav() external view returns (uint256);

  /// @notice Return the stable token price, multiplied by 1e18.
  function getStableTokenPrice() external view returns (uint256);

  /// @notice Return the stable token price with scaling to 18 decimals, multiplied by 1e18.
  function getStableTokenPriceWithScale() external view returns (uint256);

  /// @notice Preview the result of deposit.
  /// @param tokenIn The address of input token.
  /// @param amount The amount of input tokens to deposit.
  /// @return amountSharesOut The amount of pool shares should receive.
  function previewDeposit(address tokenIn, uint256 amount) external view returns (uint256 amountSharesOut);

  /// @notice Preview the result of redeem.
  /// @param amountSharesToRedeem The amount of pool shares to redeem.
  /// @return amountYieldOut The amount of yield token should receive.
  /// @return amountStableOut The amount of stable token should receive.
  function previewRedeem(
    uint256 amountSharesToRedeem
  ) external view returns (uint256 amountYieldOut, uint256 amountStableOut);

  /****************************
   * Public Mutated Functions *
   ****************************/

  /// @notice Deposit token.
  /// @param receiver The address of pool shares recipient.
  /// @param tokenIn The address of input token.
  /// @param amountTokenToDeposit The amount of input tokens to deposit.
  /// @param minSharesOut The minimum amount of pool shares should receive.
  /// @return amountSharesOut The amount of pool shares received.
  function deposit(
    address receiver,
    address tokenIn,
    uint256 amountTokenToDeposit,
    uint256 minSharesOut
  ) external returns (uint256 amountSharesOut);

  /// @notice Request redeem.
  /// @param shares The amount of shares to request.
  function requestRedeem(uint256 shares) external;

  /// @notice Redeem pool shares.
  /// @param receiver The address of token recipient.
  /// @param shares The amount of pool shares to redeem.
  /// @return amountYieldOut The amount of yield token should received.
  /// @return amountStableOut The amount of stable token should received.
  function redeem(address receiver, uint256 shares) external returns (uint256 amountYieldOut, uint256 amountStableOut);

  /// @notice Redeem pool shares instantly with withdraw fee.
  /// @param receiver The address of token recipient.
  /// @param shares The amount of pool shares to redeem.
  /// @return amountYieldOut The amount of yield token should received.
  /// @return amountStableOut The amount of stable token should received.
  function instantRedeem(address receiver, uint256 shares) external returns (uint256 amountYieldOut, uint256 amountStableOut);

  /// @notice Redeem pool shares instantly without withdraw fee.
  /// @param receiver The address of token recipient.
  /// @param shares The amount of pool shares to redeem.
  /// @return amountYieldOut The amount of yield token should received.
  /// @return amountStableOut The amount of stable token should received.
  function instantRedeemNoFee(address receiver, uint256 shares) external returns (uint256 amountYieldOut, uint256 amountStableOut);

  /// @notice Rebalance all positions in the given tick.
  /// @param pool The address of pool to rebalance.
  /// @param tick The index of tick to rebalance.
  /// @param tokenIn The address of token to rebalance.
  /// @param maxAmount The maximum amount of input token to rebalance.
  /// @param minBaseOut The minimum amount of collateral tokens should receive.
  /// @return tokenUsed The amount of input token used to rebalance.
  /// @return baseOut The amount of collateral tokens rebalanced.
  function rebalance(
    address pool,
    int16 tick,
    address tokenIn,
    uint256 maxAmount,
    uint256 minBaseOut
  ) external returns (uint256 tokenUsed, uint256 baseOut);

  /// @notice Rebalance all possible ticks.
  /// @param pool The address of pool to rebalance.
  /// @param tokenIn The address of token to rebalance.
  /// @param maxAmount The maximum amount of input token to rebalance.
  /// @param minBaseOut The minimum amount of collateral tokens should receive.
  /// @return tokenUsed The amount of input token used to rebalance.
  /// @return baseOut The amount of collateral tokens rebalanced.
  function rebalance(
    address pool,
    address tokenIn,
    uint256 maxAmount,
    uint256 minBaseOut
  ) external returns (uint256 tokenUsed, uint256 baseOut);

  /// @notice Liquidate all possible ticks.
  /// @param pool The address of pool to rebalance.
  /// @param tokenIn The address of token to rebalance.
  /// @param maxAmount The maximum amount of input token to rebalance.
  /// @param minBaseOut The minimum amount of collateral tokens should receive.
  /// @return tokenUsed The amount of input token used to rebalance.
  /// @return baseOut The amount of collateral tokens rebalanced.
  function liquidate(
    address pool,
    address tokenIn,
    uint256 maxAmount,
    uint256 minBaseOut
  ) external returns (uint256 tokenUsed, uint256 baseOut);

  /// @notice Arbitrage between yield token and stable token.
  /// @param srcToken The address of source token.
  /// @param amountIn The amount of source token to use.
  /// @param receiver The address of bonus receiver.
  /// @param data The hook data to `onSwap`.
  /// @return amountOut The amount of target token swapped.
  /// @return bonusOut The amount of bonus token.
  function arbitrage(
    address srcToken,
    uint256 amountIn,
    address receiver,
    bytes calldata data
  ) external returns (uint256 amountOut, uint256 bonusOut);
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface IFxUSDRegeneracy {
  /**********
   * Events *
   **********/
  
  /// @notice Emitted when rebalance/liquidate with stable token.
  /// @param amountStable The amount of stable token used.
  /// @param amountFxUSD The corresponding amount of fxUSD.
  event RebalanceWithStable(uint256 amountStable, uint256 amountFxUSD);
  
  /// @notice Emitted when buyback fxUSD with stable reserve.
  /// @param amountStable the amount of stable token used.
  /// @param amountFxUSD The amount of fxUSD bought.
  /// @param bonusFxUSD The amount of fxUSD as bonus for caller.
  event Buyback(uint256 amountStable, uint256 amountFxUSD, uint256 bonusFxUSD);

  /*************************
   * Public View Functions *
   *************************/

  /// @notice The address of `PoolManager` contract.
  function poolManager() external view returns (address);

  /// @notice The address of stable token.
  function stableToken() external view returns (address);

  /// @notice The address of `PegKeeper` contract.
  function pegKeeper() external view returns (address);

  /****************************
   * Public Mutated Functions *
   ****************************/

  /// @notice Mint fxUSD token someone.
  function mint(address to, uint256 amount) external;

  /// @notice Burn fxUSD from someone.
  function burn(address from, uint256 amount) external;

  /// @notice Hook for rebalance/liquidate with stable token.
  /// @param amountStableToken The amount of stable token.
  /// @param amountFxUSD The amount of fxUSD.
  function onRebalanceWithStable(uint256 amountStableToken, uint256 amountFxUSD) external;

  /// @notice Buyback fxUSD with stable token.
  /// @param amountIn the amount of stable token to use.
  /// @param receiver The address of bonus receiver.
  /// @param data The hook data to PegKeeper.
  /// @return amountOut The amount of fxUSD swapped.
  /// @return bonusOut The amount of bonus fxUSD.
  function buyback(
    uint256 amountIn,
    address receiver,
    bytes calldata data
  ) external returns (uint256 amountOut, uint256 bonusOut);
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface IPegKeeper {
  /**********
   * Events *
   **********/

  /// @notice Emitted when the converter contract is updated.
  /// @param oldConverter The address of previous converter contract.
  /// @param newConverter The address of current converter contract.
  event UpdateConverter(address indexed oldConverter, address indexed newConverter);

  /// @notice Emitted when the curve pool contract is updated.
  /// @param oldPool The address of previous curve pool contract.
  /// @param newPool The address of current curve pool contract.
  event UpdateCurvePool(address indexed oldPool, address indexed newPool);

  /// @notice Emitted when the price threshold is updated.
  /// @param oldThreshold The value of previous price threshold
  /// @param newThreshold The value of current price threshold
  event UpdatePriceThreshold(uint256 oldThreshold, uint256 newThreshold);

  /*************************
   * Public View Functions *
   *************************/

  /// @notice Return whether borrow for fxUSD is allowed.
  function isBorrowAllowed() external view returns (bool);

  /// @notice Return whether redeem fxUSD is allowed.
  function isRedeemAllowed() external view returns (bool);

  /// @notice Return whether funding costs is enabled.
  function isFundingEnabled() external view returns (bool);
  
  /// @notice Return the price of fxUSD, multiplied by 1e18
  function getFxUSDPrice() external view returns (uint256);

  /****************************
   * Public Mutated Functions *
   ****************************/

  /// @notice Buyback fxUSD with stable reserve in FxUSDSave.
  /// @param amountIn the amount of stable token to use.
  /// @param data The hook data to `onSwap`.
  /// @return amountOut The amount of fxUSD swapped.
  /// @return bonusOut The amount of bonus fxUSD.
  function buyback(uint256 amountIn, bytes calldata data) external returns (uint256 amountOut, uint256 bonusOut);

  /// @notice Stabilize the fxUSD price in curve pool.
  /// @param srcToken The address of source token (fxUSD or stable token).
  /// @param amountIn the amount of source token to use.
  /// @param data The hook data to `onSwap`.
  /// @return amountOut The amount of target token swapped.
  /// @return bonusOut The amount of bonus token.
  function stabilize(
    address srcToken,
    uint256 amountIn,
    bytes calldata data
  ) external returns (uint256 amountOut, uint256 bonusOut);

  /// @notice Swap callback from `buyback` and `stabilize`.
  /// @param srcToken The address of source token.
  /// @param srcToken The address of target token.
  /// @param amountIn the amount of source token to use.
  /// @param data The callback data.
  /// @return amountOut The amount of target token swapped.
  function onSwap(
    address srcToken,
    address targetToken,
    uint256 amountIn,
    bytes calldata data
  ) external returns (uint256 amountOut);
}

Settings
{
  "evmVersion": "cancun",
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "remappings": [
    "npm/@openzeppelin/contracts-upgradeable@5.4.0/:@openzeppelin/contracts/=npm/@openzeppelin/contracts@5.4.0/",
    "npm/@openzeppelin/contracts-upgradeable@5.4.0/:@openzeppelin/contracts/=npm/@openzeppelin/contracts@5.4.0/",
    "npm/@openzeppelin/contracts-upgradeable@5.4.0/:@openzeppelin/contracts/=npm/@openzeppelin/contracts@5.4.0/",
    "project/:@openzeppelin/contracts-upgradeable/=npm/@openzeppelin/contracts-upgradeable@5.4.0/",
    "project/:@openzeppelin/contracts-upgradeable/=npm/@openzeppelin/contracts-upgradeable@5.4.0/",
    "project/:@openzeppelin/contracts/=npm/@openzeppelin/contracts@5.4.0/",
    "project/:@openzeppelin/contracts/=npm/@openzeppelin/contracts@5.4.0/",
    "project/:@openzeppelin/contracts/=npm/@openzeppelin/contracts@5.4.0/",
    "project/:@openzeppelin/contracts/=npm/@openzeppelin/contracts@5.4.0/",
    "project/:@openzeppelin/contracts/=npm/@openzeppelin/contracts@5.4.0/",
    "project/:@openzeppelin/contracts/=npm/@openzeppelin/contracts@5.4.0/"
  ]
}

Contract Security Audit

Contract ABI

API
[{"inputs":[],"name":"AccessControlBadConfirmation","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"bytes32","name":"neededRole","type":"bytes32"}],"name":"AccessControlUnauthorizedAccount","type":"error"},{"inputs":[],"name":"ErrorMulticallFailed","type":"error"},{"inputs":[],"name":"InsufficientOutputToken","type":"error"},{"inputs":[],"name":"InvalidInitialization","type":"error"},{"inputs":[],"name":"NotInitializing","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint64","name":"version","type":"uint64"}],"name":"Initialized","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":"BATCH_TRANSFER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"BUYBACK_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DEFAULT_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MULTICALL_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PEG_KEEPER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PERMISSIONED_ROUTER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PERMISSIONED_TRADER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"STABILIZE_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"TOKEN_RECEIVER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"address[]","name":"receivers","type":"address[]"},{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"name":"batchTransfer","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"pegKeeper","type":"address"},{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"buyback","outputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"},{"internalType":"uint256","name":"bonus","type":"uint256"}],"stateMutability":"nonpayable","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":"address","name":"_admin","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address[]","name":"targets","type":"address[]"},{"internalType":"bytes[]","name":"data","type":"bytes[]"}],"name":"multicall","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"callerConfirmation","type":"address"}],"name":"renounceRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"revokeRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"pegKeeper","type":"address"},{"internalType":"address","name":"srcToken","type":"address"},{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"stabilize","outputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"},{"internalType":"uint256","name":"bonus","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"srcToken","type":"address"},{"internalType":"address","name":"dstToken","type":"address"},{"internalType":"uint256","name":"amountIn","type":"uint256"},{"components":[{"internalType":"address","name":"router","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"},{"internalType":"uint256","name":"minOut","type":"uint256"}],"internalType":"struct PermissionedSwap.TradingParameter","name":"params","type":"tuple"}],"name":"swap","outputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"baseToken","type":"address"},{"internalType":"address","name":"recipient","type":"address"}],"name":"withdraw","outputs":[],"stateMutability":"nonpayable","type":"function"}]

6080604052348015600e575f80fd5b506115168061001c5f395ff3fe608060405234801561000f575f80fd5b506004361061013d575f3560e01c8063a590bc1e116100b4578063d547741f11610079578063d547741f146102ef578063de52e72114610302578063e1ccf11c14610329578063f1b6d5ea14610350578063f940e38514610377578063fe3fc3691461038a575f80fd5b8063a590bc1e14610253578063a91c1d3c1461027b578063b720e658146102a2578063b7f11c21146102b5578063c4d66de8146102dc575f80fd5b80633500ae8e116101055780633500ae8e146101d957806336568abe146101ec57806363fb0b96146101ff578063795277651461021257806391d1485414610239578063a217fddf1461024c575f80fd5b806301ffc9a7146101415780630dda2e53146101695780631239ec8c1461019e578063248a9ca3146101b35780632f2ff15d146101c6575b5f80fd5b61015461014f366004610f3a565b6103b1565b60405190151581526020015b60405180910390f35b6101907f759995689d0b5a8d082ba285697cd721c40ae33fadfeb8da798e7c4b54e8827d81565b604051908152602001610160565b6101b16101ac366004610fca565b6103e7565b005b6101906101c1366004611048565b6104d8565b6101b16101d436600461105f565b6104f8565b6101906101e73660046110f5565b61051a565b6101b16101fa36600461105f565b610530565b6101b161020d3660046111fc565b610568565b6101907f84060c990e14b08d7c5d95f3c4be08c8b28742dee5236bc38e7559b465ca531f81565b61015461024736600461105f565b610670565b6101905f81565b6102666102613660046112a3565b6106a6565b60408051928352602083019190915201610160565b6101907f8ba312960b5597dbb6106c0155aa0551317467e13792b46ce452b4e143b06e1381565b6102666102b03660046112fb565b610752565b6101907fa7c777b85fc58675e1f97f547c6d0658b5454f6e82d1930f8a36716c5ac0de0581565b6101b16102ea366004611344565b6107fb565b6101b16102fd36600461105f565b61090b565b6101907f795faeccae94bd9eed40852cb158e30f590ffa7acbfa89a0204147c5bcf072cd81565b6101907fd0deb57dbcd9ea4bdf9c5591c75b12b446541d89029fe7721eaa93f04d0c1d8381565b6101907f607b5964b99ba60004997a77c26b85dfbfe3dd5c8325bfb94d82d08cf63c693281565b6101b161038536600461135d565b610927565b6101907f90ba4e11ad240e3543d2e8a32e330be1330b184ccfcddfdcf9cefb7f695dc7ca81565b5f6001600160e01b03198216637965db0b60e01b14806103e157506301ffc9a760e01b6001600160e01b03198316145b92915050565b7f8ba312960b5597dbb6106c0155aa0551317467e13792b46ce452b4e143b06e13610411816109af565b5f5b848110156104cf5761046b7f607b5964b99ba60004997a77c26b85dfbfe3dd5c8325bfb94d82d08cf63c693287878481811061045157610451611385565b90506020020160208101906104669190611344565b6109bc565b6104c786868381811061048057610480611385565b90506020020160208101906104959190611344565b8585848181106104a7576104a7611385565b90506020020135896001600160a01b03166109fe9092919063ffffffff16565b600101610413565b50505050505050565b5f9081525f805160206114c1833981519152602052604090206001015490565b610501826104d8565b61050a816109af565b6105148383610a5d565b50505050565b5f61052785858585610afe565b95945050505050565b6001600160a01b03811633146105595760405163334bd91960e11b815260040160405180910390fd5b6105638282610d0d565b505050565b7f759995689d0b5a8d082ba285697cd721c40ae33fadfeb8da798e7c4b54e8827d610592816109af565b5f5b84811015610668575f8686838181106105af576105af611385565b90506020020160208101906105c49190611344565b6001600160a01b03168585848181106105df576105df611385565b90506020028101906105f19190611399565b6040516105ff9291906113db565b5f604051808303815f865af19150503d805f8114610638576040519150601f19603f3d011682016040523d82523d5f602084013e61063d565b606091505b505090508061065f57604051637935110d60e01b815260040160405180910390fd5b50600101610594565b505050505050565b5f9182525f805160206114c1833981519152602090815260408084206001600160a01b0393909316845291905290205460ff1690565b5f807f90ba4e11ad240e3543d2e8a32e330be1330b184ccfcddfdcf9cefb7f695dc7ca6106d2816109af565b6040516374d98e6f60e11b81526001600160a01b0389169063e9b31cde90610704908a908a908a908a90600401611412565b60408051808303815f875af115801561071f573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107439190611439565b90999098509650505050505050565b5f807fa7c777b85fc58675e1f97f547c6d0658b5454f6e82d1930f8a36716c5ac0de0561077e816109af565b6040516307f3234560e51b81526001600160a01b0388169063fe6468a0906107ae9089908990899060040161145b565b60408051808303815f875af11580156107c9573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107ed9190611439565b909890975095505050505050565b5f610804610d86565b805490915060ff600160401b82041615906001600160401b03165f8115801561082a5750825b90505f826001600160401b031660011480156108455750303b155b905081158015610853575080155b156108715760405163f92ee8a960e01b815260040160405180910390fd5b845467ffffffffffffffff19166001178555831561089b57845460ff60401b1916600160401b1785555b6108a3610dae565b6108ab610dae565b6108b3610dae565b6108bd5f87610a5d565b50831561066857845460ff60401b19168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a1505050505050565b610914826104d8565b61091d816109af565b6105148383610d0d565b5f610931816109af565b6040516370a0823160e01b81523060048201525f906001600160a01b038516906370a0823190602401602060405180830381865afa158015610975573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906109999190611474565b90506105146001600160a01b03851684836109fe565b6109b981336109bc565b50565b6109c68282610670565b6109fa5760405163e2517d3f60e01b81526001600160a01b0382166004820152602481018390526044015b60405180910390fd5b5050565b6040516001600160a01b0383811660248301526044820183905261056391859182169063a9059cbb906064015b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050610db8565b5f5f805160206114c1833981519152610a768484610670565b610af5575f848152602082815260408083206001600160a01b03871684529091529020805460ff19166001179055610aab3390565b6001600160a01b0316836001600160a01b0316857f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a460019150506103e1565b5f9150506103e1565b5f7f84060c990e14b08d7c5d95f3c4be08c8b28742dee5236bc38e7559b465ca531f610b29816109af565b846001600160a01b0316866001600160a01b031603610b4a57839150610d04565b610b777f795faeccae94bd9eed40852cb158e30f590ffa7acbfa89a0204147c5bcf072cd845f01516109bc565b8251610b8e906001600160a01b0388169086610e24565b6040516370a0823160e01b81523060048201526001600160a01b038616906370a0823190602401602060405180830381865afa158015610bd0573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610bf49190611474565b91505f835f01516001600160a01b03168460200151604051610c16919061148b565b5f604051808303815f865af19150503d805f8114610c4f576040519150601f19603f3d011682016040523d82523d5f602084013e610c54565b606091505b5050905080610c69576040513d805f833e8082fd5b6040516370a0823160e01b815230600482015283906001600160a01b038816906370a0823190602401602060405180830381865afa158015610cad573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610cd19190611474565b610cdb91906114a1565b92508360400151831015610d0257604051638bf3fb6f60e01b815260040160405180910390fd5b505b50949350505050565b5f5f805160206114c1833981519152610d268484610670565b15610af5575f848152602082815260408083206001600160a01b0387168085529252808320805460ff1916905551339287917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a460019150506103e1565b5f807ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a006103e1565b610db6610eb3565b565b5f8060205f8451602086015f885af180610dd7576040513d5f823e3d81fd5b50505f513d91508115610dee578060011415610dfb565b6001600160a01b0384163b155b1561051457604051635274afe760e01b81526001600160a01b03851660048201526024016109f1565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663095ea7b360e01b179052610e758482610ed8565b610514576040516001600160a01b0384811660248301525f6044830152610ea991869182169063095ea7b390606401610a2b565b6105148482610db8565b610ebb610f21565b610db657604051631afcd79f60e31b815260040160405180910390fd5b5f805f8060205f8651602088015f8a5af192503d91505f519050828015610f1757508115610f095780600114610f17565b5f866001600160a01b03163b115b9695505050505050565b5f610f2a610d86565b54600160401b900460ff16919050565b5f60208284031215610f4a575f80fd5b81356001600160e01b031981168114610f61575f80fd5b9392505050565b80356001600160a01b0381168114610f7e575f80fd5b919050565b5f8083601f840112610f93575f80fd5b5081356001600160401b03811115610fa9575f80fd5b6020830191508360208260051b8501011115610fc3575f80fd5b9250929050565b5f805f805f60608688031215610fde575f80fd5b610fe786610f68565b945060208601356001600160401b03811115611001575f80fd5b61100d88828901610f83565b90955093505060408601356001600160401b0381111561102b575f80fd5b61103788828901610f83565b969995985093965092949392505050565b5f60208284031215611058575f80fd5b5035919050565b5f8060408385031215611070575f80fd5b8235915061108060208401610f68565b90509250929050565b634e487b7160e01b5f52604160045260245ffd5b604051606081016001600160401b03811182821017156110bf576110bf611089565b60405290565b604051601f8201601f191681016001600160401b03811182821017156110ed576110ed611089565b604052919050565b5f805f8060808587031215611108575f80fd5b61111185610f68565b935061111f60208601610f68565b92506040850135915060608501356001600160401b03811115611140575f80fd5b850160608188031215611151575f80fd5b61115961109d565b61116282610f68565b815260208201356001600160401b0381111561117c575f80fd5b8201601f8101891361118c575f80fd5b80356001600160401b038111156111a5576111a5611089565b6111b8601f8201601f19166020016110c5565b8181528a60208385010111156111cc575f80fd5b816020840160208301375f6020928201830152908301525060409182013591810191909152939692955090935050565b5f805f806040858703121561120f575f80fd5b84356001600160401b03811115611224575f80fd5b61123087828801610f83565b90955093505060208501356001600160401b0381111561124e575f80fd5b61125a87828801610f83565b95989497509550505050565b5f8083601f840112611276575f80fd5b5081356001600160401b0381111561128c575f80fd5b602083019150836020828501011115610fc3575f80fd5b5f805f805f608086880312156112b7575f80fd5b6112c086610f68565b94506112ce60208701610f68565b93506040860135925060608601356001600160401b038111156112ef575f80fd5b61103788828901611266565b5f805f806060858703121561130e575f80fd5b61131785610f68565b93506020850135925060408501356001600160401b03811115611338575f80fd5b61125a87828801611266565b5f60208284031215611354575f80fd5b610f6182610f68565b5f806040838503121561136e575f80fd5b61137783610f68565b915061108060208401610f68565b634e487b7160e01b5f52603260045260245ffd5b5f808335601e198436030181126113ae575f80fd5b8301803591506001600160401b038211156113c7575f80fd5b602001915036819003821315610fc3575f80fd5b818382375f9101908152919050565b81835281816020850137505f828201602090810191909152601f909101601f19169091010190565b60018060a01b0385168152836020820152606060408201525f610f176060830184866113ea565b5f806040838503121561144a575f80fd5b505080516020909101519092909150565b838152604060208201525f6105276040830184866113ea565b5f60208284031215611484575f80fd5b5051919050565b5f82518060208501845e5f920191825250919050565b818103818111156103e157634e487b7160e01b5f52601160045260245ffdfe02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800a2646970667358221220cfe2f78ac96ed6fd4d88980f0ce61229b21a697813f2ed5e52da957b7bf0a7c464736f6c634300081a0033

Deployed Bytecode

0x608060405234801561000f575f80fd5b506004361061013d575f3560e01c8063a590bc1e116100b4578063d547741f11610079578063d547741f146102ef578063de52e72114610302578063e1ccf11c14610329578063f1b6d5ea14610350578063f940e38514610377578063fe3fc3691461038a575f80fd5b8063a590bc1e14610253578063a91c1d3c1461027b578063b720e658146102a2578063b7f11c21146102b5578063c4d66de8146102dc575f80fd5b80633500ae8e116101055780633500ae8e146101d957806336568abe146101ec57806363fb0b96146101ff578063795277651461021257806391d1485414610239578063a217fddf1461024c575f80fd5b806301ffc9a7146101415780630dda2e53146101695780631239ec8c1461019e578063248a9ca3146101b35780632f2ff15d146101c6575b5f80fd5b61015461014f366004610f3a565b6103b1565b60405190151581526020015b60405180910390f35b6101907f759995689d0b5a8d082ba285697cd721c40ae33fadfeb8da798e7c4b54e8827d81565b604051908152602001610160565b6101b16101ac366004610fca565b6103e7565b005b6101906101c1366004611048565b6104d8565b6101b16101d436600461105f565b6104f8565b6101906101e73660046110f5565b61051a565b6101b16101fa36600461105f565b610530565b6101b161020d3660046111fc565b610568565b6101907f84060c990e14b08d7c5d95f3c4be08c8b28742dee5236bc38e7559b465ca531f81565b61015461024736600461105f565b610670565b6101905f81565b6102666102613660046112a3565b6106a6565b60408051928352602083019190915201610160565b6101907f8ba312960b5597dbb6106c0155aa0551317467e13792b46ce452b4e143b06e1381565b6102666102b03660046112fb565b610752565b6101907fa7c777b85fc58675e1f97f547c6d0658b5454f6e82d1930f8a36716c5ac0de0581565b6101b16102ea366004611344565b6107fb565b6101b16102fd36600461105f565b61090b565b6101907f795faeccae94bd9eed40852cb158e30f590ffa7acbfa89a0204147c5bcf072cd81565b6101907fd0deb57dbcd9ea4bdf9c5591c75b12b446541d89029fe7721eaa93f04d0c1d8381565b6101907f607b5964b99ba60004997a77c26b85dfbfe3dd5c8325bfb94d82d08cf63c693281565b6101b161038536600461135d565b610927565b6101907f90ba4e11ad240e3543d2e8a32e330be1330b184ccfcddfdcf9cefb7f695dc7ca81565b5f6001600160e01b03198216637965db0b60e01b14806103e157506301ffc9a760e01b6001600160e01b03198316145b92915050565b7f8ba312960b5597dbb6106c0155aa0551317467e13792b46ce452b4e143b06e13610411816109af565b5f5b848110156104cf5761046b7f607b5964b99ba60004997a77c26b85dfbfe3dd5c8325bfb94d82d08cf63c693287878481811061045157610451611385565b90506020020160208101906104669190611344565b6109bc565b6104c786868381811061048057610480611385565b90506020020160208101906104959190611344565b8585848181106104a7576104a7611385565b90506020020135896001600160a01b03166109fe9092919063ffffffff16565b600101610413565b50505050505050565b5f9081525f805160206114c1833981519152602052604090206001015490565b610501826104d8565b61050a816109af565b6105148383610a5d565b50505050565b5f61052785858585610afe565b95945050505050565b6001600160a01b03811633146105595760405163334bd91960e11b815260040160405180910390fd5b6105638282610d0d565b505050565b7f759995689d0b5a8d082ba285697cd721c40ae33fadfeb8da798e7c4b54e8827d610592816109af565b5f5b84811015610668575f8686838181106105af576105af611385565b90506020020160208101906105c49190611344565b6001600160a01b03168585848181106105df576105df611385565b90506020028101906105f19190611399565b6040516105ff9291906113db565b5f604051808303815f865af19150503d805f8114610638576040519150601f19603f3d011682016040523d82523d5f602084013e61063d565b606091505b505090508061065f57604051637935110d60e01b815260040160405180910390fd5b50600101610594565b505050505050565b5f9182525f805160206114c1833981519152602090815260408084206001600160a01b0393909316845291905290205460ff1690565b5f807f90ba4e11ad240e3543d2e8a32e330be1330b184ccfcddfdcf9cefb7f695dc7ca6106d2816109af565b6040516374d98e6f60e11b81526001600160a01b0389169063e9b31cde90610704908a908a908a908a90600401611412565b60408051808303815f875af115801561071f573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107439190611439565b90999098509650505050505050565b5f807fa7c777b85fc58675e1f97f547c6d0658b5454f6e82d1930f8a36716c5ac0de0561077e816109af565b6040516307f3234560e51b81526001600160a01b0388169063fe6468a0906107ae9089908990899060040161145b565b60408051808303815f875af11580156107c9573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107ed9190611439565b909890975095505050505050565b5f610804610d86565b805490915060ff600160401b82041615906001600160401b03165f8115801561082a5750825b90505f826001600160401b031660011480156108455750303b155b905081158015610853575080155b156108715760405163f92ee8a960e01b815260040160405180910390fd5b845467ffffffffffffffff19166001178555831561089b57845460ff60401b1916600160401b1785555b6108a3610dae565b6108ab610dae565b6108b3610dae565b6108bd5f87610a5d565b50831561066857845460ff60401b19168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a1505050505050565b610914826104d8565b61091d816109af565b6105148383610d0d565b5f610931816109af565b6040516370a0823160e01b81523060048201525f906001600160a01b038516906370a0823190602401602060405180830381865afa158015610975573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906109999190611474565b90506105146001600160a01b03851684836109fe565b6109b981336109bc565b50565b6109c68282610670565b6109fa5760405163e2517d3f60e01b81526001600160a01b0382166004820152602481018390526044015b60405180910390fd5b5050565b6040516001600160a01b0383811660248301526044820183905261056391859182169063a9059cbb906064015b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050610db8565b5f5f805160206114c1833981519152610a768484610670565b610af5575f848152602082815260408083206001600160a01b03871684529091529020805460ff19166001179055610aab3390565b6001600160a01b0316836001600160a01b0316857f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a460019150506103e1565b5f9150506103e1565b5f7f84060c990e14b08d7c5d95f3c4be08c8b28742dee5236bc38e7559b465ca531f610b29816109af565b846001600160a01b0316866001600160a01b031603610b4a57839150610d04565b610b777f795faeccae94bd9eed40852cb158e30f590ffa7acbfa89a0204147c5bcf072cd845f01516109bc565b8251610b8e906001600160a01b0388169086610e24565b6040516370a0823160e01b81523060048201526001600160a01b038616906370a0823190602401602060405180830381865afa158015610bd0573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610bf49190611474565b91505f835f01516001600160a01b03168460200151604051610c16919061148b565b5f604051808303815f865af19150503d805f8114610c4f576040519150601f19603f3d011682016040523d82523d5f602084013e610c54565b606091505b5050905080610c69576040513d805f833e8082fd5b6040516370a0823160e01b815230600482015283906001600160a01b038816906370a0823190602401602060405180830381865afa158015610cad573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610cd19190611474565b610cdb91906114a1565b92508360400151831015610d0257604051638bf3fb6f60e01b815260040160405180910390fd5b505b50949350505050565b5f5f805160206114c1833981519152610d268484610670565b15610af5575f848152602082815260408083206001600160a01b0387168085529252808320805460ff1916905551339287917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a460019150506103e1565b5f807ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a006103e1565b610db6610eb3565b565b5f8060205f8451602086015f885af180610dd7576040513d5f823e3d81fd5b50505f513d91508115610dee578060011415610dfb565b6001600160a01b0384163b155b1561051457604051635274afe760e01b81526001600160a01b03851660048201526024016109f1565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663095ea7b360e01b179052610e758482610ed8565b610514576040516001600160a01b0384811660248301525f6044830152610ea991869182169063095ea7b390606401610a2b565b6105148482610db8565b610ebb610f21565b610db657604051631afcd79f60e31b815260040160405180910390fd5b5f805f8060205f8651602088015f8a5af192503d91505f519050828015610f1757508115610f095780600114610f17565b5f866001600160a01b03163b115b9695505050505050565b5f610f2a610d86565b54600160401b900460ff16919050565b5f60208284031215610f4a575f80fd5b81356001600160e01b031981168114610f61575f80fd5b9392505050565b80356001600160a01b0381168114610f7e575f80fd5b919050565b5f8083601f840112610f93575f80fd5b5081356001600160401b03811115610fa9575f80fd5b6020830191508360208260051b8501011115610fc3575f80fd5b9250929050565b5f805f805f60608688031215610fde575f80fd5b610fe786610f68565b945060208601356001600160401b03811115611001575f80fd5b61100d88828901610f83565b90955093505060408601356001600160401b0381111561102b575f80fd5b61103788828901610f83565b969995985093965092949392505050565b5f60208284031215611058575f80fd5b5035919050565b5f8060408385031215611070575f80fd5b8235915061108060208401610f68565b90509250929050565b634e487b7160e01b5f52604160045260245ffd5b604051606081016001600160401b03811182821017156110bf576110bf611089565b60405290565b604051601f8201601f191681016001600160401b03811182821017156110ed576110ed611089565b604052919050565b5f805f8060808587031215611108575f80fd5b61111185610f68565b935061111f60208601610f68565b92506040850135915060608501356001600160401b03811115611140575f80fd5b850160608188031215611151575f80fd5b61115961109d565b61116282610f68565b815260208201356001600160401b0381111561117c575f80fd5b8201601f8101891361118c575f80fd5b80356001600160401b038111156111a5576111a5611089565b6111b8601f8201601f19166020016110c5565b8181528a60208385010111156111cc575f80fd5b816020840160208301375f6020928201830152908301525060409182013591810191909152939692955090935050565b5f805f806040858703121561120f575f80fd5b84356001600160401b03811115611224575f80fd5b61123087828801610f83565b90955093505060208501356001600160401b0381111561124e575f80fd5b61125a87828801610f83565b95989497509550505050565b5f8083601f840112611276575f80fd5b5081356001600160401b0381111561128c575f80fd5b602083019150836020828501011115610fc3575f80fd5b5f805f805f608086880312156112b7575f80fd5b6112c086610f68565b94506112ce60208701610f68565b93506040860135925060608601356001600160401b038111156112ef575f80fd5b61103788828901611266565b5f805f806060858703121561130e575f80fd5b61131785610f68565b93506020850135925060408501356001600160401b03811115611338575f80fd5b61125a87828801611266565b5f60208284031215611354575f80fd5b610f6182610f68565b5f806040838503121561136e575f80fd5b61137783610f68565b915061108060208401610f68565b634e487b7160e01b5f52603260045260245ffd5b5f808335601e198436030181126113ae575f80fd5b8301803591506001600160401b038211156113c7575f80fd5b602001915036819003821315610fc3575f80fd5b818382375f9101908152919050565b81835281816020850137505f828201602090810191909152601f909101601f19169091010190565b60018060a01b0385168152836020820152606060408201525f610f176060830184866113ea565b5f806040838503121561144a575f80fd5b505080516020909101519092909150565b838152604060208201525f6105276040830184866113ea565b5f60208284031215611484575f80fd5b5051919050565b5f82518060208501845e5f920191825250919050565b818103818111156103e157634e487b7160e01b5f52601160045260245ffdfe02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800a2646970667358221220cfe2f78ac96ed6fd4d88980f0ce61229b21a697813f2ed5e52da957b7bf0a7c464736f6c634300081a0033

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading
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.