creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/ContextUpgradeable.sol\";\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {\n    address private _owner;\n\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Initializes the contract setting the deployer as the initial owner.\n     */\n    function __Ownable_init() internal onlyInitializing {\n        __Ownable_init_unchained();\n    }\n\n    function __Ownable_init_unchained() internal onlyInitializing {\n        _transferOwnership(_msgSender());\n    }\n\n    /**\n     * @dev Throws if called by any account other than the owner.\n     */\n    modifier onlyOwner() {\n        _checkOwner();\n        _;\n    }\n\n    /**\n     * @dev Returns the address of the current owner.\n     */\n    function owner() public view virtual returns (address) {\n        return _owner;\n    }\n\n    /**\n     * @dev Throws if the sender is not the owner.\n     */\n    function _checkOwner() internal view virtual {\n        require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n    }\n\n    /**\n     * @dev Leaves the contract without owner. It will not be possible to call\n     * `onlyOwner` functions anymore. Can only be called by the current owner.\n     *\n     * NOTE: Renouncing ownership will leave the contract without an owner,\n     * thereby removing any functionality that is only available to the owner.\n     */\n    function renounceOwnership() public virtual onlyOwner {\n        _transferOwnership(address(0));\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Can only be called by the current owner.\n     */\n    function transferOwnership(address newOwner) public virtual onlyOwner {\n        require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n        _transferOwnership(newOwner);\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Internal function without access restriction.\n     */\n    function _transferOwnership(address newOwner) internal virtual {\n        address oldOwner = _owner;\n        _owner = newOwner;\n        emit OwnershipTransferred(oldOwner, newOwner);\n    }\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[49] private __gap;\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.1) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../../utils/AddressUpgradeable.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * contract MyToken is ERC20Upgradeable {\n *     function initialize() initializer public {\n *         __ERC20_init(\"MyToken\", \"MTK\");\n *     }\n * }\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n *     function initializeV2() reinitializer(2) public {\n *         __ERC20Permit_init(\"MyToken\");\n *     }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n *     _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n    /**\n     * @dev Indicates that the contract has been initialized.\n     * @custom:oz-retyped-from bool\n     */\n    uint8 private _initialized;\n\n    /**\n     * @dev Indicates that the contract is in the process of being initialized.\n     */\n    bool private _initializing;\n\n    /**\n     * @dev Triggered when the contract has been initialized or reinitialized.\n     */\n    event Initialized(uint8 version);\n\n    /**\n     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n     * `onlyInitializing` functions can be used to initialize parent contracts.\n     *\n     * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a\n     * constructor.\n     *\n     * Emits an {Initialized} event.\n     */\n    modifier initializer() {\n        bool isTopLevelCall = !_initializing;\n        require(\n            (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),\n            \"Initializable: contract is already initialized\"\n        );\n        _initialized = 1;\n        if (isTopLevelCall) {\n            _initializing = true;\n        }\n        _;\n        if (isTopLevelCall) {\n            _initializing = false;\n            emit Initialized(1);\n        }\n    }\n\n    /**\n     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n     * used to initialize parent contracts.\n     *\n     * A reinitializer may be used after the original initialization step. This is essential to configure modules that\n     * are added through upgrades and that require initialization.\n     *\n     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`\n     * cannot be nested. If one is invoked in the context of another, execution will revert.\n     *\n     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n     * a contract, executing them in the right order is up to the developer or operator.\n     *\n     * WARNING: setting the version to 255 will prevent any future reinitialization.\n     *\n     * Emits an {Initialized} event.\n     */\n    modifier reinitializer(uint8 version) {\n        require(!_initializing && _initialized < version, \"Initializable: contract is already initialized\");\n        _initialized = version;\n        _initializing = true;\n        _;\n        _initializing = false;\n        emit Initialized(version);\n    }\n\n    /**\n     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n     * {initializer} and {reinitializer} modifiers, directly or indirectly.\n     */\n    modifier onlyInitializing() {\n        require(_initializing, \"Initializable: contract is not initializing\");\n        _;\n    }\n\n    /**\n     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n     * through proxies.\n     *\n     * Emits an {Initialized} event the first time it is successfully executed.\n     */\n    function _disableInitializers() internal virtual {\n        require(!_initializing, \"Initializable: contract is initializing\");\n        if (_initialized < type(uint8).max) {\n            _initialized = type(uint8).max;\n            emit Initialized(type(uint8).max);\n        }\n    }\n\n    /**\n     * @dev Returns the highest version that has been initialized. See {reinitializer}.\n     */\n    function _getInitializedVersion() internal view returns (uint8) {\n        return _initialized;\n    }\n\n    /**\n     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.\n     */\n    function _isInitializing() internal view returns (bool) {\n        return _initializing;\n    }\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/ContextUpgradeable.sol\";\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module which allows children to implement an emergency stop\n * mechanism that can be triggered by an authorized account.\n *\n * This module is used through inheritance. It will make available the\n * modifiers `whenNotPaused` and `whenPaused`, which can be applied to\n * the functions of your contract. Note that they will not be pausable by\n * simply including this module, only once the modifiers are put in place.\n */\nabstract contract PausableUpgradeable is Initializable, ContextUpgradeable {\n    /**\n     * @dev Emitted when the pause is triggered by `account`.\n     */\n    event Paused(address account);\n\n    /**\n     * @dev Emitted when the pause is lifted by `account`.\n     */\n    event Unpaused(address account);\n\n    bool private _paused;\n\n    /**\n     * @dev Initializes the contract in unpaused state.\n     */\n    function __Pausable_init() internal onlyInitializing {\n        __Pausable_init_unchained();\n    }\n\n    function __Pausable_init_unchained() internal onlyInitializing {\n        _paused = false;\n    }\n\n    /**\n     * @dev Modifier to make a function callable only when the contract is not paused.\n     *\n     * Requirements:\n     *\n     * - The contract must not be paused.\n     */\n    modifier whenNotPaused() {\n        _requireNotPaused();\n        _;\n    }\n\n    /**\n     * @dev Modifier to make a function callable only when the contract is paused.\n     *\n     * Requirements:\n     *\n     * - The contract must be paused.\n     */\n    modifier whenPaused() {\n        _requirePaused();\n        _;\n    }\n\n    /**\n     * @dev Returns true if the contract is paused, and false otherwise.\n     */\n    function paused() public view virtual returns (bool) {\n        return _paused;\n    }\n\n    /**\n     * @dev Throws if the contract is paused.\n     */\n    function _requireNotPaused() internal view virtual {\n        require(!paused(), \"Pausable: paused\");\n    }\n\n    /**\n     * @dev Throws if the contract is not paused.\n     */\n    function _requirePaused() internal view virtual {\n        require(paused(), \"Pausable: not paused\");\n    }\n\n    /**\n     * @dev Triggers stopped state.\n     *\n     * Requirements:\n     *\n     * - The contract must not be paused.\n     */\n    function _pause() internal virtual whenNotPaused {\n        _paused = true;\n        emit Paused(_msgSender());\n    }\n\n    /**\n     * @dev Returns to normal state.\n     *\n     * Requirements:\n     *\n     * - The contract must be paused.\n     */\n    function _unpause() internal virtual whenPaused {\n        _paused = false;\n        emit Unpaused(_msgSender());\n    }\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[49] private __gap;\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (security/ReentrancyGuard.sol)\n\npragma solidity ^0.8.0;\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuardUpgradeable is Initializable {\n    // Booleans are more expensive than uint256 or any type that takes up a full\n    // word because each write operation emits an extra SLOAD to first read the\n    // slot's contents, replace the bits taken up by the boolean, and then write\n    // back. This is the compiler's defense against contract upgrades and\n    // pointer aliasing, and it cannot be disabled.\n\n    // The values being non-zero value makes deployment a bit more expensive,\n    // but in exchange the refund on every call to nonReentrant will be lower in\n    // amount. Since refunds are capped to a percentage of the total\n    // transaction's gas, it is best to keep them low in cases like this one, to\n    // increase the likelihood of the full refund coming into effect.\n    uint256 private constant _NOT_ENTERED = 1;\n    uint256 private constant _ENTERED = 2;\n\n    uint256 private _status;\n\n    function __ReentrancyGuard_init() internal onlyInitializing {\n        __ReentrancyGuard_init_unchained();\n    }\n\n    function __ReentrancyGuard_init_unchained() internal onlyInitializing {\n        _status = _NOT_ENTERED;\n    }\n\n    /**\n     * @dev Prevents a contract from calling itself, directly or indirectly.\n     * Calling a `nonReentrant` function from another `nonReentrant`\n     * function is not supported. It is possible to prevent this from happening\n     * by making the `nonReentrant` function external, and making it call a\n     * `private` function that does the actual work.\n     */\n    modifier nonReentrant() {\n        _nonReentrantBefore();\n        _;\n        _nonReentrantAfter();\n    }\n\n    function _nonReentrantBefore() private {\n        // On the first call to nonReentrant, _status will be _NOT_ENTERED\n        require(_status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n        // Any calls to nonReentrant after this point will fail\n        _status = _ENTERED;\n    }\n\n    function _nonReentrantAfter() private {\n        // By storing the original value once again, a refund is triggered (see\n        // https://eips.ethereum.org/EIPS/eip-2200)\n        _status = _NOT_ENTERED;\n    }\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[49] private __gap;\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20Upgradeable.sol\";\nimport \"./extensions/IERC20MetadataUpgradeable.sol\";\nimport \"../../utils/ContextUpgradeable.sol\";\nimport \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {\n    mapping(address => uint256) private _balances;\n\n    mapping(address => mapping(address => uint256)) private _allowances;\n\n    uint256 private _totalSupply;\n\n    string private _name;\n    string private _symbol;\n\n    /**\n     * @dev Sets the values for {name} and {symbol}.\n     *\n     * The default value of {decimals} is 18. To select a different value for\n     * {decimals} you should overload it.\n     *\n     * All two of these values are immutable: they can only be set once during\n     * construction.\n     */\n    function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {\n        __ERC20_init_unchained(name_, symbol_);\n    }\n\n    function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {\n        _name = name_;\n        _symbol = symbol_;\n    }\n\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() public view virtual override returns (string memory) {\n        return _name;\n    }\n\n    /**\n     * @dev Returns the symbol of the token, usually a shorter version of the\n     * name.\n     */\n    function symbol() public view virtual override returns (string memory) {\n        return _symbol;\n    }\n\n    /**\n     * @dev Returns the number of decimals used to get its user representation.\n     * For example, if `decimals` equals `2`, a balance of `505` tokens should\n     * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n     *\n     * Tokens usually opt for a value of 18, imitating the relationship between\n     * Ether and Wei. This is the value {ERC20} uses, unless this function is\n     * overridden;\n     *\n     * NOTE: This information is only used for _display_ purposes: it in\n     * no way affects any of the arithmetic of the contract, including\n     * {IERC20-balanceOf} and {IERC20-transfer}.\n     */\n    function decimals() public view virtual override returns (uint8) {\n        return 18;\n    }\n\n    /**\n     * @dev See {IERC20-totalSupply}.\n     */\n    function totalSupply() public view virtual override returns (uint256) {\n        return _totalSupply;\n    }\n\n    /**\n     * @dev See {IERC20-balanceOf}.\n     */\n    function balanceOf(address account) public view virtual override returns (uint256) {\n        return _balances[account];\n    }\n\n    /**\n     * @dev See {IERC20-transfer}.\n     *\n     * Requirements:\n     *\n     * - `to` cannot be the zero address.\n     * - the caller must have a balance of at least `amount`.\n     */\n    function transfer(address to, uint256 amount) public virtual override returns (bool) {\n        address owner = _msgSender();\n        _transfer(owner, to, amount);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-allowance}.\n     */\n    function allowance(address owner, address spender) public view virtual override returns (uint256) {\n        return _allowances[owner][spender];\n    }\n\n    /**\n     * @dev See {IERC20-approve}.\n     *\n     * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n     * `transferFrom`. This is semantically equivalent to an infinite approval.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     */\n    function approve(address spender, uint256 amount) public virtual override returns (bool) {\n        address owner = _msgSender();\n        _approve(owner, spender, amount);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-transferFrom}.\n     *\n     * Emits an {Approval} event indicating the updated allowance. This is not\n     * required by the EIP. See the note at the beginning of {ERC20}.\n     *\n     * NOTE: Does not update the allowance if the current allowance\n     * is the maximum `uint256`.\n     *\n     * Requirements:\n     *\n     * - `from` and `to` cannot be the zero address.\n     * - `from` must have a balance of at least `amount`.\n     * - the caller must have allowance for ``from``'s tokens of at least\n     * `amount`.\n     */\n    function transferFrom(\n        address from,\n        address to,\n        uint256 amount\n    ) public virtual override returns (bool) {\n        address spender = _msgSender();\n        _spendAllowance(from, spender, amount);\n        _transfer(from, to, amount);\n        return true;\n    }\n\n    /**\n     * @dev Atomically increases the allowance granted to `spender` by the caller.\n     *\n     * This is an alternative to {approve} that can be used as a mitigation for\n     * problems described in {IERC20-approve}.\n     *\n     * Emits an {Approval} event indicating the updated allowance.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     */\n    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n        address owner = _msgSender();\n        _approve(owner, spender, allowance(owner, spender) + addedValue);\n        return true;\n    }\n\n    /**\n     * @dev Atomically decreases the allowance granted to `spender` by the caller.\n     *\n     * This is an alternative to {approve} that can be used as a mitigation for\n     * problems described in {IERC20-approve}.\n     *\n     * Emits an {Approval} event indicating the updated allowance.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     * - `spender` must have allowance for the caller of at least\n     * `subtractedValue`.\n     */\n    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n        address owner = _msgSender();\n        uint256 currentAllowance = allowance(owner, spender);\n        require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n        unchecked {\n            _approve(owner, spender, currentAllowance - subtractedValue);\n        }\n\n        return true;\n    }\n\n    /**\n     * @dev Moves `amount` of tokens from `from` to `to`.\n     *\n     * This internal function is equivalent to {transfer}, and can be used to\n     * e.g. implement automatic token fees, slashing mechanisms, etc.\n     *\n     * Emits a {Transfer} event.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     * - `from` must have a balance of at least `amount`.\n     */\n    function _transfer(\n        address from,\n        address to,\n        uint256 amount\n    ) internal virtual {\n        require(from != address(0), \"ERC20: transfer from the zero address\");\n        require(to != address(0), \"ERC20: transfer to the zero address\");\n\n        _beforeTokenTransfer(from, to, amount);\n\n        uint256 fromBalance = _balances[from];\n        require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n        unchecked {\n            _balances[from] = fromBalance - amount;\n            // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by\n            // decrementing then incrementing.\n            _balances[to] += amount;\n        }\n\n        emit Transfer(from, to, amount);\n\n        _afterTokenTransfer(from, to, amount);\n    }\n\n    /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n     * the total supply.\n     *\n     * Emits a {Transfer} event with `from` set to the zero address.\n     *\n     * Requirements:\n     *\n     * - `account` cannot be the zero address.\n     */\n    function _mint(address account, uint256 amount) internal virtual {\n        require(account != address(0), \"ERC20: mint to the zero address\");\n\n        _beforeTokenTransfer(address(0), account, amount);\n\n        _totalSupply += amount;\n        unchecked {\n            // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.\n            _balances[account] += amount;\n        }\n        emit Transfer(address(0), account, amount);\n\n        _afterTokenTransfer(address(0), account, amount);\n    }\n\n    /**\n     * @dev Destroys `amount` tokens from `account`, reducing the\n     * total supply.\n     *\n     * Emits a {Transfer} event with `to` set to the zero address.\n     *\n     * Requirements:\n     *\n     * - `account` cannot be the zero address.\n     * - `account` must have at least `amount` tokens.\n     */\n    function _burn(address account, uint256 amount) internal virtual {\n        require(account != address(0), \"ERC20: burn from the zero address\");\n\n        _beforeTokenTransfer(account, address(0), amount);\n\n        uint256 accountBalance = _balances[account];\n        require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n        unchecked {\n            _balances[account] = accountBalance - amount;\n            // Overflow not possible: amount <= accountBalance <= totalSupply.\n            _totalSupply -= amount;\n        }\n\n        emit Transfer(account, address(0), amount);\n\n        _afterTokenTransfer(account, address(0), amount);\n    }\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n     *\n     * This internal function is equivalent to `approve`, and can be used to\n     * e.g. set automatic allowances for certain subsystems, etc.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `owner` cannot be the zero address.\n     * - `spender` cannot be the zero address.\n     */\n    function _approve(\n        address owner,\n        address spender,\n        uint256 amount\n    ) internal virtual {\n        require(owner != address(0), \"ERC20: approve from the zero address\");\n        require(spender != address(0), \"ERC20: approve to the zero address\");\n\n        _allowances[owner][spender] = amount;\n        emit Approval(owner, spender, amount);\n    }\n\n    /**\n     * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n     *\n     * Does not update the allowance amount in case of infinite allowance.\n     * Revert if not enough allowance is available.\n     *\n     * Might emit an {Approval} event.\n     */\n    function _spendAllowance(\n        address owner,\n        address spender,\n        uint256 amount\n    ) internal virtual {\n        uint256 currentAllowance = allowance(owner, spender);\n        if (currentAllowance != type(uint256).max) {\n            require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n            unchecked {\n                _approve(owner, spender, currentAllowance - amount);\n            }\n        }\n    }\n\n    /**\n     * @dev Hook that is called before any transfer of tokens. This includes\n     * minting and burning.\n     *\n     * Calling conditions:\n     *\n     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n     * will be transferred to `to`.\n     * - when `from` is zero, `amount` tokens will be minted for `to`.\n     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n     * - `from` and `to` are never both zero.\n     *\n     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n     */\n    function _beforeTokenTransfer(\n        address from,\n        address to,\n        uint256 amount\n    ) internal virtual {}\n\n    /**\n     * @dev Hook that is called after any transfer of tokens. This includes\n     * minting and burning.\n     *\n     * Calling conditions:\n     *\n     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n     * has been transferred to `to`.\n     * - when `from` is zero, `amount` tokens have been minted for `to`.\n     * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n     * - `from` and `to` are never both zero.\n     *\n     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n     */\n    function _afterTokenTransfer(\n        address from,\n        address to,\n        uint256 amount\n    ) internal virtual {}\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[45] private __gap;\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20Upgradeable.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20MetadataUpgradeable is IERC20Upgradeable {\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() external view returns (string memory);\n\n    /**\n     * @dev Returns the symbol of the token.\n     */\n    function symbol() external view returns (string memory);\n\n    /**\n     * @dev Returns the decimals places of the token.\n     */\n    function decimals() external view returns (uint8);\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20Upgradeable {\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n\n    /**\n     * @dev Returns the amount of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the amount of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves `amount` tokens from the caller's account to `to`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address to, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender's allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Moves `amount` tokens from `from` to `to` using the\n     * allowance mechanism. `amount` is then deducted from the caller's\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(\n        address from,\n        address to,\n        uint256 amount\n    ) external returns (bool);\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary AddressUpgradeable {\n    /**\n     * @dev Returns true if `account` is a contract.\n     *\n     * [IMPORTANT]\n     * ====\n     * It is unsafe to assume that an address for which this function returns\n     * false is an externally-owned account (EOA) and not a contract.\n     *\n     * Among others, `isContract` will return false for the following\n     * types of addresses:\n     *\n     *  - an externally-owned account\n     *  - a contract in construction\n     *  - an address where a contract will be created\n     *  - an address where a contract lived, but was destroyed\n     * ====\n     *\n     * [IMPORTANT]\n     * ====\n     * You shouldn't rely on `isContract` to protect against flash loan attacks!\n     *\n     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n     * constructor.\n     * ====\n     */\n    function isContract(address account) internal view returns (bool) {\n        // This method relies on extcodesize/address.code.length, which returns 0\n        // for contracts in construction, since the code is only stored at the end\n        // of the constructor execution.\n\n        return account.code.length > 0;\n    }\n\n    /**\n     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n     * `recipient`, forwarding all available gas and reverting on errors.\n     *\n     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n     * of certain opcodes, possibly making contracts go over the 2300 gas limit\n     * imposed by `transfer`, making them unable to receive funds via\n     * `transfer`. {sendValue} removes this limitation.\n     *\n     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n     *\n     * IMPORTANT: because control is transferred to `recipient`, care must be\n     * taken to not create reentrancy vulnerabilities. Consider using\n     * {ReentrancyGuard} or the\n     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n        (bool success, ) = recipient.call{value: amount}(\"\");\n        require(success, \"Address: unable to send value, recipient may have reverted\");\n    }\n\n    /**\n     * @dev Performs a Solidity function call using a low level `call`. A\n     * plain `call` is an unsafe replacement for a function call: use this\n     * function instead.\n     *\n     * If `target` reverts with a revert reason, it is bubbled up by this\n     * function (like regular Solidity function calls).\n     *\n     * Returns the raw returned data. To convert to the expected return value,\n     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n     *\n     * Requirements:\n     *\n     * - `target` must be a contract.\n     * - calling `target` with `data` must not revert.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0, \"Address: low-level call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n     * `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but also transferring `value` wei to `target`.\n     *\n     * Requirements:\n     *\n     * - the calling contract must have an ETH balance of at least `value`.\n     * - the called Solidity function must be `payable`.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(\n        address target,\n        bytes memory data,\n        uint256 value\n    ) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n     * with `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(\n        address target,\n        bytes memory data,\n        uint256 value,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        require(address(this).balance >= value, \"Address: insufficient balance for call\");\n        (bool success, bytes memory returndata) = target.call{value: value}(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n        return functionStaticCall(target, data, \"Address: low-level static call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.staticcall(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n     *\n     * _Available since v4.8._\n     */\n    function verifyCallResultFromTarget(\n        address target,\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        if (success) {\n            if (returndata.length == 0) {\n                // only check isContract if the call was successful and the return data is empty\n                // otherwise we already know that it was a contract\n                require(isContract(target), \"Address: call to non-contract\");\n            }\n            return returndata;\n        } else {\n            _revert(returndata, errorMessage);\n        }\n    }\n\n    /**\n     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n     * revert reason or using the provided one.\n     *\n     * _Available since v4.3._\n     */\n    function verifyCallResult(\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal pure returns (bytes memory) {\n        if (success) {\n            return returndata;\n        } else {\n            _revert(returndata, errorMessage);\n        }\n    }\n\n    function _revert(bytes memory returndata, string memory errorMessage) private pure {\n        // Look for revert reason and bubble it up if present\n        if (returndata.length > 0) {\n            // The easiest way to bubble the revert reason is using memory via assembly\n            /// @solidity memory-safe-assembly\n            assembly {\n                let returndata_size := mload(returndata)\n                revert(add(32, returndata), returndata_size)\n            }\n        } else {\n            revert(errorMessage);\n        }\n    }\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract ContextUpgradeable is Initializable {\n    function __Context_init() internal onlyInitializing {\n    }\n\n    function __Context_init_unchained() internal onlyInitializing {\n    }\n    function _msgSender() internal view virtual returns (address) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes calldata) {\n        return msg.data;\n    }\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[50] private __gap;\n}\n"
      },
      "@openzeppelin/contracts/token/ERC20/IERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n\n    /**\n     * @dev Returns the amount of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the amount of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves `amount` tokens from the caller's account to `to`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address to, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender's allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Moves `amount` tokens from `from` to `to` using the\n     * allowance mechanism. `amount` is then deducted from the caller's\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(\n        address from,\n        address to,\n        uint256 amount\n    ) external returns (bool);\n}\n"
      },
      "@openzeppelin/contracts/utils/math/Math.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n    enum Rounding {\n        Down, // Toward negative infinity\n        Up, // Toward infinity\n        Zero // Toward zero\n    }\n\n    /**\n     * @dev Returns the largest of two numbers.\n     */\n    function max(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a > b ? a : b;\n    }\n\n    /**\n     * @dev Returns the smallest of two numbers.\n     */\n    function min(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a < b ? a : b;\n    }\n\n    /**\n     * @dev Returns the average of two numbers. The result is rounded towards\n     * zero.\n     */\n    function average(uint256 a, uint256 b) internal pure returns (uint256) {\n        // (a + b) / 2 can overflow.\n        return (a & b) + (a ^ b) / 2;\n    }\n\n    /**\n     * @dev Returns the ceiling of the division of two numbers.\n     *\n     * This differs from standard division with `/` in that it rounds up instead\n     * of rounding down.\n     */\n    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n        // (a + b - 1) / b can overflow on addition, so we distribute.\n        return a == 0 ? 0 : (a - 1) / b + 1;\n    }\n\n    /**\n     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)\n     * with further edits by Uniswap Labs also under MIT license.\n     */\n    function mulDiv(\n        uint256 x,\n        uint256 y,\n        uint256 denominator\n    ) internal pure returns (uint256 result) {\n        unchecked {\n            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n            // variables such that product = prod1 * 2^256 + prod0.\n            uint256 prod0; // Least significant 256 bits of the product\n            uint256 prod1; // Most significant 256 bits of the product\n            assembly {\n                let mm := mulmod(x, y, not(0))\n                prod0 := mul(x, y)\n                prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n            }\n\n            // Handle non-overflow cases, 256 by 256 division.\n            if (prod1 == 0) {\n                return prod0 / denominator;\n            }\n\n            // Make sure the result is less than 2^256. Also prevents denominator == 0.\n            require(denominator > prod1);\n\n            ///////////////////////////////////////////////\n            // 512 by 256 division.\n            ///////////////////////////////////////////////\n\n            // Make division exact by subtracting the remainder from [prod1 prod0].\n            uint256 remainder;\n            assembly {\n                // Compute remainder using mulmod.\n                remainder := mulmod(x, y, denominator)\n\n                // Subtract 256 bit number from 512 bit number.\n                prod1 := sub(prod1, gt(remainder, prod0))\n                prod0 := sub(prod0, remainder)\n            }\n\n            // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.\n            // See https://cs.stackexchange.com/q/138556/92363.\n\n            // Does not overflow because the denominator cannot be zero at this stage in the function.\n            uint256 twos = denominator & (~denominator + 1);\n            assembly {\n                // Divide denominator by twos.\n                denominator := div(denominator, twos)\n\n                // Divide [prod1 prod0] by twos.\n                prod0 := div(prod0, twos)\n\n                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n                twos := add(div(sub(0, twos), twos), 1)\n            }\n\n            // Shift in bits from prod1 into prod0.\n            prod0 |= prod1 * twos;\n\n            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n            // four bits. That is, denominator * inv = 1 mod 2^4.\n            uint256 inverse = (3 * denominator) ^ 2;\n\n            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works\n            // in modular arithmetic, doubling the correct bits in each step.\n            inverse *= 2 - denominator * inverse; // inverse mod 2^8\n            inverse *= 2 - denominator * inverse; // inverse mod 2^16\n            inverse *= 2 - denominator * inverse; // inverse mod 2^32\n            inverse *= 2 - denominator * inverse; // inverse mod 2^64\n            inverse *= 2 - denominator * inverse; // inverse mod 2^128\n            inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n            // is no longer required.\n            result = prod0 * inverse;\n            return result;\n        }\n    }\n\n    /**\n     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n     */\n    function mulDiv(\n        uint256 x,\n        uint256 y,\n        uint256 denominator,\n        Rounding rounding\n    ) internal pure returns (uint256) {\n        uint256 result = mulDiv(x, y, denominator);\n        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {\n            result += 1;\n        }\n        return result;\n    }\n\n    /**\n     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.\n     *\n     * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n     */\n    function sqrt(uint256 a) internal pure returns (uint256) {\n        if (a == 0) {\n            return 0;\n        }\n\n        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n        //\n        // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n        //\n        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n        //\n        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n        uint256 result = 1 << (log2(a) >> 1);\n\n        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n        // into the expected uint128 result.\n        unchecked {\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            return min(result, a / result);\n        }\n    }\n\n    /**\n     * @notice Calculates sqrt(a), following the selected rounding direction.\n     */\n    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = sqrt(a);\n            return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 2, rounded down, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >> 128 > 0) {\n                value >>= 128;\n                result += 128;\n            }\n            if (value >> 64 > 0) {\n                value >>= 64;\n                result += 64;\n            }\n            if (value >> 32 > 0) {\n                value >>= 32;\n                result += 32;\n            }\n            if (value >> 16 > 0) {\n                value >>= 16;\n                result += 16;\n            }\n            if (value >> 8 > 0) {\n                value >>= 8;\n                result += 8;\n            }\n            if (value >> 4 > 0) {\n                value >>= 4;\n                result += 4;\n            }\n            if (value >> 2 > 0) {\n                value >>= 2;\n                result += 2;\n            }\n            if (value >> 1 > 0) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log2(value);\n            return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 10, rounded down, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >= 10**64) {\n                value /= 10**64;\n                result += 64;\n            }\n            if (value >= 10**32) {\n                value /= 10**32;\n                result += 32;\n            }\n            if (value >= 10**16) {\n                value /= 10**16;\n                result += 16;\n            }\n            if (value >= 10**8) {\n                value /= 10**8;\n                result += 8;\n            }\n            if (value >= 10**4) {\n                value /= 10**4;\n                result += 4;\n            }\n            if (value >= 10**2) {\n                value /= 10**2;\n                result += 2;\n            }\n            if (value >= 10**1) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log10(value);\n            return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 256, rounded down, of a positive value.\n     * Returns 0 if given 0.\n     *\n     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n     */\n    function log256(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >> 128 > 0) {\n                value >>= 128;\n                result += 16;\n            }\n            if (value >> 64 > 0) {\n                value >>= 64;\n                result += 8;\n            }\n            if (value >> 32 > 0) {\n                value >>= 32;\n                result += 4;\n            }\n            if (value >> 16 > 0) {\n                value >>= 16;\n                result += 2;\n            }\n            if (value >> 8 > 0) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log256(value);\n            return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);\n        }\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/Strings.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./math/Math.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n    bytes16 private constant _SYMBOLS = \"0123456789abcdef\";\n    uint8 private constant _ADDRESS_LENGTH = 20;\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n     */\n    function toString(uint256 value) internal pure returns (string memory) {\n        unchecked {\n            uint256 length = Math.log10(value) + 1;\n            string memory buffer = new string(length);\n            uint256 ptr;\n            /// @solidity memory-safe-assembly\n            assembly {\n                ptr := add(buffer, add(32, length))\n            }\n            while (true) {\n                ptr--;\n                /// @solidity memory-safe-assembly\n                assembly {\n                    mstore8(ptr, byte(mod(value, 10), _SYMBOLS))\n                }\n                value /= 10;\n                if (value == 0) break;\n            }\n            return buffer;\n        }\n    }\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n     */\n    function toHexString(uint256 value) internal pure returns (string memory) {\n        unchecked {\n            return toHexString(value, Math.log256(value) + 1);\n        }\n    }\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n     */\n    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n        bytes memory buffer = new bytes(2 * length + 2);\n        buffer[0] = \"0\";\n        buffer[1] = \"x\";\n        for (uint256 i = 2 * length + 1; i > 1; --i) {\n            buffer[i] = _SYMBOLS[value & 0xf];\n            value >>= 4;\n        }\n        require(value == 0, \"Strings: hex length insufficient\");\n        return string(buffer);\n    }\n\n    /**\n     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n     */\n    function toHexString(address addr) internal pure returns (string memory) {\n        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n    }\n}\n"
      },
      "contracts/interfaces/IBorrowerOperations.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\ninterface IBorrowerOperations {\n    function openTrove(\n        uint256 _maxFee,\n        uint256 _LUSDAmount,\n        address _upperHint,\n        address _lowerHint\n    ) external payable;\n\n    function closeTrove() external;\n\n    function adjustTrove(\n        uint256 _maxFee,\n        uint256 _collWithdrawal,\n        uint256 _debtChange,\n        bool isDebtIncrease,\n        address _upperHint,\n        address _lowerHint\n    ) external payable;\n\n    function withdrawColl(uint256 _amount, address _upperHint, address _lowerHint) external;\n\n    function claimCollateral() external;\n}\n"
      },
      "contracts/interfaces/ILiquityBase.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport {IPriceFeed} from \"./IPriceFeed.sol\";\n\ninterface ILiquityBase {\n    function priceFeed() external view returns (IPriceFeed);\n}\n"
      },
      "contracts/interfaces/ILiquityHandler.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\ninterface ILiquityHandler {\n    event BatchProcessed(\n        uint256 nonce,\n        uint256 amountLUSD,\n        uint256 totalSupply,\n        uint256 totalTroveDebt,\n        uint256 amountETH,\n        uint256 closed\n    );\n    event DisableBorrow(uint256 nonce, uint256 amountLUSD);\n    event SetL2HandlerGasFee(uint256 newL2HandlerGasFee);\n    event SetL2BridgeEthFee(uint256 newL2BridgeEthFee);\n    event SetRelayer(address newRelayer);\n\n    enum TroveAction {\n        NONE,\n        BORROW,\n        REPAY\n    }\n\n    /// @notice Liquity actions\n    /// @param Borrow swap tokens from ETH to LUSD.\n    /// @param Repay swap tokens from LUSD to ETH.\n    enum Action {\n        Borrow,\n        Repay\n    }\n\n    /// @notice Liquity actions\n    /// @param nonce the batch nonce.\n    /// @param amountETH the total amount ETH.\n    /// @param amountLUSD the total amount LUSD.\n    struct RequestPayload {\n        uint256 nonce;\n        uint256 amountETH;\n        uint256 amountLUSD;\n    }\n\n    /// @notice Liquity actions\n    /// @param nonce the batch nonce.\n    /// @param amountLUSD the total amount LUSD.\n    /// @param totalSupply the total tb supplied.\n    /// @param totalTroveDebt the total trove debt.\n    /// @param amountETH the total amount ETH.\n    /// @param closed state if the trove was closed.\n    struct ResponsePayload {\n        uint256 nonce;\n        uint256 amountLUSD;\n        uint256 totalSupply;\n        uint256 totalTroveDebt;\n        uint256 amountETH;\n        uint256 closed;\n    }\n}\n"
      },
      "contracts/interfaces/IPriceFeed.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\ninterface IPriceFeed {\n    function fetchPrice() external returns (uint256);\n}\n"
      },
      "contracts/interfaces/ISortedTroves.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\ninterface ISortedTroves {\n    function getLast() external view returns (address);\n\n    function getNext(address _id) external view returns (address);\n\n    function getPrev(address _id) external view returns (address);\n\n    function findInsertPosition(\n        uint256 _ICR,\n        address _prevId,\n        address _nextId\n    ) external view returns (address, address);\n}\n"
      },
      "contracts/interfaces/IStarknetBridge.sol": {
        "content": "// SPDX-License-Identifier: Apache-2.0.\npragma solidity 0.8.17;\n\ninterface IStarknetBridge {\n    function deposit(uint256 amount, uint256 l2Recipient) external payable;\n\n    function withdraw(uint256 amount, address recipient) external;\n}\n"
      },
      "contracts/interfaces/IStarknetMessaging.sol": {
        "content": "// SPDX-License-Identifier: Apache-2.0.\npragma solidity 0.8.17;\n\ninterface IStarknetMessaging {\n    /// @notice Consumes a message that was sent from an L2 contract. Returns the hash of the message.\n    function consumeMessageFromL2(\n        uint256 fromAddress,\n        uint256[] calldata payload\n    ) external returns (bytes32);\n\n    /// @notice Execute a function call on L2\n    function sendMessageToL2(\n        uint256 toAddress,\n        uint256 selector,\n        uint256[] calldata payload\n    ) external payable returns (bytes32, uint256);\n\n    function l2ToL1Messages(bytes32 msgHash) external view returns (uint256);\n}\n"
      },
      "contracts/interfaces/ITroveManager.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport {ILiquityBase} from \"./ILiquityBase.sol\";\n\ninterface ITroveManager is ILiquityBase {\n    function getCurrentICR(address _borrower, uint256 _price) external view returns (uint256);\n\n    function liquidate(address _borrower) external;\n\n    function liquidateTroves(uint256 _n) external;\n\n    function redeemCollateral(\n        uint256 _LUSDAmount,\n        address _firstRedemptionHint,\n        address _upperPartialRedemptionHint,\n        address _lowerPartialRedemptionHint,\n        uint256 _partialRedemptionHintNICR,\n        uint256 _maxIterations,\n        uint256 _maxFee\n    ) external;\n\n    function getEntireDebtAndColl(\n        address _borrower\n    )\n        external\n        view\n        returns (\n            uint256 debt,\n            uint256 coll,\n            uint256 pendingLUSDDebtReward,\n            uint256 pendingETHReward\n        );\n\n    function closeTrove(address _borrower) external;\n\n    function getTroveDebt(address _borrower) external view returns (uint256);\n\n    function getBorrowingRateWithDecay() external view returns (uint256);\n\n    function getTroveStatus(address _borrower) external view returns (uint256);\n\n    function getTCR(uint256 _price) external view returns (uint256);\n\n    function checkRecoveryMode(uint256 _price) external view returns (bool);\n}\n"
      },
      "contracts/lib/ErrorLib.sol": {
        "content": "// SPDX-License-Identifier: Apache-2.0.\npragma solidity 0.8.17;\n\nlibrary ErrorLib {\n    error InvalidBatchNonce();\n    error NotRelayer();\n    error TroveAddressAlreadySet();\n    error NonZeroTotalSupply();\n    error OwnerNotLast();\n    error TransferFailed(address token);\n    error Resend();\n}\n"
      },
      "contracts/LiquityHandler.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {OwnableUpgradeable} from \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport {PausableUpgradeable} from \"@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol\";\nimport {ReentrancyGuardUpgradeable} from \"@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol\";\n\nimport {ILiquityHandler} from \"./interfaces/ILiquityHandler.sol\";\nimport {ErrorLib} from \"./lib/ErrorLib.sol\";\nimport {Messaging} from \"./Messaging.sol\";\nimport {TroveHandler} from \"./TroveHandler.sol\";\n\n/// @title TroveHandler contract.\n/// @author Spaceshard team 2023.\ncontract LiquityHandler is\n    ILiquityHandler,\n    OwnableUpgradeable,\n    PausableUpgradeable,\n    ReentrancyGuardUpgradeable,\n    Messaging,\n    TroveHandler\n{\n    /// @notice The function selector we have to call on L2 to consume the L1 message.\n    uint256 public constant L2_HANDLER_SELECTOR =\n        0x10e13e50cb99b6b3c8270ec6e16acfccbe1164a629d74b43549567a77593aff;\n\n    /// @notice The liquity L2 trove contract address.\n    uint256 public l2Trove;\n\n    /// @notice Starknet ETH bridge address.\n    address public l1ETHBridge;\n\n    /// @notice Starknet LUSD bridge address.\n    address public l1LUSDBridge;\n\n    /// @notice The LUSD address.\n    address public lusd;\n\n    /// @notice The L2 Eth contract.\n    uint256 public l2ETHBridge;\n\n    /// @notice The L2 LUSD contract.\n    uint256 public l2LUSDBridge;\n\n    /// @notice The amount of ETH fees the l1 liquity contract has to call response_handler function on L2.\n    uint256 public l2HandlerGasFee;\n\n    /// @notice The amount of ETH fees the l1 liquity contract has to pay to execute the transaction on L2.\n    uint256 public l2BridgeEthFee;\n\n    /// @notice The relayer L1 address.\n    address public relayer;\n\n    /// @notice stop borrows.\n    bool public canBorrow;\n\n    /// @notice Allows to execyte batches in.\n    uint256 public batchCounter;\n\n    /// @notice Store the l2 message payload.\n    ResponsePayload public messagePayload;\n\n    /// @custom:oz-upgrades-unsafe-allow constructor\n    constructor() initializer {}\n\n    /// @notice Initialier the contract state.\n    /// @param _troveManager troveManager address\n    /// @param _sortedTroves sortedTroves address\n    /// @param _borrowerOperations borrowerOperations address\n    /// @param _starknetCore starknetCore address\n    /// @param _l1ETHBridge l1ETHBridge address\n    /// @param _l2ETHBridge l2ETHBridge address\n    /// @param _l1LUSDBridge l1LUSDBridge address\n    /// @param _l2LUSDBridge l2LUSDBridge address\n    /// @param _initialICRPerc initialICRPerc address\n    /// @param _relayer relayer address\n    /// @param _lusd lusd address\n    function initialize(\n        address _troveManager,\n        address _sortedTroves,\n        address _borrowerOperations,\n        address _starknetCore,\n        address _l1ETHBridge,\n        uint256 _l2ETHBridge,\n        address _l1LUSDBridge,\n        uint256 _l2LUSDBridge,\n        uint256 _initialICRPerc,\n        address _relayer,\n        address _lusd\n    ) public payable initializer {\n        __Pausable_init();\n        __Ownable_init();\n        initializeMessaging(_starknetCore);\n        initializeTroveHandler(_troveManager, _sortedTroves, _borrowerOperations, _initialICRPerc);\n        relayer = _relayer;\n        l1ETHBridge = _l1ETHBridge;\n        l2ETHBridge = _l2ETHBridge;\n        l1LUSDBridge = _l1LUSDBridge;\n        l2LUSDBridge = _l2LUSDBridge;\n        lusd = _lusd;\n        canBorrow = true;\n    }\n\n    /// @notice execute a batch.\n    /// @dev In phase 2 this could be made permissionless.\n    /// @param _payload the payload data.\n    /// @param _l2BridgeEthFee max fee to borrow.\n    /// @param _maxFees max fee to borrow.\n    function executeBatch(\n        RequestPayload calldata _payload,\n        uint256 _l2BridgeEthFee,\n        uint64 _maxFees,\n        bool _withdrawTokens\n    ) external payable nonReentrant whenNotPaused {\n        if (batchCounter + 1 != _payload.nonce) revert ErrorLib.InvalidBatchNonce();\n        if (msg.sender != relayer) revert ErrorLib.NotRelayer();\n\n        uint256 l2TroveMem = l2Trove;\n        // Consume the message sent from the L2 trove.\n        _consumeL2Message(l2TroveMem, _getRequestMessageData(_payload));\n\n        // Withdraw tokens from Starknet bridges.\n        if (_withdrawTokens) {\n            _withdrawTokensFromBridges(_payload.amountETH, _payload.amountLUSD);\n        }\n\n        // Get the trove status.\n        Status troveStatus = getTroveStatus();\n\n        // If the trove has been liquidated, the batch is returned to L2 to refund users.\n        if (troveStatus != Status.active) {\n            _sendBackBatchWithoutProcessing(_payload, _l2BridgeEthFee);\n            return;\n        }\n\n        uint256 amountLUSDOut = 0;\n        uint256 amountETHOut = 0;\n        // Store canBorrow in memory to save gas.\n        bool canBorrowMem = canBorrow;\n\n        (uint256 troveDebt, uint256 troveColl, , ) = troveManager.getEntireDebtAndColl(\n            address(this)\n        );\n\n        // If a redistribution has taken place, borrowing is disabled and users can only repay their debts.\n        if (totalSupply() != troveDebt && _payload.amountETH > 0) {\n            if (canBorrowMem) {\n                canBorrow = false;\n                canBorrowMem = false;\n            }\n            amountETHOut = _payload.amountETH;\n            emit DisableBorrow(_payload.nonce, _payload.amountETH);\n        }\n\n        (TroveAction action, uint256 actionInput) = getActionInputs(\n            canBorrowMem,\n            _payload.amountETH,\n            _payload.amountLUSD,\n            troveDebt,\n            troveColl\n        );\n\n        if (action == TroveAction.BORROW && canBorrowMem && _payload.amountETH > 0) {\n            uint256 amountLUSDBorrowed = _borrow(actionInput, _maxFees);\n            amountLUSDOut = amountLUSDBorrowed + _payload.amountLUSD;\n            amountETHOut = _payload.amountETH - actionInput;\n        } else if (action == TroveAction.REPAY && _payload.amountLUSD > 0) {\n            uint256 collateral = _repay(actionInput);\n            amountETHOut += collateral + (canBorrowMem ? _payload.amountETH : 0);\n            amountLUSDOut = _payload.amountLUSD - actionInput;\n        } else {\n            amountETHOut = _payload.amountETH;\n            amountLUSDOut = _payload.amountLUSD;\n        }\n\n        if (amountLUSDOut > 0) {\n            depositToBridgeToken(l1LUSDBridge, l2TroveMem, amountLUSDOut, _l2BridgeEthFee);\n        }\n\n        if (amountETHOut > 0) {\n            depositToBridgeToken(\n                l1ETHBridge,\n                l2TroveMem,\n                amountETHOut,\n                amountETHOut + _l2BridgeEthFee\n            );\n        }\n\n        (troveDebt, , , ) = troveManager.getEntireDebtAndColl(address(this));\n\n        messagePayload = ResponsePayload({\n            nonce: _payload.nonce,\n            amountLUSD: amountLUSDOut,\n            totalSupply: totalSupply() - initialSupply,\n            totalTroveDebt: troveDebt - initialSupply,\n            amountETH: amountETHOut,\n            closed: 0x0\n        });\n\n        emit BatchProcessed(\n            _payload.nonce,\n            amountLUSDOut,\n            totalSupply() - initialSupply,\n            troveDebt - initialSupply,\n            amountETHOut,\n            0x0\n        );\n    }\n\n    /// @notice Admin function used to create a trove on liquity core contract.\n    /// @param _maxFees max fee to pay.\n    function openTrove(uint256 _maxFees) external payable onlyOwner {\n        (address upperHint, address lowerHint) = _getHints();\n        _openTrove(lusd, upperHint, lowerHint, _maxFees);\n    }\n\n    /// @notice Admin function used to close a trove on liquity core contract.\n    function closeTrove() external payable onlyOwner {\n        _closeTrove(lusd);\n    }\n\n    /// @notice Admin function used to recover tokens that where accidentiliy transferred to this address.\n    /// @param _token The address of the token to recover.\n    /// @param _to The address to send the tokens to.\n    function recoverTokens(address _token, address _to) external onlyOwner {\n        if (_token == address(0)) {\n            payable(_to).transfer(address(this).balance);\n        } else {\n            IERC20(_token).transfer(_to, IERC20(_token).balanceOf(address(this)));\n        }\n    }\n\n    /// @notice Admin function used to pause the contract in the case of an emergency.\n    function pause() external onlyOwner {\n        _pause();\n    }\n\n    /// @notice Admin function used to unpause the contract\n    function unpause() external onlyOwner {\n        _unpause();\n    }\n\n    /// @notice Set relayer address.\n    /// @param _newRelayer relayer address.\n    function setRelayer(address _newRelayer) external onlyOwner {\n        relayer = _newRelayer;\n        emit SetRelayer(_newRelayer);\n    }\n\n    /// @notice set trove address.\n    /// @param _l2Trove The liquity L2 trove.\n    function setL2TroveAddress(uint256 _l2Trove) external onlyOwner {\n        l2Trove = _l2Trove;\n    }\n\n    /// @notice set trove address.\n    /// @param _l1LUSDBridge The lusd bridge on L1.\n    /// @param _l2LUSDBridge The lusd bridge on L2.\n    function setLUSDBridge(address _l1LUSDBridge, uint256 _l2LUSDBridge) external onlyOwner {\n        l2LUSDBridge = _l2LUSDBridge;\n        l1LUSDBridge = _l1LUSDBridge;\n    }\n\n    function _getRequestMessageData(\n        RequestPayload memory _payload\n    ) internal pure returns (uint256[] memory data) {\n        (uint256 lowNonce, uint256 highNonce) = u256(_payload.nonce);\n        (uint256 lowAmountETH, uint256 highAmountETH) = u256(_payload.amountETH);\n        (uint256 lowAmountLUSD, uint256 highAmountLUSD) = u256(_payload.amountLUSD);\n        data = new uint256[](6);\n        data[0] = lowNonce;\n        data[1] = highNonce;\n        data[2] = lowAmountETH;\n        data[3] = highAmountETH;\n        data[4] = lowAmountLUSD;\n        data[5] = highAmountLUSD;\n    }\n\n    function _getResponseMessageData(\n        ResponsePayload memory _payload\n    ) internal pure returns (uint256[] memory data) {\n        (uint256 lowNonce, uint256 highNonce) = u256(_payload.nonce);\n        (uint256 lowAmountLUSD, uint256 highAmountLUSD) = u256(_payload.amountLUSD);\n        (uint256 lowAmountETH, uint256 highAmountETH) = u256(_payload.amountETH);\n        (uint256 lowTotalSupply, uint256 highTotalSupply) = u256(_payload.totalSupply);\n        (uint256 lowTotalTroveDebt, uint256 highTotalTroveDebt) = u256(_payload.totalTroveDebt);\n        data = new uint256[](11);\n        data[0] = lowNonce;\n        data[1] = highNonce;\n        data[2] = lowAmountLUSD;\n        data[3] = highAmountLUSD;\n        data[4] = lowTotalSupply;\n        data[5] = highTotalSupply;\n        data[6] = lowTotalTroveDebt;\n        data[7] = highTotalTroveDebt;\n        data[8] = lowAmountETH;\n        data[9] = highAmountETH;\n        data[10] = _payload.closed;\n    }\n\n    function _withdrawTokensFromBridges(uint256 _amountETH, uint256 _amountLUSD) private {\n        if (_amountETH > 0) {\n            _withdrawTokenFromBridge(l1ETHBridge, address(this), _amountETH);\n        }\n\n        if (_amountLUSD > 0) {\n            _withdrawTokenFromBridge(l1LUSDBridge, address(this), _amountLUSD);\n        }\n    }\n\n    function _sendBackBatchWithoutProcessing(\n        RequestPayload calldata _payload,\n        uint256 _l2BridgeEthFee\n    ) private {\n        uint256 l2TroveMem = l2Trove;\n        if (_payload.amountLUSD > 0) {\n            depositToBridgeToken(l1LUSDBridge, l2TroveMem, _payload.amountLUSD, _l2BridgeEthFee);\n        }\n\n        if (_payload.amountETH > 0) {\n            depositToBridgeToken(\n                l1ETHBridge,\n                l2TroveMem,\n                _payload.amountETH,\n                _payload.amountETH + _l2BridgeEthFee\n            );\n        }\n\n        messagePayload = ResponsePayload({\n            nonce: _payload.nonce,\n            amountLUSD: 0,\n            totalSupply: 0,\n            totalTroveDebt: 0,\n            amountETH: 0,\n            closed: 0x1\n        });\n\n        emit BatchProcessed(_payload.nonce, 0, 0, 0, 0, 0x1);\n    }\n\n    function approveToBridge(uint256 _amount) external onlyOwner {\n        IERC20(lusd).approve(l1LUSDBridge, _amount);\n    }\n\n    /// @notice Allows to calculate which action we have to call `borrow`, `repay` or swap in place.\n    /// @param _canBorrow if borrowing is enabled.\n    /// @param _amountETH amount ETH\n    /// @param _amountLUSD amount LUSD\n    /// @param _troveDebt amount trove debt\n    /// @param _troveColl amount trove collaterals\n    /// @return action the actions that should be triggered.\n    /// @return actionAmountInput the actions input amount.\n    function getActionInputs(\n        bool _canBorrow,\n        uint256 _amountETH,\n        uint256 _amountLUSD,\n        uint256 _troveDebt,\n        uint256 _troveColl\n    ) public returns (TroveAction action, uint256 actionAmountInput) {\n        if (!_canBorrow) {\n            action = TroveAction.REPAY;\n            actionAmountInput = _amountLUSD;\n            return (action, actionAmountInput);\n        }\n\n        uint256 amountLUSDToBorrow = computeAmtToBorrow(_amountETH);\n        if (amountLUSDToBorrow < _amountLUSD) {\n            // No need to borrow as the current LUSD attached can cover the borrowing.\n            // Call repay only.\n            action = TroveAction.REPAY;\n            actionAmountInput = _amountLUSD - amountLUSDToBorrow;\n        } else if (amountLUSDToBorrow > _amountLUSD) {\n            // No need to repay as the current ETH attached can cover the repaying.\n            // Call borrow only.\n            uint256 amountETHRepay = computeCollateralAmountOut(\n                _amountLUSD,\n                _troveDebt,\n                _troveColl\n            );\n            action = TroveAction.BORROW;\n            actionAmountInput = _amountETH - amountETHRepay;\n        } else {\n            action = TroveAction.NONE;\n            actionAmountInput = 0;\n        }\n    }\n\n    /// @notice Allows the admin to send the message again to L2.\n    /// @param _resend if true resend the message to L2.\n    function sendMessageToL2(bool _resend) external payable {\n        ResponsePayload memory messagePayloadMem = messagePayload;\n        if (_resend && messagePayloadMem.nonce != batchCounter) revert ErrorLib.Resend();\n        if (!_resend) {\n            if (messagePayloadMem.nonce != batchCounter + 1) revert ErrorLib.InvalidBatchNonce();\n            batchCounter++;\n        }\n\n        _sendMessageToL2(\n            l2Trove,\n            L2_HANDLER_SELECTOR,\n            _getResponseMessageData(\n                ResponsePayload({\n                    nonce: messagePayloadMem.nonce,\n                    amountLUSD: messagePayloadMem.amountLUSD,\n                    totalSupply: messagePayloadMem.totalSupply,\n                    totalTroveDebt: messagePayloadMem.totalTroveDebt,\n                    amountETH: messagePayloadMem.amountETH,\n                    closed: messagePayloadMem.closed\n                })\n            ),\n            msg.value\n        );\n    }\n\n    function adminRepay(uint256 _amountLUSD, address _receiver) external onlyOwner {\n        _adminRepay(_amountLUSD, _receiver, lusd);\n    }\n}\n"
      },
      "contracts/Messaging.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport {IStarknetMessaging} from \"./interfaces/IStarknetMessaging.sol\";\nimport {IStarknetBridge} from \"./interfaces/IStarknetBridge.sol\";\n\n/// @title Messaging contract.\n/// @author Spaceshard team 2023.\ncontract Messaging {\n    uint256 private constant UINT256_PART_SIZE_BITS = 128;\n    uint256 private constant UINT256_PART_SIZE = 2 ** UINT256_PART_SIZE_BITS;\n\n    /// @notice Starknet messaging interface.\n    IStarknetMessaging public starknetCore;\n\n    /// @notice initialize the trove handler.\n    /// @param _starknetCore Starknet core interface.\n    function initializeMessaging(address _starknetCore) internal {\n        starknetCore = IStarknetMessaging(_starknetCore);\n    }\n\n    /// @notice Consume l2 message.\n    function _consumeL2Message(uint256 l2ContractAddress, uint256[] memory data) internal {\n        starknetCore.consumeMessageFromL2(l2ContractAddress, data);\n    }\n\n    /// @notice Withdraw tokens from Starkgate bridge.\n    function _withdrawTokenFromBridge(\n        address l1BridgeAddress,\n        address _receiver,\n        uint256 _amount\n    ) internal {\n        IStarknetBridge(l1BridgeAddress).withdraw(_amount, _receiver);\n    }\n\n    /// @notice deposit tokens to Starknet bridge.\n    function depositToBridgeToken(\n        address l1BridgeAddress,\n        uint256 _l2Receiver,\n        uint256 _amount,\n        uint256 _value\n    ) internal {\n        if (_amount > 0) {\n            IStarknetBridge(l1BridgeAddress).deposit{value: _value}(_amount, _l2Receiver);\n        }\n    }\n\n    /// @notice send message to l2.\n    function _sendMessageToL2(\n        uint256 _l2Contract,\n        uint256 _selector,\n        uint256[] memory payload,\n        uint256 _value\n    ) internal {\n        starknetCore.sendMessageToL2{value: _value}(_l2Contract, _selector, payload);\n    }\n\n    function u256(uint256 _value) internal pure returns (uint256 low, uint256 high) {\n        low = _value & (UINT256_PART_SIZE - 1);\n        high = _value >> UINT256_PART_SIZE_BITS;\n    }\n}\n"
      },
      "contracts/TroveHandler.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {ERC20Upgradeable} from \"@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol\";\nimport {ErrorLib} from \"./lib/ErrorLib.sol\";\nimport {Strings} from \"@openzeppelin/contracts/utils/Strings.sol\";\nimport {ITroveManager} from \"./interfaces/ITroveManager.sol\";\nimport {ISortedTroves} from \"./interfaces/ISortedTroves.sol\";\nimport {IBorrowerOperations} from \"./interfaces/IBorrowerOperations.sol\";\n\n/// @title TroveHandler contract.\n/// @author Spaceshard team 2023.\n/// @notice The contract handels the interactions with liquity contract.\n/// @dev UTILIZE EXISTING AZTECT LIQUITY BRIDGE CONTRACT\n/// THE MORE WE RE-USE EXISTING CODE, THE BETTER\ncontract TroveHandler is ERC20Upgradeable {\n    using Strings for uint256;\n\n    /// @notice Trove status taken from TroveManager.sol\n    enum Status {\n        nonExistent,\n        active,\n        closedByOwner,\n        closedByLiquidation,\n        closedByRedemption\n    }\n\n    /// @notice troveManager the trove manager interface.\n    ITroveManager internal troveManager;\n\n    /// @notice sortedManager the sorted manager interface.\n    ISortedTroves internal sortedManager;\n\n    /// @notice borrowerOperations the borrower operations interface.\n    IBorrowerOperations internal borrowerOperations;\n\n    /// @notice The individual collateral rate.\n    uint256 public INITIAL_ICR;\n\n    /// @notice The amount of dust to leave in the contract.\n    /// @dev Optimization based on EIP-1087.\n    uint256 public constant DUST = 1;\n\n    /// @notice Initial debt supply to create a trove.\n    uint256 public initialSupply;\n\n    /// @notice Used to check whether collateral has already been claimed during redemptions.\n    bool private collateralClaimed;\n\n    /// @notice initialize the trove handler.\n    /// @param _troveManager the trove manager interface.\n    /// @param _sortedManager the sorted manager interface.\n    /// @param _borrowerOperations the borrower operations interface.\n    /// @param _initialICRPerc Collateral ratio denominated in percents to be used when opening the Trove\n    function initializeTroveHandler(\n        address _troveManager,\n        address _sortedManager,\n        address _borrowerOperations,\n        uint256 _initialICRPerc\n    ) internal {\n        __ERC20_init(\"TroveDebt\", string(abi.encodePacked(\"TD-\", _initialICRPerc.toString())));\n        troveManager = ITroveManager(_troveManager);\n        sortedManager = ISortedTroves(_sortedManager);\n        borrowerOperations = IBorrowerOperations(_borrowerOperations);\n        INITIAL_ICR = _initialICRPerc * 1e16;\n        _mint(address(this), DUST);\n    }\n\n    /// @notice Borrow LUSD\n    /// @param _collateral Amount of ETH denominated in Wei\n    /// @param _maxFee Maximum borrowing fee\n    /// @return lusdBorrowed Amount of LUSD borrowed.\n    function _borrow(uint256 _collateral, uint64 _maxFee) internal returns (uint256 lusdBorrowed) {\n        ITroveManager troveManagerMem = troveManager;\n        lusdBorrowed = computeAmtToBorrow(_collateral); // LUSD amount to borrow\n        (uint256 debtBefore, , , ) = troveManagerMem.getEntireDebtAndColl(address(this));\n\n        (address upperHint, address lowerHint) = _getHints();\n        borrowerOperations.adjustTrove{value: _collateral}(\n            _maxFee,\n            0,\n            lusdBorrowed,\n            true,\n            upperHint,\n            lowerHint\n        );\n        (uint256 debtAfter, , , ) = troveManagerMem.getEntireDebtAndColl(address(this));\n        // tbMinted = amount of TB to mint = (debtIncrease [LUSD] / debtBefore [LUSD]) * tbTotalSupply\n        // debtIncrease = debtAfter - debtBefore\n        // In case no redistribution took place (TB/LUSD = 1) then debt_before = TB_total_supply\n        // and debt_increase amount of TB is minted.\n        // In case there was redistribution, 1 TB corresponds to more than 1 LUSD and the amount of TB minted\n        // will be lower than the amount of LUSD borrowed.\n        uint256 tbMinted = ((debtAfter - debtBefore) * totalSupply()) / debtBefore;\n        _mint(address(this), tbMinted);\n    }\n\n    /// @notice Repay debt.\n    /// @param _amountLUSD Amount of LUSD.\n    /// @return collateral Amount of collateral withdrawn.\n    function _repay(uint256 _amountLUSD) internal returns (uint256 collateral) {\n        (uint256 debtBefore, uint256 collBefore, , ) = troveManager.getEntireDebtAndColl(\n            address(this)\n        );\n        uint256 tbTotalSupply = totalSupply(); // SLOAD optimization\n        uint256 tbToBurn = (_amountLUSD * tbTotalSupply) / debtBefore;\n        uint256 collToWithdraw = computeCollateralAmountOut(_amountLUSD, debtBefore, collBefore);\n\n        (address upperHint, address lowerHint) = _getHints();\n        uint256 beforeBalance = address(this).balance;\n\n        borrowerOperations.adjustTrove(0, collToWithdraw, _amountLUSD, false, upperHint, lowerHint);\n        uint256 afterBalance = address(this).balance;\n        collateral = afterBalance - beforeBalance;\n\n        _burn(address(this), tbToBurn);\n    }\n\n    /// @notice A function which opens the trove.\n    /// @param _upperHint Address of a Trove with a position in the sorted list before the correct insert position.\n    /// @param _lowerHint Address of a Trove with a position in the sorted list after the correct insert position.\n    /// See https://github.com/liquity/dev#supplying-hints-to-trove-operations for more details about hints.\n    /// @param _maxFee Maximum borrower fee.\n    /// @dev Sufficient amount of ETH has to be send so that at least 2000 LUSD gets borrowed. 2000 LUSD is a minimum\n    /// amount allowed by Liquity.\n    function _openTrove(\n        address _lusd,\n        address _upperHint,\n        address _lowerHint,\n        uint256 _maxFee\n    ) internal {\n        ITroveManager troveManagerMem = troveManager;\n        // Checks whether the trove can be safely opened/reopened\n        if (totalSupply() != 0) revert ErrorLib.NonZeroTotalSupply();\n\n        uint256 amtToBorrow = computeAmtToBorrow(msg.value);\n\n        (uint256 debtBefore, , , ) = troveManagerMem.getEntireDebtAndColl(address(this));\n        borrowerOperations.openTrove{value: msg.value}(\n            _maxFee,\n            amtToBorrow,\n            _upperHint,\n            _lowerHint\n        );\n        (uint256 debtAfter, , , ) = troveManagerMem.getEntireDebtAndColl(address(this));\n\n        IERC20(_lusd).transfer(msg.sender, IERC20(_lusd).balanceOf(address(this)) - DUST);\n        initialSupply = debtAfter - debtBefore;\n\n        // I mint TB token to msg.sender to be able to track collateral ownership. Minted amount equals debt increase.\n        _mint(msg.sender, debtAfter - debtBefore);\n    }\n\n    /// @notice Compute how much LUSD to borrow against collateral in order to keep ICR constant and by how much total\n    /// trove debt will increase.\n    /// @param _collateral Amount of ETH denominated in Wei\n    /// @return amtToBorrow Amount of LUSD to borrow to keep ICR constant.\n    /// + borrowing fee)\n    /// @dev I don\"t use view modifier here because the function updates PriceFeed state.\n    ///\n    /// Since the Trove opening and adjustment processes have desired amount of LUSD to borrow on the input and not\n    /// the desired ICR I have to do the computation of borrowing fee \"backwards\". Here are the operations I did in order\n    /// to get the final formula:\n    ///      1) debtIncrease = amtToBorrow + amtToBorrow * BORROWING_RATE / DECIMAL_PRECISION + 200LUSD\n    ///      2) debtIncrease - 200LUSD = amtToBorrow * (1 + BORROWING_RATE / DECIMAL_PRECISION)\n    ///      3) amtToBorrow = (debtIncrease - 200LUSD) / (1 + BORROWING_RATE / DECIMAL_PRECISION)\n    ///      4) amtToBorrow = (debtIncrease - 200LUSD) * DECIMAL_PRECISION / (DECIMAL_PRECISION + BORROWING_RATE)\n    /// Note1: For trove adjustments (not opening) remove the 200 LUSD fee compensation from the formulas above.\n    /// Note2: Step 4 is necessary to avoid loss of precision. BORROWING_RATE / DECIMAL_PRECISION was rounded to 0.\n    /// Note3: The borrowing fee computation is on this line in Liquity code: https://github.com/liquity/dev/blob/cb583ddf5e7de6010e196cfe706bd0ca816ea40e/packages/contracts/contracts/TroveManager.sol#L1433\n    function computeAmtToBorrow(uint256 _collateral) public returns (uint256 amtToBorrow) {\n        ITroveManager troveManagerMem = troveManager;\n\n        uint256 price = troveManagerMem.priceFeed().fetchPrice();\n        if (troveManagerMem.getTroveStatus(address(this)) == 1) {\n            // Trove is active - use current ICR and not the initial one\n            uint256 icr = troveManagerMem.getCurrentICR(address(this), price);\n            amtToBorrow = (_collateral * price) / icr;\n        } else {\n            // Trove is inactive - I will use initial ICR to compute debt\n            // 200e18 - 200 LUSD gas compensation to liquidators\n            amtToBorrow = (_collateral * price) / INITIAL_ICR - 200e18;\n        }\n\n        if (!troveManagerMem.checkRecoveryMode(price)) {\n            // Liquity is not in recovery mode so borrowing fee applies\n            uint256 borrowingRate = troveManagerMem.getBorrowingRateWithDecay();\n            amtToBorrow = (amtToBorrow * 1e18) / (borrowingRate + 1e18);\n        }\n    }\n\n    /// @notice Compute how much ETH is received after paying LUSD amount.\n    /// @param _amountLUSD amount LUSD.\n    /// @param _troveDebt trove debt.\n    /// @param _troveColl trove coll.\n    /// @return _collateral received ETH collateral.\n    function computeCollateralAmountOut(\n        uint256 _amountLUSD,\n        uint256 _troveDebt,\n        uint256 _troveColl\n    ) public pure returns (uint256 _collateral) {\n        return (_amountLUSD * _troveColl) / _troveDebt;\n    }\n\n    /// @notice Get lower and upper insertion hints.\n    /// @return upperHint Upper insertion hint.\n    /// @return lowerHint Lower insertion hint.\n    /// @dev See https://github.com/liquity/dev#supplying-hints-to-trove-operations for more details on hints.\n    function _getHints() internal view returns (address upperHint, address lowerHint) {\n        ISortedTroves sortedManagerMem = sortedManager;\n        return (sortedManagerMem.getPrev(address(this)), sortedManagerMem.getNext(address(this)));\n    }\n\n    /// @inheritdoc\tERC20Upgradeable\n    function totalSupply() public view override(ERC20Upgradeable) returns (uint256) {\n        return super.totalSupply() - DUST;\n    }\n\n    /// @notice Get the trove status.\n    /// @return status the trove status.\n    function getTroveStatus() public view returns (Status) {\n        return Status(troveManager.getTroveStatus(address(this)));\n    }\n\n    /// @notice A function which closes the trove.\n    /// @dev LUSD allowance has to be at least (remaining debt - 200 LUSD).\n    function _closeTrove(address _lusd) internal {\n        address payable owner = payable(msg.sender);\n        uint256 ownerTBBalance = balanceOf(owner);\n        if (ownerTBBalance != totalSupply()) revert ErrorLib.OwnerNotLast();\n\n        _burn(owner, ownerTBBalance);\n\n        Status troveStatus = Status(troveManager.getTroveStatus(address(this)));\n        if (troveStatus == Status.active) {\n            (uint256 remainingDebt, , , ) = troveManager.getEntireDebtAndColl(address(this));\n            // 200e18 is a part of debt which gets repaid from LUSD_GAS_COMPENSATION.\n            if (!IERC20(_lusd).transferFrom(owner, address(this), remainingDebt - 200e18)) {\n                revert ErrorLib.TransferFailed(_lusd);\n            }\n            borrowerOperations.closeTrove();\n        } else if (\n            troveStatus == Status.closedByRedemption || troveStatus == Status.closedByLiquidation\n        ) {\n            if (!collateralClaimed) {\n                borrowerOperations.claimCollateral();\n            } else {\n                collateralClaimed = false;\n            }\n        }\n        owner.transfer(address(this).balance);\n    }\n\n    /// @notice A function which closes the trove.\n    receive() external payable {}\n\n    function _adminRepay(uint256 _amountLUSD, address _receiver, address _lusd) internal {\n        (uint256 debtBefore, uint256 collBefore, , ) = troveManager.getEntireDebtAndColl(\n            address(this)\n        );\n        uint256 collToWithdraw = computeCollateralAmountOut(_amountLUSD, debtBefore, collBefore);\n        IERC20(_lusd).transferFrom(msg.sender, address(this), _amountLUSD);\n        (address upperHint, address lowerHint) = _getHints();\n        borrowerOperations.adjustTrove(0, collToWithdraw, _amountLUSD, false, upperHint, lowerHint);\n\n        uint256 ehtBalance = address(this).balance;\n        payable(_receiver).transfer(ehtBalance);\n    }\n}\n"
      }
    },
    "settings": {
      "optimizer": {
        "enabled": true,
        "runs": 1000,
        "details": {
          "yul": true
        }
      },
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "metadata": {
        "useLiteralContent": true
      },
      "libraries": {}
    }
  }}