ETH Price: $2,532.65 (+1.56%)

Transaction Decoder

Block:
22854029 at Jul-05-2025 03:52:11 PM +UTC
Transaction Fee:
0.000137447022237096 ETH $0.35
Gas Used:
260,472 Gas / 0.527684443 Gwei

Emitted Events:

321 FiatTokenProxy.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x000000000000000000000000b8f275fbf7a959f4bce59999a2ef122a099e81a8, 0x0000000000000000000000005523985926aa12ba58dc5ad00ddca99678d7227e, 00000000000000000000000000000000000000000000000000000000000b71b0 )
322 FiatTokenProxy.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x000000000000000000000000b8f275fbf7a959f4bce59999a2ef122a099e81a8, 0x000000000000000000000000f621fb08bbe51af70e7e0f4ea63496894166ff7f, 0000000000000000000000000000000000000000000000000000000006d71558 )
323 FiatTokenProxy.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x000000000000000000000000f621fb08bbe51af70e7e0f4ea63496894166ff7f, 0x0000000000000000000000005141b82f5ffda4c6fe1e372978f1c5427640a190, 0000000000000000000000000000000000000000000000000000000006d71558 )
324 FiatTokenProxy.0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925( 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925, 0x0000000000000000000000005141b82f5ffda4c6fe1e372978f1c5427640a190, 0x0000000000000000000000009995855c00494d039ab6792f18e368e530dff931, 0000000000000000000000000000000000000000000000000000000006d71558 )
325 Core.( 614e2ba87050c938ccff35e3260b7ea9c6f5303365b8ee172ebd07e916015046, ffffffffffffffffff5d853066e1084d00000000000000000000000006d71558, 000000000000000000fac37f422f9bb34000d2160d5e2d04953aeffcfed1d2c5 )
326 FiatTokenProxy.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x0000000000000000000000005141b82f5ffda4c6fe1e372978f1c5427640a190, 0x000000000000000000000000e0e0e08a6a4b9dc7bd67bcb7aade5cf48157d444, 0000000000000000000000000000000000000000000000000000000006d71558 )
327 TransparentUpgradeableProxy.0xaeef64b7687b985665b6620c7fa271b6f051a3fbe2bfc366fb9c964602eb6d26( 0xaeef64b7687b985665b6620c7fa271b6f051a3fbe2bfc366fb9c964602eb6d26, 0xe08499ad1fe9417b0f6e8c5bfb60995035af35503c6e0a9d07f8689b736180f7, 0x378e5b01e7420a80a8d0b40f920d93578b3e0e8353c1e086df2d3626c3a55d0f, 0x000000000000000000000000f8ed3a12832b106b0edc947b007c64439ad74402, 0000000000000000000000000000000000000000000000000000000006d71558, 00000000000000000000000000000000000000000000000000000000000b71b0, 000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48 )

Account State Difference:

  Address   Before After State Difference Code
0xA0b86991...E3606eB48
0xb8f275fB...A099e81A8
(Symbiosis Finance: Portal)
0xd99ac068...81ADbe0C3
0.574260529767577168 Eth
Nonce: 144109
0.574123082745340072 Eth
Nonce: 144110
0.000137447022237096
(BuilderNet)
29.342360536462716593 Eth29.342373602375872049 Eth0.000013065913155456
0xe0e0e08A...48157d444
(Ekubo: Core)
329.917240044755300596 Eth329.871506066482411841 Eth0.045733978272888755
0xF8Ed3A12...39Ad74402 0.003094717416859516 Eth0.048828695689748271 Eth0.045733978272888755

Execution Trace

TransparentUpgradeableProxy.84d61c97( )
  • BridgeV2.receiveRequestV2Signed( _callData=0xC23A4C8800000000000000000000000000000000000000000000000000000000000B71B0378E5B01E7420A80A8D0B40F920D93578B3E0E8353C1E086DF2D3626C3A55D0FE08499AD1FE9417B0F6E8C5BFB60995035AF35503C6E0A9D07F8689B736180F7000000000000000000000000F8ED3A12832B106B0EDC947B007C64439AD744020000000000000000000000000000000000000000000000000000000006E28708000000000000000000000000A0B86991C6218B36C1D19D4A2E9EB0CE3606EB480000000000000000000000001111111254EEB25477B68FB85ED929F73A960582000000000000000000000000000000000000000000000000000000000000012000000000000000000000000000000000000000000000000000000000000000C4000000000000000000000000000000000000000000000000000000000000032812AA3CAF0000000000000000000000005141B82F5FFDA4C6FE1E372978F1C5427640A190000000000000000000000000A0B86991C6218B36C1D19D4A2E9EB0CE3606EB48000000000000000000000000EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE0000000000000000000000005141B82F5FFDA4C6FE1E372978F1C5427640A190000000000000000000000000F8ED3A12832B106B0EDC947B007C64439AD744020000000000000000000000000000000000000000000000000000000006BC935E000000000000000000000000000000000000000000000000009DA0F12E717E790000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000014000000000000000000000000000000000000000000000000000000000000001600000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000018800000000000000000000000000000000000000000000000000016A00001A0020D6BDBF78A0B86991C6218B36C1D19D4A2E9EB0CE3606EB4851309995855C00494D039AB6792F18E368E530DFF931A0B86991C6218B36C1D19D4A2E9EB0CE3606EB480084F196187F0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000A0B86991C6218B36C1D19D4A2E9EB0CE3606EB480000000000000000000000000000000000000000000D1B71758E21960000137E000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000FFFF9A5889F795069A41A8A3000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000001111111254EEB25477B68FB85ED929F73A9605820000000000000000000000000000000000000000000000003D2F69A4000000000000000000000000000000000000000000000000, _receiveSide=0xb8f275fBf7A959F4BCE59999A2EF122A099e81A8, signature=0x56BADA39A331409707470F61749DCA4382821C7D75387B1F8CAB77EB727418DA1FA9F9917D1E76CCA9ECB3F0BF3EE94283C8B5567AE6EA8F7450AD6BE2E4AE371B )
    • Null: 0x000...001.e4b34a53( )
    • TransparentUpgradeableProxy.c23a4c88( )
      • Portal.metaUnsynthesize( _stableBridgingFee=750000, _crossChainID=378E5B01E7420A80A8D0B40F920D93578B3E0E8353C1E086DF2D3626C3A55D0F, _externalID=E08499AD1FE9417B0F6E8C5BFB60995035AF35503C6E0A9D07F8689B736180F7, _to=0xF8Ed3A12832b106b0EDc947b007C64439Ad74402, _amount=115509000, _rToken=0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48, _finalReceiveSide=0x1111111254EEB25477B68fb85Ed929f73A960582, _finalCalldata=0x12AA3CAF0000000000000000000000005141B82F5FFDA4C6FE1E372978F1C5427640A190000000000000000000000000A0B86991C6218B36C1D19D4A2E9EB0CE3606EB48000000000000000000000000EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE0000000000000000000000005141B82F5FFDA4C6FE1E372978F1C5427640A190000000000000000000000000F8ED3A12832B106B0EDC947B007C64439AD744020000000000000000000000000000000000000000000000000000000006BC935E000000000000000000000000000000000000000000000000009DA0F12E717E790000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000014000000000000000000000000000000000000000000000000000000000000001600000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000018800000000000000000000000000000000000000000000000000016A00001A0020D6BDBF78A0B86991C6218B36C1D19D4A2E9EB0CE3606EB4851309995855C00494D039AB6792F18E368E530DFF931A0B86991C6218B36C1D19D4A2E9EB0CE3606EB480084F196187F0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000A0B86991C6218B36C1D19D4A2E9EB0CE3606EB480000000000000000000000000000000000000000000D1B71758E21960000137E000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000FFFF9A5889F795069A41A8A3000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000001111111254EEB25477B68FB85ED929F73A9605820000000000000000000000000000000000000000000000003D2F69A4, _finalOffset=196 )
        • FiatTokenProxy.a9059cbb( )
          • FiatTokenV2_2.transfer( to=0x5523985926Aa12BA58DC5Ad00DDca99678D7227E, value=750000 ) => ( True )
          • FiatTokenProxy.a9059cbb( )
            • FiatTokenV2_2.transfer( to=0xf621Fb08BBE51aF70e7E0F4EA63496894166Ff7F, value=114759000 ) => ( True )
            • MetaRouter.externalCall( _token=0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48, _amount=114759000, _receiveSide=0x1111111254EEB25477B68fb85Ed929f73A960582, _calldata=0x12AA3CAF0000000000000000000000005141B82F5FFDA4C6FE1E372978F1C5427640A190000000000000000000000000A0B86991C6218B36C1D19D4A2E9EB0CE3606EB48000000000000000000000000EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE0000000000000000000000005141B82F5FFDA4C6FE1E372978F1C5427640A190000000000000000000000000F8ED3A12832B106B0EDC947B007C64439AD744020000000000000000000000000000000000000000000000000000000006BC935E000000000000000000000000000000000000000000000000009DA0F12E717E790000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000014000000000000000000000000000000000000000000000000000000000000001600000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000018800000000000000000000000000000000000000000000000000016A00001A0020D6BDBF78A0B86991C6218B36C1D19D4A2E9EB0CE3606EB4851309995855C00494D039AB6792F18E368E530DFF931A0B86991C6218B36C1D19D4A2E9EB0CE3606EB480084F196187F0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000A0B86991C6218B36C1D19D4A2E9EB0CE3606EB480000000000000000000000000000000000000000000D1B71758E21960000137E000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000FFFF9A5889F795069A41A8A3000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000001111111254EEB25477B68FB85ED929F73A9605820000000000000000000000000000000000000000000000003D2F69A4, _offset=196, _to=0xF8Ed3A12832b106b0EDc947b007C64439Ad74402 )
              • FiatTokenProxy.dd62ed3e( )
                • FiatTokenV2_2.allowance( owner=0xf621Fb08BBE51aF70e7E0F4EA63496894166Ff7F, spender=0x1111111254EEB25477B68fb85Ed929f73A960582 ) => ( 115792089237316195423570985008687907853269984665640564039457583942257727250181 )
                • AggregationRouterV5.swap( executor=0x5141B82f5fFDa4c6fE1E372978F1C5427640a190, desc=[{name:srcToken, type:address, order:1, indexed:false, value:0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48, valueString:0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48}, {name:dstToken, type:address, order:2, indexed:false, value:0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, valueString:0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE}, {name:srcReceiver, type:address, order:3, indexed:false, value:0x5141B82f5fFDa4c6fE1E372978F1C5427640a190, valueString:0x5141B82f5fFDa4c6fE1E372978F1C5427640a190}, {name:dstReceiver, type:address, order:4, indexed:false, value:0xF8Ed3A12832b106b0EDc947b007C64439Ad74402, valueString:0xF8Ed3A12832b106b0EDc947b007C64439Ad74402}, {name:amount, type:uint256, order:5, indexed:false, value:114759000, valueString:114759000}, {name:minReturnAmount, type:uint256, order:6, indexed:false, value:44368529070325369, valueString:44368529070325369}, {name:flags, type:uint256, order:7, indexed:false, value:4, valueString:4}], permit=0x, data=0x00000000000000000000000000000000000000000000000000016A00001A0020D6BDBF78A0B86991C6218B36C1D19D4A2E9EB0CE3606EB4851309995855C00494D039AB6792F18E368E530DFF931A0B86991C6218B36C1D19D4A2E9EB0CE3606EB480084F196187F0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000A0B86991C6218B36C1D19D4A2E9EB0CE3606EB480000000000000000000000000000000000000000000D1B71758E21960000137E000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000FFFF9A5889F795069A41A8A3000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000001111111254EEB25477B68FB85ED929F73A960582 ) => ( returnAmount=45733978272888755, spentAmount=114759000 )
                  • FiatTokenProxy.23b872dd( )
                  • 0x5141b82f5ffda4c6fe1e372978f1c5427640a190.4b64e492( )
                  • ETH 0.045733978272888755 0xf8ed3a12832b106b0edc947b007c64439ad74402.CALL( )
                    File 1 of 9: TransparentUpgradeableProxy
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.8.0;
                    import "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol";
                    import "@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol";
                    import "@openzeppelin/contracts/proxy/transparent/ProxyAdmin.sol";
                    // Kept for backwards compatibility with older versions of Hardhat and Truffle plugins.
                    contract AdminUpgradeabilityProxy is TransparentUpgradeableProxy {
                        constructor(address logic, address admin, bytes memory data) payable TransparentUpgradeableProxy(logic, admin, data) {}
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.8.0;
                    import "../Proxy.sol";
                    import "./ERC1967Upgrade.sol";
                    /**
                     * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
                     * implementation address that can be changed. This address is stored in storage in the location specified by
                     * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
                     * implementation behind the proxy.
                     */
                    contract ERC1967Proxy is Proxy, ERC1967Upgrade {
                        /**
                         * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
                         *
                         * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded
                         * function call, and allows initializating the storage of the proxy like a Solidity constructor.
                         */
                        constructor(address _logic, bytes memory _data) payable {
                            assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
                            _upgradeToAndCall(_logic, _data, false);
                        }
                        /**
                         * @dev Returns the current implementation address.
                         */
                        function _implementation() internal view virtual override returns (address impl) {
                            return ERC1967Upgrade._getImplementation();
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.8.0;
                    import "../ERC1967/ERC1967Proxy.sol";
                    /**
                     * @dev This contract implements a proxy that is upgradeable by an admin.
                     *
                     * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector
                     * clashing], which can potentially be used in an attack, this contract uses the
                     * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two
                     * things that go hand in hand:
                     *
                     * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if
                     * that call matches one of the admin functions exposed by the proxy itself.
                     * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the
                     * implementation. If the admin tries to call a function on the implementation it will fail with an error that says
                     * "admin cannot fallback to proxy target".
                     *
                     * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing
                     * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due
                     * to sudden errors when trying to call a function from the proxy implementation.
                     *
                     * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way,
                     * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.
                     */
                    contract TransparentUpgradeableProxy is ERC1967Proxy {
                        /**
                         * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and
                         * optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}.
                         */
                        constructor(address _logic, address admin_, bytes memory _data) payable ERC1967Proxy(_logic, _data) {
                            assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1));
                            _changeAdmin(admin_);
                        }
                        /**
                         * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin.
                         */
                        modifier ifAdmin() {
                            if (msg.sender == _getAdmin()) {
                                _;
                            } else {
                                _fallback();
                            }
                        }
                        /**
                         * @dev Returns the current admin.
                         *
                         * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}.
                         *
                         * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
                         * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
                         * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
                         */
                        function admin() external ifAdmin returns (address admin_) {
                            admin_ = _getAdmin();
                        }
                        /**
                         * @dev Returns the current implementation.
                         *
                         * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}.
                         *
                         * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
                         * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
                         * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
                         */
                        function implementation() external ifAdmin returns (address implementation_) {
                            implementation_ = _implementation();
                        }
                        /**
                         * @dev Changes the admin of the proxy.
                         *
                         * Emits an {AdminChanged} event.
                         *
                         * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}.
                         */
                        function changeAdmin(address newAdmin) external virtual ifAdmin {
                            _changeAdmin(newAdmin);
                        }
                        /**
                         * @dev Upgrade the implementation of the proxy.
                         *
                         * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}.
                         */
                        function upgradeTo(address newImplementation) external ifAdmin {
                            _upgradeToAndCall(newImplementation, bytes(""), false);
                        }
                        /**
                         * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified
                         * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the
                         * proxied contract.
                         *
                         * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}.
                         */
                        function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin {
                            _upgradeToAndCall(newImplementation, data, true);
                        }
                        /**
                         * @dev Returns the current admin.
                         */
                        function _admin() internal view virtual returns (address) {
                            return _getAdmin();
                        }
                        /**
                         * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}.
                         */
                        function _beforeFallback() internal virtual override {
                            require(msg.sender != _getAdmin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target");
                            super._beforeFallback();
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.8.0;
                    import "./TransparentUpgradeableProxy.sol";
                    import "../../access/Ownable.sol";
                    /**
                     * @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an
                     * explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}.
                     */
                    contract ProxyAdmin is Ownable {
                        /**
                         * @dev Returns the current implementation of `proxy`.
                         *
                         * Requirements:
                         *
                         * - This contract must be the admin of `proxy`.
                         */
                        function getProxyImplementation(TransparentUpgradeableProxy proxy) public view virtual returns (address) {
                            // We need to manually run the static call since the getter cannot be flagged as view
                            // bytes4(keccak256("implementation()")) == 0x5c60da1b
                            (bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b");
                            require(success);
                            return abi.decode(returndata, (address));
                        }
                        /**
                         * @dev Returns the current admin of `proxy`.
                         *
                         * Requirements:
                         *
                         * - This contract must be the admin of `proxy`.
                         */
                        function getProxyAdmin(TransparentUpgradeableProxy proxy) public view virtual returns (address) {
                            // We need to manually run the static call since the getter cannot be flagged as view
                            // bytes4(keccak256("admin()")) == 0xf851a440
                            (bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440");
                            require(success);
                            return abi.decode(returndata, (address));
                        }
                        /**
                         * @dev Changes the admin of `proxy` to `newAdmin`.
                         *
                         * Requirements:
                         *
                         * - This contract must be the current admin of `proxy`.
                         */
                        function changeProxyAdmin(TransparentUpgradeableProxy proxy, address newAdmin) public virtual onlyOwner {
                            proxy.changeAdmin(newAdmin);
                        }
                        /**
                         * @dev Upgrades `proxy` to `implementation`. See {TransparentUpgradeableProxy-upgradeTo}.
                         *
                         * Requirements:
                         *
                         * - This contract must be the admin of `proxy`.
                         */
                        function upgrade(TransparentUpgradeableProxy proxy, address implementation) public virtual onlyOwner {
                            proxy.upgradeTo(implementation);
                        }
                        /**
                         * @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. See
                         * {TransparentUpgradeableProxy-upgradeToAndCall}.
                         *
                         * Requirements:
                         *
                         * - This contract must be the admin of `proxy`.
                         */
                        function upgradeAndCall(TransparentUpgradeableProxy proxy, address implementation, bytes memory data) public payable virtual onlyOwner {
                            proxy.upgradeToAndCall{value: msg.value}(implementation, data);
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.8.0;
                    /**
                     * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
                     * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
                     * be specified by overriding the virtual {_implementation} function.
                     *
                     * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
                     * different contract through the {_delegate} function.
                     *
                     * The success and return data of the delegated call will be returned back to the caller of the proxy.
                     */
                    abstract contract Proxy {
                        /**
                         * @dev Delegates the current call to `implementation`.
                         *
                         * This function does not return to its internall call site, it will return directly to the external caller.
                         */
                        function _delegate(address implementation) internal virtual {
                            // solhint-disable-next-line no-inline-assembly
                            assembly {
                                // Copy msg.data. We take full control of memory in this inline assembly
                                // block because it will not return to Solidity code. We overwrite the
                                // Solidity scratch pad at memory position 0.
                                calldatacopy(0, 0, calldatasize())
                                // Call the implementation.
                                // out and outsize are 0 because we don't know the size yet.
                                let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
                                // Copy the returned data.
                                returndatacopy(0, 0, returndatasize())
                                switch result
                                // delegatecall returns 0 on error.
                                case 0 { revert(0, returndatasize()) }
                                default { return(0, returndatasize()) }
                            }
                        }
                        /**
                         * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
                         * and {_fallback} should delegate.
                         */
                        function _implementation() internal view virtual returns (address);
                        /**
                         * @dev Delegates the current call to the address returned by `_implementation()`.
                         *
                         * This function does not return to its internall call site, it will return directly to the external caller.
                         */
                        function _fallback() internal virtual {
                            _beforeFallback();
                            _delegate(_implementation());
                        }
                        /**
                         * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
                         * function in the contract matches the call data.
                         */
                        fallback () external payable virtual {
                            _fallback();
                        }
                        /**
                         * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
                         * is empty.
                         */
                        receive () external payable virtual {
                            _fallback();
                        }
                        /**
                         * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
                         * call, or as part of the Solidity `fallback` or `receive` functions.
                         *
                         * If overriden should call `super._beforeFallback()`.
                         */
                        function _beforeFallback() internal virtual {
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.8.2;
                    import "../beacon/IBeacon.sol";
                    import "../../utils/Address.sol";
                    import "../../utils/StorageSlot.sol";
                    /**
                     * @dev This abstract contract provides getters and event emitting update functions for
                     * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
                     *
                     * _Available since v4.1._
                     *
                     * @custom:oz-upgrades-unsafe-allow delegatecall
                     */
                    abstract contract ERC1967Upgrade {
                        // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
                        bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
                        /**
                         * @dev Storage slot with the address of the current implementation.
                         * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
                         * validated in the constructor.
                         */
                        bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
                        /**
                         * @dev Emitted when the implementation is upgraded.
                         */
                        event Upgraded(address indexed implementation);
                        /**
                         * @dev Returns the current implementation address.
                         */
                        function _getImplementation() internal view returns (address) {
                            return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
                        }
                        /**
                         * @dev Stores a new address in the EIP1967 implementation slot.
                         */
                        function _setImplementation(address newImplementation) private {
                            require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
                            StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
                        }
                        /**
                         * @dev Perform implementation upgrade
                         *
                         * Emits an {Upgraded} event.
                         */
                        function _upgradeTo(address newImplementation) internal {
                            _setImplementation(newImplementation);
                            emit Upgraded(newImplementation);
                        }
                        /**
                         * @dev Perform implementation upgrade with additional setup call.
                         *
                         * Emits an {Upgraded} event.
                         */
                        function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal {
                            _setImplementation(newImplementation);
                            emit Upgraded(newImplementation);
                            if (data.length > 0 || forceCall) {
                                Address.functionDelegateCall(newImplementation, data);
                            }
                        }
                        /**
                         * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
                         *
                         * Emits an {Upgraded} event.
                         */
                        function _upgradeToAndCallSecure(address newImplementation, bytes memory data, bool forceCall) internal {
                            address oldImplementation = _getImplementation();
                            // Initial upgrade and setup call
                            _setImplementation(newImplementation);
                            if (data.length > 0 || forceCall) {
                                Address.functionDelegateCall(newImplementation, data);
                            }
                            // Perform rollback test if not already in progress
                            StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot(_ROLLBACK_SLOT);
                            if (!rollbackTesting.value) {
                                // Trigger rollback using upgradeTo from the new implementation
                                rollbackTesting.value = true;
                                Address.functionDelegateCall(
                                    newImplementation,
                                    abi.encodeWithSignature(
                                        "upgradeTo(address)",
                                        oldImplementation
                                    )
                                );
                                rollbackTesting.value = false;
                                // Check rollback was effective
                                require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
                                // Finally reset to the new implementation and log the upgrade
                                _setImplementation(newImplementation);
                                emit Upgraded(newImplementation);
                            }
                        }
                        /**
                         * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
                         * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
                         *
                         * Emits a {BeaconUpgraded} event.
                         */
                        function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal {
                            _setBeacon(newBeacon);
                            emit BeaconUpgraded(newBeacon);
                            if (data.length > 0 || forceCall) {
                                Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
                            }
                        }
                        /**
                         * @dev Storage slot with the admin of the contract.
                         * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
                         * validated in the constructor.
                         */
                        bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
                        /**
                         * @dev Emitted when the admin account has changed.
                         */
                        event AdminChanged(address previousAdmin, address newAdmin);
                        /**
                         * @dev Returns the current admin.
                         */
                        function _getAdmin() internal view returns (address) {
                            return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
                        }
                        /**
                         * @dev Stores a new address in the EIP1967 admin slot.
                         */
                        function _setAdmin(address newAdmin) private {
                            require(newAdmin != address(0), "ERC1967: new admin is the zero address");
                            StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
                        }
                        /**
                         * @dev Changes the admin of the proxy.
                         *
                         * Emits an {AdminChanged} event.
                         */
                        function _changeAdmin(address newAdmin) internal {
                            emit AdminChanged(_getAdmin(), newAdmin);
                            _setAdmin(newAdmin);
                        }
                        /**
                         * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
                         * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
                         */
                        bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
                        /**
                         * @dev Emitted when the beacon is upgraded.
                         */
                        event BeaconUpgraded(address indexed beacon);
                        /**
                         * @dev Returns the current beacon.
                         */
                        function _getBeacon() internal view returns (address) {
                            return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
                        }
                        /**
                         * @dev Stores a new beacon in the EIP1967 beacon slot.
                         */
                        function _setBeacon(address newBeacon) private {
                            require(
                                Address.isContract(newBeacon),
                                "ERC1967: new beacon is not a contract"
                            );
                            require(
                                Address.isContract(IBeacon(newBeacon).implementation()),
                                "ERC1967: beacon implementation is not a contract"
                            );
                            StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.8.0;
                    /**
                     * @dev This is the interface that {BeaconProxy} expects of its beacon.
                     */
                    interface IBeacon {
                        /**
                         * @dev Must return an address that can be used as a delegate call target.
                         *
                         * {BeaconProxy} will check that this address is a contract.
                         */
                        function implementation() external view returns (address);
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.8.0;
                    /**
                     * @dev Collection of functions related to the address type
                     */
                    library Address {
                        /**
                         * @dev Returns true if `account` is a contract.
                         *
                         * [IMPORTANT]
                         * ====
                         * It is unsafe to assume that an address for which this function returns
                         * false is an externally-owned account (EOA) and not a contract.
                         *
                         * Among others, `isContract` will return false for the following
                         * types of addresses:
                         *
                         *  - an externally-owned account
                         *  - a contract in construction
                         *  - an address where a contract will be created
                         *  - an address where a contract lived, but was destroyed
                         * ====
                         */
                        function isContract(address account) internal view returns (bool) {
                            // This method relies on extcodesize, which returns 0 for contracts in
                            // construction, since the code is only stored at the end of the
                            // constructor execution.
                            uint256 size;
                            // solhint-disable-next-line no-inline-assembly
                            assembly { size := extcodesize(account) }
                            return size > 0;
                        }
                        /**
                         * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
                         * `recipient`, forwarding all available gas and reverting on errors.
                         *
                         * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
                         * of certain opcodes, possibly making contracts go over the 2300 gas limit
                         * imposed by `transfer`, making them unable to receive funds via
                         * `transfer`. {sendValue} removes this limitation.
                         *
                         * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
                         *
                         * IMPORTANT: because control is transferred to `recipient`, care must be
                         * taken to not create reentrancy vulnerabilities. Consider using
                         * {ReentrancyGuard} or the
                         * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                         */
                        function sendValue(address payable recipient, uint256 amount) internal {
                            require(address(this).balance >= amount, "Address: insufficient balance");
                            // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
                            (bool success, ) = recipient.call{ value: amount }("");
                            require(success, "Address: unable to send value, recipient may have reverted");
                        }
                        /**
                         * @dev Performs a Solidity function call using a low level `call`. A
                         * plain`call` is an unsafe replacement for a function call: use this
                         * function instead.
                         *
                         * If `target` reverts with a revert reason, it is bubbled up by this
                         * function (like regular Solidity function calls).
                         *
                         * Returns the raw returned data. To convert to the expected return value,
                         * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
                         *
                         * Requirements:
                         *
                         * - `target` must be a contract.
                         * - calling `target` with `data` must not revert.
                         *
                         * _Available since v3.1._
                         */
                        function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                          return functionCall(target, data, "Address: low-level call failed");
                        }
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
                         * `errorMessage` as a fallback revert reason when `target` reverts.
                         *
                         * _Available since v3.1._
                         */
                        function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
                            return functionCallWithValue(target, data, 0, errorMessage);
                        }
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                         * but also transferring `value` wei to `target`.
                         *
                         * Requirements:
                         *
                         * - the calling contract must have an ETH balance of at least `value`.
                         * - the called Solidity function must be `payable`.
                         *
                         * _Available since v3.1._
                         */
                        function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
                            return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
                        }
                        /**
                         * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
                         * with `errorMessage` as a fallback revert reason when `target` reverts.
                         *
                         * _Available since v3.1._
                         */
                        function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
                            require(address(this).balance >= value, "Address: insufficient balance for call");
                            require(isContract(target), "Address: call to non-contract");
                            // solhint-disable-next-line avoid-low-level-calls
                            (bool success, bytes memory returndata) = target.call{ value: value }(data);
                            return _verifyCallResult(success, returndata, errorMessage);
                        }
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                         * but performing a static call.
                         *
                         * _Available since v3.3._
                         */
                        function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                            return functionStaticCall(target, data, "Address: low-level static call failed");
                        }
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                         * but performing a static call.
                         *
                         * _Available since v3.3._
                         */
                        function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
                            require(isContract(target), "Address: static call to non-contract");
                            // solhint-disable-next-line avoid-low-level-calls
                            (bool success, bytes memory returndata) = target.staticcall(data);
                            return _verifyCallResult(success, returndata, errorMessage);
                        }
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                         * but performing a delegate call.
                         *
                         * _Available since v3.4._
                         */
                        function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                            return functionDelegateCall(target, data, "Address: low-level delegate call failed");
                        }
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                         * but performing a delegate call.
                         *
                         * _Available since v3.4._
                         */
                        function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
                            require(isContract(target), "Address: delegate call to non-contract");
                            // solhint-disable-next-line avoid-low-level-calls
                            (bool success, bytes memory returndata) = target.delegatecall(data);
                            return _verifyCallResult(success, returndata, errorMessage);
                        }
                        function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
                            if (success) {
                                return returndata;
                            } else {
                                // Look for revert reason and bubble it up if present
                                if (returndata.length > 0) {
                                    // The easiest way to bubble the revert reason is using memory via assembly
                                    // solhint-disable-next-line no-inline-assembly
                                    assembly {
                                        let returndata_size := mload(returndata)
                                        revert(add(32, returndata), returndata_size)
                                    }
                                } else {
                                    revert(errorMessage);
                                }
                            }
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.8.0;
                    /**
                     * @dev Library for reading and writing primitive types to specific storage slots.
                     *
                     * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
                     * This library helps with reading and writing to such slots without the need for inline assembly.
                     *
                     * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
                     *
                     * Example usage to set ERC1967 implementation slot:
                     * ```
                     * contract ERC1967 {
                     *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
                     *
                     *     function _getImplementation() internal view returns (address) {
                     *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
                     *     }
                     *
                     *     function _setImplementation(address newImplementation) internal {
                     *         require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
                     *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
                     *     }
                     * }
                     * ```
                     *
                     * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
                     */
                    library StorageSlot {
                        struct AddressSlot {
                            address value;
                        }
                        struct BooleanSlot {
                            bool value;
                        }
                        struct Bytes32Slot {
                            bytes32 value;
                        }
                        struct Uint256Slot {
                            uint256 value;
                        }
                        /**
                         * @dev Returns an `AddressSlot` with member `value` located at `slot`.
                         */
                        function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
                            assembly {
                                r.slot := slot
                            }
                        }
                        /**
                         * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
                         */
                        function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
                            assembly {
                                r.slot := slot
                            }
                        }
                        /**
                         * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
                         */
                        function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
                            assembly {
                                r.slot := slot
                            }
                        }
                        /**
                         * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
                         */
                        function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
                            assembly {
                                r.slot := slot
                            }
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.8.0;
                    import "../utils/Context.sol";
                    /**
                     * @dev Contract module which provides a basic access control mechanism, where
                     * there is an account (an owner) that can be granted exclusive access to
                     * specific functions.
                     *
                     * By default, the owner account will be the one that deploys the contract. This
                     * can later be changed with {transferOwnership}.
                     *
                     * This module is used through inheritance. It will make available the modifier
                     * `onlyOwner`, which can be applied to your functions to restrict their use to
                     * the owner.
                     */
                    abstract contract Ownable is Context {
                        address private _owner;
                        event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                        /**
                         * @dev Initializes the contract setting the deployer as the initial owner.
                         */
                        constructor () {
                            address msgSender = _msgSender();
                            _owner = msgSender;
                            emit OwnershipTransferred(address(0), msgSender);
                        }
                        /**
                         * @dev Returns the address of the current owner.
                         */
                        function owner() public view virtual returns (address) {
                            return _owner;
                        }
                        /**
                         * @dev Throws if called by any account other than the owner.
                         */
                        modifier onlyOwner() {
                            require(owner() == _msgSender(), "Ownable: caller is not the owner");
                            _;
                        }
                        /**
                         * @dev Leaves the contract without owner. It will not be possible to call
                         * `onlyOwner` functions anymore. Can only be called by the current owner.
                         *
                         * NOTE: Renouncing ownership will leave the contract without an owner,
                         * thereby removing any functionality that is only available to the owner.
                         */
                        function renounceOwnership() public virtual onlyOwner {
                            emit OwnershipTransferred(_owner, address(0));
                            _owner = address(0);
                        }
                        /**
                         * @dev Transfers ownership of the contract to a new account (`newOwner`).
                         * Can only be called by the current owner.
                         */
                        function transferOwnership(address newOwner) public virtual onlyOwner {
                            require(newOwner != address(0), "Ownable: new owner is the zero address");
                            emit OwnershipTransferred(_owner, newOwner);
                            _owner = newOwner;
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.8.0;
                    /*
                     * @dev Provides information about the current execution context, including the
                     * sender of the transaction and its data. While these are generally available
                     * via msg.sender and msg.data, they should not be accessed in such a direct
                     * manner, since when dealing with meta-transactions the account sending and
                     * paying for execution may not be the actual sender (as far as an application
                     * is concerned).
                     *
                     * This contract is only required for intermediate, library-like contracts.
                     */
                    abstract contract Context {
                        function _msgSender() internal view virtual returns (address) {
                            return msg.sender;
                        }
                        function _msgData() internal view virtual returns (bytes calldata) {
                            this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
                            return msg.data;
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.8.0;
                    import "../ERC1967/ERC1967Upgrade.sol";
                    /**
                     * @dev Base contract for building openzeppelin-upgrades compatible implementations for the {ERC1967Proxy}. It includes
                     * publicly available upgrade functions that are called by the plugin and by the secure upgrade mechanism to verify
                     * continuation of the upgradability.
                     *
                     * The {_authorizeUpgrade} function MUST be overridden to include access restriction to the upgrade mechanism.
                     *
                     * _Available since v4.1._
                     */
                    abstract contract UUPSUpgradeable is ERC1967Upgrade {
                        function upgradeTo(address newImplementation) external virtual {
                            _authorizeUpgrade(newImplementation);
                            _upgradeToAndCallSecure(newImplementation, bytes(""), false);
                        }
                        function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual {
                            _authorizeUpgrade(newImplementation);
                            _upgradeToAndCallSecure(newImplementation, data, true);
                        }
                        function _authorizeUpgrade(address newImplementation) internal virtual;
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.8.2;
                    import "@openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol";
                    abstract contract Proxiable is UUPSUpgradeable {
                        function _authorizeUpgrade(address newImplementation) internal override {
                            _beforeUpgrade(newImplementation);
                        }
                        function _beforeUpgrade(address newImplementation) internal virtual;
                    }
                    contract ChildOfProxiable is Proxiable {
                        function _beforeUpgrade(address newImplementation) internal virtual override {}
                    }
                    

                    File 2 of 9: FiatTokenProxy
                    pragma solidity ^0.4.24;
                    
                    // File: zos-lib/contracts/upgradeability/Proxy.sol
                    
                    /**
                     * @title Proxy
                     * @dev Implements delegation of calls to other contracts, with proper
                     * forwarding of return values and bubbling of failures.
                     * It defines a fallback function that delegates all calls to the address
                     * returned by the abstract _implementation() internal function.
                     */
                    contract Proxy {
                      /**
                       * @dev Fallback function.
                       * Implemented entirely in `_fallback`.
                       */
                      function () payable external {
                        _fallback();
                      }
                    
                      /**
                       * @return The Address of the implementation.
                       */
                      function _implementation() internal view returns (address);
                    
                      /**
                       * @dev Delegates execution to an implementation contract.
                       * This is a low level function that doesn't return to its internal call site.
                       * It will return to the external caller whatever the implementation returns.
                       * @param implementation Address to delegate.
                       */
                      function _delegate(address implementation) internal {
                        assembly {
                          // Copy msg.data. We take full control of memory in this inline assembly
                          // block because it will not return to Solidity code. We overwrite the
                          // Solidity scratch pad at memory position 0.
                          calldatacopy(0, 0, calldatasize)
                    
                          // Call the implementation.
                          // out and outsize are 0 because we don't know the size yet.
                          let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0)
                    
                          // Copy the returned data.
                          returndatacopy(0, 0, returndatasize)
                    
                          switch result
                          // delegatecall returns 0 on error.
                          case 0 { revert(0, returndatasize) }
                          default { return(0, returndatasize) }
                        }
                      }
                    
                      /**
                       * @dev Function that is run as the first thing in the fallback function.
                       * Can be redefined in derived contracts to add functionality.
                       * Redefinitions must call super._willFallback().
                       */
                      function _willFallback() internal {
                      }
                    
                      /**
                       * @dev fallback implementation.
                       * Extracted to enable manual triggering.
                       */
                      function _fallback() internal {
                        _willFallback();
                        _delegate(_implementation());
                      }
                    }
                    
                    // File: openzeppelin-solidity/contracts/AddressUtils.sol
                    
                    /**
                     * Utility library of inline functions on addresses
                     */
                    library AddressUtils {
                    
                      /**
                       * Returns whether the target address is a contract
                       * @dev This function will return false if invoked during the constructor of a contract,
                       * as the code is not actually created until after the constructor finishes.
                       * @param addr address to check
                       * @return whether the target address is a contract
                       */
                      function isContract(address addr) internal view returns (bool) {
                        uint256 size;
                        // XXX Currently there is no better way to check if there is a contract in an address
                        // than to check the size of the code at that address.
                        // See https://ethereum.stackexchange.com/a/14016/36603
                        // for more details about how this works.
                        // TODO Check this again before the Serenity release, because all addresses will be
                        // contracts then.
                        // solium-disable-next-line security/no-inline-assembly
                        assembly { size := extcodesize(addr) }
                        return size > 0;
                      }
                    
                    }
                    
                    // File: zos-lib/contracts/upgradeability/UpgradeabilityProxy.sol
                    
                    /**
                     * @title UpgradeabilityProxy
                     * @dev This contract implements a proxy that allows to change the
                     * implementation address to which it will delegate.
                     * Such a change is called an implementation upgrade.
                     */
                    contract UpgradeabilityProxy is Proxy {
                      /**
                       * @dev Emitted when the implementation is upgraded.
                       * @param implementation Address of the new implementation.
                       */
                      event Upgraded(address implementation);
                    
                      /**
                       * @dev Storage slot with the address of the current implementation.
                       * This is the keccak-256 hash of "org.zeppelinos.proxy.implementation", and is
                       * validated in the constructor.
                       */
                      bytes32 private constant IMPLEMENTATION_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3;
                    
                      /**
                       * @dev Contract constructor.
                       * @param _implementation Address of the initial implementation.
                       */
                      constructor(address _implementation) public {
                        assert(IMPLEMENTATION_SLOT == keccak256("org.zeppelinos.proxy.implementation"));
                    
                        _setImplementation(_implementation);
                      }
                    
                      /**
                       * @dev Returns the current implementation.
                       * @return Address of the current implementation
                       */
                      function _implementation() internal view returns (address impl) {
                        bytes32 slot = IMPLEMENTATION_SLOT;
                        assembly {
                          impl := sload(slot)
                        }
                      }
                    
                      /**
                       * @dev Upgrades the proxy to a new implementation.
                       * @param newImplementation Address of the new implementation.
                       */
                      function _upgradeTo(address newImplementation) internal {
                        _setImplementation(newImplementation);
                        emit Upgraded(newImplementation);
                      }
                    
                      /**
                       * @dev Sets the implementation address of the proxy.
                       * @param newImplementation Address of the new implementation.
                       */
                      function _setImplementation(address newImplementation) private {
                        require(AddressUtils.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
                    
                        bytes32 slot = IMPLEMENTATION_SLOT;
                    
                        assembly {
                          sstore(slot, newImplementation)
                        }
                      }
                    }
                    
                    // File: zos-lib/contracts/upgradeability/AdminUpgradeabilityProxy.sol
                    
                    /**
                     * @title AdminUpgradeabilityProxy
                     * @dev This contract combines an upgradeability proxy with an authorization
                     * mechanism for administrative tasks.
                     * All external functions in this contract must be guarded by the
                     * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity
                     * feature proposal that would enable this to be done automatically.
                     */
                    contract AdminUpgradeabilityProxy is UpgradeabilityProxy {
                      /**
                       * @dev Emitted when the administration has been transferred.
                       * @param previousAdmin Address of the previous admin.
                       * @param newAdmin Address of the new admin.
                       */
                      event AdminChanged(address previousAdmin, address newAdmin);
                    
                      /**
                       * @dev Storage slot with the admin of the contract.
                       * This is the keccak-256 hash of "org.zeppelinos.proxy.admin", and is
                       * validated in the constructor.
                       */
                      bytes32 private constant ADMIN_SLOT = 0x10d6a54a4754c8869d6886b5f5d7fbfa5b4522237ea5c60d11bc4e7a1ff9390b;
                    
                      /**
                       * @dev Modifier to check whether the `msg.sender` is the admin.
                       * If it is, it will run the function. Otherwise, it will delegate the call
                       * to the implementation.
                       */
                      modifier ifAdmin() {
                        if (msg.sender == _admin()) {
                          _;
                        } else {
                          _fallback();
                        }
                      }
                    
                      /**
                       * Contract constructor.
                       * It sets the `msg.sender` as the proxy administrator.
                       * @param _implementation address of the initial implementation.
                       */
                      constructor(address _implementation) UpgradeabilityProxy(_implementation) public {
                        assert(ADMIN_SLOT == keccak256("org.zeppelinos.proxy.admin"));
                    
                        _setAdmin(msg.sender);
                      }
                    
                      /**
                       * @return The address of the proxy admin.
                       */
                      function admin() external view ifAdmin returns (address) {
                        return _admin();
                      }
                    
                      /**
                       * @return The address of the implementation.
                       */
                      function implementation() external view ifAdmin returns (address) {
                        return _implementation();
                      }
                    
                      /**
                       * @dev Changes the admin of the proxy.
                       * Only the current admin can call this function.
                       * @param newAdmin Address to transfer proxy administration to.
                       */
                      function changeAdmin(address newAdmin) external ifAdmin {
                        require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
                        emit AdminChanged(_admin(), newAdmin);
                        _setAdmin(newAdmin);
                      }
                    
                      /**
                       * @dev Upgrade the backing implementation of the proxy.
                       * Only the admin can call this function.
                       * @param newImplementation Address of the new implementation.
                       */
                      function upgradeTo(address newImplementation) external ifAdmin {
                        _upgradeTo(newImplementation);
                      }
                    
                      /**
                       * @dev Upgrade the backing implementation of the proxy and call a function
                       * on the new implementation.
                       * This is useful to initialize the proxied contract.
                       * @param newImplementation Address of the new implementation.
                       * @param data Data to send as msg.data in the low level call.
                       * It should include the signature and the parameters of the function to be
                       * called, as described in
                       * https://solidity.readthedocs.io/en/develop/abi-spec.html#function-selector-and-argument-encoding.
                       */
                      function upgradeToAndCall(address newImplementation, bytes data) payable external ifAdmin {
                        _upgradeTo(newImplementation);
                        require(address(this).call.value(msg.value)(data));
                      }
                    
                      /**
                       * @return The admin slot.
                       */
                      function _admin() internal view returns (address adm) {
                        bytes32 slot = ADMIN_SLOT;
                        assembly {
                          adm := sload(slot)
                        }
                      }
                    
                      /**
                       * @dev Sets the address of the proxy admin.
                       * @param newAdmin Address of the new proxy admin.
                       */
                      function _setAdmin(address newAdmin) internal {
                        bytes32 slot = ADMIN_SLOT;
                    
                        assembly {
                          sstore(slot, newAdmin)
                        }
                      }
                    
                      /**
                       * @dev Only fall back when the sender is not the admin.
                       */
                      function _willFallback() internal {
                        require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
                        super._willFallback();
                      }
                    }
                    
                    // File: contracts/FiatTokenProxy.sol
                    
                    /**
                    * Copyright CENTRE SECZ 2018
                    *
                    * Permission is hereby granted, free of charge, to any person obtaining a copy 
                    * of this software and associated documentation files (the "Software"), to deal 
                    * in the Software without restriction, including without limitation the rights 
                    * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
                    * copies of the Software, and to permit persons to whom the Software is furnished to 
                    * do so, subject to the following conditions:
                    *
                    * The above copyright notice and this permission notice shall be included in all 
                    * copies or substantial portions of the Software.
                    *
                    * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
                    * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
                    * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
                    * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
                    * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 
                    * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
                    */
                    
                    pragma solidity ^0.4.24;
                    
                    
                    /**
                     * @title FiatTokenProxy
                     * @dev This contract proxies FiatToken calls and enables FiatToken upgrades
                    */ 
                    contract FiatTokenProxy is AdminUpgradeabilityProxy {
                        constructor(address _implementation) public AdminUpgradeabilityProxy(_implementation) {
                        }
                    }

                    File 3 of 9: Core
                    // SPDX-License-Identifier: UNLICENSED
                    pragma solidity =0.8.28;
                    import {CallPoints, addressToCallPoints} from "./types/callPoints.sol";
                    import {PoolKey} from "./types/poolKey.sol";
                    import {PositionKey, Bounds} from "./types/positionKey.sol";
                    import {FeesPerLiquidity, feesPerLiquidityFromAmounts} from "./types/feesPerLiquidity.sol";
                    import {isPriceIncreasing, SqrtRatioLimitWrongDirection, SwapResult, swapResult} from "./math/swap.sol";
                    import {Position} from "./types/position.sol";
                    import {Ownable} from "solady/auth/Ownable.sol";
                    import {tickToSqrtRatio, sqrtRatioToTick} from "./math/ticks.sol";
                    import {Bitmap} from "./math/bitmap.sol";
                    import {
                        shouldCallBeforeInitializePool,
                        shouldCallAfterInitializePool,
                        shouldCallBeforeUpdatePosition,
                        shouldCallAfterUpdatePosition,
                        shouldCallBeforeSwap,
                        shouldCallAfterSwap,
                        shouldCallBeforeCollectFees,
                        shouldCallAfterCollectFees
                    } from "./types/callPoints.sol";
                    import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol";
                    import {SafeTransferLib} from "solady/utils/SafeTransferLib.sol";
                    import {SafeCastLib} from "solady/utils/SafeCastLib.sol";
                    import {ExposedStorage} from "./base/ExposedStorage.sol";
                    import {liquidityDeltaToAmountDelta, addLiquidityDelta, subLiquidityDelta} from "./math/liquidity.sol";
                    import {computeFee} from "./math/fee.sol";
                    import {findNextInitializedTick, findPrevInitializedTick, flipTick} from "./math/tickBitmap.sol";
                    import {ICore, UpdatePositionParameters, IExtension} from "./interfaces/ICore.sol";
                    import {FlashAccountant} from "./base/FlashAccountant.sol";
                    import {EfficientHashLib} from "solady/utils/EfficientHashLib.sol";
                    import {
                        MIN_TICK,
                        MAX_TICK,
                        NATIVE_TOKEN_ADDRESS,
                        FULL_RANGE_ONLY_TICK_SPACING,
                        MAX_TICK_SPACING
                    } from "./math/constants.sol";
                    import {MIN_SQRT_RATIO, MAX_SQRT_RATIO, SqrtRatio} from "./types/sqrtRatio.sol";
                    /// @title Ekubo Protocol
                    /// @author Moody Salem <[email protected]>
                    /// @notice Singleton holding all the tokens and containing all the possible operations in Ekubo Protocol
                    contract Core is ICore, FlashAccountant, Ownable, ExposedStorage {
                        using {findNextInitializedTick, findPrevInitializedTick, flipTick} for mapping(uint256 word => Bitmap bitmap);
                        struct TickInfo {
                            int128 liquidityDelta;
                            uint128 liquidityNet;
                        }
                        struct PoolState {
                            SqrtRatio sqrtRatio;
                            int32 tick;
                            uint128 liquidity;
                        }
                        mapping(address extension => bool isRegistered) private isExtensionRegistered;
                        mapping(address token => uint256 amountCollected) private protocolFeesCollected;
                        mapping(bytes32 poolId => PoolState) private poolState;
                        mapping(bytes32 poolId => FeesPerLiquidity feesPerLiquidity) private poolFeesPerLiquidity;
                        mapping(bytes32 poolId => mapping(bytes32 positionId => Position position)) private poolPositions;
                        mapping(bytes32 poolId => mapping(int32 tick => TickInfo tickInfo)) private poolTicks;
                        mapping(bytes32 poolId => mapping(int32 tick => FeesPerLiquidity feesPerLiquidityOutside)) private
                            poolTickFeesPerLiquidityOutside;
                        mapping(bytes32 poolId => mapping(uint256 word => Bitmap bitmap)) private poolInitializedTickBitmaps;
                        mapping(bytes32 key => uint256) private savedBalances;
                        constructor(address owner) {
                            _initializeOwner(owner);
                        }
                        function withdrawProtocolFees(address recipient, address token, uint256 amount) external onlyOwner {
                            protocolFeesCollected[token] -= amount;
                            if (token == NATIVE_TOKEN_ADDRESS) {
                                SafeTransferLib.safeTransferETH(recipient, amount);
                            } else {
                                SafeTransferLib.safeTransfer(token, recipient, amount);
                            }
                            emit ProtocolFeesWithdrawn(recipient, token, amount);
                        }
                        // Extensions must call this function to become registered. The call points are validated against the caller address
                        function registerExtension(CallPoints memory expectedCallPoints) external {
                            CallPoints memory computed = addressToCallPoints(msg.sender);
                            if (!computed.eq(expectedCallPoints) || !computed.isValid()) revert FailedRegisterInvalidCallPoints();
                            if (isExtensionRegistered[msg.sender]) revert ExtensionAlreadyRegistered();
                            isExtensionRegistered[msg.sender] = true;
                            emit ExtensionRegistered(msg.sender);
                        }
                        function initializePool(PoolKey memory poolKey, int32 tick) external returns (SqrtRatio sqrtRatio) {
                            poolKey.validatePoolKey();
                            address extension = poolKey.extension();
                            if (extension != address(0)) {
                                if (!isExtensionRegistered[extension]) {
                                    revert ExtensionNotRegistered();
                                }
                                if (shouldCallBeforeInitializePool(extension) && extension != msg.sender) {
                                    IExtension(extension).beforeInitializePool(msg.sender, poolKey, tick);
                                }
                            }
                            bytes32 poolId = poolKey.toPoolId();
                            PoolState memory price = poolState[poolId];
                            if (SqrtRatio.unwrap(price.sqrtRatio) != 0) revert PoolAlreadyInitialized();
                            sqrtRatio = tickToSqrtRatio(tick);
                            poolState[poolId] = PoolState({sqrtRatio: sqrtRatio, tick: tick, liquidity: 0});
                            emit PoolInitialized(poolId, poolKey, tick, sqrtRatio);
                            if (shouldCallAfterInitializePool(extension) && extension != msg.sender) {
                                IExtension(extension).afterInitializePool(msg.sender, poolKey, tick, sqrtRatio);
                            }
                        }
                        function prevInitializedTick(bytes32 poolId, int32 fromTick, uint32 tickSpacing, uint256 skipAhead)
                            external
                            view
                            returns (int32 tick, bool isInitialized)
                        {
                            (tick, isInitialized) =
                                poolInitializedTickBitmaps[poolId].findPrevInitializedTick(fromTick, tickSpacing, skipAhead);
                        }
                        function nextInitializedTick(bytes32 poolId, int32 fromTick, uint32 tickSpacing, uint256 skipAhead)
                            external
                            view
                            returns (int32 tick, bool isInitialized)
                        {
                            (tick, isInitialized) =
                                poolInitializedTickBitmaps[poolId].findNextInitializedTick(fromTick, tickSpacing, skipAhead);
                        }
                        function load(address token0, address token1, bytes32 salt, uint128 amount0, uint128 amount1) public {
                            // note we do not check sort order because for save it must be sorted,
                            //  so balances will always be zero if token0 and token1 are not sorted
                            //  and this method will throw InsufficientSavedBalance for non-zero amount
                            (uint256 id,) = _getLocker();
                            bytes32 key = EfficientHashLib.hash(
                                bytes32(uint256(uint160(msg.sender))),
                                bytes32(uint256(uint160(token0))),
                                bytes32(uint256(uint160(token1))),
                                salt
                            );
                            unchecked {
                                uint256 packedBalance = savedBalances[key];
                                uint128 balance0 = uint128(packedBalance >> 128);
                                uint128 balance1 = uint128(packedBalance);
                                if (balance0 < amount0 || balance1 < amount1) {
                                    revert InsufficientSavedBalance();
                                }
                                // unchecked is ok because we reverted if either balance < amount
                                savedBalances[key] = (uint256(balance0 - amount0) << 128) + uint256(balance1 - amount1);
                                _accountDebt(id, token0, -int256(uint256(amount0)));
                                _accountDebt(id, token1, -int256(uint256(amount1)));
                            }
                        }
                        function save(address owner, address token0, address token1, bytes32 salt, uint128 amount0, uint128 amount1)
                            public
                            payable
                        {
                            if (token0 >= token1) revert SavedBalanceTokensNotSorted();
                            (uint256 id,) = _requireLocker();
                            bytes32 key = EfficientHashLib.hash(
                                bytes32(uint256(uint160(owner))), bytes32(uint256(uint160(token0))), bytes32(uint256(uint160(token1))), salt
                            );
                            uint256 packedBalances = savedBalances[key];
                            uint128 balance0 = uint128(packedBalances >> 128);
                            uint128 balance1 = uint128(packedBalances);
                            // we are using checked math here to protect the uint128 additions from overflowing
                            savedBalances[key] = (uint256(balance0 + amount0) << 128) + uint256(balance1 + amount1);
                            _maybeAccountDebtToken0(id, token0, int256(uint256(amount0)));
                            _accountDebt(id, token1, int256(uint256(amount1)));
                        }
                        // Returns the pool fees per liquidity inside the given bounds.
                        function _getPoolFeesPerLiquidityInside(bytes32 poolId, Bounds memory bounds, uint32 tickSpacing)
                            internal
                            view
                            returns (FeesPerLiquidity memory)
                        {
                            if (tickSpacing == FULL_RANGE_ONLY_TICK_SPACING) return poolFeesPerLiquidity[poolId];
                            int32 tick = poolState[poolId].tick;
                            mapping(int32 => FeesPerLiquidity) storage poolIdEntry = poolTickFeesPerLiquidityOutside[poolId];
                            FeesPerLiquidity memory lower = poolIdEntry[bounds.lower];
                            FeesPerLiquidity memory upper = poolIdEntry[bounds.upper];
                            if (tick < bounds.lower) {
                                return lower.sub(upper);
                            } else if (tick < bounds.upper) {
                                FeesPerLiquidity memory fees = poolFeesPerLiquidity[poolId];
                                return fees.sub(lower).sub(upper);
                            } else {
                                return upper.sub(lower);
                            }
                        }
                        function getPoolFeesPerLiquidityInside(PoolKey memory poolKey, Bounds memory bounds)
                            external
                            view
                            returns (FeesPerLiquidity memory)
                        {
                            return _getPoolFeesPerLiquidityInside(poolKey.toPoolId(), bounds, poolKey.tickSpacing());
                        }
                        // Accumulates tokens to fees of a pool. Only callable by the extension of the specified pool
                        // key, i.e. the current locker _must_ be the extension.
                        // The extension must call this function within a lock callback.
                        function accumulateAsFees(PoolKey memory poolKey, uint128 amount0, uint128 amount1) external payable {
                            (uint256 id, address locker) = _requireLocker();
                            require(locker == poolKey.extension());
                            bytes32 poolId = poolKey.toPoolId();
                            // Note we do not check pool is initialized. If the extension calls this for a pool that does not exist,
                            //  the fees are simply burned since liquidity is 0.
                            assembly ("memory-safe") {
                                if or(amount0, amount1) {
                                    mstore(0, poolId)
                                    mstore(32, 2)
                                    let liquidity := shr(128, sload(keccak256(0, 64)))
                                    if liquidity {
                                        mstore(32, 3)
                                        let slot0 := keccak256(0, 64)
                                        if amount0 {
                                            let v := div(shl(128, amount0), liquidity)
                                            sstore(slot0, add(sload(slot0), v))
                                        }
                                        if amount1 {
                                            let slot1 := add(slot0, 1)
                                            let v := div(shl(128, amount1), liquidity)
                                            sstore(slot1, add(sload(slot1), v))
                                        }
                                    }
                                }
                            }
                            // whether the fees are actually accounted to any position, the caller owes the debt
                            _maybeAccountDebtToken0(id, poolKey.token0, int256(uint256(amount0)));
                            _accountDebt(id, poolKey.token1, int256(uint256(amount1)));
                            emit FeesAccumulated(poolId, amount0, amount1);
                        }
                        function _updateTick(bytes32 poolId, int32 tick, uint32 tickSpacing, int128 liquidityDelta, bool isUpper) private {
                            TickInfo storage tickInfo = poolTicks[poolId][tick];
                            uint128 liquidityNetNext = addLiquidityDelta(tickInfo.liquidityNet, liquidityDelta);
                            // this is checked math
                            int128 liquidityDeltaNext =
                                isUpper ? tickInfo.liquidityDelta - liquidityDelta : tickInfo.liquidityDelta + liquidityDelta;
                            if ((tickInfo.liquidityNet == 0) != (liquidityNetNext == 0)) {
                                flipTick(poolInitializedTickBitmaps[poolId], tick, tickSpacing);
                            }
                            tickInfo.liquidityDelta = liquidityDeltaNext;
                            tickInfo.liquidityNet = liquidityNetNext;
                        }
                        function _maybeAccountDebtToken0(uint256 id, address token0, int256 debtChange) private {
                            if (msg.value == 0) {
                                _accountDebt(id, token0, debtChange);
                            } else {
                                if (msg.value > type(uint128).max) revert PaymentOverflow();
                                if (token0 == NATIVE_TOKEN_ADDRESS) {
                                    unchecked {
                                        _accountDebt(id, NATIVE_TOKEN_ADDRESS, debtChange - int256(msg.value));
                                    }
                                } else {
                                    unchecked {
                                        _accountDebt(id, token0, debtChange);
                                        _accountDebt(id, NATIVE_TOKEN_ADDRESS, -int256(msg.value));
                                    }
                                }
                            }
                        }
                        function updatePosition(PoolKey memory poolKey, UpdatePositionParameters memory params)
                            external
                            payable
                            returns (int128 delta0, int128 delta1)
                        {
                            (uint256 id, address locker) = _requireLocker();
                            address extension = poolKey.extension();
                            if (shouldCallBeforeUpdatePosition(extension) && locker != extension) {
                                IExtension(extension).beforeUpdatePosition(locker, poolKey, params);
                            }
                            params.bounds.validateBounds(poolKey.tickSpacing());
                            if (params.liquidityDelta != 0) {
                                bytes32 poolId = poolKey.toPoolId();
                                PoolState memory price = poolState[poolId];
                                if (SqrtRatio.unwrap(price.sqrtRatio) == 0) revert PoolNotInitialized();
                                (SqrtRatio sqrtRatioLower, SqrtRatio sqrtRatioUpper) =
                                    (tickToSqrtRatio(params.bounds.lower), tickToSqrtRatio(params.bounds.upper));
                                (delta0, delta1) =
                                    liquidityDeltaToAmountDelta(price.sqrtRatio, params.liquidityDelta, sqrtRatioLower, sqrtRatioUpper);
                                PositionKey memory positionKey = PositionKey({salt: params.salt, owner: locker, bounds: params.bounds});
                                if (params.liquidityDelta < 0) {
                                    if (poolKey.fee() != 0) {
                                        unchecked {
                                            // uint128(-delta0) is ok in unchecked block
                                            uint128 protocolFees0 = computeFee(uint128(-delta0), poolKey.fee());
                                            uint128 protocolFees1 = computeFee(uint128(-delta1), poolKey.fee());
                                            if (protocolFees0 > 0) {
                                                // this will never overflow for a well behaved token since protocol fees are stored as uint256
                                                protocolFeesCollected[poolKey.token0] += protocolFees0;
                                                // magnitude of protocolFees0 is at most equal to -delta0, so after addition delta0 will maximally reach 0 and no overflow/underflow check is needed
                                                // in addition, casting is safe because computed fee is never g.t. the input amount, which is an int128
                                                delta0 += int128(protocolFees0);
                                            }
                                            // same reasoning applies for the unchecked safety here
                                            if (protocolFees1 > 0) {
                                                protocolFeesCollected[poolKey.token1] += protocolFees1;
                                                delta1 += int128(protocolFees1);
                                            }
                                        }
                                    }
                                }
                                bytes32 positionId = positionKey.toPositionId();
                                Position storage position = poolPositions[poolId][positionId];
                                FeesPerLiquidity memory feesPerLiquidityInside =
                                    _getPoolFeesPerLiquidityInside(poolId, params.bounds, poolKey.tickSpacing());
                                (uint128 fees0, uint128 fees1) = position.fees(feesPerLiquidityInside);
                                uint128 liquidityNext = addLiquidityDelta(position.liquidity, params.liquidityDelta);
                                if (liquidityNext != 0) {
                                    position.liquidity = liquidityNext;
                                    position.feesPerLiquidityInsideLast =
                                        feesPerLiquidityInside.sub(feesPerLiquidityFromAmounts(fees0, fees1, liquidityNext));
                                } else {
                                    if (fees0 != 0 || fees1 != 0) revert MustCollectFeesBeforeWithdrawingAllLiquidity();
                                    position.liquidity = 0;
                                    position.feesPerLiquidityInsideLast = FeesPerLiquidity(0, 0);
                                }
                                if (!poolKey.isFullRange()) {
                                    _updateTick(poolId, params.bounds.lower, poolKey.tickSpacing(), params.liquidityDelta, false);
                                    _updateTick(poolId, params.bounds.upper, poolKey.tickSpacing(), params.liquidityDelta, true);
                                    if (price.tick >= params.bounds.lower && price.tick < params.bounds.upper) {
                                        poolState[poolId].liquidity = addLiquidityDelta(poolState[poolId].liquidity, params.liquidityDelta);
                                    }
                                } else {
                                    poolState[poolId].liquidity = addLiquidityDelta(poolState[poolId].liquidity, params.liquidityDelta);
                                }
                                _maybeAccountDebtToken0(id, poolKey.token0, delta0);
                                _accountDebt(id, poolKey.token1, delta1);
                                emit PositionUpdated(locker, poolId, params, delta0, delta1);
                            }
                            if (shouldCallAfterUpdatePosition(extension) && locker != extension) {
                                IExtension(extension).afterUpdatePosition(locker, poolKey, params, delta0, delta1);
                            }
                        }
                        function collectFees(PoolKey memory poolKey, bytes32 salt, Bounds memory bounds)
                            external
                            returns (uint128 amount0, uint128 amount1)
                        {
                            (uint256 id, address locker) = _requireLocker();
                            address extension = poolKey.extension();
                            if (shouldCallBeforeCollectFees(extension) && locker != extension) {
                                IExtension(extension).beforeCollectFees(locker, poolKey, salt, bounds);
                            }
                            bytes32 poolId = poolKey.toPoolId();
                            PositionKey memory positionKey = PositionKey({salt: salt, owner: locker, bounds: bounds});
                            bytes32 positionId = positionKey.toPositionId();
                            Position memory position = poolPositions[poolId][positionId];
                            FeesPerLiquidity memory feesPerLiquidityInside =
                                _getPoolFeesPerLiquidityInside(poolId, bounds, poolKey.tickSpacing());
                            (amount0, amount1) = position.fees(feesPerLiquidityInside);
                            poolPositions[poolId][positionId] =
                                Position({liquidity: position.liquidity, feesPerLiquidityInsideLast: feesPerLiquidityInside});
                            _accountDebt(id, poolKey.token0, -int256(uint256(amount0)));
                            _accountDebt(id, poolKey.token1, -int256(uint256(amount1)));
                            emit PositionFeesCollected(poolId, positionKey, amount0, amount1);
                            if (shouldCallAfterCollectFees(extension) && locker != extension) {
                                IExtension(extension).afterCollectFees(locker, poolKey, salt, bounds, amount0, amount1);
                            }
                        }
                        function swap_611415377(
                            PoolKey memory poolKey,
                            int128 amount,
                            bool isToken1,
                            SqrtRatio sqrtRatioLimit,
                            uint256 skipAhead
                        ) external payable returns (int128 delta0, int128 delta1) {
                            if (!sqrtRatioLimit.isValid()) revert InvalidSqrtRatioLimit();
                            (uint256 id, address locker) = _requireLocker();
                            address extension = poolKey.extension();
                            if (shouldCallBeforeSwap(extension) && locker != extension) {
                                IExtension(extension).beforeSwap(locker, poolKey, amount, isToken1, sqrtRatioLimit, skipAhead);
                            }
                            bytes32 poolId = poolKey.toPoolId();
                            SqrtRatio sqrtRatio;
                            int32 tick;
                            uint128 liquidity;
                            {
                                PoolState storage state = poolState[poolId];
                                (sqrtRatio, tick, liquidity) = (state.sqrtRatio, state.tick, state.liquidity);
                            }
                            if (sqrtRatio.isZero()) revert PoolNotInitialized();
                            // 0 swap amount is no-op
                            if (amount != 0) {
                                bool increasing = isPriceIncreasing(amount, isToken1);
                                if (increasing) {
                                    if (sqrtRatioLimit < sqrtRatio) revert SqrtRatioLimitWrongDirection();
                                } else {
                                    if (sqrtRatioLimit > sqrtRatio) revert SqrtRatioLimitWrongDirection();
                                }
                                int128 amountRemaining = amount;
                                uint128 calculatedAmount = 0;
                                // the slot where inputTokenFeesPerLiquidity is stored, reused later
                                bytes32 inputTokenFeesPerLiquiditySlot;
                                // fees per liquidity only for the input token
                                uint256 inputTokenFeesPerLiquidity;
                                // this loads only the input token fees per liquidity
                                if (poolKey.mustLoadFees()) {
                                    assembly ("memory-safe") {
                                        mstore(0, poolId)
                                        mstore(32, 3)
                                        inputTokenFeesPerLiquiditySlot := add(keccak256(0, 64), increasing)
                                        inputTokenFeesPerLiquidity := sload(inputTokenFeesPerLiquiditySlot)
                                    }
                                }
                                while (amountRemaining != 0 && sqrtRatio != sqrtRatioLimit) {
                                    int32 nextTick;
                                    bool isInitialized;
                                    SqrtRatio nextTickSqrtRatio;
                                    SwapResult memory result;
                                    if (poolKey.tickSpacing() != FULL_RANGE_ONLY_TICK_SPACING) {
                                        (nextTick, isInitialized) = increasing
                                            ? poolInitializedTickBitmaps[poolId].findNextInitializedTick(tick, poolKey.tickSpacing(), skipAhead)
                                            : poolInitializedTickBitmaps[poolId].findPrevInitializedTick(tick, poolKey.tickSpacing(), skipAhead);
                                        nextTickSqrtRatio = tickToSqrtRatio(nextTick);
                                    } else {
                                        // we never cross ticks in the full range version
                                        // isInitialized = false;
                                        (nextTick, nextTickSqrtRatio) = increasing ? (MAX_TICK, MAX_SQRT_RATIO) : (MIN_TICK, MIN_SQRT_RATIO);
                                    }
                                    SqrtRatio limitedNextSqrtRatio =
                                        increasing ? nextTickSqrtRatio.min(sqrtRatioLimit) : nextTickSqrtRatio.max(sqrtRatioLimit);
                                    result =
                                        swapResult(sqrtRatio, liquidity, limitedNextSqrtRatio, amountRemaining, isToken1, poolKey.fee());
                                    // this accounts the fees into the feesPerLiquidity memory struct
                                    assembly ("memory-safe") {
                                        // div by 0 returns 0, so it's ok
                                        let v := div(shl(128, mload(add(result, 96))), liquidity)
                                        inputTokenFeesPerLiquidity := add(inputTokenFeesPerLiquidity, v)
                                    }
                                    amountRemaining -= result.consumedAmount;
                                    calculatedAmount += result.calculatedAmount;
                                    if (result.sqrtRatioNext == nextTickSqrtRatio) {
                                        sqrtRatio = result.sqrtRatioNext;
                                        tick = increasing ? nextTick : nextTick - 1;
                                        if (isInitialized) {
                                            int128 liquidityDelta = poolTicks[poolId][nextTick].liquidityDelta;
                                            liquidity = increasing
                                                ? addLiquidityDelta(liquidity, liquidityDelta)
                                                : subLiquidityDelta(liquidity, liquidityDelta);
                                            FeesPerLiquidity memory tickFpl = poolTickFeesPerLiquidityOutside[poolId][nextTick];
                                            FeesPerLiquidity memory totalFpl;
                                            // load only the slot we didn't load before into totalFpl
                                            assembly ("memory-safe") {
                                                mstore(add(totalFpl, mul(32, increasing)), inputTokenFeesPerLiquidity)
                                                let outputTokenFeesPerLiquidity :=
                                                    sload(add(sub(inputTokenFeesPerLiquiditySlot, increasing), iszero(increasing)))
                                                mstore(add(totalFpl, mul(32, iszero(increasing))), outputTokenFeesPerLiquidity)
                                            }
                                            poolTickFeesPerLiquidityOutside[poolId][nextTick] = totalFpl.sub(tickFpl);
                                        }
                                    } else if (sqrtRatio != result.sqrtRatioNext) {
                                        sqrtRatio = result.sqrtRatioNext;
                                        tick = sqrtRatioToTick(sqrtRatio);
                                    }
                                }
                                unchecked {
                                    int256 calculatedAmountSign = int256(FixedPointMathLib.ternary(amount < 0, 1, type(uint256).max));
                                    int128 calculatedAmountDelta = SafeCastLib.toInt128(
                                        FixedPointMathLib.max(type(int128).min, calculatedAmountSign * int256(uint256(calculatedAmount)))
                                    );
                                    (delta0, delta1) = isToken1
                                        ? (calculatedAmountDelta, amount - amountRemaining)
                                        : (amount - amountRemaining, calculatedAmountDelta);
                                }
                                assembly ("memory-safe") {
                                    mstore(0, poolId)
                                    mstore(32, 2)
                                    sstore(keccak256(0, 64), add(add(sqrtRatio, shl(96, and(tick, 0xffffffff))), shl(128, liquidity)))
                                }
                                if (poolKey.mustLoadFees()) {
                                    assembly ("memory-safe") {
                                        // this stores only the input token fees per liquidity
                                        sstore(inputTokenFeesPerLiquiditySlot, inputTokenFeesPerLiquidity)
                                    }
                                }
                                _maybeAccountDebtToken0(id, poolKey.token0, delta0);
                                _accountDebt(id, poolKey.token1, delta1);
                                assembly ("memory-safe") {
                                    let o := mload(0x40)
                                    mstore(o, shl(96, locker))
                                    mstore(add(o, 20), poolId)
                                    mstore(add(o, 52), or(shl(128, delta0), and(delta1, 0xffffffffffffffffffffffffffffffff)))
                                    mstore(add(o, 84), shl(128, liquidity))
                                    mstore(add(o, 100), shl(160, sqrtRatio))
                                    mstore(add(o, 112), shl(224, tick))
                                    log0(o, 116)
                                }
                            }
                            if (shouldCallAfterSwap(extension) && locker != extension) {
                                IExtension(extension).afterSwap(
                                    locker, poolKey, amount, isToken1, sqrtRatioLimit, skipAhead, delta0, delta1
                                );
                            }
                        }
                    }
                    // SPDX-License-Identifier: UNLICENSED
                    pragma solidity =0.8.28;
                    struct CallPoints {
                        bool beforeInitializePool;
                        bool afterInitializePool;
                        bool beforeSwap;
                        bool afterSwap;
                        bool beforeUpdatePosition;
                        bool afterUpdatePosition;
                        bool beforeCollectFees;
                        bool afterCollectFees;
                    }
                    using {eq, isValid, toUint8} for CallPoints global;
                    function eq(CallPoints memory a, CallPoints memory b) pure returns (bool) {
                        return (
                            a.beforeInitializePool == b.beforeInitializePool && a.afterInitializePool == b.afterInitializePool
                                && a.beforeSwap == b.beforeSwap && a.afterSwap == b.afterSwap
                                && a.beforeUpdatePosition == b.beforeUpdatePosition && a.afterUpdatePosition == b.afterUpdatePosition
                                && a.beforeCollectFees == b.beforeCollectFees && a.afterCollectFees == b.afterCollectFees
                        );
                    }
                    function isValid(CallPoints memory a) pure returns (bool) {
                        return (
                            a.beforeInitializePool || a.afterInitializePool || a.beforeSwap || a.afterSwap || a.beforeUpdatePosition
                                || a.afterUpdatePosition || a.beforeCollectFees || a.afterCollectFees
                        );
                    }
                    function toUint8(CallPoints memory callPoints) pure returns (uint8 b) {
                        assembly ("memory-safe") {
                            b :=
                                add(
                                    add(
                                        add(
                                            add(
                                                add(
                                                    add(
                                                        add(mload(callPoints), mul(128, mload(add(callPoints, 32)))),
                                                        mul(64, mload(add(callPoints, 64)))
                                                    ),
                                                    mul(32, mload(add(callPoints, 96)))
                                                ),
                                                mul(16, mload(add(callPoints, 128)))
                                            ),
                                            mul(8, mload(add(callPoints, 160)))
                                        ),
                                        mul(4, mload(add(callPoints, 192)))
                                    ),
                                    mul(2, mload(add(callPoints, 224)))
                                )
                        }
                    }
                    function addressToCallPoints(address a) pure returns (CallPoints memory result) {
                        result = byteToCallPoints(uint8(uint160(a) >> 152));
                    }
                    function byteToCallPoints(uint8 b) pure returns (CallPoints memory result) {
                        // note the order of bytes does not match the struct order of elements because we are matching the cairo implementation
                        // which for legacy reasons has the fields in this order
                        result = CallPoints({
                            beforeInitializePool: (b & 1) != 0,
                            afterInitializePool: (b & 128) != 0,
                            beforeSwap: (b & 64) != 0,
                            afterSwap: (b & 32) != 0,
                            beforeUpdatePosition: (b & 16) != 0,
                            afterUpdatePosition: (b & 8) != 0,
                            beforeCollectFees: (b & 4) != 0,
                            afterCollectFees: (b & 2) != 0
                        });
                    }
                    function shouldCallBeforeInitializePool(address a) pure returns (bool yes) {
                        assembly ("memory-safe") {
                            yes := and(shr(152, a), 1)
                        }
                    }
                    function shouldCallAfterInitializePool(address a) pure returns (bool yes) {
                        assembly ("memory-safe") {
                            yes := and(shr(159, a), 1)
                        }
                    }
                    function shouldCallBeforeSwap(address a) pure returns (bool yes) {
                        assembly ("memory-safe") {
                            yes := and(shr(158, a), 1)
                        }
                    }
                    function shouldCallAfterSwap(address a) pure returns (bool yes) {
                        assembly ("memory-safe") {
                            yes := and(shr(157, a), 1)
                        }
                    }
                    function shouldCallBeforeUpdatePosition(address a) pure returns (bool yes) {
                        assembly ("memory-safe") {
                            yes := and(shr(156, a), 1)
                        }
                    }
                    function shouldCallAfterUpdatePosition(address a) pure returns (bool yes) {
                        assembly ("memory-safe") {
                            yes := and(shr(155, a), 1)
                        }
                    }
                    function shouldCallBeforeCollectFees(address a) pure returns (bool yes) {
                        assembly ("memory-safe") {
                            yes := and(shr(154, a), 1)
                        }
                    }
                    function shouldCallAfterCollectFees(address a) pure returns (bool yes) {
                        assembly ("memory-safe") {
                            yes := and(shr(153, a), 1)
                        }
                    }
                    // SPDX-License-Identifier: UNLICENSED
                    pragma solidity =0.8.28;
                    import {MAX_TICK_SPACING, FULL_RANGE_ONLY_TICK_SPACING} from "../math/constants.sol";
                    using {toPoolId, validatePoolKey, isFullRange, mustLoadFees, tickSpacing, fee, extension} for PoolKey global;
                    // address (20 bytes) | fee (8 bytes) | tickSpacing (4 bytes)
                    type Config is bytes32;
                    function tickSpacing(PoolKey memory pk) pure returns (uint32 r) {
                        assembly ("memory-safe") {
                            r := and(mload(add(64, pk)), 0xffffffff)
                        }
                    }
                    function fee(PoolKey memory pk) pure returns (uint64 r) {
                        assembly ("memory-safe") {
                            r := and(mload(add(60, pk)), 0xffffffffffffffff)
                        }
                    }
                    function extension(PoolKey memory pk) pure returns (address r) {
                        assembly ("memory-safe") {
                            r := and(mload(add(52, pk)), 0xffffffffffffffffffffffffffffffffffffffff)
                        }
                    }
                    function mustLoadFees(PoolKey memory pk) pure returns (bool r) {
                        assembly ("memory-safe") {
                            // only if either of tick spacing and fee are nonzero
                            // if _both_ are zero, then we know we do not need to load fees for swaps
                            r := iszero(iszero(and(mload(add(64, pk)), 0xffffffffffffffffffffffff)))
                        }
                    }
                    function isFullRange(PoolKey memory pk) pure returns (bool r) {
                        r = pk.tickSpacing() == FULL_RANGE_ONLY_TICK_SPACING;
                    }
                    function toConfig(uint64 _fee, uint32 _tickSpacing, address _extension) pure returns (Config c) {
                        assembly ("memory-safe") {
                            c := add(add(shl(96, _extension), shl(32, _fee)), _tickSpacing)
                        }
                    }
                    // Each pool has its own state associated with this key
                    struct PoolKey {
                        address token0;
                        address token1;
                        Config config;
                    }
                    error TokensMustBeSorted();
                    error InvalidTickSpacing();
                    function validatePoolKey(PoolKey memory key) pure {
                        if (key.token0 >= key.token1) revert TokensMustBeSorted();
                        if (key.tickSpacing() > MAX_TICK_SPACING) {
                            revert InvalidTickSpacing();
                        }
                    }
                    function toPoolId(PoolKey memory key) pure returns (bytes32 result) {
                        assembly ("memory-safe") {
                            // it's already copied into memory
                            result := keccak256(key, 96)
                        }
                    }
                    // SPDX-License-Identifier: UNLICENSED
                    pragma solidity =0.8.28;
                    import {MIN_TICK, MAX_TICK, FULL_RANGE_ONLY_TICK_SPACING} from "../math/constants.sol";
                    using {toPositionId} for PositionKey global;
                    using {validateBounds} for Bounds global;
                    // Bounds are lower and upper prices for which a position is active
                    struct Bounds {
                        int32 lower;
                        int32 upper;
                    }
                    error BoundsOrder();
                    error MinMaxBounds();
                    error BoundsTickSpacing();
                    error FullRangeOnlyPool();
                    function validateBounds(Bounds memory bounds, uint32 tickSpacing) pure {
                        if (tickSpacing == FULL_RANGE_ONLY_TICK_SPACING) {
                            if (bounds.lower != MIN_TICK || bounds.upper != MAX_TICK) revert FullRangeOnlyPool();
                        } else {
                            if (bounds.lower >= bounds.upper) revert BoundsOrder();
                            if (bounds.lower < MIN_TICK || bounds.upper > MAX_TICK) revert MinMaxBounds();
                            int32 spacing = int32(tickSpacing);
                            if (bounds.lower % spacing != 0 || bounds.upper % spacing != 0) revert BoundsTickSpacing();
                        }
                    }
                    // A position is keyed by the pool and this position key
                    struct PositionKey {
                        bytes32 salt;
                        address owner;
                        Bounds bounds;
                    }
                    function toPositionId(PositionKey memory key) pure returns (bytes32 result) {
                        assembly ("memory-safe") {
                            // salt and owner
                            mstore(0, keccak256(key, 64))
                            // bounds
                            mstore(32, keccak256(mload(add(key, 64)), 64))
                            result := keccak256(0, 64)
                        }
                    }
                    // SPDX-License-Identifier: UNLICENSED
                    pragma solidity =0.8.28;
                    // The total fees per liquidity for each token.
                    // Since these are always read together we put them in a struct, even though they cannot be packed.
                    struct FeesPerLiquidity {
                        uint256 value0;
                        uint256 value1;
                    }
                    using {sub} for FeesPerLiquidity global;
                    function sub(FeesPerLiquidity memory a, FeesPerLiquidity memory b) pure returns (FeesPerLiquidity memory result) {
                        assembly ("memory-safe") {
                            mstore(result, sub(mload(a), mload(b)))
                            mstore(add(result, 32), sub(mload(add(a, 32)), mload(add(b, 32))))
                        }
                    }
                    function feesPerLiquidityFromAmounts(uint128 amount0, uint128 amount1, uint128 liquidity)
                        pure
                        returns (FeesPerLiquidity memory result)
                    {
                        assembly ("memory-safe") {
                            mstore(result, div(shl(128, amount0), liquidity))
                            mstore(add(result, 32), div(shl(128, amount1), liquidity))
                        }
                    }
                    // SPDX-License-Identifier: UNLICENSED
                    pragma solidity =0.8.28;
                    import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol";
                    import {computeFee, amountBeforeFee} from "./fee.sol";
                    import {nextSqrtRatioFromAmount0, nextSqrtRatioFromAmount1} from "./sqrtRatio.sol";
                    import {amount0Delta, amount1Delta} from "./delta.sol";
                    import {SafeCastLib} from "solady/utils/SafeCastLib.sol";
                    import {isPriceIncreasing} from "./isPriceIncreasing.sol";
                    import {SqrtRatio} from "../types/sqrtRatio.sol";
                    struct SwapResult {
                        int128 consumedAmount;
                        uint128 calculatedAmount;
                        SqrtRatio sqrtRatioNext;
                        uint128 feeAmount;
                    }
                    function noOpSwapResult(SqrtRatio sqrtRatioNext) pure returns (SwapResult memory) {
                        return SwapResult({consumedAmount: 0, calculatedAmount: 0, feeAmount: 0, sqrtRatioNext: sqrtRatioNext});
                    }
                    error SqrtRatioLimitWrongDirection();
                    function swapResult(
                        SqrtRatio sqrtRatio,
                        uint128 liquidity,
                        SqrtRatio sqrtRatioLimit,
                        int128 amount,
                        bool isToken1,
                        uint64 fee
                    ) pure returns (SwapResult memory) {
                        if (amount == 0 || sqrtRatio == sqrtRatioLimit) {
                            return noOpSwapResult(sqrtRatio);
                        }
                        bool increasing = isPriceIncreasing(amount, isToken1);
                        // We know sqrtRatio != sqrtRatioLimit because we early return above if it is
                        if ((sqrtRatioLimit > sqrtRatio) != increasing) revert SqrtRatioLimitWrongDirection();
                        if (liquidity == 0) {
                            // if the pool is empty, the swap will always move all the way to the limit price
                            return noOpSwapResult(sqrtRatioLimit);
                        }
                        bool isExactOut = amount < 0;
                        // this amount is what moves the price
                        int128 priceImpactAmount;
                        if (isExactOut) {
                            priceImpactAmount = amount;
                        } else {
                            unchecked {
                                // cast is safe because amount is g.t.e. 0
                                // then cast back to int128 is also safe because computeFee never returns a value g.t. the input amount
                                priceImpactAmount = amount - int128(computeFee(uint128(amount), fee));
                            }
                        }
                        SqrtRatio sqrtRatioNextFromAmount;
                        if (isToken1) {
                            sqrtRatioNextFromAmount = nextSqrtRatioFromAmount1(sqrtRatio, liquidity, priceImpactAmount);
                        } else {
                            sqrtRatioNextFromAmount = nextSqrtRatioFromAmount0(sqrtRatio, liquidity, priceImpactAmount);
                        }
                        int128 consumedAmount;
                        uint128 calculatedAmount;
                        uint128 feeAmount;
                        // the amount requires a swapping past the sqrt ratio limit,
                        // so we need to compute the result of swapping only to the limit
                        if (
                            (increasing && sqrtRatioNextFromAmount > sqrtRatioLimit)
                                || (!increasing && sqrtRatioNextFromAmount < sqrtRatioLimit)
                        ) {
                            uint128 specifiedAmountDelta;
                            uint128 calculatedAmountDelta;
                            if (isToken1) {
                                specifiedAmountDelta = amount1Delta(sqrtRatioLimit, sqrtRatio, liquidity, !isExactOut);
                                calculatedAmountDelta = amount0Delta(sqrtRatioLimit, sqrtRatio, liquidity, isExactOut);
                            } else {
                                specifiedAmountDelta = amount0Delta(sqrtRatioLimit, sqrtRatio, liquidity, !isExactOut);
                                calculatedAmountDelta = amount1Delta(sqrtRatioLimit, sqrtRatio, liquidity, isExactOut);
                            }
                            if (isExactOut) {
                                uint128 beforeFee = amountBeforeFee(calculatedAmountDelta, fee);
                                consumedAmount = -SafeCastLib.toInt128(specifiedAmountDelta);
                                calculatedAmount = beforeFee;
                                feeAmount = beforeFee - calculatedAmountDelta;
                            } else {
                                uint128 beforeFee = amountBeforeFee(specifiedAmountDelta, fee);
                                consumedAmount = SafeCastLib.toInt128(beforeFee);
                                calculatedAmount = calculatedAmountDelta;
                                feeAmount = beforeFee - specifiedAmountDelta;
                            }
                            return SwapResult({
                                consumedAmount: consumedAmount,
                                calculatedAmount: calculatedAmount,
                                sqrtRatioNext: sqrtRatioLimit,
                                feeAmount: feeAmount
                            });
                        }
                        if (sqrtRatioNextFromAmount == sqrtRatio) {
                            assert(!isExactOut);
                            return SwapResult({
                                consumedAmount: amount,
                                calculatedAmount: 0,
                                sqrtRatioNext: sqrtRatio,
                                feeAmount: uint128(amount)
                            });
                        }
                        // rounds down for calculated == output, up for calculated == input
                        uint128 calculatedAmountWithoutFee;
                        if (isToken1) {
                            calculatedAmountWithoutFee = amount0Delta(sqrtRatioNextFromAmount, sqrtRatio, liquidity, isExactOut);
                        } else {
                            calculatedAmountWithoutFee = amount1Delta(sqrtRatioNextFromAmount, sqrtRatio, liquidity, isExactOut);
                        }
                        // add on the fee to calculated amount for exact output
                        if (isExactOut) {
                            uint128 includingFee = amountBeforeFee(calculatedAmountWithoutFee, fee);
                            calculatedAmount = includingFee;
                            feeAmount = includingFee - calculatedAmountWithoutFee;
                        } else {
                            calculatedAmount = calculatedAmountWithoutFee;
                            feeAmount = uint128(amount - priceImpactAmount);
                        }
                        return SwapResult({
                            consumedAmount: amount,
                            calculatedAmount: calculatedAmount,
                            sqrtRatioNext: sqrtRatioNextFromAmount,
                            feeAmount: feeAmount
                        });
                    }
                    // SPDX-License-Identifier: UNLICENSED
                    pragma solidity =0.8.28;
                    import {FeesPerLiquidity} from "./feesPerLiquidity.sol";
                    import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol";
                    struct Position {
                        uint128 liquidity;
                        FeesPerLiquidity feesPerLiquidityInsideLast;
                    }
                    using {fees} for Position global;
                    /// @dev Returns the fee amounts of token0 and token1 owed to a position based on the given fees per liquidity inside snapshot
                    ///      Note if the computed fees overflows the uint128 type, it will return only the lower 128 bits. It is assumed that accumulated
                    ///      fees will never exceed type(uint128).max.
                    function fees(Position memory position, FeesPerLiquidity memory feesPerLiquidityInside)
                        pure
                        returns (uint128, uint128)
                    {
                        FeesPerLiquidity memory difference = feesPerLiquidityInside.sub(position.feesPerLiquidityInsideLast);
                        return (
                            uint128(FixedPointMathLib.fullMulDivN(difference.value0, position.liquidity, 128)),
                            uint128(FixedPointMathLib.fullMulDivN(difference.value1, position.liquidity, 128))
                        );
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.8.4;
                    /// @notice Simple single owner authorization mixin.
                    /// @author Solady (https://github.com/vectorized/solady/blob/main/src/auth/Ownable.sol)
                    ///
                    /// @dev Note:
                    /// This implementation does NOT auto-initialize the owner to `msg.sender`.
                    /// You MUST call the `_initializeOwner` in the constructor / initializer.
                    ///
                    /// While the ownable portion follows
                    /// [EIP-173](https://eips.ethereum.org/EIPS/eip-173) for compatibility,
                    /// the nomenclature for the 2-step ownership handover may be unique to this codebase.
                    abstract contract Ownable {
                        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                        /*                       CUSTOM ERRORS                        */
                        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                        /// @dev The caller is not authorized to call the function.
                        error Unauthorized();
                        /// @dev The `newOwner` cannot be the zero address.
                        error NewOwnerIsZeroAddress();
                        /// @dev The `pendingOwner` does not have a valid handover request.
                        error NoHandoverRequest();
                        /// @dev Cannot double-initialize.
                        error AlreadyInitialized();
                        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                        /*                           EVENTS                           */
                        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                        /// @dev The ownership is transferred from `oldOwner` to `newOwner`.
                        /// This event is intentionally kept the same as OpenZeppelin's Ownable to be
                        /// compatible with indexers and [EIP-173](https://eips.ethereum.org/EIPS/eip-173),
                        /// despite it not being as lightweight as a single argument event.
                        event OwnershipTransferred(address indexed oldOwner, address indexed newOwner);
                        /// @dev An ownership handover to `pendingOwner` has been requested.
                        event OwnershipHandoverRequested(address indexed pendingOwner);
                        /// @dev The ownership handover to `pendingOwner` has been canceled.
                        event OwnershipHandoverCanceled(address indexed pendingOwner);
                        /// @dev `keccak256(bytes("OwnershipTransferred(address,address)"))`.
                        uint256 private constant _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE =
                            0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0;
                        /// @dev `keccak256(bytes("OwnershipHandoverRequested(address)"))`.
                        uint256 private constant _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE =
                            0xdbf36a107da19e49527a7176a1babf963b4b0ff8cde35ee35d6cd8f1f9ac7e1d;
                        /// @dev `keccak256(bytes("OwnershipHandoverCanceled(address)"))`.
                        uint256 private constant _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE =
                            0xfa7b8eab7da67f412cc9575ed43464468f9bfbae89d1675917346ca6d8fe3c92;
                        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                        /*                          STORAGE                           */
                        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                        /// @dev The owner slot is given by:
                        /// `bytes32(~uint256(uint32(bytes4(keccak256("_OWNER_SLOT_NOT")))))`.
                        /// It is intentionally chosen to be a high value
                        /// to avoid collision with lower slots.
                        /// The choice of manual storage layout is to enable compatibility
                        /// with both regular and upgradeable contracts.
                        bytes32 internal constant _OWNER_SLOT =
                            0xffffffffffffffffffffffffffffffffffffffffffffffffffffffff74873927;
                        /// The ownership handover slot of `newOwner` is given by:
                        /// ```
                        ///     mstore(0x00, or(shl(96, user), _HANDOVER_SLOT_SEED))
                        ///     let handoverSlot := keccak256(0x00, 0x20)
                        /// ```
                        /// It stores the expiry timestamp of the two-step ownership handover.
                        uint256 private constant _HANDOVER_SLOT_SEED = 0x389a75e1;
                        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                        /*                     INTERNAL FUNCTIONS                     */
                        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                        /// @dev Override to return true to make `_initializeOwner` prevent double-initialization.
                        function _guardInitializeOwner() internal pure virtual returns (bool guard) {}
                        /// @dev Initializes the owner directly without authorization guard.
                        /// This function must be called upon initialization,
                        /// regardless of whether the contract is upgradeable or not.
                        /// This is to enable generalization to both regular and upgradeable contracts,
                        /// and to save gas in case the initial owner is not the caller.
                        /// For performance reasons, this function will not check if there
                        /// is an existing owner.
                        function _initializeOwner(address newOwner) internal virtual {
                            if (_guardInitializeOwner()) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    let ownerSlot := _OWNER_SLOT
                                    if sload(ownerSlot) {
                                        mstore(0x00, 0x0dc149f0) // `AlreadyInitialized()`.
                                        revert(0x1c, 0x04)
                                    }
                                    // Clean the upper 96 bits.
                                    newOwner := shr(96, shl(96, newOwner))
                                    // Store the new value.
                                    sstore(ownerSlot, or(newOwner, shl(255, iszero(newOwner))))
                                    // Emit the {OwnershipTransferred} event.
                                    log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
                                }
                            } else {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // Clean the upper 96 bits.
                                    newOwner := shr(96, shl(96, newOwner))
                                    // Store the new value.
                                    sstore(_OWNER_SLOT, newOwner)
                                    // Emit the {OwnershipTransferred} event.
                                    log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
                                }
                            }
                        }
                        /// @dev Sets the owner directly without authorization guard.
                        function _setOwner(address newOwner) internal virtual {
                            if (_guardInitializeOwner()) {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    let ownerSlot := _OWNER_SLOT
                                    // Clean the upper 96 bits.
                                    newOwner := shr(96, shl(96, newOwner))
                                    // Emit the {OwnershipTransferred} event.
                                    log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
                                    // Store the new value.
                                    sstore(ownerSlot, or(newOwner, shl(255, iszero(newOwner))))
                                }
                            } else {
                                /// @solidity memory-safe-assembly
                                assembly {
                                    let ownerSlot := _OWNER_SLOT
                                    // Clean the upper 96 bits.
                                    newOwner := shr(96, shl(96, newOwner))
                                    // Emit the {OwnershipTransferred} event.
                                    log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
                                    // Store the new value.
                                    sstore(ownerSlot, newOwner)
                                }
                            }
                        }
                        /// @dev Throws if the sender is not the owner.
                        function _checkOwner() internal view virtual {
                            /// @solidity memory-safe-assembly
                            assembly {
                                // If the caller is not the stored owner, revert.
                                if iszero(eq(caller(), sload(_OWNER_SLOT))) {
                                    mstore(0x00, 0x82b42900) // `Unauthorized()`.
                                    revert(0x1c, 0x04)
                                }
                            }
                        }
                        /// @dev Returns how long a two-step ownership handover is valid for in seconds.
                        /// Override to return a different value if needed.
                        /// Made internal to conserve bytecode. Wrap it in a public function if needed.
                        function _ownershipHandoverValidFor() internal view virtual returns (uint64) {
                            return 48 * 3600;
                        }
                        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                        /*                  PUBLIC UPDATE FUNCTIONS                   */
                        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                        /// @dev Allows the owner to transfer the ownership to `newOwner`.
                        function transferOwnership(address newOwner) public payable virtual onlyOwner {
                            /// @solidity memory-safe-assembly
                            assembly {
                                if iszero(shl(96, newOwner)) {
                                    mstore(0x00, 0x7448fbae) // `NewOwnerIsZeroAddress()`.
                                    revert(0x1c, 0x04)
                                }
                            }
                            _setOwner(newOwner);
                        }
                        /// @dev Allows the owner to renounce their ownership.
                        function renounceOwnership() public payable virtual onlyOwner {
                            _setOwner(address(0));
                        }
                        /// @dev Request a two-step ownership handover to the caller.
                        /// The request will automatically expire in 48 hours (172800 seconds) by default.
                        function requestOwnershipHandover() public payable virtual {
                            unchecked {
                                uint256 expires = block.timestamp + _ownershipHandoverValidFor();
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // Compute and set the handover slot to `expires`.
                                    mstore(0x0c, _HANDOVER_SLOT_SEED)
                                    mstore(0x00, caller())
                                    sstore(keccak256(0x0c, 0x20), expires)
                                    // Emit the {OwnershipHandoverRequested} event.
                                    log2(0, 0, _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE, caller())
                                }
                            }
                        }
                        /// @dev Cancels the two-step ownership handover to the caller, if any.
                        function cancelOwnershipHandover() public payable virtual {
                            /// @solidity memory-safe-assembly
                            assembly {
                                // Compute and set the handover slot to 0.
                                mstore(0x0c, _HANDOVER_SLOT_SEED)
                                mstore(0x00, caller())
                                sstore(keccak256(0x0c, 0x20), 0)
                                // Emit the {OwnershipHandoverCanceled} event.
                                log2(0, 0, _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE, caller())
                            }
                        }
                        /// @dev Allows the owner to complete the two-step ownership handover to `pendingOwner`.
                        /// Reverts if there is no existing ownership handover requested by `pendingOwner`.
                        function completeOwnershipHandover(address pendingOwner) public payable virtual onlyOwner {
                            /// @solidity memory-safe-assembly
                            assembly {
                                // Compute and set the handover slot to 0.
                                mstore(0x0c, _HANDOVER_SLOT_SEED)
                                mstore(0x00, pendingOwner)
                                let handoverSlot := keccak256(0x0c, 0x20)
                                // If the handover does not exist, or has expired.
                                if gt(timestamp(), sload(handoverSlot)) {
                                    mstore(0x00, 0x6f5e8818) // `NoHandoverRequest()`.
                                    revert(0x1c, 0x04)
                                }
                                // Set the handover slot to 0.
                                sstore(handoverSlot, 0)
                            }
                            _setOwner(pendingOwner);
                        }
                        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                        /*                   PUBLIC READ FUNCTIONS                    */
                        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                        /// @dev Returns the owner of the contract.
                        function owner() public view virtual returns (address result) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                result := sload(_OWNER_SLOT)
                            }
                        }
                        /// @dev Returns the expiry timestamp for the two-step ownership handover to `pendingOwner`.
                        function ownershipHandoverExpiresAt(address pendingOwner)
                            public
                            view
                            virtual
                            returns (uint256 result)
                        {
                            /// @solidity memory-safe-assembly
                            assembly {
                                // Compute the handover slot.
                                mstore(0x0c, _HANDOVER_SLOT_SEED)
                                mstore(0x00, pendingOwner)
                                // Load the handover slot.
                                result := sload(keccak256(0x0c, 0x20))
                            }
                        }
                        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                        /*                         MODIFIERS                          */
                        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                        /// @dev Marks a function as only callable by the owner.
                        modifier onlyOwner() virtual {
                            _checkOwner();
                            _;
                        }
                    }
                    // SPDX-License-Identifier: UNLICENSED
                    pragma solidity =0.8.28;
                    import {MAX_TICK_SPACING, MAX_TICK_MAGNITUDE} from "./constants.sol";
                    import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol";
                    import {SqrtRatio, toSqrtRatio} from "../types/sqrtRatio.sol";
                    error InvalidTick(int32 tick);
                    // Returns the sqrtRatio corresponding for the tick
                    function tickToSqrtRatio(int32 tick) pure returns (SqrtRatio r) {
                        unchecked {
                            uint256 t = FixedPointMathLib.abs(tick);
                            if (t > MAX_TICK_MAGNITUDE) revert InvalidTick(tick);
                            uint256 ratio;
                            assembly ("memory-safe") {
                                ratio := sub(0x100000000000000000000000000000000, mul(and(t, 0x1), 0x8637b66cd638344daef276cd7c5))
                            }
                            if ((t & 0x2) != 0) {
                                ratio = (ratio * 0xffffef390978c398134b4ff3764fe410) >> 128;
                            }
                            if ((t & 0x4) != 0) {
                                ratio = (ratio * 0xffffde72140b00a354bd3dc828e976c9) >> 128;
                            }
                            if ((t & 0x8) != 0) {
                                ratio = (ratio * 0xffffbce42c7be6c998ad6318193c0b18) >> 128;
                            }
                            if ((t & 0x10) != 0) {
                                ratio = (ratio * 0xffff79c86a8f6150a32d9778eceef97c) >> 128;
                            }
                            if ((t & 0x20) != 0) {
                                ratio = (ratio * 0xfffef3911b7cff24ba1b3dbb5f8f5974) >> 128;
                            }
                            if ((t & 0x40) != 0) {
                                ratio = (ratio * 0xfffde72350725cc4ea8feece3b5f13c8) >> 128;
                            }
                            if ((t & 0x80) != 0) {
                                ratio = (ratio * 0xfffbce4b06c196e9247ac87695d53c60) >> 128;
                            }
                            if ((t & 0x100) != 0) {
                                ratio = (ratio * 0xfff79ca7a4d1bf1ee8556cea23cdbaa5) >> 128;
                            }
                            if ((t & 0x200) != 0) {
                                ratio = (ratio * 0xffef3995a5b6a6267530f207142a5764) >> 128;
                            }
                            if ((t & 0x400) != 0) {
                                ratio = (ratio * 0xffde7444b28145508125d10077ba83b8) >> 128;
                            }
                            if ((t & 0x800) != 0) {
                                ratio = (ratio * 0xffbceceeb791747f10df216f2e53ec57) >> 128;
                            }
                            if ((t & 0x1000) != 0) {
                                ratio = (ratio * 0xff79eb706b9a64c6431d76e63531e929) >> 128;
                            }
                            if ((t & 0x2000) != 0) {
                                ratio = (ratio * 0xfef41d1a5f2ae3a20676bec6f7f9459a) >> 128;
                            }
                            if ((t & 0x4000) != 0) {
                                ratio = (ratio * 0xfde95287d26d81bea159c37073122c73) >> 128;
                            }
                            if ((t & 0x8000) != 0) {
                                ratio = (ratio * 0xfbd701c7cbc4c8a6bb81efd232d1e4e7) >> 128;
                            }
                            if ((t & 0x10000) != 0) {
                                ratio = (ratio * 0xf7bf5211c72f5185f372aeb1d48f937e) >> 128;
                            }
                            if ((t & 0x20000) != 0) {
                                ratio = (ratio * 0xefc2bf59df33ecc28125cf78ec4f167f) >> 128;
                            }
                            if ((t & 0x40000) != 0) {
                                ratio = (ratio * 0xe08d35706200796273f0b3a981d90cfd) >> 128;
                            }
                            if ((t & 0x80000) != 0) {
                                ratio = (ratio * 0xc4f76b68947482dc198a48a54348c4ed) >> 128;
                            }
                            if ((t & 0x100000) != 0) {
                                ratio = (ratio * 0x978bcb9894317807e5fa4498eee7c0fa) >> 128;
                            }
                            if ((t & 0x200000) != 0) {
                                ratio = (ratio * 0x59b63684b86e9f486ec54727371ba6ca) >> 128;
                            }
                            if ((t & 0x400000) != 0) {
                                ratio = (ratio * 0x1f703399d88f6aa83a28b22d4a1f56e3) >> 128;
                            }
                            if ((t & 0x800000) != 0) {
                                ratio = (ratio * 0x3dc5dac7376e20fc8679758d1bcdcfc) >> 128;
                            }
                            if ((t & 0x1000000) != 0) {
                                ratio = (ratio * 0xee7e32d61fdb0a5e622b820f681d0) >> 128;
                            }
                            if ((t & 0x2000000) != 0) {
                                ratio = (ratio * 0xde2ee4bc381afa7089aa84bb66) >> 128;
                            }
                            if ((t & 0x4000000) != 0) {
                                ratio = (ratio * 0xc0d55d4d7152c25fb139) >> 128;
                            }
                            if (tick > 0) {
                                ratio = type(uint256).max / ratio;
                            }
                            r = toSqrtRatio(ratio, false);
                        }
                    }
                    function sqrtRatioToTick(SqrtRatio sqrtRatio) pure returns (int32) {
                        unchecked {
                            uint256 sqrtRatioFixed = sqrtRatio.toFixed();
                            bool negative = (sqrtRatioFixed >> 128) == 0;
                            uint256 x = negative ? (type(uint256).max / sqrtRatioFixed) : sqrtRatioFixed;
                            // we know x >> 128 is never zero because we check bounds above and then reciprocate sqrtRatio if the high 128 bits are zero
                            // so we don't need to handle the exceptional case of log2(0)
                            uint256 msbHigh = FixedPointMathLib.log2(x >> 128);
                            x = x >> (msbHigh + 1);
                            uint256 log2_unsigned = msbHigh * 0x10000000000000000;
                            assembly ("memory-safe") {
                                // 63
                                x := shr(127, mul(x, x))
                                let is_high_nonzero := eq(iszero(shr(128, x)), 0)
                                log2_unsigned := add(log2_unsigned, mul(is_high_nonzero, 0x8000000000000000))
                                x := shr(is_high_nonzero, x)
                                // 62
                                x := shr(127, mul(x, x))
                                is_high_nonzero := eq(iszero(shr(128, x)), 0)
                                log2_unsigned := add(log2_unsigned, mul(is_high_nonzero, 0x4000000000000000))
                                x := shr(is_high_nonzero, x)
                                // 61
                                x := shr(127, mul(x, x))
                                is_high_nonzero := eq(iszero(shr(128, x)), 0)
                                log2_unsigned := add(log2_unsigned, mul(is_high_nonzero, 0x2000000000000000))
                                x := shr(is_high_nonzero, x)
                                // 60
                                x := shr(127, mul(x, x))
                                is_high_nonzero := eq(iszero(shr(128, x)), 0)
                                log2_unsigned := add(log2_unsigned, mul(is_high_nonzero, 0x1000000000000000))
                                x := shr(is_high_nonzero, x)
                                // 59
                                x := shr(127, mul(x, x))
                                is_high_nonzero := eq(iszero(shr(128, x)), 0)
                                log2_unsigned := add(log2_unsigned, mul(is_high_nonzero, 0x800000000000000))
                                x := shr(is_high_nonzero, x)
                                // 58
                                x := shr(127, mul(x, x))
                                is_high_nonzero := eq(iszero(shr(128, x)), 0)
                                log2_unsigned := add(log2_unsigned, mul(is_high_nonzero, 0x400000000000000))
                                x := shr(is_high_nonzero, x)
                                // 57
                                x := shr(127, mul(x, x))
                                is_high_nonzero := eq(iszero(shr(128, x)), 0)
                                log2_unsigned := add(log2_unsigned, mul(is_high_nonzero, 0x200000000000000))
                                x := shr(is_high_nonzero, x)
                                // 56
                                x := shr(127, mul(x, x))
                                is_high_nonzero := eq(iszero(shr(128, x)), 0)
                                log2_unsigned := add(log2_unsigned, mul(is_high_nonzero, 0x100000000000000))
                                x := shr(is_high_nonzero, x)
                                // 55
                                x := shr(127, mul(x, x))
                                is_high_nonzero := eq(iszero(shr(128, x)), 0)
                                log2_unsigned := add(log2_unsigned, mul(is_high_nonzero, 0x80000000000000))
                                x := shr(is_high_nonzero, x)
                                // 54
                                x := shr(127, mul(x, x))
                                is_high_nonzero := eq(iszero(shr(128, x)), 0)
                                log2_unsigned := add(log2_unsigned, mul(is_high_nonzero, 0x40000000000000))
                                x := shr(is_high_nonzero, x)
                                // 53
                                x := shr(127, mul(x, x))
                                is_high_nonzero := eq(iszero(shr(128, x)), 0)
                                log2_unsigned := add(log2_unsigned, mul(is_high_nonzero, 0x20000000000000))
                                x := shr(is_high_nonzero, x)
                                // 52
                                x := shr(127, mul(x, x))
                                is_high_nonzero := eq(iszero(shr(128, x)), 0)
                                log2_unsigned := add(log2_unsigned, mul(is_high_nonzero, 0x10000000000000))
                                x := shr(is_high_nonzero, x)
                                // 51
                                x := shr(127, mul(x, x))
                                is_high_nonzero := eq(iszero(shr(128, x)), 0)
                                log2_unsigned := add(log2_unsigned, mul(is_high_nonzero, 0x8000000000000))
                                x := shr(is_high_nonzero, x)
                                // 50
                                x := shr(127, mul(x, x))
                                is_high_nonzero := eq(iszero(shr(128, x)), 0)
                                log2_unsigned := add(log2_unsigned, mul(is_high_nonzero, 0x4000000000000))
                                x := shr(is_high_nonzero, x)
                                // 49
                                x := shr(127, mul(x, x))
                                is_high_nonzero := eq(iszero(shr(128, x)), 0)
                                log2_unsigned := add(log2_unsigned, mul(is_high_nonzero, 0x2000000000000))
                                x := shr(is_high_nonzero, x)
                                // 48
                                x := shr(127, mul(x, x))
                                is_high_nonzero := eq(iszero(shr(128, x)), 0)
                                log2_unsigned := add(log2_unsigned, mul(is_high_nonzero, 0x1000000000000))
                                x := shr(is_high_nonzero, x)
                                // 47
                                x := shr(127, mul(x, x))
                                is_high_nonzero := eq(iszero(shr(128, x)), 0)
                                log2_unsigned := add(log2_unsigned, mul(is_high_nonzero, 0x800000000000))
                                x := shr(is_high_nonzero, x)
                                // 46
                                x := shr(127, mul(x, x))
                                is_high_nonzero := eq(iszero(shr(128, x)), 0)
                                log2_unsigned := add(log2_unsigned, mul(is_high_nonzero, 0x400000000000))
                                x := shr(is_high_nonzero, x)
                                // 45
                                x := shr(127, mul(x, x))
                                is_high_nonzero := eq(iszero(shr(128, x)), 0)
                                log2_unsigned := add(log2_unsigned, mul(is_high_nonzero, 0x200000000000))
                                x := shr(is_high_nonzero, x)
                                // 44
                                x := shr(127, mul(x, x))
                                is_high_nonzero := eq(iszero(shr(128, x)), 0)
                                log2_unsigned := add(log2_unsigned, mul(is_high_nonzero, 0x100000000000))
                                x := shr(is_high_nonzero, x)
                                // 43
                                x := shr(127, mul(x, x))
                                is_high_nonzero := eq(iszero(shr(128, x)), 0)
                                log2_unsigned := add(log2_unsigned, mul(is_high_nonzero, 0x80000000000))
                                x := shr(is_high_nonzero, x)
                                // 42
                                x := shr(127, mul(x, x))
                                is_high_nonzero := eq(iszero(shr(128, x)), 0)
                                log2_unsigned := add(log2_unsigned, mul(is_high_nonzero, 0x40000000000))
                            }
                            // 25572630076711825471857579 == 2**64/(log base 2 of sqrt tick size)
                            // https://www.wolframalpha.com/input?i=floor%28%281%2F+log+base+2+of+%28sqrt%281.000001%29%29%29*2**64%29
                            int256 logBaseTickSizeX128 =
                                (negative ? -int256(log2_unsigned) : int256(log2_unsigned)) * 25572630076711825471857579;
                            int32 tickLow;
                            int32 tickHigh;
                            if (negative) {
                                tickLow = int32((logBaseTickSizeX128 - 112469616488610087266845472033458199637) >> 128);
                                tickHigh = int32((logBaseTickSizeX128) >> 128);
                            } else {
                                tickLow = int32((logBaseTickSizeX128) >> 128);
                                tickHigh = int32((logBaseTickSizeX128 + 112469616488610087266845472033458199637) >> 128);
                            }
                            if (tickLow == tickHigh) {
                                return tickLow;
                            }
                            if (tickToSqrtRatio(tickHigh) <= sqrtRatio) return tickHigh;
                            return tickLow;
                        }
                    }
                    // SPDX-License-Identifier: UNLICENSED
                    pragma solidity =0.8.28;
                    import {LibBit} from "solady/utils/LibBit.sol";
                    type Bitmap is uint256;
                    using {toggle, isSet, leSetBit, geSetBit} for Bitmap global;
                    function toggle(Bitmap bitmap, uint8 index) pure returns (Bitmap result) {
                        assembly ("memory-safe") {
                            result := xor(bitmap, shl(index, 1))
                        }
                    }
                    function isSet(Bitmap bitmap, uint8 index) pure returns (bool yes) {
                        assembly ("memory-safe") {
                            yes := and(shr(index, bitmap), 1)
                        }
                    }
                    // Returns the index of the most significant bit that is set _and_ less or equally significant to index, or 256 if no such bit exists.
                    function leSetBit(Bitmap bitmap, uint8 index) pure returns (uint256) {
                        unchecked {
                            uint256 masked;
                            assembly ("memory-safe") {
                                masked := and(bitmap, sub(shl(add(index, 1), 1), 1))
                            }
                            return LibBit.fls(masked);
                        }
                    }
                    // Returns the index of the least significant bit that is set _and_ more or equally significant to index, or 256 if no such bit exists.
                    function geSetBit(Bitmap bitmap, uint8 index) pure returns (uint256) {
                        unchecked {
                            uint256 masked;
                            assembly ("memory-safe") {
                                masked := and(bitmap, not(sub(shl(index, 1), 1)))
                            }
                            return LibBit.ffs(masked);
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.8.4;
                    /// @notice Arithmetic library with operations for fixed-point numbers.
                    /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/FixedPointMathLib.sol)
                    /// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
                    library FixedPointMathLib {
                        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                        /*                       CUSTOM ERRORS                        */
                        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                        /// @dev The operation failed, as the output exceeds the maximum value of uint256.
                        error ExpOverflow();
                        /// @dev The operation failed, as the output exceeds the maximum value of uint256.
                        error FactorialOverflow();
                        /// @dev The operation failed, due to an overflow.
                        error RPowOverflow();
                        /// @dev The mantissa is too big to fit.
                        error MantissaOverflow();
                        /// @dev The operation failed, due to an multiplication overflow.
                        error MulWadFailed();
                        /// @dev The operation failed, due to an multiplication overflow.
                        error SMulWadFailed();
                        /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
                        error DivWadFailed();
                        /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
                        error SDivWadFailed();
                        /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
                        error MulDivFailed();
                        /// @dev The division failed, as the denominator is zero.
                        error DivFailed();
                        /// @dev The full precision multiply-divide operation failed, either due
                        /// to the result being larger than 256 bits, or a division by a zero.
                        error FullMulDivFailed();
                        /// @dev The output is undefined, as the input is less-than-or-equal to zero.
                        error LnWadUndefined();
                        /// @dev The input outside the acceptable domain.
                        error OutOfDomain();
                        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                        /*                         CONSTANTS                          */
                        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                        /// @dev The scalar of ETH and most ERC20s.
                        uint256 internal constant WAD = 1e18;
                        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                        /*              SIMPLIFIED FIXED POINT OPERATIONS             */
                        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                        /// @dev Equivalent to `(x * y) / WAD` rounded down.
                        function mulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
                                if gt(x, div(not(0), y)) {
                                    if y {
                                        mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                }
                                z := div(mul(x, y), WAD)
                            }
                        }
                        /// @dev Equivalent to `(x * y) / WAD` rounded down.
                        function sMulWad(int256 x, int256 y) internal pure returns (int256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := mul(x, y)
                                // Equivalent to `require((x == 0 || z / x == y) && !(x == -1 && y == type(int256).min))`.
                                if iszero(gt(or(iszero(x), eq(sdiv(z, x), y)), lt(not(x), eq(y, shl(255, 1))))) {
                                    mstore(0x00, 0xedcd4dd4) // `SMulWadFailed()`.
                                    revert(0x1c, 0x04)
                                }
                                z := sdiv(z, WAD)
                            }
                        }
                        /// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
                        function rawMulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := div(mul(x, y), WAD)
                            }
                        }
                        /// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
                        function rawSMulWad(int256 x, int256 y) internal pure returns (int256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := sdiv(mul(x, y), WAD)
                            }
                        }
                        /// @dev Equivalent to `(x * y) / WAD` rounded up.
                        function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := mul(x, y)
                                // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
                                if iszero(eq(div(z, y), x)) {
                                    if y {
                                        mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                }
                                z := add(iszero(iszero(mod(z, WAD))), div(z, WAD))
                            }
                        }
                        /// @dev Equivalent to `(x * y) / WAD` rounded up, but without overflow checks.
                        function rawMulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD))
                            }
                        }
                        /// @dev Equivalent to `(x * WAD) / y` rounded down.
                        function divWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                // Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`.
                                if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) {
                                    mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
                                    revert(0x1c, 0x04)
                                }
                                z := div(mul(x, WAD), y)
                            }
                        }
                        /// @dev Equivalent to `(x * WAD) / y` rounded down.
                        function sDivWad(int256 x, int256 y) internal pure returns (int256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := mul(x, WAD)
                                // Equivalent to `require(y != 0 && ((x * WAD) / WAD == x))`.
                                if iszero(mul(y, eq(sdiv(z, WAD), x))) {
                                    mstore(0x00, 0x5c43740d) // `SDivWadFailed()`.
                                    revert(0x1c, 0x04)
                                }
                                z := sdiv(z, y)
                            }
                        }
                        /// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
                        function rawDivWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := div(mul(x, WAD), y)
                            }
                        }
                        /// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
                        function rawSDivWad(int256 x, int256 y) internal pure returns (int256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := sdiv(mul(x, WAD), y)
                            }
                        }
                        /// @dev Equivalent to `(x * WAD) / y` rounded up.
                        function divWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                // Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`.
                                if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) {
                                    mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
                                    revert(0x1c, 0x04)
                                }
                                z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
                            }
                        }
                        /// @dev Equivalent to `(x * WAD) / y` rounded up, but without overflow and divide by zero checks.
                        function rawDivWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
                            }
                        }
                        /// @dev Equivalent to `x` to the power of `y`.
                        /// because `x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)`.
                        /// Note: This function is an approximation.
                        function powWad(int256 x, int256 y) internal pure returns (int256) {
                            // Using `ln(x)` means `x` must be greater than 0.
                            return expWad((lnWad(x) * y) / int256(WAD));
                        }
                        /// @dev Returns `exp(x)`, denominated in `WAD`.
                        /// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
                        /// Note: This function is an approximation. Monotonically increasing.
                        function expWad(int256 x) internal pure returns (int256 r) {
                            unchecked {
                                // When the result is less than 0.5 we return zero.
                                // This happens when `x <= (log(1e-18) * 1e18) ~ -4.15e19`.
                                if (x <= -41446531673892822313) return r;
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // When the result is greater than `(2**255 - 1) / 1e18` we can not represent it as
                                    // an int. This happens when `x >= floor(log((2**255 - 1) / 1e18) * 1e18) ≈ 135`.
                                    if iszero(slt(x, 135305999368893231589)) {
                                        mstore(0x00, 0xa37bfec9) // `ExpOverflow()`.
                                        revert(0x1c, 0x04)
                                    }
                                }
                                // `x` is now in the range `(-42, 136) * 1e18`. Convert to `(-42, 136) * 2**96`
                                // for more intermediate precision and a binary basis. This base conversion
                                // is a multiplication by 1e18 / 2**96 = 5**18 / 2**78.
                                x = (x << 78) / 5 ** 18;
                                // Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers
                                // of two such that exp(x) = exp(x') * 2**k, where k is an integer.
                                // Solving this gives k = round(x / log(2)) and x' = x - k * log(2).
                                int256 k = ((x << 96) / 54916777467707473351141471128 + 2 ** 95) >> 96;
                                x = x - k * 54916777467707473351141471128;
                                // `k` is in the range `[-61, 195]`.
                                // Evaluate using a (6, 7)-term rational approximation.
                                // `p` is made monic, we'll multiply by a scale factor later.
                                int256 y = x + 1346386616545796478920950773328;
                                y = ((y * x) >> 96) + 57155421227552351082224309758442;
                                int256 p = y + x - 94201549194550492254356042504812;
                                p = ((p * y) >> 96) + 28719021644029726153956944680412240;
                                p = p * x + (4385272521454847904659076985693276 << 96);
                                // We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
                                int256 q = x - 2855989394907223263936484059900;
                                q = ((q * x) >> 96) + 50020603652535783019961831881945;
                                q = ((q * x) >> 96) - 533845033583426703283633433725380;
                                q = ((q * x) >> 96) + 3604857256930695427073651918091429;
                                q = ((q * x) >> 96) - 14423608567350463180887372962807573;
                                q = ((q * x) >> 96) + 26449188498355588339934803723976023;
                                /// @solidity memory-safe-assembly
                                assembly {
                                    // Div in assembly because solidity adds a zero check despite the unchecked.
                                    // The q polynomial won't have zeros in the domain as all its roots are complex.
                                    // No scaling is necessary because p is already `2**96` too large.
                                    r := sdiv(p, q)
                                }
                                // r should be in the range `(0.09, 0.25) * 2**96`.
                                // We now need to multiply r by:
                                // - The scale factor `s ≈ 6.031367120`.
                                // - The `2**k` factor from the range reduction.
                                // - The `1e18 / 2**96` factor for base conversion.
                                // We do this all at once, with an intermediate result in `2**213`
                                // basis, so the final right shift is always by a positive amount.
                                r = int256(
                                    (uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k)
                                );
                            }
                        }
                        /// @dev Returns `ln(x)`, denominated in `WAD`.
                        /// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
                        /// Note: This function is an approximation. Monotonically increasing.
                        function lnWad(int256 x) internal pure returns (int256 r) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                // We want to convert `x` from `10**18` fixed point to `2**96` fixed point.
                                // We do this by multiplying by `2**96 / 10**18`. But since
                                // `ln(x * C) = ln(x) + ln(C)`, we can simply do nothing here
                                // and add `ln(2**96 / 10**18)` at the end.
                                // Compute `k = log2(x) - 96`, `r = 159 - k = 255 - log2(x) = 255 ^ log2(x)`.
                                r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
                                r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
                                r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
                                r := or(r, shl(4, lt(0xffff, shr(r, x))))
                                r := or(r, shl(3, lt(0xff, shr(r, x))))
                                // We place the check here for more optimal stack operations.
                                if iszero(sgt(x, 0)) {
                                    mstore(0x00, 0x1615e638) // `LnWadUndefined()`.
                                    revert(0x1c, 0x04)
                                }
                                // forgefmt: disable-next-item
                                r := xor(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                                    0xf8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff))
                                // Reduce range of x to (1, 2) * 2**96
                                // ln(2^k * x) = k * ln(2) + ln(x)
                                x := shr(159, shl(r, x))
                                // Evaluate using a (8, 8)-term rational approximation.
                                // `p` is made monic, we will multiply by a scale factor later.
                                // forgefmt: disable-next-item
                                let p := sub( // This heavily nested expression is to avoid stack-too-deep for via-ir.
                                    sar(96, mul(add(43456485725739037958740375743393,
                                    sar(96, mul(add(24828157081833163892658089445524,
                                    sar(96, mul(add(3273285459638523848632254066296,
                                        x), x))), x))), x)), 11111509109440967052023855526967)
                                p := sub(sar(96, mul(p, x)), 45023709667254063763336534515857)
                                p := sub(sar(96, mul(p, x)), 14706773417378608786704636184526)
                                p := sub(mul(p, x), shl(96, 795164235651350426258249787498))
                                // We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
                                // `q` is monic by convention.
                                let q := add(5573035233440673466300451813936, x)
                                q := add(71694874799317883764090561454958, sar(96, mul(x, q)))
                                q := add(283447036172924575727196451306956, sar(96, mul(x, q)))
                                q := add(401686690394027663651624208769553, sar(96, mul(x, q)))
                                q := add(204048457590392012362485061816622, sar(96, mul(x, q)))
                                q := add(31853899698501571402653359427138, sar(96, mul(x, q)))
                                q := add(909429971244387300277376558375, sar(96, mul(x, q)))
                                // `p / q` is in the range `(0, 0.125) * 2**96`.
                                // Finalization, we need to:
                                // - Multiply by the scale factor `s = 5.549…`.
                                // - Add `ln(2**96 / 10**18)`.
                                // - Add `k * ln(2)`.
                                // - Multiply by `10**18 / 2**96 = 5**18 >> 78`.
                                // The q polynomial is known not to have zeros in the domain.
                                // No scaling required because p is already `2**96` too large.
                                p := sdiv(p, q)
                                // Multiply by the scaling factor: `s * 5**18 * 2**96`, base is now `5**18 * 2**192`.
                                p := mul(1677202110996718588342820967067443963516166, p)
                                // Add `ln(2) * k * 5**18 * 2**192`.
                                // forgefmt: disable-next-item
                                p := add(mul(16597577552685614221487285958193947469193820559219878177908093499208371, sub(159, r)), p)
                                // Add `ln(2**96 / 10**18) * 5**18 * 2**192`.
                                p := add(600920179829731861736702779321621459595472258049074101567377883020018308, p)
                                // Base conversion: mul `2**18 / 2**192`.
                                r := sar(174, p)
                            }
                        }
                        /// @dev Returns `W_0(x)`, denominated in `WAD`.
                        /// See: https://en.wikipedia.org/wiki/Lambert_W_function
                        /// a.k.a. Product log function. This is an approximation of the principal branch.
                        /// Note: This function is an approximation. Monotonically increasing.
                        function lambertW0Wad(int256 x) internal pure returns (int256 w) {
                            // forgefmt: disable-next-item
                            unchecked {
                                if ((w = x) <= -367879441171442322) revert OutOfDomain(); // `x` less than `-1/e`.
                                (int256 wad, int256 p) = (int256(WAD), x);
                                uint256 c; // Whether we need to avoid catastrophic cancellation.
                                uint256 i = 4; // Number of iterations.
                                if (w <= 0x1ffffffffffff) {
                                    if (-0x4000000000000 <= w) {
                                        i = 1; // Inputs near zero only take one step to converge.
                                    } else if (w <= -0x3ffffffffffffff) {
                                        i = 32; // Inputs near `-1/e` take very long to converge.
                                    }
                                } else if (uint256(w >> 63) == uint256(0)) {
                                    /// @solidity memory-safe-assembly
                                    assembly {
                                        // Inline log2 for more performance, since the range is small.
                                        let v := shr(49, w)
                                        let l := shl(3, lt(0xff, v))
                                        l := add(or(l, byte(and(0x1f, shr(shr(l, v), 0x8421084210842108cc6318c6db6d54be)),
                                            0x0706060506020504060203020504030106050205030304010505030400000000)), 49)
                                        w := sdiv(shl(l, 7), byte(sub(l, 31), 0x0303030303030303040506080c13))
                                        c := gt(l, 60)
                                        i := add(2, add(gt(l, 53), c))
                                    }
                                } else {
                                    int256 ll = lnWad(w = lnWad(w));
                                    /// @solidity memory-safe-assembly
                                    assembly {
                                        // `w = ln(x) - ln(ln(x)) + b * ln(ln(x)) / ln(x)`.
                                        w := add(sdiv(mul(ll, 1023715080943847266), w), sub(w, ll))
                                        i := add(3, iszero(shr(68, x)))
                                        c := iszero(shr(143, x))
                                    }
                                    if (c == uint256(0)) {
                                        do { // If `x` is big, use Newton's so that intermediate values won't overflow.
                                            int256 e = expWad(w);
                                            /// @solidity memory-safe-assembly
                                            assembly {
                                                let t := mul(w, div(e, wad))
                                                w := sub(w, sdiv(sub(t, x), div(add(e, t), wad)))
                                            }
                                            if (p <= w) break;
                                            p = w;
                                        } while (--i != uint256(0));
                                        /// @solidity memory-safe-assembly
                                        assembly {
                                            w := sub(w, sgt(w, 2))
                                        }
                                        return w;
                                    }
                                }
                                do { // Otherwise, use Halley's for faster convergence.
                                    int256 e = expWad(w);
                                    /// @solidity memory-safe-assembly
                                    assembly {
                                        let t := add(w, wad)
                                        let s := sub(mul(w, e), mul(x, wad))
                                        w := sub(w, sdiv(mul(s, wad), sub(mul(e, t), sdiv(mul(add(t, wad), s), add(t, t)))))
                                    }
                                    if (p <= w) break;
                                    p = w;
                                } while (--i != c);
                                /// @solidity memory-safe-assembly
                                assembly {
                                    w := sub(w, sgt(w, 2))
                                }
                                // For certain ranges of `x`, we'll use the quadratic-rate recursive formula of
                                // R. Iacono and J.P. Boyd for the last iteration, to avoid catastrophic cancellation.
                                if (c == uint256(0)) return w;
                                int256 t = w | 1;
                                /// @solidity memory-safe-assembly
                                assembly {
                                    x := sdiv(mul(x, wad), t)
                                }
                                x = (t * (wad + lnWad(x)));
                                /// @solidity memory-safe-assembly
                                assembly {
                                    w := sdiv(x, add(wad, t))
                                }
                            }
                        }
                        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                        /*                  GENERAL NUMBER UTILITIES                  */
                        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                        /// @dev Returns `a * b == x * y`, with full precision.
                        function fullMulEq(uint256 a, uint256 b, uint256 x, uint256 y)
                            internal
                            pure
                            returns (bool result)
                        {
                            /// @solidity memory-safe-assembly
                            assembly {
                                result := and(eq(mul(a, b), mul(x, y)), eq(mulmod(x, y, not(0)), mulmod(a, b, not(0))))
                            }
                        }
                        /// @dev Calculates `floor(x * y / d)` with full precision.
                        /// Throws if result overflows a uint256 or when `d` is zero.
                        /// Credit to Remco Bloemen under MIT license: https://2π.com/21/muldiv
                        function fullMulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                // 512-bit multiply `[p1 p0] = x * y`.
                                // Compute the product mod `2**256` and mod `2**256 - 1`
                                // then use the Chinese Remainder Theorem to reconstruct
                                // the 512 bit result. The result is stored in two 256
                                // variables such that `product = p1 * 2**256 + p0`.
                                // Temporarily use `z` as `p0` to save gas.
                                z := mul(x, y) // Lower 256 bits of `x * y`.
                                for {} 1 {} {
                                    // If overflows.
                                    if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
                                        let mm := mulmod(x, y, not(0))
                                        let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`.
                                        /*------------------- 512 by 256 division --------------------*/
                                        // Make division exact by subtracting the remainder from `[p1 p0]`.
                                        let r := mulmod(x, y, d) // Compute remainder using mulmod.
                                        let t := and(d, sub(0, d)) // The least significant bit of `d`. `t >= 1`.
                                        // Make sure `z` is less than `2**256`. Also prevents `d == 0`.
                                        // Placing the check here seems to give more optimal stack operations.
                                        if iszero(gt(d, p1)) {
                                            mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
                                            revert(0x1c, 0x04)
                                        }
                                        d := div(d, t) // Divide `d` by `t`, which is a power of two.
                                        // Invert `d mod 2**256`
                                        // Now that `d` is an odd number, it has an inverse
                                        // modulo `2**256` such that `d * inv = 1 mod 2**256`.
                                        // Compute the inverse by starting with a seed that is correct
                                        // correct for four bits. That is, `d * inv = 1 mod 2**4`.
                                        let inv := xor(2, mul(3, d))
                                        // Now use Newton-Raphson iteration to improve the precision.
                                        // Thanks to Hensel's lifting lemma, this also works in modular
                                        // arithmetic, doubling the correct bits in each step.
                                        inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**8
                                        inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**16
                                        inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**32
                                        inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**64
                                        inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**128
                                        z :=
                                            mul(
                                                // Divide [p1 p0] by the factors of two.
                                                // Shift in bits from `p1` into `p0`. For this we need
                                                // to flip `t` such that it is `2**256 / t`.
                                                or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)),
                                                mul(sub(2, mul(d, inv)), inv) // inverse mod 2**256
                                            )
                                        break
                                    }
                                    z := div(z, d)
                                    break
                                }
                            }
                        }
                        /// @dev Calculates `floor(x * y / d)` with full precision.
                        /// Behavior is undefined if `d` is zero or the final result cannot fit in 256 bits.
                        /// Performs the full 512 bit calculation regardless.
                        function fullMulDivUnchecked(uint256 x, uint256 y, uint256 d)
                            internal
                            pure
                            returns (uint256 z)
                        {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := mul(x, y)
                                let mm := mulmod(x, y, not(0))
                                let p1 := sub(mm, add(z, lt(mm, z)))
                                let t := and(d, sub(0, d))
                                let r := mulmod(x, y, d)
                                d := div(d, t)
                                let inv := xor(2, mul(3, d))
                                inv := mul(inv, sub(2, mul(d, inv)))
                                inv := mul(inv, sub(2, mul(d, inv)))
                                inv := mul(inv, sub(2, mul(d, inv)))
                                inv := mul(inv, sub(2, mul(d, inv)))
                                inv := mul(inv, sub(2, mul(d, inv)))
                                z :=
                                    mul(
                                        or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)),
                                        mul(sub(2, mul(d, inv)), inv)
                                    )
                            }
                        }
                        /// @dev Calculates `floor(x * y / d)` with full precision, rounded up.
                        /// Throws if result overflows a uint256 or when `d` is zero.
                        /// Credit to Uniswap-v3-core under MIT license:
                        /// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries/FullMath.sol
                        function fullMulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
                            z = fullMulDiv(x, y, d);
                            /// @solidity memory-safe-assembly
                            assembly {
                                if mulmod(x, y, d) {
                                    z := add(z, 1)
                                    if iszero(z) {
                                        mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                }
                            }
                        }
                        /// @dev Calculates `floor(x * y / 2 ** n)` with full precision.
                        /// Throws if result overflows a uint256.
                        /// Credit to Philogy under MIT license:
                        /// https://github.com/SorellaLabs/angstrom/blob/main/contracts/src/libraries/X128MathLib.sol
                        function fullMulDivN(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                // Temporarily use `z` as `p0` to save gas.
                                z := mul(x, y) // Lower 256 bits of `x * y`. We'll call this `z`.
                                for {} 1 {} {
                                    if iszero(or(iszero(x), eq(div(z, x), y))) {
                                        let k := and(n, 0xff) // `n`, cleaned.
                                        let mm := mulmod(x, y, not(0))
                                        let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`.
                                        //         |      p1     |      z     |
                                        // Before: | p1_0 ¦ p1_1 | z_0  ¦ z_1 |
                                        // Final:  |   0  ¦ p1_0 | p1_1 ¦ z_0 |
                                        // Check that final `z` doesn't overflow by checking that p1_0 = 0.
                                        if iszero(shr(k, p1)) {
                                            z := add(shl(sub(256, k), p1), shr(k, z))
                                            break
                                        }
                                        mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                    z := shr(and(n, 0xff), z)
                                    break
                                }
                            }
                        }
                        /// @dev Returns `floor(x * y / d)`.
                        /// Reverts if `x * y` overflows, or `d` is zero.
                        function mulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := mul(x, y)
                                // Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`.
                                if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
                                    mstore(0x00, 0xad251c27) // `MulDivFailed()`.
                                    revert(0x1c, 0x04)
                                }
                                z := div(z, d)
                            }
                        }
                        /// @dev Returns `ceil(x * y / d)`.
                        /// Reverts if `x * y` overflows, or `d` is zero.
                        function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := mul(x, y)
                                // Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`.
                                if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
                                    mstore(0x00, 0xad251c27) // `MulDivFailed()`.
                                    revert(0x1c, 0x04)
                                }
                                z := add(iszero(iszero(mod(z, d))), div(z, d))
                            }
                        }
                        /// @dev Returns `x`, the modular multiplicative inverse of `a`, such that `(a * x) % n == 1`.
                        function invMod(uint256 a, uint256 n) internal pure returns (uint256 x) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                let g := n
                                let r := mod(a, n)
                                for { let y := 1 } 1 {} {
                                    let q := div(g, r)
                                    let t := g
                                    g := r
                                    r := sub(t, mul(r, q))
                                    let u := x
                                    x := y
                                    y := sub(u, mul(y, q))
                                    if iszero(r) { break }
                                }
                                x := mul(eq(g, 1), add(x, mul(slt(x, 0), n)))
                            }
                        }
                        /// @dev Returns `ceil(x / d)`.
                        /// Reverts if `d` is zero.
                        function divUp(uint256 x, uint256 d) internal pure returns (uint256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                if iszero(d) {
                                    mstore(0x00, 0x65244e4e) // `DivFailed()`.
                                    revert(0x1c, 0x04)
                                }
                                z := add(iszero(iszero(mod(x, d))), div(x, d))
                            }
                        }
                        /// @dev Returns `max(0, x - y)`. Alias for `saturatingSub`.
                        function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := mul(gt(x, y), sub(x, y))
                            }
                        }
                        /// @dev Returns `max(0, x - y)`.
                        function saturatingSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := mul(gt(x, y), sub(x, y))
                            }
                        }
                        /// @dev Returns `min(2 ** 256 - 1, x + y)`.
                        function saturatingAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := or(sub(0, lt(add(x, y), x)), add(x, y))
                            }
                        }
                        /// @dev Returns `min(2 ** 256 - 1, x * y)`.
                        function saturatingMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := or(sub(or(iszero(x), eq(div(mul(x, y), x), y)), 1), mul(x, y))
                            }
                        }
                        /// @dev Returns `condition ? x : y`, without branching.
                        function ternary(bool condition, uint256 x, uint256 y) internal pure returns (uint256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := xor(x, mul(xor(x, y), iszero(condition)))
                            }
                        }
                        /// @dev Returns `condition ? x : y`, without branching.
                        function ternary(bool condition, bytes32 x, bytes32 y) internal pure returns (bytes32 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := xor(x, mul(xor(x, y), iszero(condition)))
                            }
                        }
                        /// @dev Returns `condition ? x : y`, without branching.
                        function ternary(bool condition, address x, address y) internal pure returns (address z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := xor(x, mul(xor(x, y), iszero(condition)))
                            }
                        }
                        /// @dev Returns `x != 0 ? x : y`, without branching.
                        function coalesce(uint256 x, uint256 y) internal pure returns (uint256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := or(x, mul(y, iszero(x)))
                            }
                        }
                        /// @dev Returns `x != bytes32(0) ? x : y`, without branching.
                        function coalesce(bytes32 x, bytes32 y) internal pure returns (bytes32 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := or(x, mul(y, iszero(x)))
                            }
                        }
                        /// @dev Returns `x != address(0) ? x : y`, without branching.
                        function coalesce(address x, address y) internal pure returns (address z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := or(x, mul(y, iszero(shl(96, x))))
                            }
                        }
                        /// @dev Exponentiate `x` to `y` by squaring, denominated in base `b`.
                        /// Reverts if the computation overflows.
                        function rpow(uint256 x, uint256 y, uint256 b) internal pure returns (uint256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := mul(b, iszero(y)) // `0 ** 0 = 1`. Otherwise, `0 ** n = 0`.
                                if x {
                                    z := xor(b, mul(xor(b, x), and(y, 1))) // `z = isEven(y) ? scale : x`
                                    let half := shr(1, b) // Divide `b` by 2.
                                    // Divide `y` by 2 every iteration.
                                    for { y := shr(1, y) } y { y := shr(1, y) } {
                                        let xx := mul(x, x) // Store x squared.
                                        let xxRound := add(xx, half) // Round to the nearest number.
                                        // Revert if `xx + half` overflowed, or if `x ** 2` overflows.
                                        if or(lt(xxRound, xx), shr(128, x)) {
                                            mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
                                            revert(0x1c, 0x04)
                                        }
                                        x := div(xxRound, b) // Set `x` to scaled `xxRound`.
                                        // If `y` is odd:
                                        if and(y, 1) {
                                            let zx := mul(z, x) // Compute `z * x`.
                                            let zxRound := add(zx, half) // Round to the nearest number.
                                            // If `z * x` overflowed or `zx + half` overflowed:
                                            if or(xor(div(zx, x), z), lt(zxRound, zx)) {
                                                // Revert if `x` is non-zero.
                                                if x {
                                                    mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
                                                    revert(0x1c, 0x04)
                                                }
                                            }
                                            z := div(zxRound, b) // Return properly scaled `zxRound`.
                                        }
                                    }
                                }
                            }
                        }
                        /// @dev Returns the square root of `x`, rounded down.
                        function sqrt(uint256 x) internal pure returns (uint256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                // `floor(sqrt(2**15)) = 181`. `sqrt(2**15) - 181 = 2.84`.
                                z := 181 // The "correct" value is 1, but this saves a multiplication later.
                                // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad
                                // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.
                                // Let `y = x / 2**r`. We check `y >= 2**(k + 8)`
                                // but shift right by `k` bits to ensure that if `x >= 256`, then `y >= 256`.
                                let r := shl(7, lt(0xffffffffffffffffffffffffffffffffff, x))
                                r := or(r, shl(6, lt(0xffffffffffffffffff, shr(r, x))))
                                r := or(r, shl(5, lt(0xffffffffff, shr(r, x))))
                                r := or(r, shl(4, lt(0xffffff, shr(r, x))))
                                z := shl(shr(1, r), z)
                                // Goal was to get `z*z*y` within a small factor of `x`. More iterations could
                                // get y in a tighter range. Currently, we will have y in `[256, 256*(2**16))`.
                                // We ensured `y >= 256` so that the relative difference between `y` and `y+1` is small.
                                // That's not possible if `x < 256` but we can just verify those cases exhaustively.
                                // Now, `z*z*y <= x < z*z*(y+1)`, and `y <= 2**(16+8)`, and either `y >= 256`, or `x < 256`.
                                // Correctness can be checked exhaustively for `x < 256`, so we assume `y >= 256`.
                                // Then `z*sqrt(y)` is within `sqrt(257)/sqrt(256)` of `sqrt(x)`, or about 20bps.
                                // For `s` in the range `[1/256, 256]`, the estimate `f(s) = (181/1024) * (s+1)`
                                // is in the range `(1/2.84 * sqrt(s), 2.84 * sqrt(s))`,
                                // with largest error when `s = 1` and when `s = 256` or `1/256`.
                                // Since `y` is in `[256, 256*(2**16))`, let `a = y/65536`, so that `a` is in `[1/256, 256)`.
                                // Then we can estimate `sqrt(y)` using
                                // `sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2**18`.
                                // There is no overflow risk here since `y < 2**136` after the first branch above.
                                z := shr(18, mul(z, add(shr(r, x), 65536))) // A `mul()` is saved from starting `z` at 181.
                                // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.
                                z := shr(1, add(z, div(x, z)))
                                z := shr(1, add(z, div(x, z)))
                                z := shr(1, add(z, div(x, z)))
                                z := shr(1, add(z, div(x, z)))
                                z := shr(1, add(z, div(x, z)))
                                z := shr(1, add(z, div(x, z)))
                                z := shr(1, add(z, div(x, z)))
                                // If `x+1` is a perfect square, the Babylonian method cycles between
                                // `floor(sqrt(x))` and `ceil(sqrt(x))`. This statement ensures we return floor.
                                // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
                                z := sub(z, lt(div(x, z), z))
                            }
                        }
                        /// @dev Returns the cube root of `x`, rounded down.
                        /// Credit to bout3fiddy and pcaversaccio under AGPLv3 license:
                        /// https://github.com/pcaversaccio/snekmate/blob/main/src/utils/Math.vy
                        /// Formally verified by xuwinnie:
                        /// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf
                        function cbrt(uint256 x) internal pure returns (uint256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                let r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
                                r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
                                r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
                                r := or(r, shl(4, lt(0xffff, shr(r, x))))
                                r := or(r, shl(3, lt(0xff, shr(r, x))))
                                // Makeshift lookup table to nudge the approximate log2 result.
                                z := div(shl(div(r, 3), shl(lt(0xf, shr(r, x)), 0xf)), xor(7, mod(r, 3)))
                                // Newton-Raphson's.
                                z := div(add(add(div(x, mul(z, z)), z), z), 3)
                                z := div(add(add(div(x, mul(z, z)), z), z), 3)
                                z := div(add(add(div(x, mul(z, z)), z), z), 3)
                                z := div(add(add(div(x, mul(z, z)), z), z), 3)
                                z := div(add(add(div(x, mul(z, z)), z), z), 3)
                                z := div(add(add(div(x, mul(z, z)), z), z), 3)
                                z := div(add(add(div(x, mul(z, z)), z), z), 3)
                                // Round down.
                                z := sub(z, lt(div(x, mul(z, z)), z))
                            }
                        }
                        /// @dev Returns the square root of `x`, denominated in `WAD`, rounded down.
                        function sqrtWad(uint256 x) internal pure returns (uint256 z) {
                            unchecked {
                                if (x <= type(uint256).max / 10 ** 18) return sqrt(x * 10 ** 18);
                                z = (1 + sqrt(x)) * 10 ** 9;
                                z = (fullMulDivUnchecked(x, 10 ** 18, z) + z) >> 1;
                            }
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := sub(z, gt(999999999999999999, sub(mulmod(z, z, x), 1))) // Round down.
                            }
                        }
                        /// @dev Returns the cube root of `x`, denominated in `WAD`, rounded down.
                        /// Formally verified by xuwinnie:
                        /// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf
                        function cbrtWad(uint256 x) internal pure returns (uint256 z) {
                            unchecked {
                                if (x <= type(uint256).max / 10 ** 36) return cbrt(x * 10 ** 36);
                                z = (1 + cbrt(x)) * 10 ** 12;
                                z = (fullMulDivUnchecked(x, 10 ** 36, z * z) + z + z) / 3;
                            }
                            /// @solidity memory-safe-assembly
                            assembly {
                                let p := x
                                for {} 1 {} {
                                    if iszero(shr(229, p)) {
                                        if iszero(shr(199, p)) {
                                            p := mul(p, 100000000000000000) // 10 ** 17.
                                            break
                                        }
                                        p := mul(p, 100000000) // 10 ** 8.
                                        break
                                    }
                                    if iszero(shr(249, p)) { p := mul(p, 100) }
                                    break
                                }
                                let t := mulmod(mul(z, z), z, p)
                                z := sub(z, gt(lt(t, shr(1, p)), iszero(t))) // Round down.
                            }
                        }
                        /// @dev Returns the factorial of `x`.
                        function factorial(uint256 x) internal pure returns (uint256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := 1
                                if iszero(lt(x, 58)) {
                                    mstore(0x00, 0xaba0f2a2) // `FactorialOverflow()`.
                                    revert(0x1c, 0x04)
                                }
                                for {} x { x := sub(x, 1) } { z := mul(z, x) }
                            }
                        }
                        /// @dev Returns the log2 of `x`.
                        /// Equivalent to computing the index of the most significant bit (MSB) of `x`.
                        /// Returns 0 if `x` is zero.
                        function log2(uint256 x) internal pure returns (uint256 r) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
                                r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
                                r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
                                r := or(r, shl(4, lt(0xffff, shr(r, x))))
                                r := or(r, shl(3, lt(0xff, shr(r, x))))
                                // forgefmt: disable-next-item
                                r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                                    0x0706060506020504060203020504030106050205030304010505030400000000))
                            }
                        }
                        /// @dev Returns the log2 of `x`, rounded up.
                        /// Returns 0 if `x` is zero.
                        function log2Up(uint256 x) internal pure returns (uint256 r) {
                            r = log2(x);
                            /// @solidity memory-safe-assembly
                            assembly {
                                r := add(r, lt(shl(r, 1), x))
                            }
                        }
                        /// @dev Returns the log10 of `x`.
                        /// Returns 0 if `x` is zero.
                        function log10(uint256 x) internal pure returns (uint256 r) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                if iszero(lt(x, 100000000000000000000000000000000000000)) {
                                    x := div(x, 100000000000000000000000000000000000000)
                                    r := 38
                                }
                                if iszero(lt(x, 100000000000000000000)) {
                                    x := div(x, 100000000000000000000)
                                    r := add(r, 20)
                                }
                                if iszero(lt(x, 10000000000)) {
                                    x := div(x, 10000000000)
                                    r := add(r, 10)
                                }
                                if iszero(lt(x, 100000)) {
                                    x := div(x, 100000)
                                    r := add(r, 5)
                                }
                                r := add(r, add(gt(x, 9), add(gt(x, 99), add(gt(x, 999), gt(x, 9999)))))
                            }
                        }
                        /// @dev Returns the log10 of `x`, rounded up.
                        /// Returns 0 if `x` is zero.
                        function log10Up(uint256 x) internal pure returns (uint256 r) {
                            r = log10(x);
                            /// @solidity memory-safe-assembly
                            assembly {
                                r := add(r, lt(exp(10, r), x))
                            }
                        }
                        /// @dev Returns the log256 of `x`.
                        /// Returns 0 if `x` is zero.
                        function log256(uint256 x) internal pure returns (uint256 r) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
                                r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
                                r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
                                r := or(r, shl(4, lt(0xffff, shr(r, x))))
                                r := or(shr(3, r), lt(0xff, shr(r, x)))
                            }
                        }
                        /// @dev Returns the log256 of `x`, rounded up.
                        /// Returns 0 if `x` is zero.
                        function log256Up(uint256 x) internal pure returns (uint256 r) {
                            r = log256(x);
                            /// @solidity memory-safe-assembly
                            assembly {
                                r := add(r, lt(shl(shl(3, r), 1), x))
                            }
                        }
                        /// @dev Returns the scientific notation format `mantissa * 10 ** exponent` of `x`.
                        /// Useful for compressing prices (e.g. using 25 bit mantissa and 7 bit exponent).
                        function sci(uint256 x) internal pure returns (uint256 mantissa, uint256 exponent) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                mantissa := x
                                if mantissa {
                                    if iszero(mod(mantissa, 1000000000000000000000000000000000)) {
                                        mantissa := div(mantissa, 1000000000000000000000000000000000)
                                        exponent := 33
                                    }
                                    if iszero(mod(mantissa, 10000000000000000000)) {
                                        mantissa := div(mantissa, 10000000000000000000)
                                        exponent := add(exponent, 19)
                                    }
                                    if iszero(mod(mantissa, 1000000000000)) {
                                        mantissa := div(mantissa, 1000000000000)
                                        exponent := add(exponent, 12)
                                    }
                                    if iszero(mod(mantissa, 1000000)) {
                                        mantissa := div(mantissa, 1000000)
                                        exponent := add(exponent, 6)
                                    }
                                    if iszero(mod(mantissa, 10000)) {
                                        mantissa := div(mantissa, 10000)
                                        exponent := add(exponent, 4)
                                    }
                                    if iszero(mod(mantissa, 100)) {
                                        mantissa := div(mantissa, 100)
                                        exponent := add(exponent, 2)
                                    }
                                    if iszero(mod(mantissa, 10)) {
                                        mantissa := div(mantissa, 10)
                                        exponent := add(exponent, 1)
                                    }
                                }
                            }
                        }
                        /// @dev Convenience function for packing `x` into a smaller number using `sci`.
                        /// The `mantissa` will be in bits [7..255] (the upper 249 bits).
                        /// The `exponent` will be in bits [0..6] (the lower 7 bits).
                        /// Use `SafeCastLib` to safely ensure that the `packed` number is small
                        /// enough to fit in the desired unsigned integer type:
                        /// ```
                        ///     uint32 packed = SafeCastLib.toUint32(FixedPointMathLib.packSci(777 ether));
                        /// ```
                        function packSci(uint256 x) internal pure returns (uint256 packed) {
                            (x, packed) = sci(x); // Reuse for `mantissa` and `exponent`.
                            /// @solidity memory-safe-assembly
                            assembly {
                                if shr(249, x) {
                                    mstore(0x00, 0xce30380c) // `MantissaOverflow()`.
                                    revert(0x1c, 0x04)
                                }
                                packed := or(shl(7, x), packed)
                            }
                        }
                        /// @dev Convenience function for unpacking a packed number from `packSci`.
                        function unpackSci(uint256 packed) internal pure returns (uint256 unpacked) {
                            unchecked {
                                unpacked = (packed >> 7) * 10 ** (packed & 0x7f);
                            }
                        }
                        /// @dev Returns the average of `x` and `y`. Rounds towards zero.
                        function avg(uint256 x, uint256 y) internal pure returns (uint256 z) {
                            unchecked {
                                z = (x & y) + ((x ^ y) >> 1);
                            }
                        }
                        /// @dev Returns the average of `x` and `y`. Rounds towards negative infinity.
                        function avg(int256 x, int256 y) internal pure returns (int256 z) {
                            unchecked {
                                z = (x >> 1) + (y >> 1) + (x & y & 1);
                            }
                        }
                        /// @dev Returns the absolute value of `x`.
                        function abs(int256 x) internal pure returns (uint256 z) {
                            unchecked {
                                z = (uint256(x) + uint256(x >> 255)) ^ uint256(x >> 255);
                            }
                        }
                        /// @dev Returns the absolute distance between `x` and `y`.
                        function dist(uint256 x, uint256 y) internal pure returns (uint256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := add(xor(sub(0, gt(x, y)), sub(y, x)), gt(x, y))
                            }
                        }
                        /// @dev Returns the absolute distance between `x` and `y`.
                        function dist(int256 x, int256 y) internal pure returns (uint256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := add(xor(sub(0, sgt(x, y)), sub(y, x)), sgt(x, y))
                            }
                        }
                        /// @dev Returns the minimum of `x` and `y`.
                        function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := xor(x, mul(xor(x, y), lt(y, x)))
                            }
                        }
                        /// @dev Returns the minimum of `x` and `y`.
                        function min(int256 x, int256 y) internal pure returns (int256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := xor(x, mul(xor(x, y), slt(y, x)))
                            }
                        }
                        /// @dev Returns the maximum of `x` and `y`.
                        function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := xor(x, mul(xor(x, y), gt(y, x)))
                            }
                        }
                        /// @dev Returns the maximum of `x` and `y`.
                        function max(int256 x, int256 y) internal pure returns (int256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := xor(x, mul(xor(x, y), sgt(y, x)))
                            }
                        }
                        /// @dev Returns `x`, bounded to `minValue` and `maxValue`.
                        function clamp(uint256 x, uint256 minValue, uint256 maxValue)
                            internal
                            pure
                            returns (uint256 z)
                        {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := xor(x, mul(xor(x, minValue), gt(minValue, x)))
                                z := xor(z, mul(xor(z, maxValue), lt(maxValue, z)))
                            }
                        }
                        /// @dev Returns `x`, bounded to `minValue` and `maxValue`.
                        function clamp(int256 x, int256 minValue, int256 maxValue) internal pure returns (int256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := xor(x, mul(xor(x, minValue), sgt(minValue, x)))
                                z := xor(z, mul(xor(z, maxValue), slt(maxValue, z)))
                            }
                        }
                        /// @dev Returns greatest common divisor of `x` and `y`.
                        function gcd(uint256 x, uint256 y) internal pure returns (uint256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                for { z := x } y {} {
                                    let t := y
                                    y := mod(z, y)
                                    z := t
                                }
                            }
                        }
                        /// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`,
                        /// with `t` clamped between `begin` and `end` (inclusive).
                        /// Agnostic to the order of (`a`, `b`) and (`end`, `begin`).
                        /// If `begins == end`, returns `t <= begin ? a : b`.
                        function lerp(uint256 a, uint256 b, uint256 t, uint256 begin, uint256 end)
                            internal
                            pure
                            returns (uint256)
                        {
                            if (begin > end) (t, begin, end) = (~t, ~begin, ~end);
                            if (t <= begin) return a;
                            if (t >= end) return b;
                            unchecked {
                                if (b >= a) return a + fullMulDiv(b - a, t - begin, end - begin);
                                return a - fullMulDiv(a - b, t - begin, end - begin);
                            }
                        }
                        /// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`.
                        /// with `t` clamped between `begin` and `end` (inclusive).
                        /// Agnostic to the order of (`a`, `b`) and (`end`, `begin`).
                        /// If `begins == end`, returns `t <= begin ? a : b`.
                        function lerp(int256 a, int256 b, int256 t, int256 begin, int256 end)
                            internal
                            pure
                            returns (int256)
                        {
                            if (begin > end) (t, begin, end) = (~t, ~begin, ~end);
                            if (t <= begin) return a;
                            if (t >= end) return b;
                            // forgefmt: disable-next-item
                            unchecked {
                                if (b >= a) return int256(uint256(a) + fullMulDiv(uint256(b - a),
                                    uint256(t - begin), uint256(end - begin)));
                                return int256(uint256(a) - fullMulDiv(uint256(a - b),
                                    uint256(t - begin), uint256(end - begin)));
                            }
                        }
                        /// @dev Returns if `x` is an even number. Some people may need this.
                        function isEven(uint256 x) internal pure returns (bool) {
                            return x & uint256(1) == uint256(0);
                        }
                        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                        /*                   RAW NUMBER OPERATIONS                    */
                        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                        /// @dev Returns `x + y`, without checking for overflow.
                        function rawAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
                            unchecked {
                                z = x + y;
                            }
                        }
                        /// @dev Returns `x + y`, without checking for overflow.
                        function rawAdd(int256 x, int256 y) internal pure returns (int256 z) {
                            unchecked {
                                z = x + y;
                            }
                        }
                        /// @dev Returns `x - y`, without checking for underflow.
                        function rawSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
                            unchecked {
                                z = x - y;
                            }
                        }
                        /// @dev Returns `x - y`, without checking for underflow.
                        function rawSub(int256 x, int256 y) internal pure returns (int256 z) {
                            unchecked {
                                z = x - y;
                            }
                        }
                        /// @dev Returns `x * y`, without checking for overflow.
                        function rawMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
                            unchecked {
                                z = x * y;
                            }
                        }
                        /// @dev Returns `x * y`, without checking for overflow.
                        function rawMul(int256 x, int256 y) internal pure returns (int256 z) {
                            unchecked {
                                z = x * y;
                            }
                        }
                        /// @dev Returns `x / y`, returning 0 if `y` is zero.
                        function rawDiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := div(x, y)
                            }
                        }
                        /// @dev Returns `x / y`, returning 0 if `y` is zero.
                        function rawSDiv(int256 x, int256 y) internal pure returns (int256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := sdiv(x, y)
                            }
                        }
                        /// @dev Returns `x % y`, returning 0 if `y` is zero.
                        function rawMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := mod(x, y)
                            }
                        }
                        /// @dev Returns `x % y`, returning 0 if `y` is zero.
                        function rawSMod(int256 x, int256 y) internal pure returns (int256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := smod(x, y)
                            }
                        }
                        /// @dev Returns `(x + y) % d`, return 0 if `d` if zero.
                        function rawAddMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := addmod(x, y, d)
                            }
                        }
                        /// @dev Returns `(x * y) % d`, return 0 if `d` if zero.
                        function rawMulMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := mulmod(x, y, d)
                            }
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.8.4;
                    /// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
                    /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeTransferLib.sol)
                    /// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
                    /// @author Permit2 operations from (https://github.com/Uniswap/permit2/blob/main/src/libraries/Permit2Lib.sol)
                    ///
                    /// @dev Note:
                    /// - For ETH transfers, please use `forceSafeTransferETH` for DoS protection.
                    library SafeTransferLib {
                        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                        /*                       CUSTOM ERRORS                        */
                        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                        /// @dev The ETH transfer has failed.
                        error ETHTransferFailed();
                        /// @dev The ERC20 `transferFrom` has failed.
                        error TransferFromFailed();
                        /// @dev The ERC20 `transfer` has failed.
                        error TransferFailed();
                        /// @dev The ERC20 `approve` has failed.
                        error ApproveFailed();
                        /// @dev The ERC20 `totalSupply` query has failed.
                        error TotalSupplyQueryFailed();
                        /// @dev The Permit2 operation has failed.
                        error Permit2Failed();
                        /// @dev The Permit2 amount must be less than `2**160 - 1`.
                        error Permit2AmountOverflow();
                        /// @dev The Permit2 approve operation has failed.
                        error Permit2ApproveFailed();
                        /// @dev The Permit2 lockdown operation has failed.
                        error Permit2LockdownFailed();
                        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                        /*                         CONSTANTS                          */
                        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                        /// @dev Suggested gas stipend for contract receiving ETH that disallows any storage writes.
                        uint256 internal constant GAS_STIPEND_NO_STORAGE_WRITES = 2300;
                        /// @dev Suggested gas stipend for contract receiving ETH to perform a few
                        /// storage reads and writes, but low enough to prevent griefing.
                        uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000;
                        /// @dev The unique EIP-712 domain domain separator for the DAI token contract.
                        bytes32 internal constant DAI_DOMAIN_SEPARATOR =
                            0xdbb8cf42e1ecb028be3f3dbc922e1d878b963f411dc388ced501601c60f7c6f7;
                        /// @dev The address for the WETH9 contract on Ethereum mainnet.
                        address internal constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
                        /// @dev The canonical Permit2 address.
                        /// [Github](https://github.com/Uniswap/permit2)
                        /// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)
                        address internal constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;
                        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                        /*                       ETH OPERATIONS                       */
                        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                        // If the ETH transfer MUST succeed with a reasonable gas budget, use the force variants.
                        //
                        // The regular variants:
                        // - Forwards all remaining gas to the target.
                        // - Reverts if the target reverts.
                        // - Reverts if the current contract has insufficient balance.
                        //
                        // The force variants:
                        // - Forwards with an optional gas stipend
                        //   (defaults to `GAS_STIPEND_NO_GRIEF`, which is sufficient for most cases).
                        // - If the target reverts, or if the gas stipend is exhausted,
                        //   creates a temporary contract to force send the ETH via `SELFDESTRUCT`.
                        //   Future compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758.
                        // - Reverts if the current contract has insufficient balance.
                        //
                        // The try variants:
                        // - Forwards with a mandatory gas stipend.
                        // - Instead of reverting, returns whether the transfer succeeded.
                        /// @dev Sends `amount` (in wei) ETH to `to`.
                        function safeTransferETH(address to, uint256 amount) internal {
                            /// @solidity memory-safe-assembly
                            assembly {
                                if iszero(call(gas(), to, amount, codesize(), 0x00, codesize(), 0x00)) {
                                    mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                                    revert(0x1c, 0x04)
                                }
                            }
                        }
                        /// @dev Sends all the ETH in the current contract to `to`.
                        function safeTransferAllETH(address to) internal {
                            /// @solidity memory-safe-assembly
                            assembly {
                                // Transfer all the ETH and check if it succeeded or not.
                                if iszero(call(gas(), to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                                    mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                                    revert(0x1c, 0x04)
                                }
                            }
                        }
                        /// @dev Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
                        function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal {
                            /// @solidity memory-safe-assembly
                            assembly {
                                if lt(selfbalance(), amount) {
                                    mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                                    revert(0x1c, 0x04)
                                }
                                if iszero(call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)) {
                                    mstore(0x00, to) // Store the address in scratch space.
                                    mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                                    mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                                    if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
                                }
                            }
                        }
                        /// @dev Force sends all the ETH in the current contract to `to`, with a `gasStipend`.
                        function forceSafeTransferAllETH(address to, uint256 gasStipend) internal {
                            /// @solidity memory-safe-assembly
                            assembly {
                                if iszero(call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                                    mstore(0x00, to) // Store the address in scratch space.
                                    mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                                    mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                                    if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
                                }
                            }
                        }
                        /// @dev Force sends `amount` (in wei) ETH to `to`, with `GAS_STIPEND_NO_GRIEF`.
                        function forceSafeTransferETH(address to, uint256 amount) internal {
                            /// @solidity memory-safe-assembly
                            assembly {
                                if lt(selfbalance(), amount) {
                                    mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                                    revert(0x1c, 0x04)
                                }
                                if iszero(call(GAS_STIPEND_NO_GRIEF, to, amount, codesize(), 0x00, codesize(), 0x00)) {
                                    mstore(0x00, to) // Store the address in scratch space.
                                    mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                                    mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                                    if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
                                }
                            }
                        }
                        /// @dev Force sends all the ETH in the current contract to `to`, with `GAS_STIPEND_NO_GRIEF`.
                        function forceSafeTransferAllETH(address to) internal {
                            /// @solidity memory-safe-assembly
                            assembly {
                                // forgefmt: disable-next-item
                                if iszero(call(GAS_STIPEND_NO_GRIEF, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                                    mstore(0x00, to) // Store the address in scratch space.
                                    mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                                    mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                                    if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
                                }
                            }
                        }
                        /// @dev Sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
                        function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend)
                            internal
                            returns (bool success)
                        {
                            /// @solidity memory-safe-assembly
                            assembly {
                                success := call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)
                            }
                        }
                        /// @dev Sends all the ETH in the current contract to `to`, with a `gasStipend`.
                        function trySafeTransferAllETH(address to, uint256 gasStipend)
                            internal
                            returns (bool success)
                        {
                            /// @solidity memory-safe-assembly
                            assembly {
                                success := call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)
                            }
                        }
                        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                        /*                      ERC20 OPERATIONS                      */
                        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                        /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
                        /// Reverts upon failure.
                        ///
                        /// The `from` account must have at least `amount` approved for
                        /// the current contract to manage.
                        function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
                            /// @solidity memory-safe-assembly
                            assembly {
                                let m := mload(0x40) // Cache the free memory pointer.
                                mstore(0x60, amount) // Store the `amount` argument.
                                mstore(0x40, to) // Store the `to` argument.
                                mstore(0x2c, shl(96, from)) // Store the `from` argument.
                                mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
                                let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
                                if iszero(and(eq(mload(0x00), 1), success)) {
                                    if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                                        mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                }
                                mstore(0x60, 0) // Restore the zero slot to zero.
                                mstore(0x40, m) // Restore the free memory pointer.
                            }
                        }
                        /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
                        ///
                        /// The `from` account must have at least `amount` approved for the current contract to manage.
                        function trySafeTransferFrom(address token, address from, address to, uint256 amount)
                            internal
                            returns (bool success)
                        {
                            /// @solidity memory-safe-assembly
                            assembly {
                                let m := mload(0x40) // Cache the free memory pointer.
                                mstore(0x60, amount) // Store the `amount` argument.
                                mstore(0x40, to) // Store the `to` argument.
                                mstore(0x2c, shl(96, from)) // Store the `from` argument.
                                mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
                                success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
                                if iszero(and(eq(mload(0x00), 1), success)) {
                                    success := lt(or(iszero(extcodesize(token)), returndatasize()), success)
                                }
                                mstore(0x60, 0) // Restore the zero slot to zero.
                                mstore(0x40, m) // Restore the free memory pointer.
                            }
                        }
                        /// @dev Sends all of ERC20 `token` from `from` to `to`.
                        /// Reverts upon failure.
                        ///
                        /// The `from` account must have their entire balance approved for the current contract to manage.
                        function safeTransferAllFrom(address token, address from, address to)
                            internal
                            returns (uint256 amount)
                        {
                            /// @solidity memory-safe-assembly
                            assembly {
                                let m := mload(0x40) // Cache the free memory pointer.
                                mstore(0x40, to) // Store the `to` argument.
                                mstore(0x2c, shl(96, from)) // Store the `from` argument.
                                mstore(0x0c, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
                                // Read the balance, reverting upon failure.
                                if iszero(
                                    and( // The arguments of `and` are evaluated from right to left.
                                        gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                                        staticcall(gas(), token, 0x1c, 0x24, 0x60, 0x20)
                                    )
                                ) {
                                    mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                                    revert(0x1c, 0x04)
                                }
                                mstore(0x00, 0x23b872dd) // `transferFrom(address,address,uint256)`.
                                amount := mload(0x60) // The `amount` is already at 0x60. We'll need to return it.
                                // Perform the transfer, reverting upon failure.
                                let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
                                if iszero(and(eq(mload(0x00), 1), success)) {
                                    if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                                        mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                }
                                mstore(0x60, 0) // Restore the zero slot to zero.
                                mstore(0x40, m) // Restore the free memory pointer.
                            }
                        }
                        /// @dev Sends `amount` of ERC20 `token` from the current contract to `to`.
                        /// Reverts upon failure.
                        function safeTransfer(address token, address to, uint256 amount) internal {
                            /// @solidity memory-safe-assembly
                            assembly {
                                mstore(0x14, to) // Store the `to` argument.
                                mstore(0x34, amount) // Store the `amount` argument.
                                mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
                                // Perform the transfer, reverting upon failure.
                                let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                                if iszero(and(eq(mload(0x00), 1), success)) {
                                    if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                                        mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                }
                                mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
                            }
                        }
                        /// @dev Sends all of ERC20 `token` from the current contract to `to`.
                        /// Reverts upon failure.
                        function safeTransferAll(address token, address to) internal returns (uint256 amount) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`.
                                mstore(0x20, address()) // Store the address of the current contract.
                                // Read the balance, reverting upon failure.
                                if iszero(
                                    and( // The arguments of `and` are evaluated from right to left.
                                        gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                                        staticcall(gas(), token, 0x1c, 0x24, 0x34, 0x20)
                                    )
                                ) {
                                    mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                                    revert(0x1c, 0x04)
                                }
                                mstore(0x14, to) // Store the `to` argument.
                                amount := mload(0x34) // The `amount` is already at 0x34. We'll need to return it.
                                mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
                                // Perform the transfer, reverting upon failure.
                                let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                                if iszero(and(eq(mload(0x00), 1), success)) {
                                    if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                                        mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                }
                                mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
                            }
                        }
                        /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
                        /// Reverts upon failure.
                        function safeApprove(address token, address to, uint256 amount) internal {
                            /// @solidity memory-safe-assembly
                            assembly {
                                mstore(0x14, to) // Store the `to` argument.
                                mstore(0x34, amount) // Store the `amount` argument.
                                mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
                                let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                                if iszero(and(eq(mload(0x00), 1), success)) {
                                    if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                                        mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
                                        revert(0x1c, 0x04)
                                    }
                                }
                                mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
                            }
                        }
                        /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
                        /// If the initial attempt to approve fails, attempts to reset the approved amount to zero,
                        /// then retries the approval again (some tokens, e.g. USDT, requires this).
                        /// Reverts upon failure.
                        function safeApproveWithRetry(address token, address to, uint256 amount) internal {
                            /// @solidity memory-safe-assembly
                            assembly {
                                mstore(0x14, to) // Store the `to` argument.
                                mstore(0x34, amount) // Store the `amount` argument.
                                mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
                                // Perform the approval, retrying upon failure.
                                let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                                if iszero(and(eq(mload(0x00), 1), success)) {
                                    if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                                        mstore(0x34, 0) // Store 0 for the `amount`.
                                        mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
                                        pop(call(gas(), token, 0, 0x10, 0x44, codesize(), 0x00)) // Reset the approval.
                                        mstore(0x34, amount) // Store back the original `amount`.
                                        // Retry the approval, reverting upon failure.
                                        success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                                        if iszero(and(eq(mload(0x00), 1), success)) {
                                            // Check the `extcodesize` again just in case the token selfdestructs lol.
                                            if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                                                mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
                                                revert(0x1c, 0x04)
                                            }
                                        }
                                    }
                                }
                                mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
                            }
                        }
                        /// @dev Returns the amount of ERC20 `token` owned by `account`.
                        /// Returns zero if the `token` does not exist.
                        function balanceOf(address token, address account) internal view returns (uint256 amount) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                mstore(0x14, account) // Store the `account` argument.
                                mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
                                amount :=
                                    mul( // The arguments of `mul` are evaluated from right to left.
                                        mload(0x20),
                                        and( // The arguments of `and` are evaluated from right to left.
                                            gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                                            staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
                                        )
                                    )
                            }
                        }
                        /// @dev Returns the total supply of the `token`.
                        /// Reverts if the token does not exist or does not implement `totalSupply()`.
                        function totalSupply(address token) internal view returns (uint256 result) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                mstore(0x00, 0x18160ddd) // `totalSupply()`.
                                if iszero(
                                    and(gt(returndatasize(), 0x1f), staticcall(gas(), token, 0x1c, 0x04, 0x00, 0x20))
                                ) {
                                    mstore(0x00, 0x54cd9435) // `TotalSupplyQueryFailed()`.
                                    revert(0x1c, 0x04)
                                }
                                result := mload(0x00)
                            }
                        }
                        /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
                        /// If the initial attempt fails, try to use Permit2 to transfer the token.
                        /// Reverts upon failure.
                        ///
                        /// The `from` account must have at least `amount` approved for the current contract to manage.
                        function safeTransferFrom2(address token, address from, address to, uint256 amount) internal {
                            if (!trySafeTransferFrom(token, from, to, amount)) {
                                permit2TransferFrom(token, from, to, amount);
                            }
                        }
                        /// @dev Sends `amount` of ERC20 `token` from `from` to `to` via Permit2.
                        /// Reverts upon failure.
                        function permit2TransferFrom(address token, address from, address to, uint256 amount)
                            internal
                        {
                            /// @solidity memory-safe-assembly
                            assembly {
                                let m := mload(0x40)
                                mstore(add(m, 0x74), shr(96, shl(96, token)))
                                mstore(add(m, 0x54), amount)
                                mstore(add(m, 0x34), to)
                                mstore(add(m, 0x20), shl(96, from))
                                // `transferFrom(address,address,uint160,address)`.
                                mstore(m, 0x36c78516000000000000000000000000)
                                let p := PERMIT2
                                let exists := eq(chainid(), 1)
                                if iszero(exists) { exists := iszero(iszero(extcodesize(p))) }
                                if iszero(
                                    and(
                                        call(gas(), p, 0, add(m, 0x10), 0x84, codesize(), 0x00),
                                        lt(iszero(extcodesize(token)), exists) // Token has code and Permit2 exists.
                                    )
                                ) {
                                    mstore(0x00, 0x7939f4248757f0fd) // `TransferFromFailed()` or `Permit2AmountOverflow()`.
                                    revert(add(0x18, shl(2, iszero(iszero(shr(160, amount))))), 0x04)
                                }
                            }
                        }
                        /// @dev Permit a user to spend a given amount of
                        /// another user's tokens via native EIP-2612 permit if possible, falling
                        /// back to Permit2 if native permit fails or is not implemented on the token.
                        function permit2(
                            address token,
                            address owner,
                            address spender,
                            uint256 amount,
                            uint256 deadline,
                            uint8 v,
                            bytes32 r,
                            bytes32 s
                        ) internal {
                            bool success;
                            /// @solidity memory-safe-assembly
                            assembly {
                                for {} shl(96, xor(token, WETH9)) {} {
                                    mstore(0x00, 0x3644e515) // `DOMAIN_SEPARATOR()`.
                                    if iszero(
                                        and( // The arguments of `and` are evaluated from right to left.
                                            lt(iszero(mload(0x00)), eq(returndatasize(), 0x20)), // Returns 1 non-zero word.
                                            // Gas stipend to limit gas burn for tokens that don't refund gas when
                                            // an non-existing function is called. 5K should be enough for a SLOAD.
                                            staticcall(5000, token, 0x1c, 0x04, 0x00, 0x20)
                                        )
                                    ) { break }
                                    // After here, we can be sure that token is a contract.
                                    let m := mload(0x40)
                                    mstore(add(m, 0x34), spender)
                                    mstore(add(m, 0x20), shl(96, owner))
                                    mstore(add(m, 0x74), deadline)
                                    if eq(mload(0x00), DAI_DOMAIN_SEPARATOR) {
                                        mstore(0x14, owner)
                                        mstore(0x00, 0x7ecebe00000000000000000000000000) // `nonces(address)`.
                                        mstore(
                                            add(m, 0x94),
                                            lt(iszero(amount), staticcall(gas(), token, 0x10, 0x24, add(m, 0x54), 0x20))
                                        )
                                        mstore(m, 0x8fcbaf0c000000000000000000000000) // `IDAIPermit.permit`.
                                        // `nonces` is already at `add(m, 0x54)`.
                                        // `amount != 0` is already stored at `add(m, 0x94)`.
                                        mstore(add(m, 0xb4), and(0xff, v))
                                        mstore(add(m, 0xd4), r)
                                        mstore(add(m, 0xf4), s)
                                        success := call(gas(), token, 0, add(m, 0x10), 0x104, codesize(), 0x00)
                                        break
                                    }
                                    mstore(m, 0xd505accf000000000000000000000000) // `IERC20Permit.permit`.
                                    mstore(add(m, 0x54), amount)
                                    mstore(add(m, 0x94), and(0xff, v))
                                    mstore(add(m, 0xb4), r)
                                    mstore(add(m, 0xd4), s)
                                    success := call(gas(), token, 0, add(m, 0x10), 0xe4, codesize(), 0x00)
                                    break
                                }
                            }
                            if (!success) simplePermit2(token, owner, spender, amount, deadline, v, r, s);
                        }
                        /// @dev Simple permit on the Permit2 contract.
                        function simplePermit2(
                            address token,
                            address owner,
                            address spender,
                            uint256 amount,
                            uint256 deadline,
                            uint8 v,
                            bytes32 r,
                            bytes32 s
                        ) internal {
                            /// @solidity memory-safe-assembly
                            assembly {
                                let m := mload(0x40)
                                mstore(m, 0x927da105) // `allowance(address,address,address)`.
                                {
                                    let addressMask := shr(96, not(0))
                                    mstore(add(m, 0x20), and(addressMask, owner))
                                    mstore(add(m, 0x40), and(addressMask, token))
                                    mstore(add(m, 0x60), and(addressMask, spender))
                                    mstore(add(m, 0xc0), and(addressMask, spender))
                                }
                                let p := mul(PERMIT2, iszero(shr(160, amount)))
                                if iszero(
                                    and( // The arguments of `and` are evaluated from right to left.
                                        gt(returndatasize(), 0x5f), // Returns 3 words: `amount`, `expiration`, `nonce`.
                                        staticcall(gas(), p, add(m, 0x1c), 0x64, add(m, 0x60), 0x60)
                                    )
                                ) {
                                    mstore(0x00, 0x6b836e6b8757f0fd) // `Permit2Failed()` or `Permit2AmountOverflow()`.
                                    revert(add(0x18, shl(2, iszero(p))), 0x04)
                                }
                                mstore(m, 0x2b67b570) // `Permit2.permit` (PermitSingle variant).
                                // `owner` is already `add(m, 0x20)`.
                                // `token` is already at `add(m, 0x40)`.
                                mstore(add(m, 0x60), amount)
                                mstore(add(m, 0x80), 0xffffffffffff) // `expiration = type(uint48).max`.
                                // `nonce` is already at `add(m, 0xa0)`.
                                // `spender` is already at `add(m, 0xc0)`.
                                mstore(add(m, 0xe0), deadline)
                                mstore(add(m, 0x100), 0x100) // `signature` offset.
                                mstore(add(m, 0x120), 0x41) // `signature` length.
                                mstore(add(m, 0x140), r)
                                mstore(add(m, 0x160), s)
                                mstore(add(m, 0x180), shl(248, v))
                                if iszero( // Revert if token does not have code, or if the call fails.
                                mul(extcodesize(token), call(gas(), p, 0, add(m, 0x1c), 0x184, codesize(), 0x00))) {
                                    mstore(0x00, 0x6b836e6b) // `Permit2Failed()`.
                                    revert(0x1c, 0x04)
                                }
                            }
                        }
                        /// @dev Approves `spender` to spend `amount` of `token` for `address(this)`.
                        function permit2Approve(address token, address spender, uint160 amount, uint48 expiration)
                            internal
                        {
                            /// @solidity memory-safe-assembly
                            assembly {
                                let addressMask := shr(96, not(0))
                                let m := mload(0x40)
                                mstore(m, 0x87517c45) // `approve(address,address,uint160,uint48)`.
                                mstore(add(m, 0x20), and(addressMask, token))
                                mstore(add(m, 0x40), and(addressMask, spender))
                                mstore(add(m, 0x60), and(addressMask, amount))
                                mstore(add(m, 0x80), and(0xffffffffffff, expiration))
                                if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) {
                                    mstore(0x00, 0x324f14ae) // `Permit2ApproveFailed()`.
                                    revert(0x1c, 0x04)
                                }
                            }
                        }
                        /// @dev Revokes an approval for `token` and `spender` for `address(this)`.
                        function permit2Lockdown(address token, address spender) internal {
                            /// @solidity memory-safe-assembly
                            assembly {
                                let m := mload(0x40)
                                mstore(m, 0xcc53287f) // `Permit2.lockdown`.
                                mstore(add(m, 0x20), 0x20) // Offset of the `approvals`.
                                mstore(add(m, 0x40), 1) // `approvals.length`.
                                mstore(add(m, 0x60), shr(96, shl(96, token)))
                                mstore(add(m, 0x80), shr(96, shl(96, spender)))
                                if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) {
                                    mstore(0x00, 0x96b3de23) // `Permit2LockdownFailed()`.
                                    revert(0x1c, 0x04)
                                }
                            }
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.8.4;
                    /// @notice Safe integer casting library that reverts on overflow.
                    /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeCastLib.sol)
                    /// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeCast.sol)
                    /// @dev Optimized for runtime gas for very high number of optimizer runs (i.e. >= 1000000).
                    library SafeCastLib {
                        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                        /*                       CUSTOM ERRORS                        */
                        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                        /// @dev Unable to cast to the target type due to overflow.
                        error Overflow();
                        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                        /*          UNSIGNED INTEGER SAFE CASTING OPERATIONS          */
                        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                        /// @dev Casts `x` to a uint8. Reverts on overflow.
                        function toUint8(uint256 x) internal pure returns (uint8) {
                            if (x >= 1 << 8) _revertOverflow();
                            return uint8(x);
                        }
                        /// @dev Casts `x` to a uint16. Reverts on overflow.
                        function toUint16(uint256 x) internal pure returns (uint16) {
                            if (x >= 1 << 16) _revertOverflow();
                            return uint16(x);
                        }
                        /// @dev Casts `x` to a uint24. Reverts on overflow.
                        function toUint24(uint256 x) internal pure returns (uint24) {
                            if (x >= 1 << 24) _revertOverflow();
                            return uint24(x);
                        }
                        /// @dev Casts `x` to a uint32. Reverts on overflow.
                        function toUint32(uint256 x) internal pure returns (uint32) {
                            if (x >= 1 << 32) _revertOverflow();
                            return uint32(x);
                        }
                        /// @dev Casts `x` to a uint40. Reverts on overflow.
                        function toUint40(uint256 x) internal pure returns (uint40) {
                            if (x >= 1 << 40) _revertOverflow();
                            return uint40(x);
                        }
                        /// @dev Casts `x` to a uint48. Reverts on overflow.
                        function toUint48(uint256 x) internal pure returns (uint48) {
                            if (x >= 1 << 48) _revertOverflow();
                            return uint48(x);
                        }
                        /// @dev Casts `x` to a uint56. Reverts on overflow.
                        function toUint56(uint256 x) internal pure returns (uint56) {
                            if (x >= 1 << 56) _revertOverflow();
                            return uint56(x);
                        }
                        /// @dev Casts `x` to a uint64. Reverts on overflow.
                        function toUint64(uint256 x) internal pure returns (uint64) {
                            if (x >= 1 << 64) _revertOverflow();
                            return uint64(x);
                        }
                        /// @dev Casts `x` to a uint72. Reverts on overflow.
                        function toUint72(uint256 x) internal pure returns (uint72) {
                            if (x >= 1 << 72) _revertOverflow();
                            return uint72(x);
                        }
                        /// @dev Casts `x` to a uint80. Reverts on overflow.
                        function toUint80(uint256 x) internal pure returns (uint80) {
                            if (x >= 1 << 80) _revertOverflow();
                            return uint80(x);
                        }
                        /// @dev Casts `x` to a uint88. Reverts on overflow.
                        function toUint88(uint256 x) internal pure returns (uint88) {
                            if (x >= 1 << 88) _revertOverflow();
                            return uint88(x);
                        }
                        /// @dev Casts `x` to a uint96. Reverts on overflow.
                        function toUint96(uint256 x) internal pure returns (uint96) {
                            if (x >= 1 << 96) _revertOverflow();
                            return uint96(x);
                        }
                        /// @dev Casts `x` to a uint104. Reverts on overflow.
                        function toUint104(uint256 x) internal pure returns (uint104) {
                            if (x >= 1 << 104) _revertOverflow();
                            return uint104(x);
                        }
                        /// @dev Casts `x` to a uint112. Reverts on overflow.
                        function toUint112(uint256 x) internal pure returns (uint112) {
                            if (x >= 1 << 112) _revertOverflow();
                            return uint112(x);
                        }
                        /// @dev Casts `x` to a uint120. Reverts on overflow.
                        function toUint120(uint256 x) internal pure returns (uint120) {
                            if (x >= 1 << 120) _revertOverflow();
                            return uint120(x);
                        }
                        /// @dev Casts `x` to a uint128. Reverts on overflow.
                        function toUint128(uint256 x) internal pure returns (uint128) {
                            if (x >= 1 << 128) _revertOverflow();
                            return uint128(x);
                        }
                        /// @dev Casts `x` to a uint136. Reverts on overflow.
                        function toUint136(uint256 x) internal pure returns (uint136) {
                            if (x >= 1 << 136) _revertOverflow();
                            return uint136(x);
                        }
                        /// @dev Casts `x` to a uint144. Reverts on overflow.
                        function toUint144(uint256 x) internal pure returns (uint144) {
                            if (x >= 1 << 144) _revertOverflow();
                            return uint144(x);
                        }
                        /// @dev Casts `x` to a uint152. Reverts on overflow.
                        function toUint152(uint256 x) internal pure returns (uint152) {
                            if (x >= 1 << 152) _revertOverflow();
                            return uint152(x);
                        }
                        /// @dev Casts `x` to a uint160. Reverts on overflow.
                        function toUint160(uint256 x) internal pure returns (uint160) {
                            if (x >= 1 << 160) _revertOverflow();
                            return uint160(x);
                        }
                        /// @dev Casts `x` to a uint168. Reverts on overflow.
                        function toUint168(uint256 x) internal pure returns (uint168) {
                            if (x >= 1 << 168) _revertOverflow();
                            return uint168(x);
                        }
                        /// @dev Casts `x` to a uint176. Reverts on overflow.
                        function toUint176(uint256 x) internal pure returns (uint176) {
                            if (x >= 1 << 176) _revertOverflow();
                            return uint176(x);
                        }
                        /// @dev Casts `x` to a uint184. Reverts on overflow.
                        function toUint184(uint256 x) internal pure returns (uint184) {
                            if (x >= 1 << 184) _revertOverflow();
                            return uint184(x);
                        }
                        /// @dev Casts `x` to a uint192. Reverts on overflow.
                        function toUint192(uint256 x) internal pure returns (uint192) {
                            if (x >= 1 << 192) _revertOverflow();
                            return uint192(x);
                        }
                        /// @dev Casts `x` to a uint200. Reverts on overflow.
                        function toUint200(uint256 x) internal pure returns (uint200) {
                            if (x >= 1 << 200) _revertOverflow();
                            return uint200(x);
                        }
                        /// @dev Casts `x` to a uint208. Reverts on overflow.
                        function toUint208(uint256 x) internal pure returns (uint208) {
                            if (x >= 1 << 208) _revertOverflow();
                            return uint208(x);
                        }
                        /// @dev Casts `x` to a uint216. Reverts on overflow.
                        function toUint216(uint256 x) internal pure returns (uint216) {
                            if (x >= 1 << 216) _revertOverflow();
                            return uint216(x);
                        }
                        /// @dev Casts `x` to a uint224. Reverts on overflow.
                        function toUint224(uint256 x) internal pure returns (uint224) {
                            if (x >= 1 << 224) _revertOverflow();
                            return uint224(x);
                        }
                        /// @dev Casts `x` to a uint232. Reverts on overflow.
                        function toUint232(uint256 x) internal pure returns (uint232) {
                            if (x >= 1 << 232) _revertOverflow();
                            return uint232(x);
                        }
                        /// @dev Casts `x` to a uint240. Reverts on overflow.
                        function toUint240(uint256 x) internal pure returns (uint240) {
                            if (x >= 1 << 240) _revertOverflow();
                            return uint240(x);
                        }
                        /// @dev Casts `x` to a uint248. Reverts on overflow.
                        function toUint248(uint256 x) internal pure returns (uint248) {
                            if (x >= 1 << 248) _revertOverflow();
                            return uint248(x);
                        }
                        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                        /*           SIGNED INTEGER SAFE CASTING OPERATIONS           */
                        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                        /// @dev Casts `x` to a int8. Reverts on overflow.
                        function toInt8(int256 x) internal pure returns (int8) {
                            unchecked {
                                if (((1 << 7) + uint256(x)) >> 8 == uint256(0)) return int8(x);
                                _revertOverflow();
                            }
                        }
                        /// @dev Casts `x` to a int16. Reverts on overflow.
                        function toInt16(int256 x) internal pure returns (int16) {
                            unchecked {
                                if (((1 << 15) + uint256(x)) >> 16 == uint256(0)) return int16(x);
                                _revertOverflow();
                            }
                        }
                        /// @dev Casts `x` to a int24. Reverts on overflow.
                        function toInt24(int256 x) internal pure returns (int24) {
                            unchecked {
                                if (((1 << 23) + uint256(x)) >> 24 == uint256(0)) return int24(x);
                                _revertOverflow();
                            }
                        }
                        /// @dev Casts `x` to a int32. Reverts on overflow.
                        function toInt32(int256 x) internal pure returns (int32) {
                            unchecked {
                                if (((1 << 31) + uint256(x)) >> 32 == uint256(0)) return int32(x);
                                _revertOverflow();
                            }
                        }
                        /// @dev Casts `x` to a int40. Reverts on overflow.
                        function toInt40(int256 x) internal pure returns (int40) {
                            unchecked {
                                if (((1 << 39) + uint256(x)) >> 40 == uint256(0)) return int40(x);
                                _revertOverflow();
                            }
                        }
                        /// @dev Casts `x` to a int48. Reverts on overflow.
                        function toInt48(int256 x) internal pure returns (int48) {
                            unchecked {
                                if (((1 << 47) + uint256(x)) >> 48 == uint256(0)) return int48(x);
                                _revertOverflow();
                            }
                        }
                        /// @dev Casts `x` to a int56. Reverts on overflow.
                        function toInt56(int256 x) internal pure returns (int56) {
                            unchecked {
                                if (((1 << 55) + uint256(x)) >> 56 == uint256(0)) return int56(x);
                                _revertOverflow();
                            }
                        }
                        /// @dev Casts `x` to a int64. Reverts on overflow.
                        function toInt64(int256 x) internal pure returns (int64) {
                            unchecked {
                                if (((1 << 63) + uint256(x)) >> 64 == uint256(0)) return int64(x);
                                _revertOverflow();
                            }
                        }
                        /// @dev Casts `x` to a int72. Reverts on overflow.
                        function toInt72(int256 x) internal pure returns (int72) {
                            unchecked {
                                if (((1 << 71) + uint256(x)) >> 72 == uint256(0)) return int72(x);
                                _revertOverflow();
                            }
                        }
                        /// @dev Casts `x` to a int80. Reverts on overflow.
                        function toInt80(int256 x) internal pure returns (int80) {
                            unchecked {
                                if (((1 << 79) + uint256(x)) >> 80 == uint256(0)) return int80(x);
                                _revertOverflow();
                            }
                        }
                        /// @dev Casts `x` to a int88. Reverts on overflow.
                        function toInt88(int256 x) internal pure returns (int88) {
                            unchecked {
                                if (((1 << 87) + uint256(x)) >> 88 == uint256(0)) return int88(x);
                                _revertOverflow();
                            }
                        }
                        /// @dev Casts `x` to a int96. Reverts on overflow.
                        function toInt96(int256 x) internal pure returns (int96) {
                            unchecked {
                                if (((1 << 95) + uint256(x)) >> 96 == uint256(0)) return int96(x);
                                _revertOverflow();
                            }
                        }
                        /// @dev Casts `x` to a int104. Reverts on overflow.
                        function toInt104(int256 x) internal pure returns (int104) {
                            unchecked {
                                if (((1 << 103) + uint256(x)) >> 104 == uint256(0)) return int104(x);
                                _revertOverflow();
                            }
                        }
                        /// @dev Casts `x` to a int112. Reverts on overflow.
                        function toInt112(int256 x) internal pure returns (int112) {
                            unchecked {
                                if (((1 << 111) + uint256(x)) >> 112 == uint256(0)) return int112(x);
                                _revertOverflow();
                            }
                        }
                        /// @dev Casts `x` to a int120. Reverts on overflow.
                        function toInt120(int256 x) internal pure returns (int120) {
                            unchecked {
                                if (((1 << 119) + uint256(x)) >> 120 == uint256(0)) return int120(x);
                                _revertOverflow();
                            }
                        }
                        /// @dev Casts `x` to a int128. Reverts on overflow.
                        function toInt128(int256 x) internal pure returns (int128) {
                            unchecked {
                                if (((1 << 127) + uint256(x)) >> 128 == uint256(0)) return int128(x);
                                _revertOverflow();
                            }
                        }
                        /// @dev Casts `x` to a int136. Reverts on overflow.
                        function toInt136(int256 x) internal pure returns (int136) {
                            unchecked {
                                if (((1 << 135) + uint256(x)) >> 136 == uint256(0)) return int136(x);
                                _revertOverflow();
                            }
                        }
                        /// @dev Casts `x` to a int144. Reverts on overflow.
                        function toInt144(int256 x) internal pure returns (int144) {
                            unchecked {
                                if (((1 << 143) + uint256(x)) >> 144 == uint256(0)) return int144(x);
                                _revertOverflow();
                            }
                        }
                        /// @dev Casts `x` to a int152. Reverts on overflow.
                        function toInt152(int256 x) internal pure returns (int152) {
                            unchecked {
                                if (((1 << 151) + uint256(x)) >> 152 == uint256(0)) return int152(x);
                                _revertOverflow();
                            }
                        }
                        /// @dev Casts `x` to a int160. Reverts on overflow.
                        function toInt160(int256 x) internal pure returns (int160) {
                            unchecked {
                                if (((1 << 159) + uint256(x)) >> 160 == uint256(0)) return int160(x);
                                _revertOverflow();
                            }
                        }
                        /// @dev Casts `x` to a int168. Reverts on overflow.
                        function toInt168(int256 x) internal pure returns (int168) {
                            unchecked {
                                if (((1 << 167) + uint256(x)) >> 168 == uint256(0)) return int168(x);
                                _revertOverflow();
                            }
                        }
                        /// @dev Casts `x` to a int176. Reverts on overflow.
                        function toInt176(int256 x) internal pure returns (int176) {
                            unchecked {
                                if (((1 << 175) + uint256(x)) >> 176 == uint256(0)) return int176(x);
                                _revertOverflow();
                            }
                        }
                        /// @dev Casts `x` to a int184. Reverts on overflow.
                        function toInt184(int256 x) internal pure returns (int184) {
                            unchecked {
                                if (((1 << 183) + uint256(x)) >> 184 == uint256(0)) return int184(x);
                                _revertOverflow();
                            }
                        }
                        /// @dev Casts `x` to a int192. Reverts on overflow.
                        function toInt192(int256 x) internal pure returns (int192) {
                            unchecked {
                                if (((1 << 191) + uint256(x)) >> 192 == uint256(0)) return int192(x);
                                _revertOverflow();
                            }
                        }
                        /// @dev Casts `x` to a int200. Reverts on overflow.
                        function toInt200(int256 x) internal pure returns (int200) {
                            unchecked {
                                if (((1 << 199) + uint256(x)) >> 200 == uint256(0)) return int200(x);
                                _revertOverflow();
                            }
                        }
                        /// @dev Casts `x` to a int208. Reverts on overflow.
                        function toInt208(int256 x) internal pure returns (int208) {
                            unchecked {
                                if (((1 << 207) + uint256(x)) >> 208 == uint256(0)) return int208(x);
                                _revertOverflow();
                            }
                        }
                        /// @dev Casts `x` to a int216. Reverts on overflow.
                        function toInt216(int256 x) internal pure returns (int216) {
                            unchecked {
                                if (((1 << 215) + uint256(x)) >> 216 == uint256(0)) return int216(x);
                                _revertOverflow();
                            }
                        }
                        /// @dev Casts `x` to a int224. Reverts on overflow.
                        function toInt224(int256 x) internal pure returns (int224) {
                            unchecked {
                                if (((1 << 223) + uint256(x)) >> 224 == uint256(0)) return int224(x);
                                _revertOverflow();
                            }
                        }
                        /// @dev Casts `x` to a int232. Reverts on overflow.
                        function toInt232(int256 x) internal pure returns (int232) {
                            unchecked {
                                if (((1 << 231) + uint256(x)) >> 232 == uint256(0)) return int232(x);
                                _revertOverflow();
                            }
                        }
                        /// @dev Casts `x` to a int240. Reverts on overflow.
                        function toInt240(int256 x) internal pure returns (int240) {
                            unchecked {
                                if (((1 << 239) + uint256(x)) >> 240 == uint256(0)) return int240(x);
                                _revertOverflow();
                            }
                        }
                        /// @dev Casts `x` to a int248. Reverts on overflow.
                        function toInt248(int256 x) internal pure returns (int248) {
                            unchecked {
                                if (((1 << 247) + uint256(x)) >> 248 == uint256(0)) return int248(x);
                                _revertOverflow();
                            }
                        }
                        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                        /*               OTHER SAFE CASTING OPERATIONS                */
                        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                        /// @dev Casts `x` to a int8. Reverts on overflow.
                        function toInt8(uint256 x) internal pure returns (int8) {
                            if (x >= 1 << 7) _revertOverflow();
                            return int8(int256(x));
                        }
                        /// @dev Casts `x` to a int16. Reverts on overflow.
                        function toInt16(uint256 x) internal pure returns (int16) {
                            if (x >= 1 << 15) _revertOverflow();
                            return int16(int256(x));
                        }
                        /// @dev Casts `x` to a int24. Reverts on overflow.
                        function toInt24(uint256 x) internal pure returns (int24) {
                            if (x >= 1 << 23) _revertOverflow();
                            return int24(int256(x));
                        }
                        /// @dev Casts `x` to a int32. Reverts on overflow.
                        function toInt32(uint256 x) internal pure returns (int32) {
                            if (x >= 1 << 31) _revertOverflow();
                            return int32(int256(x));
                        }
                        /// @dev Casts `x` to a int40. Reverts on overflow.
                        function toInt40(uint256 x) internal pure returns (int40) {
                            if (x >= 1 << 39) _revertOverflow();
                            return int40(int256(x));
                        }
                        /// @dev Casts `x` to a int48. Reverts on overflow.
                        function toInt48(uint256 x) internal pure returns (int48) {
                            if (x >= 1 << 47) _revertOverflow();
                            return int48(int256(x));
                        }
                        /// @dev Casts `x` to a int56. Reverts on overflow.
                        function toInt56(uint256 x) internal pure returns (int56) {
                            if (x >= 1 << 55) _revertOverflow();
                            return int56(int256(x));
                        }
                        /// @dev Casts `x` to a int64. Reverts on overflow.
                        function toInt64(uint256 x) internal pure returns (int64) {
                            if (x >= 1 << 63) _revertOverflow();
                            return int64(int256(x));
                        }
                        /// @dev Casts `x` to a int72. Reverts on overflow.
                        function toInt72(uint256 x) internal pure returns (int72) {
                            if (x >= 1 << 71) _revertOverflow();
                            return int72(int256(x));
                        }
                        /// @dev Casts `x` to a int80. Reverts on overflow.
                        function toInt80(uint256 x) internal pure returns (int80) {
                            if (x >= 1 << 79) _revertOverflow();
                            return int80(int256(x));
                        }
                        /// @dev Casts `x` to a int88. Reverts on overflow.
                        function toInt88(uint256 x) internal pure returns (int88) {
                            if (x >= 1 << 87) _revertOverflow();
                            return int88(int256(x));
                        }
                        /// @dev Casts `x` to a int96. Reverts on overflow.
                        function toInt96(uint256 x) internal pure returns (int96) {
                            if (x >= 1 << 95) _revertOverflow();
                            return int96(int256(x));
                        }
                        /// @dev Casts `x` to a int104. Reverts on overflow.
                        function toInt104(uint256 x) internal pure returns (int104) {
                            if (x >= 1 << 103) _revertOverflow();
                            return int104(int256(x));
                        }
                        /// @dev Casts `x` to a int112. Reverts on overflow.
                        function toInt112(uint256 x) internal pure returns (int112) {
                            if (x >= 1 << 111) _revertOverflow();
                            return int112(int256(x));
                        }
                        /// @dev Casts `x` to a int120. Reverts on overflow.
                        function toInt120(uint256 x) internal pure returns (int120) {
                            if (x >= 1 << 119) _revertOverflow();
                            return int120(int256(x));
                        }
                        /// @dev Casts `x` to a int128. Reverts on overflow.
                        function toInt128(uint256 x) internal pure returns (int128) {
                            if (x >= 1 << 127) _revertOverflow();
                            return int128(int256(x));
                        }
                        /// @dev Casts `x` to a int136. Reverts on overflow.
                        function toInt136(uint256 x) internal pure returns (int136) {
                            if (x >= 1 << 135) _revertOverflow();
                            return int136(int256(x));
                        }
                        /// @dev Casts `x` to a int144. Reverts on overflow.
                        function toInt144(uint256 x) internal pure returns (int144) {
                            if (x >= 1 << 143) _revertOverflow();
                            return int144(int256(x));
                        }
                        /// @dev Casts `x` to a int152. Reverts on overflow.
                        function toInt152(uint256 x) internal pure returns (int152) {
                            if (x >= 1 << 151) _revertOverflow();
                            return int152(int256(x));
                        }
                        /// @dev Casts `x` to a int160. Reverts on overflow.
                        function toInt160(uint256 x) internal pure returns (int160) {
                            if (x >= 1 << 159) _revertOverflow();
                            return int160(int256(x));
                        }
                        /// @dev Casts `x` to a int168. Reverts on overflow.
                        function toInt168(uint256 x) internal pure returns (int168) {
                            if (x >= 1 << 167) _revertOverflow();
                            return int168(int256(x));
                        }
                        /// @dev Casts `x` to a int176. Reverts on overflow.
                        function toInt176(uint256 x) internal pure returns (int176) {
                            if (x >= 1 << 175) _revertOverflow();
                            return int176(int256(x));
                        }
                        /// @dev Casts `x` to a int184. Reverts on overflow.
                        function toInt184(uint256 x) internal pure returns (int184) {
                            if (x >= 1 << 183) _revertOverflow();
                            return int184(int256(x));
                        }
                        /// @dev Casts `x` to a int192. Reverts on overflow.
                        function toInt192(uint256 x) internal pure returns (int192) {
                            if (x >= 1 << 191) _revertOverflow();
                            return int192(int256(x));
                        }
                        /// @dev Casts `x` to a int200. Reverts on overflow.
                        function toInt200(uint256 x) internal pure returns (int200) {
                            if (x >= 1 << 199) _revertOverflow();
                            return int200(int256(x));
                        }
                        /// @dev Casts `x` to a int208. Reverts on overflow.
                        function toInt208(uint256 x) internal pure returns (int208) {
                            if (x >= 1 << 207) _revertOverflow();
                            return int208(int256(x));
                        }
                        /// @dev Casts `x` to a int216. Reverts on overflow.
                        function toInt216(uint256 x) internal pure returns (int216) {
                            if (x >= 1 << 215) _revertOverflow();
                            return int216(int256(x));
                        }
                        /// @dev Casts `x` to a int224. Reverts on overflow.
                        function toInt224(uint256 x) internal pure returns (int224) {
                            if (x >= 1 << 223) _revertOverflow();
                            return int224(int256(x));
                        }
                        /// @dev Casts `x` to a int232. Reverts on overflow.
                        function toInt232(uint256 x) internal pure returns (int232) {
                            if (x >= 1 << 231) _revertOverflow();
                            return int232(int256(x));
                        }
                        /// @dev Casts `x` to a int240. Reverts on overflow.
                        function toInt240(uint256 x) internal pure returns (int240) {
                            if (x >= 1 << 239) _revertOverflow();
                            return int240(int256(x));
                        }
                        /// @dev Casts `x` to a int248. Reverts on overflow.
                        function toInt248(uint256 x) internal pure returns (int248) {
                            if (x >= 1 << 247) _revertOverflow();
                            return int248(int256(x));
                        }
                        /// @dev Casts `x` to a int256. Reverts on overflow.
                        function toInt256(uint256 x) internal pure returns (int256) {
                            if (int256(x) >= 0) return int256(x);
                            _revertOverflow();
                        }
                        /// @dev Casts `x` to a uint256. Reverts on overflow.
                        function toUint256(int256 x) internal pure returns (uint256) {
                            if (x >= 0) return uint256(x);
                            _revertOverflow();
                        }
                        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                        /*                      PRIVATE HELPERS                       */
                        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                        function _revertOverflow() private pure {
                            /// @solidity memory-safe-assembly
                            assembly {
                                // Store the function selector of `Overflow()`.
                                mstore(0x00, 0x35278d12)
                                // Revert with (offset, size).
                                revert(0x1c, 0x04)
                            }
                        }
                    }
                    // SPDX-License-Identifier: UNLICENSED
                    pragma solidity =0.8.28;
                    import {IExposedStorage} from "../interfaces/IExposedStorage.sol";
                    abstract contract ExposedStorage is IExposedStorage {
                        function sload() external view {
                            assembly ("memory-safe") {
                                for { let i := 4 } lt(i, calldatasize()) { i := add(i, 32) } { mstore(sub(i, 4), sload(calldataload(i))) }
                                return(0, sub(calldatasize(), 4))
                            }
                        }
                        function tload() external view {
                            assembly ("memory-safe") {
                                for { let i := 4 } lt(i, calldatasize()) { i := add(i, 32) } { mstore(sub(i, 4), tload(calldataload(i))) }
                                return(0, sub(calldatasize(), 4))
                            }
                        }
                    }
                    // SPDX-License-Identifier: UNLICENSED
                    pragma solidity =0.8.28;
                    import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol";
                    import {SafeCastLib} from "solady/utils/SafeCastLib.sol";
                    import {amount0Delta, amount1Delta, sortAndConvertToFixedSqrtRatios} from "./delta.sol";
                    import {SqrtRatio} from "../types/sqrtRatio.sol";
                    /**
                     * @notice Returns the token0 and token1 delta owed for a given change in liquidity.
                     * @param sqrtRatio        Current price (as a sqrt ratio).
                     * @param liquidityDelta   Signed liquidity change; positive = added, negative = removed.
                     * @param sqrtRatioLower   The lower bound of the price range (as a sqrt ratio).
                     * @param sqrtRatioUpper   The upper bound of the price range (as a sqrt ratio).
                     */
                    function liquidityDeltaToAmountDelta(
                        SqrtRatio sqrtRatio,
                        int128 liquidityDelta,
                        SqrtRatio sqrtRatioLower,
                        SqrtRatio sqrtRatioUpper
                    ) pure returns (int128 delta0, int128 delta1) {
                        unchecked {
                            if (liquidityDelta == 0) {
                                return (0, 0);
                            }
                            bool isPositive = (liquidityDelta > 0);
                            // type(uint256).max cast to int256 is -1
                            int256 sign = int256(FixedPointMathLib.ternary(isPositive, 1, type(uint256).max));
                            // absolute value of a int128 always fits in a uint128
                            uint128 magnitude = uint128(FixedPointMathLib.abs(liquidityDelta));
                            if (sqrtRatio <= sqrtRatioLower) {
                                delta0 = SafeCastLib.toInt128(
                                    sign * int256(uint256(amount0Delta(sqrtRatioLower, sqrtRatioUpper, magnitude, isPositive)))
                                );
                            } else if (sqrtRatio < sqrtRatioUpper) {
                                delta0 = SafeCastLib.toInt128(
                                    sign * int256(uint256(amount0Delta(sqrtRatio, sqrtRatioUpper, magnitude, isPositive)))
                                );
                                delta1 = SafeCastLib.toInt128(
                                    sign * int256(uint256(amount1Delta(sqrtRatioLower, sqrtRatio, magnitude, isPositive)))
                                );
                            } else {
                                delta1 = SafeCastLib.toInt128(
                                    sign * int256(uint256(amount1Delta(sqrtRatioLower, sqrtRatioUpper, magnitude, isPositive)))
                                );
                            }
                        }
                    }
                    function maxLiquidityForToken0(uint256 sqrtRatioLower, uint256 sqrtRatioUpper, uint128 amount) pure returns (uint256) {
                        unchecked {
                            uint256 numerator_1 = FixedPointMathLib.fullMulDivN(sqrtRatioLower, sqrtRatioUpper, 128);
                            return FixedPointMathLib.fullMulDiv(amount, numerator_1, (sqrtRatioUpper - sqrtRatioLower));
                        }
                    }
                    function maxLiquidityForToken1(uint256 sqrtRatioLower, uint256 sqrtRatioUpper, uint128 amount) pure returns (uint256) {
                        unchecked {
                            return (uint256(amount) << 128) / (sqrtRatioUpper - sqrtRatioLower);
                        }
                    }
                    function maxLiquidity(
                        SqrtRatio _sqrtRatio,
                        SqrtRatio sqrtRatioA,
                        SqrtRatio sqrtRatioB,
                        uint128 amount0,
                        uint128 amount1
                    ) pure returns (uint128) {
                        uint256 sqrtRatio = _sqrtRatio.toFixed();
                        (uint256 sqrtRatioLower, uint256 sqrtRatioUpper) = sortAndConvertToFixedSqrtRatios(sqrtRatioA, sqrtRatioB);
                        if (sqrtRatio <= sqrtRatioLower) {
                            return uint128(
                                FixedPointMathLib.min(type(uint128).max, maxLiquidityForToken0(sqrtRatioLower, sqrtRatioUpper, amount0))
                            );
                        } else if (sqrtRatio < sqrtRatioUpper) {
                            return uint128(
                                FixedPointMathLib.min(
                                    type(uint128).max,
                                    FixedPointMathLib.min(
                                        maxLiquidityForToken0(sqrtRatio, sqrtRatioUpper, amount0),
                                        maxLiquidityForToken1(sqrtRatioLower, sqrtRatio, amount1)
                                    )
                                )
                            );
                        } else {
                            return uint128(
                                FixedPointMathLib.min(type(uint128).max, maxLiquidityForToken1(sqrtRatioLower, sqrtRatioUpper, amount1))
                            );
                        }
                    }
                    error LiquidityDeltaOverflow();
                    function addLiquidityDelta(uint128 liquidity, int128 liquidityDelta) pure returns (uint128 result) {
                        assembly ("memory-safe") {
                            result := add(liquidity, liquidityDelta)
                            if and(result, shl(128, 0xffffffffffffffffffffffffffffffff)) {
                                mstore(0, shl(224, 0x6d862c50))
                                revert(0, 4)
                            }
                        }
                    }
                    function subLiquidityDelta(uint128 liquidity, int128 liquidityDelta) pure returns (uint128 result) {
                        assembly ("memory-safe") {
                            result := sub(liquidity, liquidityDelta)
                            if and(result, shl(128, 0xffffffffffffffffffffffffffffffff)) {
                                mstore(0, shl(224, 0x6d862c50))
                                revert(0, 4)
                            }
                        }
                    }
                    // SPDX-License-Identifier: UNLICENSED
                    pragma solidity =0.8.28;
                    // Returns the fee to charge based on the amount, which is the fee (a 0.64 number) times the
                    // amount, rounded up
                    function computeFee(uint128 amount, uint64 fee) pure returns (uint128 result) {
                        assembly ("memory-safe") {
                            result := shr(64, add(mul(amount, fee), 0xffffffffffffffff))
                        }
                    }
                    error AmountBeforeFeeOverflow();
                    // Returns the amount before the fee is applied, which is the amount minus the fee, rounded up
                    function amountBeforeFee(uint128 afterFee, uint64 fee) pure returns (uint128 result) {
                        uint256 r;
                        assembly ("memory-safe") {
                            let v := shl(64, afterFee)
                            let d := sub(0x10000000000000000, fee)
                            let q := div(v, d)
                            r := add(iszero(iszero(mod(v, d))), q)
                        }
                        if (r > type(uint128).max) {
                            revert AmountBeforeFeeOverflow();
                        }
                        result = uint128(r);
                    }
                    // SPDX-License-Identifier: UNLICENSED
                    pragma solidity =0.8.28;
                    import {Bitmap} from "../math/bitmap.sol";
                    import {MIN_TICK, MAX_TICK} from "../math/constants.sol";
                    import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol";
                    // Returns the index of the word and the index _in_ that word which contains the bit representing whether the tick is initialized
                    // Addition of the offset does two things--it centers the 0 tick within a single bitmap regardless of tick spacing,
                    // and gives us a contiguous range of unsigned integers for all ticks
                    // Always rounds the tick down to the nearest multiple of tickSpacing
                    function tickToBitmapWordAndIndex(int32 tick, uint32 tickSpacing) pure returns (uint256 word, uint256 index) {
                        assembly ("memory-safe") {
                            let rawIndex := add(sub(sdiv(tick, tickSpacing), slt(smod(tick, tickSpacing), 0)), 89421695)
                            word := div(rawIndex, 256)
                            index := mod(rawIndex, 256)
                        }
                    }
                    // Returns the index of the word and the index _in_ that word which contains the bit representing whether the tick is initialized
                    /// @dev This function is only safe if tickSpacing is between 1 and MAX_TICK_SPACING, and word/index correspond to the results of tickToBitmapWordAndIndex for a tick between MIN_TICK and MAX_TICK
                    function bitmapWordAndIndexToTick(uint256 word, uint256 index, uint32 tickSpacing) pure returns (int32 tick) {
                        assembly ("memory-safe") {
                            let rawIndex := add(mul(word, 256), index)
                            tick := mul(sub(rawIndex, 89421695), tickSpacing)
                        }
                    }
                    // Flips the tick in the bitmap from true to false or vice versa
                    function flipTick(mapping(uint256 word => Bitmap bitmap) storage map, int32 tick, uint32 tickSpacing) {
                        (uint256 word, uint256 index) = tickToBitmapWordAndIndex(tick, tickSpacing);
                        assembly ("memory-safe") {
                            mstore(0, word)
                            mstore(32, map.slot)
                            let k := keccak256(0, 64)
                            let v := sload(k)
                            sstore(k, xor(v, shl(index, 1)))
                        }
                    }
                    function findNextInitializedTick(
                        mapping(uint256 word => Bitmap bitmap) storage map,
                        int32 fromTick,
                        uint32 tickSpacing,
                        uint256 skipAhead
                    ) view returns (int32 nextTick, bool isInitialized) {
                        unchecked {
                            nextTick = fromTick;
                            while (true) {
                                // convert the given tick to the bitmap position of the next nearest potential initialized tick
                                (uint256 word, uint256 index) = tickToBitmapWordAndIndex(nextTick + int32(tickSpacing), tickSpacing);
                                // find the index of the previous tick in that word
                                uint256 nextIndex = map[word].geSetBit(uint8(index));
                                // if we found one, return it
                                if (nextIndex != 256) {
                                    (nextTick, isInitialized) = (bitmapWordAndIndexToTick(word, nextIndex, tickSpacing), true);
                                    break;
                                }
                                // otherwise, return the tick of the most significant bit in the word
                                nextTick = bitmapWordAndIndexToTick(word, 255, tickSpacing);
                                if (nextTick >= MAX_TICK) {
                                    nextTick = MAX_TICK;
                                    break;
                                }
                                // if we are done searching, stop here
                                if (skipAhead == 0) {
                                    break;
                                }
                                skipAhead--;
                            }
                        }
                    }
                    function findPrevInitializedTick(
                        mapping(uint256 word => Bitmap bitmap) storage map,
                        int32 fromTick,
                        uint32 tickSpacing,
                        uint256 skipAhead
                    ) view returns (int32 prevTick, bool isInitialized) {
                        unchecked {
                            prevTick = fromTick;
                            while (true) {
                                // convert the given tick to its bitmap position
                                (uint256 word, uint256 index) = tickToBitmapWordAndIndex(prevTick, tickSpacing);
                                // find the index of the previous tick in that word
                                uint256 prevIndex = map[word].leSetBit(uint8(index));
                                if (prevIndex != 256) {
                                    (prevTick, isInitialized) = (bitmapWordAndIndexToTick(word, prevIndex, tickSpacing), true);
                                    break;
                                }
                                prevTick = bitmapWordAndIndexToTick(word, 0, tickSpacing);
                                if (prevTick <= MIN_TICK) {
                                    prevTick = MIN_TICK;
                                    break;
                                }
                                if (skipAhead == 0) {
                                    break;
                                }
                                skipAhead--;
                                prevTick--;
                            }
                        }
                    }
                    // SPDX-License-Identifier: UNLICENSED
                    pragma solidity =0.8.28;
                    import {CallPoints} from "../types/callPoints.sol";
                    import {PoolKey} from "../types/poolKey.sol";
                    import {PositionKey, Bounds} from "../types/positionKey.sol";
                    import {FeesPerLiquidity} from "../types/feesPerLiquidity.sol";
                    import {IExposedStorage} from "../interfaces/IExposedStorage.sol";
                    import {IFlashAccountant} from "../interfaces/IFlashAccountant.sol";
                    import {SqrtRatio} from "../types/sqrtRatio.sol";
                    struct UpdatePositionParameters {
                        bytes32 salt;
                        Bounds bounds;
                        int128 liquidityDelta;
                    }
                    interface IExtension {
                        function beforeInitializePool(address caller, PoolKey calldata key, int32 tick) external;
                        function afterInitializePool(address caller, PoolKey calldata key, int32 tick, SqrtRatio sqrtRatio) external;
                        function beforeUpdatePosition(address locker, PoolKey memory poolKey, UpdatePositionParameters memory params)
                            external;
                        function afterUpdatePosition(
                            address locker,
                            PoolKey memory poolKey,
                            UpdatePositionParameters memory params,
                            int128 delta0,
                            int128 delta1
                        ) external;
                        function beforeSwap(
                            address locker,
                            PoolKey memory poolKey,
                            int128 amount,
                            bool isToken1,
                            SqrtRatio sqrtRatioLimit,
                            uint256 skipAhead
                        ) external;
                        function afterSwap(
                            address locker,
                            PoolKey memory poolKey,
                            int128 amount,
                            bool isToken1,
                            SqrtRatio sqrtRatioLimit,
                            uint256 skipAhead,
                            int128 delta0,
                            int128 delta1
                        ) external;
                        function beforeCollectFees(address locker, PoolKey memory poolKey, bytes32 salt, Bounds memory bounds) external;
                        function afterCollectFees(
                            address locker,
                            PoolKey memory poolKey,
                            bytes32 salt,
                            Bounds memory bounds,
                            uint128 amount0,
                            uint128 amount1
                        ) external;
                    }
                    interface ICore is IFlashAccountant, IExposedStorage {
                        event ProtocolFeesWithdrawn(address recipient, address token, uint256 amount);
                        event ExtensionRegistered(address extension);
                        event PoolInitialized(bytes32 poolId, PoolKey poolKey, int32 tick, SqrtRatio sqrtRatio);
                        event PositionFeesCollected(bytes32 poolId, PositionKey positionKey, uint128 amount0, uint128 amount1);
                        event FeesAccumulated(bytes32 poolId, uint128 amount0, uint128 amount1);
                        event PositionUpdated(
                            address locker, bytes32 poolId, UpdatePositionParameters params, int128 delta0, int128 delta1
                        );
                        // This error is thrown by swaps and deposits when this particular deployment of the contract is expired.
                        error FailedRegisterInvalidCallPoints();
                        error ExtensionAlreadyRegistered();
                        error InsufficientSavedBalance();
                        error PoolAlreadyInitialized();
                        error ExtensionNotRegistered();
                        error PoolNotInitialized();
                        error MustCollectFeesBeforeWithdrawingAllLiquidity();
                        error SqrtRatioLimitOutOfRange();
                        error InvalidSqrtRatioLimit();
                        error SavedBalanceTokensNotSorted();
                        // Allows the owner of the contract to withdraw the protocol withdrawal fees collected
                        // To withdraw the native token protocol fees, call with token = NATIVE_TOKEN_ADDRESS
                        function withdrawProtocolFees(address recipient, address token, uint256 amount) external;
                        // Extensions must call this function to become registered. The call points are validated against the caller address
                        function registerExtension(CallPoints memory expectedCallPoints) external;
                        // Sets the initial price for a new pool in terms of tick.
                        function initializePool(PoolKey memory poolKey, int32 tick) external returns (SqrtRatio sqrtRatio);
                        function prevInitializedTick(bytes32 poolId, int32 fromTick, uint32 tickSpacing, uint256 skipAhead)
                            external
                            view
                            returns (int32 tick, bool isInitialized);
                        function nextInitializedTick(bytes32 poolId, int32 fromTick, uint32 tickSpacing, uint256 skipAhead)
                            external
                            view
                            returns (int32 tick, bool isInitialized);
                        // Loads 2 tokens from the saved balances of the caller as payment in the current context.
                        function load(address token0, address token1, bytes32 salt, uint128 amount0, uint128 amount1) external;
                        // Saves an amount of 2 tokens to be used later, in a single slot.
                        function save(address owner, address token0, address token1, bytes32 salt, uint128 amount0, uint128 amount1)
                            external
                            payable;
                        // Returns the pool fees per liquidity inside the given bounds.
                        function getPoolFeesPerLiquidityInside(PoolKey memory poolKey, Bounds memory bounds)
                            external
                            view
                            returns (FeesPerLiquidity memory);
                        // Accumulates tokens to fees of a pool. Only callable by the extension of the specified pool
                        // key, i.e. the current locker _must_ be the extension.
                        // The extension must call this function within a lock callback.
                        function accumulateAsFees(PoolKey memory poolKey, uint128 amount0, uint128 amount1) external payable;
                        function updatePosition(PoolKey memory poolKey, UpdatePositionParameters memory params)
                            external
                            payable
                            returns (int128 delta0, int128 delta1);
                        function collectFees(PoolKey memory poolKey, bytes32 salt, Bounds memory bounds)
                            external
                            returns (uint128 amount0, uint128 amount1);
                        function swap_611415377(
                            PoolKey memory poolKey,
                            int128 amount,
                            bool isToken1,
                            SqrtRatio sqrtRatioLimit,
                            uint256 skipAhead
                        ) external payable returns (int128 delta0, int128 delta1);
                    }
                    // SPDX-License-Identifier: UNLICENSED
                    pragma solidity =0.8.28;
                    import {NATIVE_TOKEN_ADDRESS} from "../math/constants.sol";
                    import {IPayer, IFlashAccountant} from "../interfaces/IFlashAccountant.sol";
                    import {SafeTransferLib} from "solady/utils/SafeTransferLib.sol";
                    abstract contract FlashAccountant is IFlashAccountant {
                        // These offsets are selected so that they do not accidentally overlap with any other base contract's use of transient storage
                        // cast keccak "FlashAccountant#CURRENT_LOCKER_SLOT"
                        uint256 private constant _CURRENT_LOCKER_SLOT = 0x07cc7f5195d862f505d6b095c82f92e00cfc1766f5bca4383c28dc5fca1555fd;
                        // cast keccak "FlashAccountant#NONZERO_DEBT_COUNT_OFFSET"
                        uint256 private constant _NONZERO_DEBT_COUNT_OFFSET =
                            0x7772acfd7e0f66ebb20a058830296c3dc1301b111d23348e1c961d324223190d;
                        // cast keccak "FlashAccountant#DEBT_HASH_OFFSET"
                        uint256 private constant _DEBT_HASH_OFFSET = 0x3fee1dc3ade45aa30d633b5b8645760533723e46597841ef1126c6577a091742;
                        // cast keccak "FlashAccountant#PAY_REENTRANCY_LOCK"
                        uint256 private constant _PAY_REENTRANCY_LOCK = 0xe1be600102d456bf2d4dee36e1641404df82292916888bf32557e00dfe166412;
                        function _getLocker() internal view returns (uint256 id, address locker) {
                            assembly ("memory-safe") {
                                let current := tload(_CURRENT_LOCKER_SLOT)
                                if iszero(current) {
                                    // cast sig "NotLocked()"
                                    mstore(0, shl(224, 0x1834e265))
                                    revert(0, 4)
                                }
                                id := sub(shr(160, current), 1)
                                locker := shr(96, shl(96, current))
                            }
                        }
                        function _requireLocker() internal view returns (uint256 id, address locker) {
                            (id, locker) = _getLocker();
                            if (locker != msg.sender) revert LockerOnly();
                        }
                        // We assume debtChange cannot exceed a 128 bits value, even though it uses a int256 container
                        // This must be enforced at the places it is called for this contract's safety
                        // Negative means erasing debt, positive means adding debt
                        function _accountDebt(uint256 id, address token, int256 debtChange) internal {
                            assembly ("memory-safe") {
                                if iszero(iszero(debtChange)) {
                                    mstore(0, add(add(shl(160, id), token), _DEBT_HASH_OFFSET))
                                    let deltaSlot := keccak256(0, 32)
                                    let current := tload(deltaSlot)
                                    // we know this never overflows because debtChange is only ever derived from 128 bit values in inheriting contracts
                                    let next := add(current, debtChange)
                                    let nextZero := iszero(next)
                                    if xor(iszero(current), nextZero) {
                                        let nzdCountSlot := add(id, _NONZERO_DEBT_COUNT_OFFSET)
                                        tstore(nzdCountSlot, add(sub(tload(nzdCountSlot), nextZero), iszero(nextZero)))
                                    }
                                    tstore(deltaSlot, next)
                                }
                            }
                        }
                        // The entrypoint for all operations on the core contract
                        function lock() external {
                            assembly ("memory-safe") {
                                let current := tload(_CURRENT_LOCKER_SLOT)
                                let id := shr(160, current)
                                // store the count
                                tstore(_CURRENT_LOCKER_SLOT, or(shl(160, add(id, 1)), caller()))
                                let free := mload(0x40)
                                // Prepare call to locked(uint256) -> selector 0xb45a3c0e
                                mstore(free, shl(224, 0xb45a3c0e))
                                mstore(add(free, 4), id) // ID argument
                                calldatacopy(add(free, 36), 4, sub(calldatasize(), 4))
                                // Call the original caller with the packed data
                                let success := call(gas(), caller(), 0, free, add(calldatasize(), 32), 0, 0)
                                // Pass through the error on failure
                                if iszero(success) {
                                    returndatacopy(free, 0, returndatasize())
                                    revert(free, returndatasize())
                                }
                                // Undo the "locker" state changes
                                tstore(_CURRENT_LOCKER_SLOT, current)
                                // Check if something is nonzero
                                let nonzeroDebtCount := tload(add(_NONZERO_DEBT_COUNT_OFFSET, id))
                                if nonzeroDebtCount {
                                    // cast sig "DebtsNotZeroed(uint256)"
                                    mstore(0x00, 0x9731ba37)
                                    mstore(0x20, id)
                                    revert(0x1c, 0x24)
                                }
                                // Directly return whatever the subcall returned
                                returndatacopy(free, 0, returndatasize())
                                return(free, returndatasize())
                            }
                        }
                        // Allows forwarding the lock context to another actor, allowing them to act on the original locker's debt
                        function forward(address to) external {
                            (uint256 id, address locker) = _requireLocker();
                            // update this lock's locker to the forwarded address for the duration of the forwarded
                            // call, meaning only the forwarded address can update state
                            assembly ("memory-safe") {
                                tstore(_CURRENT_LOCKER_SLOT, or(shl(160, add(id, 1)), to))
                                let free := mload(0x40)
                                // Prepare call to forwarded(uint256,address) -> selector 0x64919dea
                                mstore(free, shl(224, 0x64919dea))
                                mstore(add(free, 4), id)
                                mstore(add(free, 36), locker)
                                calldatacopy(add(free, 68), 36, sub(calldatasize(), 36))
                                // Call the forwardee with the packed data
                                let success := call(gas(), to, 0, free, add(32, calldatasize()), 0, 0)
                                // Pass through the error on failure
                                if iszero(success) {
                                    returndatacopy(free, 0, returndatasize())
                                    revert(free, returndatasize())
                                }
                                tstore(_CURRENT_LOCKER_SLOT, or(shl(160, add(id, 1)), locker))
                                // Directly return whatever the subcall returned
                                returndatacopy(free, 0, returndatasize())
                                return(free, returndatasize())
                            }
                        }
                        function pay(address token) external returns (uint128 payment) {
                            assembly ("memory-safe") {
                                if tload(_PAY_REENTRANCY_LOCK) {
                                    // cast sig "PayReentrance()"
                                    mstore(0, 0xced108be)
                                    revert(0x1c, 0x04)
                                }
                                tstore(_PAY_REENTRANCY_LOCK, 1)
                            }
                            (uint256 id,) = _getLocker();
                            assembly ("memory-safe") {
                                let free := mload(0x40)
                                mstore(20, address()) // Store the `account` argument.
                                mstore(0, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
                                let tokenBalanceBefore :=
                                    mul( // The arguments of `mul` are evaluated from right to left.
                                        mload(free),
                                        and( // The arguments of `and` are evaluated from right to left.
                                            gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                                            staticcall(gas(), token, 0x10, 0x24, free, 0x20)
                                        )
                                    )
                                // Prepare call to "payCallback(uint256,address)"
                                mstore(free, shl(224, 0x599d0714))
                                mstore(add(free, 4), id)
                                mstore(add(free, 36), token)
                                // copy the token, plus anything else that they wanted to forward
                                calldatacopy(add(free, 68), 36, sub(calldatasize(), 36))
                                // Call the forwardee with the packed data
                                // Pass through the error on failure
                                if iszero(call(gas(), caller(), 0, free, add(32, calldatasize()), 0, 0)) {
                                    returndatacopy(free, 0, returndatasize())
                                    revert(free, returndatasize())
                                }
                                // Arguments are still in scratch, we don't need to rewrite them
                                let tokenBalanceAfter :=
                                    mul( // The arguments of `mul` are evaluated from right to left.
                                        mload(0x20),
                                        and( // The arguments of `and` are evaluated from right to left.
                                            gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                                            staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
                                        )
                                    )
                                if lt(tokenBalanceAfter, tokenBalanceBefore) {
                                    // cast sig "NoPaymentMade()"
                                    mstore(0x00, 0x01b243b9)
                                    revert(0x1c, 4)
                                }
                                payment := sub(tokenBalanceAfter, tokenBalanceBefore)
                                // We never expect tokens to have this much total supply
                                if gt(payment, 0xffffffffffffffffffffffffffffffff) {
                                    // cast sig "PaymentOverflow()"
                                    mstore(0x00, 0x9cac58ca)
                                    revert(0x1c, 4)
                                }
                            }
                            // The unary negative operator never fails because payment is less than max uint128
                            unchecked {
                                _accountDebt(id, token, -int256(uint256(payment)));
                            }
                            assembly ("memory-safe") {
                                tstore(_PAY_REENTRANCY_LOCK, 0)
                            }
                        }
                        function withdraw(address token, address recipient, uint128 amount) external {
                            (uint256 id,) = _requireLocker();
                            _accountDebt(id, token, int256(uint256(amount)));
                            if (token == NATIVE_TOKEN_ADDRESS) {
                                SafeTransferLib.safeTransferETH(recipient, amount);
                            } else {
                                SafeTransferLib.safeTransfer(token, recipient, amount);
                            }
                        }
                        receive() external payable {
                            (uint256 id,) = _getLocker();
                            // Note because we use msg.value here, this contract can never be multicallable, i.e. it should never expose the ability
                            //      to delegatecall itself more than once in a single call
                            unchecked {
                                // We never expect the native token to exceed this supply
                                if (msg.value > type(uint128).max) revert PaymentOverflow();
                                _accountDebt(id, NATIVE_TOKEN_ADDRESS, -int256(msg.value));
                            }
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.8.4;
                    /// @notice Library for efficiently performing keccak256 hashes.
                    /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/EfficientHashLib.sol)
                    /// @dev To avoid stack-too-deep, you can use:
                    /// ```
                    /// bytes32[] memory buffer = EfficientHashLib.malloc(10);
                    /// EfficientHashLib.set(buffer, 0, value0);
                    /// ..
                    /// EfficientHashLib.set(buffer, 9, value9);
                    /// bytes32 finalHash = EfficientHashLib.hash(buffer);
                    /// ```
                    library EfficientHashLib {
                        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                        /*               MALLOC-LESS HASHING OPERATIONS               */
                        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                        /// @dev Returns `keccak256(abi.encode(v0))`.
                        function hash(bytes32 v0) internal pure returns (bytes32 result) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                mstore(0x00, v0)
                                result := keccak256(0x00, 0x20)
                            }
                        }
                        /// @dev Returns `keccak256(abi.encode(v0))`.
                        function hash(uint256 v0) internal pure returns (bytes32 result) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                mstore(0x00, v0)
                                result := keccak256(0x00, 0x20)
                            }
                        }
                        /// @dev Returns `keccak256(abi.encode(v0, v1))`.
                        function hash(bytes32 v0, bytes32 v1) internal pure returns (bytes32 result) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                mstore(0x00, v0)
                                mstore(0x20, v1)
                                result := keccak256(0x00, 0x40)
                            }
                        }
                        /// @dev Returns `keccak256(abi.encode(v0, v1))`.
                        function hash(uint256 v0, uint256 v1) internal pure returns (bytes32 result) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                mstore(0x00, v0)
                                mstore(0x20, v1)
                                result := keccak256(0x00, 0x40)
                            }
                        }
                        /// @dev Returns `keccak256(abi.encode(v0, v1, v2))`.
                        function hash(bytes32 v0, bytes32 v1, bytes32 v2) internal pure returns (bytes32 result) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                let m := mload(0x40)
                                mstore(m, v0)
                                mstore(add(m, 0x20), v1)
                                mstore(add(m, 0x40), v2)
                                result := keccak256(m, 0x60)
                            }
                        }
                        /// @dev Returns `keccak256(abi.encode(v0, v1, v2))`.
                        function hash(uint256 v0, uint256 v1, uint256 v2) internal pure returns (bytes32 result) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                let m := mload(0x40)
                                mstore(m, v0)
                                mstore(add(m, 0x20), v1)
                                mstore(add(m, 0x40), v2)
                                result := keccak256(m, 0x60)
                            }
                        }
                        /// @dev Returns `keccak256(abi.encode(v0, v1, v2, v3))`.
                        function hash(bytes32 v0, bytes32 v1, bytes32 v2, bytes32 v3)
                            internal
                            pure
                            returns (bytes32 result)
                        {
                            /// @solidity memory-safe-assembly
                            assembly {
                                let m := mload(0x40)
                                mstore(m, v0)
                                mstore(add(m, 0x20), v1)
                                mstore(add(m, 0x40), v2)
                                mstore(add(m, 0x60), v3)
                                result := keccak256(m, 0x80)
                            }
                        }
                        /// @dev Returns `keccak256(abi.encode(v0, v1, v2, v3))`.
                        function hash(uint256 v0, uint256 v1, uint256 v2, uint256 v3)
                            internal
                            pure
                            returns (bytes32 result)
                        {
                            /// @solidity memory-safe-assembly
                            assembly {
                                let m := mload(0x40)
                                mstore(m, v0)
                                mstore(add(m, 0x20), v1)
                                mstore(add(m, 0x40), v2)
                                mstore(add(m, 0x60), v3)
                                result := keccak256(m, 0x80)
                            }
                        }
                        /// @dev Returns `keccak256(abi.encode(v0, .., v4))`.
                        function hash(bytes32 v0, bytes32 v1, bytes32 v2, bytes32 v3, bytes32 v4)
                            internal
                            pure
                            returns (bytes32 result)
                        {
                            /// @solidity memory-safe-assembly
                            assembly {
                                let m := mload(0x40)
                                mstore(m, v0)
                                mstore(add(m, 0x20), v1)
                                mstore(add(m, 0x40), v2)
                                mstore(add(m, 0x60), v3)
                                mstore(add(m, 0x80), v4)
                                result := keccak256(m, 0xa0)
                            }
                        }
                        /// @dev Returns `keccak256(abi.encode(v0, .., v4))`.
                        function hash(uint256 v0, uint256 v1, uint256 v2, uint256 v3, uint256 v4)
                            internal
                            pure
                            returns (bytes32 result)
                        {
                            /// @solidity memory-safe-assembly
                            assembly {
                                let m := mload(0x40)
                                mstore(m, v0)
                                mstore(add(m, 0x20), v1)
                                mstore(add(m, 0x40), v2)
                                mstore(add(m, 0x60), v3)
                                mstore(add(m, 0x80), v4)
                                result := keccak256(m, 0xa0)
                            }
                        }
                        /// @dev Returns `keccak256(abi.encode(v0, .., v5))`.
                        function hash(bytes32 v0, bytes32 v1, bytes32 v2, bytes32 v3, bytes32 v4, bytes32 v5)
                            internal
                            pure
                            returns (bytes32 result)
                        {
                            /// @solidity memory-safe-assembly
                            assembly {
                                let m := mload(0x40)
                                mstore(m, v0)
                                mstore(add(m, 0x20), v1)
                                mstore(add(m, 0x40), v2)
                                mstore(add(m, 0x60), v3)
                                mstore(add(m, 0x80), v4)
                                mstore(add(m, 0xa0), v5)
                                result := keccak256(m, 0xc0)
                            }
                        }
                        /// @dev Returns `keccak256(abi.encode(v0, .., v5))`.
                        function hash(uint256 v0, uint256 v1, uint256 v2, uint256 v3, uint256 v4, uint256 v5)
                            internal
                            pure
                            returns (bytes32 result)
                        {
                            /// @solidity memory-safe-assembly
                            assembly {
                                let m := mload(0x40)
                                mstore(m, v0)
                                mstore(add(m, 0x20), v1)
                                mstore(add(m, 0x40), v2)
                                mstore(add(m, 0x60), v3)
                                mstore(add(m, 0x80), v4)
                                mstore(add(m, 0xa0), v5)
                                result := keccak256(m, 0xc0)
                            }
                        }
                        /// @dev Returns `keccak256(abi.encode(v0, .., v6))`.
                        function hash(
                            bytes32 v0,
                            bytes32 v1,
                            bytes32 v2,
                            bytes32 v3,
                            bytes32 v4,
                            bytes32 v5,
                            bytes32 v6
                        ) internal pure returns (bytes32 result) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                let m := mload(0x40)
                                mstore(m, v0)
                                mstore(add(m, 0x20), v1)
                                mstore(add(m, 0x40), v2)
                                mstore(add(m, 0x60), v3)
                                mstore(add(m, 0x80), v4)
                                mstore(add(m, 0xa0), v5)
                                mstore(add(m, 0xc0), v6)
                                result := keccak256(m, 0xe0)
                            }
                        }
                        /// @dev Returns `keccak256(abi.encode(v0, .., v6))`.
                        function hash(
                            uint256 v0,
                            uint256 v1,
                            uint256 v2,
                            uint256 v3,
                            uint256 v4,
                            uint256 v5,
                            uint256 v6
                        ) internal pure returns (bytes32 result) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                let m := mload(0x40)
                                mstore(m, v0)
                                mstore(add(m, 0x20), v1)
                                mstore(add(m, 0x40), v2)
                                mstore(add(m, 0x60), v3)
                                mstore(add(m, 0x80), v4)
                                mstore(add(m, 0xa0), v5)
                                mstore(add(m, 0xc0), v6)
                                result := keccak256(m, 0xe0)
                            }
                        }
                        /// @dev Returns `keccak256(abi.encode(v0, .., v7))`.
                        function hash(
                            bytes32 v0,
                            bytes32 v1,
                            bytes32 v2,
                            bytes32 v3,
                            bytes32 v4,
                            bytes32 v5,
                            bytes32 v6,
                            bytes32 v7
                        ) internal pure returns (bytes32 result) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                let m := mload(0x40)
                                mstore(m, v0)
                                mstore(add(m, 0x20), v1)
                                mstore(add(m, 0x40), v2)
                                mstore(add(m, 0x60), v3)
                                mstore(add(m, 0x80), v4)
                                mstore(add(m, 0xa0), v5)
                                mstore(add(m, 0xc0), v6)
                                mstore(add(m, 0xe0), v7)
                                result := keccak256(m, 0x100)
                            }
                        }
                        /// @dev Returns `keccak256(abi.encode(v0, .., v7))`.
                        function hash(
                            uint256 v0,
                            uint256 v1,
                            uint256 v2,
                            uint256 v3,
                            uint256 v4,
                            uint256 v5,
                            uint256 v6,
                            uint256 v7
                        ) internal pure returns (bytes32 result) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                let m := mload(0x40)
                                mstore(m, v0)
                                mstore(add(m, 0x20), v1)
                                mstore(add(m, 0x40), v2)
                                mstore(add(m, 0x60), v3)
                                mstore(add(m, 0x80), v4)
                                mstore(add(m, 0xa0), v5)
                                mstore(add(m, 0xc0), v6)
                                mstore(add(m, 0xe0), v7)
                                result := keccak256(m, 0x100)
                            }
                        }
                        /// @dev Returns `keccak256(abi.encode(v0, .., v8))`.
                        function hash(
                            bytes32 v0,
                            bytes32 v1,
                            bytes32 v2,
                            bytes32 v3,
                            bytes32 v4,
                            bytes32 v5,
                            bytes32 v6,
                            bytes32 v7,
                            bytes32 v8
                        ) internal pure returns (bytes32 result) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                let m := mload(0x40)
                                mstore(m, v0)
                                mstore(add(m, 0x20), v1)
                                mstore(add(m, 0x40), v2)
                                mstore(add(m, 0x60), v3)
                                mstore(add(m, 0x80), v4)
                                mstore(add(m, 0xa0), v5)
                                mstore(add(m, 0xc0), v6)
                                mstore(add(m, 0xe0), v7)
                                mstore(add(m, 0x100), v8)
                                result := keccak256(m, 0x120)
                            }
                        }
                        /// @dev Returns `keccak256(abi.encode(v0, .., v8))`.
                        function hash(
                            uint256 v0,
                            uint256 v1,
                            uint256 v2,
                            uint256 v3,
                            uint256 v4,
                            uint256 v5,
                            uint256 v6,
                            uint256 v7,
                            uint256 v8
                        ) internal pure returns (bytes32 result) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                let m := mload(0x40)
                                mstore(m, v0)
                                mstore(add(m, 0x20), v1)
                                mstore(add(m, 0x40), v2)
                                mstore(add(m, 0x60), v3)
                                mstore(add(m, 0x80), v4)
                                mstore(add(m, 0xa0), v5)
                                mstore(add(m, 0xc0), v6)
                                mstore(add(m, 0xe0), v7)
                                mstore(add(m, 0x100), v8)
                                result := keccak256(m, 0x120)
                            }
                        }
                        /// @dev Returns `keccak256(abi.encode(v0, .., v9))`.
                        function hash(
                            bytes32 v0,
                            bytes32 v1,
                            bytes32 v2,
                            bytes32 v3,
                            bytes32 v4,
                            bytes32 v5,
                            bytes32 v6,
                            bytes32 v7,
                            bytes32 v8,
                            bytes32 v9
                        ) internal pure returns (bytes32 result) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                let m := mload(0x40)
                                mstore(m, v0)
                                mstore(add(m, 0x20), v1)
                                mstore(add(m, 0x40), v2)
                                mstore(add(m, 0x60), v3)
                                mstore(add(m, 0x80), v4)
                                mstore(add(m, 0xa0), v5)
                                mstore(add(m, 0xc0), v6)
                                mstore(add(m, 0xe0), v7)
                                mstore(add(m, 0x100), v8)
                                mstore(add(m, 0x120), v9)
                                result := keccak256(m, 0x140)
                            }
                        }
                        /// @dev Returns `keccak256(abi.encode(v0, .., v9))`.
                        function hash(
                            uint256 v0,
                            uint256 v1,
                            uint256 v2,
                            uint256 v3,
                            uint256 v4,
                            uint256 v5,
                            uint256 v6,
                            uint256 v7,
                            uint256 v8,
                            uint256 v9
                        ) internal pure returns (bytes32 result) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                let m := mload(0x40)
                                mstore(m, v0)
                                mstore(add(m, 0x20), v1)
                                mstore(add(m, 0x40), v2)
                                mstore(add(m, 0x60), v3)
                                mstore(add(m, 0x80), v4)
                                mstore(add(m, 0xa0), v5)
                                mstore(add(m, 0xc0), v6)
                                mstore(add(m, 0xe0), v7)
                                mstore(add(m, 0x100), v8)
                                mstore(add(m, 0x120), v9)
                                result := keccak256(m, 0x140)
                            }
                        }
                        /// @dev Returns `keccak256(abi.encode(v0, .., v10))`.
                        function hash(
                            bytes32 v0,
                            bytes32 v1,
                            bytes32 v2,
                            bytes32 v3,
                            bytes32 v4,
                            bytes32 v5,
                            bytes32 v6,
                            bytes32 v7,
                            bytes32 v8,
                            bytes32 v9,
                            bytes32 v10
                        ) internal pure returns (bytes32 result) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                let m := mload(0x40)
                                mstore(m, v0)
                                mstore(add(m, 0x20), v1)
                                mstore(add(m, 0x40), v2)
                                mstore(add(m, 0x60), v3)
                                mstore(add(m, 0x80), v4)
                                mstore(add(m, 0xa0), v5)
                                mstore(add(m, 0xc0), v6)
                                mstore(add(m, 0xe0), v7)
                                mstore(add(m, 0x100), v8)
                                mstore(add(m, 0x120), v9)
                                mstore(add(m, 0x140), v10)
                                result := keccak256(m, 0x160)
                            }
                        }
                        /// @dev Returns `keccak256(abi.encode(v0, .., v10))`.
                        function hash(
                            uint256 v0,
                            uint256 v1,
                            uint256 v2,
                            uint256 v3,
                            uint256 v4,
                            uint256 v5,
                            uint256 v6,
                            uint256 v7,
                            uint256 v8,
                            uint256 v9,
                            uint256 v10
                        ) internal pure returns (bytes32 result) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                let m := mload(0x40)
                                mstore(m, v0)
                                mstore(add(m, 0x20), v1)
                                mstore(add(m, 0x40), v2)
                                mstore(add(m, 0x60), v3)
                                mstore(add(m, 0x80), v4)
                                mstore(add(m, 0xa0), v5)
                                mstore(add(m, 0xc0), v6)
                                mstore(add(m, 0xe0), v7)
                                mstore(add(m, 0x100), v8)
                                mstore(add(m, 0x120), v9)
                                mstore(add(m, 0x140), v10)
                                result := keccak256(m, 0x160)
                            }
                        }
                        /// @dev Returns `keccak256(abi.encode(v0, .., v11))`.
                        function hash(
                            bytes32 v0,
                            bytes32 v1,
                            bytes32 v2,
                            bytes32 v3,
                            bytes32 v4,
                            bytes32 v5,
                            bytes32 v6,
                            bytes32 v7,
                            bytes32 v8,
                            bytes32 v9,
                            bytes32 v10,
                            bytes32 v11
                        ) internal pure returns (bytes32 result) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                let m := mload(0x40)
                                mstore(m, v0)
                                mstore(add(m, 0x20), v1)
                                mstore(add(m, 0x40), v2)
                                mstore(add(m, 0x60), v3)
                                mstore(add(m, 0x80), v4)
                                mstore(add(m, 0xa0), v5)
                                mstore(add(m, 0xc0), v6)
                                mstore(add(m, 0xe0), v7)
                                mstore(add(m, 0x100), v8)
                                mstore(add(m, 0x120), v9)
                                mstore(add(m, 0x140), v10)
                                mstore(add(m, 0x160), v11)
                                result := keccak256(m, 0x180)
                            }
                        }
                        /// @dev Returns `keccak256(abi.encode(v0, .., v11))`.
                        function hash(
                            uint256 v0,
                            uint256 v1,
                            uint256 v2,
                            uint256 v3,
                            uint256 v4,
                            uint256 v5,
                            uint256 v6,
                            uint256 v7,
                            uint256 v8,
                            uint256 v9,
                            uint256 v10,
                            uint256 v11
                        ) internal pure returns (bytes32 result) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                let m := mload(0x40)
                                mstore(m, v0)
                                mstore(add(m, 0x20), v1)
                                mstore(add(m, 0x40), v2)
                                mstore(add(m, 0x60), v3)
                                mstore(add(m, 0x80), v4)
                                mstore(add(m, 0xa0), v5)
                                mstore(add(m, 0xc0), v6)
                                mstore(add(m, 0xe0), v7)
                                mstore(add(m, 0x100), v8)
                                mstore(add(m, 0x120), v9)
                                mstore(add(m, 0x140), v10)
                                mstore(add(m, 0x160), v11)
                                result := keccak256(m, 0x180)
                            }
                        }
                        /// @dev Returns `keccak256(abi.encode(v0, .., v12))`.
                        function hash(
                            bytes32 v0,
                            bytes32 v1,
                            bytes32 v2,
                            bytes32 v3,
                            bytes32 v4,
                            bytes32 v5,
                            bytes32 v6,
                            bytes32 v7,
                            bytes32 v8,
                            bytes32 v9,
                            bytes32 v10,
                            bytes32 v11,
                            bytes32 v12
                        ) internal pure returns (bytes32 result) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                let m := mload(0x40)
                                mstore(m, v0)
                                mstore(add(m, 0x20), v1)
                                mstore(add(m, 0x40), v2)
                                mstore(add(m, 0x60), v3)
                                mstore(add(m, 0x80), v4)
                                mstore(add(m, 0xa0), v5)
                                mstore(add(m, 0xc0), v6)
                                mstore(add(m, 0xe0), v7)
                                mstore(add(m, 0x100), v8)
                                mstore(add(m, 0x120), v9)
                                mstore(add(m, 0x140), v10)
                                mstore(add(m, 0x160), v11)
                                mstore(add(m, 0x180), v12)
                                result := keccak256(m, 0x1a0)
                            }
                        }
                        /// @dev Returns `keccak256(abi.encode(v0, .., v12))`.
                        function hash(
                            uint256 v0,
                            uint256 v1,
                            uint256 v2,
                            uint256 v3,
                            uint256 v4,
                            uint256 v5,
                            uint256 v6,
                            uint256 v7,
                            uint256 v8,
                            uint256 v9,
                            uint256 v10,
                            uint256 v11,
                            uint256 v12
                        ) internal pure returns (bytes32 result) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                let m := mload(0x40)
                                mstore(m, v0)
                                mstore(add(m, 0x20), v1)
                                mstore(add(m, 0x40), v2)
                                mstore(add(m, 0x60), v3)
                                mstore(add(m, 0x80), v4)
                                mstore(add(m, 0xa0), v5)
                                mstore(add(m, 0xc0), v6)
                                mstore(add(m, 0xe0), v7)
                                mstore(add(m, 0x100), v8)
                                mstore(add(m, 0x120), v9)
                                mstore(add(m, 0x140), v10)
                                mstore(add(m, 0x160), v11)
                                mstore(add(m, 0x180), v12)
                                result := keccak256(m, 0x1a0)
                            }
                        }
                        /// @dev Returns `keccak256(abi.encode(v0, .., v13))`.
                        function hash(
                            bytes32 v0,
                            bytes32 v1,
                            bytes32 v2,
                            bytes32 v3,
                            bytes32 v4,
                            bytes32 v5,
                            bytes32 v6,
                            bytes32 v7,
                            bytes32 v8,
                            bytes32 v9,
                            bytes32 v10,
                            bytes32 v11,
                            bytes32 v12,
                            bytes32 v13
                        ) internal pure returns (bytes32 result) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                let m := mload(0x40)
                                mstore(m, v0)
                                mstore(add(m, 0x20), v1)
                                mstore(add(m, 0x40), v2)
                                mstore(add(m, 0x60), v3)
                                mstore(add(m, 0x80), v4)
                                mstore(add(m, 0xa0), v5)
                                mstore(add(m, 0xc0), v6)
                                mstore(add(m, 0xe0), v7)
                                mstore(add(m, 0x100), v8)
                                mstore(add(m, 0x120), v9)
                                mstore(add(m, 0x140), v10)
                                mstore(add(m, 0x160), v11)
                                mstore(add(m, 0x180), v12)
                                mstore(add(m, 0x1a0), v13)
                                result := keccak256(m, 0x1c0)
                            }
                        }
                        /// @dev Returns `keccak256(abi.encode(v0, .., v13))`.
                        function hash(
                            uint256 v0,
                            uint256 v1,
                            uint256 v2,
                            uint256 v3,
                            uint256 v4,
                            uint256 v5,
                            uint256 v6,
                            uint256 v7,
                            uint256 v8,
                            uint256 v9,
                            uint256 v10,
                            uint256 v11,
                            uint256 v12,
                            uint256 v13
                        ) internal pure returns (bytes32 result) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                let m := mload(0x40)
                                mstore(m, v0)
                                mstore(add(m, 0x20), v1)
                                mstore(add(m, 0x40), v2)
                                mstore(add(m, 0x60), v3)
                                mstore(add(m, 0x80), v4)
                                mstore(add(m, 0xa0), v5)
                                mstore(add(m, 0xc0), v6)
                                mstore(add(m, 0xe0), v7)
                                mstore(add(m, 0x100), v8)
                                mstore(add(m, 0x120), v9)
                                mstore(add(m, 0x140), v10)
                                mstore(add(m, 0x160), v11)
                                mstore(add(m, 0x180), v12)
                                mstore(add(m, 0x1a0), v13)
                                result := keccak256(m, 0x1c0)
                            }
                        }
                        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                        /*             BYTES32 BUFFER HASHING OPERATIONS              */
                        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                        /// @dev Returns `keccak256(abi.encode(buffer[0], .., buffer[buffer.length - 1]))`.
                        function hash(bytes32[] memory buffer) internal pure returns (bytes32 result) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                result := keccak256(add(buffer, 0x20), shl(5, mload(buffer)))
                            }
                        }
                        /// @dev Sets `buffer[i]` to `value`, without a bounds check.
                        /// Returns the `buffer` for function chaining.
                        function set(bytes32[] memory buffer, uint256 i, bytes32 value)
                            internal
                            pure
                            returns (bytes32[] memory)
                        {
                            /// @solidity memory-safe-assembly
                            assembly {
                                mstore(add(buffer, shl(5, add(1, i))), value)
                            }
                            return buffer;
                        }
                        /// @dev Sets `buffer[i]` to `value`, without a bounds check.
                        /// Returns the `buffer` for function chaining.
                        function set(bytes32[] memory buffer, uint256 i, uint256 value)
                            internal
                            pure
                            returns (bytes32[] memory)
                        {
                            /// @solidity memory-safe-assembly
                            assembly {
                                mstore(add(buffer, shl(5, add(1, i))), value)
                            }
                            return buffer;
                        }
                        /// @dev Returns `new bytes32[](n)`, without zeroing out the memory.
                        function malloc(uint256 n) internal pure returns (bytes32[] memory buffer) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                buffer := mload(0x40)
                                mstore(buffer, n)
                                mstore(0x40, add(shl(5, add(1, n)), buffer))
                            }
                        }
                        /// @dev Frees memory that has been allocated for `buffer`.
                        /// No-op if `buffer.length` is zero, or if new memory has been allocated after `buffer`.
                        function free(bytes32[] memory buffer) internal pure {
                            /// @solidity memory-safe-assembly
                            assembly {
                                let n := mload(buffer)
                                mstore(shl(6, lt(iszero(n), eq(add(shl(5, add(1, n)), buffer), mload(0x40)))), buffer)
                            }
                        }
                        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                        /*                      EQUALITY CHECKS                       */
                        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                        /// @dev Returns `a == abi.decode(b, (bytes32))`.
                        function eq(bytes32 a, bytes memory b) internal pure returns (bool result) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                result := and(eq(0x20, mload(b)), eq(a, mload(add(b, 0x20))))
                            }
                        }
                        /// @dev Returns `abi.decode(a, (bytes32)) == a`.
                        function eq(bytes memory a, bytes32 b) internal pure returns (bool result) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                result := and(eq(0x20, mload(a)), eq(b, mload(add(a, 0x20))))
                            }
                        }
                        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                        /*               BYTE SLICE HASHING OPERATIONS                */
                        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                        /// @dev Returns the keccak256 of the slice from `start` to `end` (exclusive).
                        /// `start` and `end` are byte offsets.
                        function hash(bytes memory b, uint256 start, uint256 end)
                            internal
                            pure
                            returns (bytes32 result)
                        {
                            /// @solidity memory-safe-assembly
                            assembly {
                                let n := mload(b)
                                end := xor(end, mul(xor(end, n), lt(n, end)))
                                start := xor(start, mul(xor(start, n), lt(n, start)))
                                result := keccak256(add(add(b, 0x20), start), mul(gt(end, start), sub(end, start)))
                            }
                        }
                        /// @dev Returns the keccak256 of the slice from `start` to the end of the bytes.
                        function hash(bytes memory b, uint256 start) internal pure returns (bytes32 result) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                let n := mload(b)
                                start := xor(start, mul(xor(start, n), lt(n, start)))
                                result := keccak256(add(add(b, 0x20), start), mul(gt(n, start), sub(n, start)))
                            }
                        }
                        /// @dev Returns the keccak256 of the bytes.
                        function hash(bytes memory b) internal pure returns (bytes32 result) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                result := keccak256(add(b, 0x20), mload(b))
                            }
                        }
                        /// @dev Returns the keccak256 of the slice from `start` to `end` (exclusive).
                        /// `start` and `end` are byte offsets.
                        function hashCalldata(bytes calldata b, uint256 start, uint256 end)
                            internal
                            pure
                            returns (bytes32 result)
                        {
                            /// @solidity memory-safe-assembly
                            assembly {
                                end := xor(end, mul(xor(end, b.length), lt(b.length, end)))
                                start := xor(start, mul(xor(start, b.length), lt(b.length, start)))
                                let n := mul(gt(end, start), sub(end, start))
                                calldatacopy(mload(0x40), add(b.offset, start), n)
                                result := keccak256(mload(0x40), n)
                            }
                        }
                        /// @dev Returns the keccak256 of the slice from `start` to the end of the bytes.
                        function hashCalldata(bytes calldata b, uint256 start) internal pure returns (bytes32 result) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                start := xor(start, mul(xor(start, b.length), lt(b.length, start)))
                                let n := mul(gt(b.length, start), sub(b.length, start))
                                calldatacopy(mload(0x40), add(b.offset, start), n)
                                result := keccak256(mload(0x40), n)
                            }
                        }
                        /// @dev Returns the keccak256 of the bytes.
                        function hashCalldata(bytes calldata b) internal pure returns (bytes32 result) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                calldatacopy(mload(0x40), b.offset, b.length)
                                result := keccak256(mload(0x40), b.length)
                            }
                        }
                        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                        /*                      SHA2-256 HELPERS                      */
                        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                        /// @dev Returns `sha256(abi.encode(b))`. Yes, it's more efficient.
                        function sha2(bytes32 b) internal view returns (bytes32 result) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                mstore(0x00, b)
                                result := mload(staticcall(gas(), 2, 0x00, 0x20, 0x01, 0x20))
                                if iszero(returndatasize()) { invalid() }
                            }
                        }
                        /// @dev Returns the sha256 of the slice from `start` to `end` (exclusive).
                        /// `start` and `end` are byte offsets.
                        function sha2(bytes memory b, uint256 start, uint256 end)
                            internal
                            view
                            returns (bytes32 result)
                        {
                            /// @solidity memory-safe-assembly
                            assembly {
                                let n := mload(b)
                                end := xor(end, mul(xor(end, n), lt(n, end)))
                                start := xor(start, mul(xor(start, n), lt(n, start)))
                                // forgefmt: disable-next-item
                                result := mload(staticcall(gas(), 2, add(add(b, 0x20), start),
                                    mul(gt(end, start), sub(end, start)), 0x01, 0x20))
                                if iszero(returndatasize()) { invalid() }
                            }
                        }
                        /// @dev Returns the sha256 of the slice from `start` to the end of the bytes.
                        function sha2(bytes memory b, uint256 start) internal view returns (bytes32 result) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                let n := mload(b)
                                start := xor(start, mul(xor(start, n), lt(n, start)))
                                // forgefmt: disable-next-item
                                result := mload(staticcall(gas(), 2, add(add(b, 0x20), start),
                                    mul(gt(n, start), sub(n, start)), 0x01, 0x20))
                                if iszero(returndatasize()) { invalid() }
                            }
                        }
                        /// @dev Returns the sha256 of the bytes.
                        function sha2(bytes memory b) internal view returns (bytes32 result) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                result := mload(staticcall(gas(), 2, add(b, 0x20), mload(b), 0x01, 0x20))
                                if iszero(returndatasize()) { invalid() }
                            }
                        }
                        /// @dev Returns the sha256 of the slice from `start` to `end` (exclusive).
                        /// `start` and `end` are byte offsets.
                        function sha2Calldata(bytes calldata b, uint256 start, uint256 end)
                            internal
                            view
                            returns (bytes32 result)
                        {
                            /// @solidity memory-safe-assembly
                            assembly {
                                end := xor(end, mul(xor(end, b.length), lt(b.length, end)))
                                start := xor(start, mul(xor(start, b.length), lt(b.length, start)))
                                let n := mul(gt(end, start), sub(end, start))
                                calldatacopy(mload(0x40), add(b.offset, start), n)
                                result := mload(staticcall(gas(), 2, mload(0x40), n, 0x01, 0x20))
                                if iszero(returndatasize()) { invalid() }
                            }
                        }
                        /// @dev Returns the sha256 of the slice from `start` to the end of the bytes.
                        function sha2Calldata(bytes calldata b, uint256 start) internal view returns (bytes32 result) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                start := xor(start, mul(xor(start, b.length), lt(b.length, start)))
                                let n := mul(gt(b.length, start), sub(b.length, start))
                                calldatacopy(mload(0x40), add(b.offset, start), n)
                                result := mload(staticcall(gas(), 2, mload(0x40), n, 0x01, 0x20))
                                if iszero(returndatasize()) { invalid() }
                            }
                        }
                        /// @dev Returns the sha256 of the bytes.
                        function sha2Calldata(bytes calldata b) internal view returns (bytes32 result) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                calldatacopy(mload(0x40), b.offset, b.length)
                                result := mload(staticcall(gas(), 2, mload(0x40), b.length, 0x01, 0x20))
                                if iszero(returndatasize()) { invalid() }
                            }
                        }
                    }
                    // SPDX-License-Identifier: UNLICENSED
                    pragma solidity =0.8.28;
                    int32 constant MIN_TICK = -88722835;
                    int32 constant MAX_TICK = 88722835;
                    uint32 constant MAX_TICK_MAGNITUDE = uint32(MAX_TICK);
                    uint32 constant MAX_TICK_SPACING = 698605;
                    uint32 constant FULL_RANGE_ONLY_TICK_SPACING = 0;
                    // We use this address to represent the native token within the protocol
                    address constant NATIVE_TOKEN_ADDRESS = address(0);
                    // SPDX-License-Identifier: UNLICENSED
                    pragma solidity =0.8.28;
                    // A dynamic fixed point number (a la floating point) that stores a shifting 94 bit view of the underlying fixed point value,
                    //  based on the most significant bits (mantissa)
                    // If the most significant 2 bits are 11, it represents a 64.30
                    // If the most significant 2 bits are 10, it represents a 32.62 number
                    // If the most significant 2 bits are 01, it represents a 0.94 number
                    // If the most significant 2 bits are 00, it represents a 0.126 number that is always less than 2**-32
                    type SqrtRatio is uint96;
                    uint96 constant MIN_SQRT_RATIO_RAW = 4611797791050542631;
                    SqrtRatio constant MIN_SQRT_RATIO = SqrtRatio.wrap(MIN_SQRT_RATIO_RAW);
                    uint96 constant MAX_SQRT_RATIO_RAW = 79227682466138141934206691491;
                    SqrtRatio constant MAX_SQRT_RATIO = SqrtRatio.wrap(MAX_SQRT_RATIO_RAW);
                    uint96 constant TWO_POW_95 = 0x800000000000000000000000;
                    uint96 constant TWO_POW_94 = 0x400000000000000000000000;
                    uint96 constant TWO_POW_62 = 0x4000000000000000;
                    uint96 constant TWO_POW_62_MINUS_ONE = 0x3fffffffffffffff;
                    uint96 constant BIT_MASK = 0xc00000000000000000000000; // TWO_POW_95 | TWO_POW_94
                    SqrtRatio constant ONE = SqrtRatio.wrap((TWO_POW_95) + (1 << 62));
                    using {
                        toFixed,
                        isValid,
                        ge as >=,
                        le as <=,
                        lt as <,
                        gt as >,
                        eq as ==,
                        neq as !=,
                        isZero,
                        min,
                        max
                    } for SqrtRatio global;
                    function isValid(SqrtRatio sqrtRatio) pure returns (bool r) {
                        assembly ("memory-safe") {
                            r :=
                                and(
                                    // greater than or equal to TWO_POW_62, i.e. the whole number portion is nonzero
                                    gt(and(sqrtRatio, not(BIT_MASK)), TWO_POW_62_MINUS_ONE),
                                    // and between min/max sqrt ratio
                                    and(iszero(lt(sqrtRatio, MIN_SQRT_RATIO_RAW)), iszero(gt(sqrtRatio, MAX_SQRT_RATIO_RAW)))
                                )
                        }
                    }
                    error ValueOverflowsSqrtRatioContainer();
                    // If passing a value greater than this constant with roundUp = true, toSqrtRatio will overflow
                    // For roundUp = false, the constant is type(uint192).max
                    uint256 constant MAX_FIXED_VALUE_ROUND_UP =
                        0x1000000000000000000000000000000000000000000000000 - 0x4000000000000000000000000;
                    // Converts a 64.128 value into the compact SqrtRatio representation
                    function toSqrtRatio(uint256 sqrtRatio, bool roundUp) pure returns (SqrtRatio r) {
                        assembly ("memory-safe") {
                            let addend := mul(roundUp, 0x3)
                            // lt 2**96 after rounding up
                            switch lt(sqrtRatio, sub(0x1000000000000000000000000, addend))
                            case 1 { r := shr(2, add(sqrtRatio, addend)) }
                            default {
                                // 2**34 - 1
                                addend := mul(roundUp, 0x3ffffffff)
                                // lt 2**128 after rounding up
                                switch lt(sqrtRatio, sub(0x100000000000000000000000000000000, addend))
                                case 1 { r := or(TWO_POW_94, shr(34, add(sqrtRatio, addend))) }
                                default {
                                    addend := mul(roundUp, 0x3ffffffffffffffff)
                                    // lt 2**160 after rounding up
                                    switch lt(sqrtRatio, sub(0x10000000000000000000000000000000000000000, addend))
                                    case 1 { r := or(TWO_POW_95, shr(66, add(sqrtRatio, addend))) }
                                    default {
                                        // 2**98 - 1
                                        addend := mul(roundUp, 0x3ffffffffffffffffffffffff)
                                        switch lt(sqrtRatio, sub(0x1000000000000000000000000000000000000000000000000, addend))
                                        case 1 { r := or(BIT_MASK, shr(98, add(sqrtRatio, addend))) }
                                        default {
                                            // cast sig "ValueOverflowsSqrtRatioContainer()"
                                            mstore(0, shl(224, 0xa10459f4))
                                            revert(0, 4)
                                        }
                                    }
                                }
                            }
                        }
                    }
                    // Returns the 64.128 representation of the given sqrt ratio
                    function toFixed(SqrtRatio sqrtRatio) pure returns (uint256 r) {
                        assembly ("memory-safe") {
                            r := shl(add(2, shr(89, and(sqrtRatio, BIT_MASK))), and(sqrtRatio, not(BIT_MASK)))
                        }
                    }
                    // The below operators assume that the SqrtRatio is valid, i.e. SqrtRatio#isValid returns true
                    function lt(SqrtRatio a, SqrtRatio b) pure returns (bool r) {
                        r = SqrtRatio.unwrap(a) < SqrtRatio.unwrap(b);
                    }
                    function gt(SqrtRatio a, SqrtRatio b) pure returns (bool r) {
                        r = SqrtRatio.unwrap(a) > SqrtRatio.unwrap(b);
                    }
                    function le(SqrtRatio a, SqrtRatio b) pure returns (bool r) {
                        r = SqrtRatio.unwrap(a) <= SqrtRatio.unwrap(b);
                    }
                    function ge(SqrtRatio a, SqrtRatio b) pure returns (bool r) {
                        r = SqrtRatio.unwrap(a) >= SqrtRatio.unwrap(b);
                    }
                    function eq(SqrtRatio a, SqrtRatio b) pure returns (bool r) {
                        r = SqrtRatio.unwrap(a) == SqrtRatio.unwrap(b);
                    }
                    function neq(SqrtRatio a, SqrtRatio b) pure returns (bool r) {
                        r = SqrtRatio.unwrap(a) != SqrtRatio.unwrap(b);
                    }
                    function isZero(SqrtRatio a) pure returns (bool r) {
                        assembly ("memory-safe") {
                            r := iszero(a)
                        }
                    }
                    function max(SqrtRatio a, SqrtRatio b) pure returns (SqrtRatio r) {
                        assembly ("memory-safe") {
                            r := xor(a, mul(xor(a, b), gt(b, a)))
                        }
                    }
                    function min(SqrtRatio a, SqrtRatio b) pure returns (SqrtRatio r) {
                        assembly ("memory-safe") {
                            r := xor(a, mul(xor(a, b), lt(b, a)))
                        }
                    }
                    // SPDX-License-Identifier: UNLICENSED
                    pragma solidity =0.8.28;
                    import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol";
                    import {SqrtRatio, toSqrtRatio, MAX_FIXED_VALUE_ROUND_UP} from "../types/sqrtRatio.sol";
                    error ZeroLiquidityNextSqrtRatioFromAmount0();
                    // Compute the next ratio from a delta amount0, always rounded towards starting price for input, and
                    // away from starting price for output
                    function nextSqrtRatioFromAmount0(SqrtRatio _sqrtRatio, uint128 liquidity, int128 amount)
                        pure
                        returns (SqrtRatio sqrtRatioNext)
                    {
                        if (amount == 0) {
                            return _sqrtRatio;
                        }
                        if (liquidity == 0) {
                            revert ZeroLiquidityNextSqrtRatioFromAmount0();
                        }
                        uint256 sqrtRatio = _sqrtRatio.toFixed();
                        uint256 liquidityX128 = uint256(liquidity) << 128;
                        uint256 amountAbs = FixedPointMathLib.abs(int256(amount));
                        if (amount < 0) {
                            unchecked {
                                // multiplication will revert on overflow, so we return the maximum value for the type
                                if (amountAbs > type(uint256).max / sqrtRatio) {
                                    return SqrtRatio.wrap(type(uint96).max);
                                }
                                uint256 product = sqrtRatio * amountAbs;
                                // again it will overflow if this is the case, so return the max value
                                if (product >= liquidityX128) {
                                    return SqrtRatio.wrap(type(uint96).max);
                                }
                                uint256 denominator = liquidityX128 - product;
                                uint256 resultFixed = FixedPointMathLib.fullMulDivUp(liquidityX128, sqrtRatio, denominator);
                                if (resultFixed > MAX_FIXED_VALUE_ROUND_UP) {
                                    return SqrtRatio.wrap(type(uint96).max);
                                }
                                sqrtRatioNext = toSqrtRatio(resultFixed, true);
                            }
                        } else {
                            uint256 denominator;
                            unchecked {
                                uint256 denominatorP1 = liquidityX128 / sqrtRatio;
                                // this can never overflow, amountAbs is limited to 2**128-1 and liquidityX128 / sqrtRatio is limited to (2**128-1 << 128)
                                // adding the 2 values can at most equal type(uint256).max
                                denominator = denominatorP1 + amountAbs;
                            }
                            sqrtRatioNext = toSqrtRatio(FixedPointMathLib.divUp(liquidityX128, denominator), true);
                        }
                    }
                    error ZeroLiquidityNextSqrtRatioFromAmount1();
                    function nextSqrtRatioFromAmount1(SqrtRatio _sqrtRatio, uint128 liquidity, int128 amount)
                        pure
                        returns (SqrtRatio sqrtRatioNext)
                    {
                        if (amount == 0) {
                            return _sqrtRatio;
                        }
                        if (liquidity == 0) {
                            revert ZeroLiquidityNextSqrtRatioFromAmount1();
                        }
                        uint256 sqrtRatio = _sqrtRatio.toFixed();
                        unchecked {
                            uint256 shiftedAmountAbs = FixedPointMathLib.abs(int256(amount)) << 128;
                            uint256 quotient = shiftedAmountAbs / liquidity;
                            if (amount < 0) {
                                if (quotient >= sqrtRatio) {
                                    // Underflow => return 0
                                    return SqrtRatio.wrap(0);
                                }
                                uint256 sqrtRatioNextFixed = sqrtRatio - quotient;
                                assembly ("memory-safe") {
                                    // subtraction of 1 is safe because sqrtRatio > quotient => sqrtRatio - quotient >= 1
                                    sqrtRatioNextFixed := sub(sqrtRatioNextFixed, iszero(iszero(mod(shiftedAmountAbs, liquidity))))
                                }
                                sqrtRatioNext = toSqrtRatio(sqrtRatioNextFixed, false);
                            } else {
                                uint256 sum = sqrtRatio + quotient;
                                if (sum < sqrtRatio || sum > type(uint192).max) {
                                    return SqrtRatio.wrap(type(uint96).max);
                                }
                                sqrtRatioNext = toSqrtRatio(sum, false);
                            }
                        }
                    }
                    // SPDX-License-Identifier: UNLICENSED
                    pragma solidity =0.8.28;
                    import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol";
                    import {SqrtRatio} from "../types/sqrtRatio.sol";
                    error Amount0DeltaOverflow();
                    error Amount1DeltaOverflow();
                    function sortAndConvertToFixedSqrtRatios(SqrtRatio sqrtRatioA, SqrtRatio sqrtRatioB)
                        pure
                        returns (uint256 sqrtRatioLower, uint256 sqrtRatioUpper)
                    {
                        uint256 aFixed = sqrtRatioA.toFixed();
                        uint256 bFixed = sqrtRatioB.toFixed();
                        (sqrtRatioLower, sqrtRatioUpper) = (FixedPointMathLib.min(aFixed, bFixed), FixedPointMathLib.max(aFixed, bFixed));
                    }
                    function amount0Delta(SqrtRatio sqrtRatioA, SqrtRatio sqrtRatioB, uint128 liquidity, bool roundUp)
                        pure
                        returns (uint128 amount0)
                    {
                        unchecked {
                            (uint256 sqrtRatioLower, uint256 sqrtRatioUpper) = sortAndConvertToFixedSqrtRatios(sqrtRatioA, sqrtRatioB);
                            if (roundUp) {
                                uint256 result0 = FixedPointMathLib.fullMulDivUp(
                                    (uint256(liquidity) << 128), (sqrtRatioUpper - sqrtRatioLower), sqrtRatioUpper
                                );
                                uint256 result = FixedPointMathLib.divUp(result0, sqrtRatioLower);
                                if (result > type(uint128).max) revert Amount0DeltaOverflow();
                                amount0 = uint128(result);
                            } else {
                                uint256 result0 = FixedPointMathLib.fullMulDiv(
                                    (uint256(liquidity) << 128), (sqrtRatioUpper - sqrtRatioLower), sqrtRatioUpper
                                );
                                uint256 result = result0 / sqrtRatioLower;
                                if (result > type(uint128).max) revert Amount0DeltaOverflow();
                                amount0 = uint128(result);
                            }
                        }
                    }
                    function amount1Delta(SqrtRatio sqrtRatioA, SqrtRatio sqrtRatioB, uint128 liquidity, bool roundUp)
                        pure
                        returns (uint128 amount1)
                    {
                        unchecked {
                            (uint256 sqrtRatioLower, uint256 sqrtRatioUpper) = sortAndConvertToFixedSqrtRatios(sqrtRatioA, sqrtRatioB);
                            uint256 difference = sqrtRatioUpper - sqrtRatioLower;
                            if (roundUp) {
                                uint256 result = FixedPointMathLib.fullMulDivN(difference, liquidity, 128);
                                assembly {
                                    // addition is safe from overflow because the result of fullMulDivN will never equal type(uint256).max
                                    result :=
                                        add(result, iszero(iszero(mulmod(difference, liquidity, 0x100000000000000000000000000000000))))
                                }
                                if (result > type(uint128).max) revert Amount1DeltaOverflow();
                                amount1 = uint128(result);
                            } else {
                                uint256 result = FixedPointMathLib.fullMulDivN(difference, liquidity, 128);
                                if (result > type(uint128).max) revert Amount1DeltaOverflow();
                                amount1 = uint128(result);
                            }
                        }
                    }
                    // SPDX-License-Identifier: UNLICENSED
                    pragma solidity =0.8.28;
                    function isPriceIncreasing(int128 amount, bool isToken1) pure returns (bool increasing) {
                        assembly ("memory-safe") {
                            increasing := xor(isToken1, slt(amount, 0))
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.8.4;
                    /// @notice Library for bit twiddling and boolean operations.
                    /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/LibBit.sol)
                    /// @author Inspired by (https://graphics.stanford.edu/~seander/bithacks.html)
                    library LibBit {
                        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                        /*                  BIT TWIDDLING OPERATIONS                  */
                        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                        /// @dev Find last set.
                        /// Returns the index of the most significant bit of `x`,
                        /// counting from the least significant bit position.
                        /// If `x` is zero, returns 256.
                        function fls(uint256 x) internal pure returns (uint256 r) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                r := or(shl(8, iszero(x)), shl(7, lt(0xffffffffffffffffffffffffffffffff, x)))
                                r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
                                r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
                                r := or(r, shl(4, lt(0xffff, shr(r, x))))
                                r := or(r, shl(3, lt(0xff, shr(r, x))))
                                // forgefmt: disable-next-item
                                r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                                    0x0706060506020504060203020504030106050205030304010505030400000000))
                            }
                        }
                        /// @dev Count leading zeros.
                        /// Returns the number of zeros preceding the most significant one bit.
                        /// If `x` is zero, returns 256.
                        function clz(uint256 x) internal pure returns (uint256 r) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
                                r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
                                r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
                                r := or(r, shl(4, lt(0xffff, shr(r, x))))
                                r := or(r, shl(3, lt(0xff, shr(r, x))))
                                // forgefmt: disable-next-item
                                r := add(xor(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                                    0xf8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff)), iszero(x))
                            }
                        }
                        /// @dev Find first set.
                        /// Returns the index of the least significant bit of `x`,
                        /// counting from the least significant bit position.
                        /// If `x` is zero, returns 256.
                        /// Equivalent to `ctz` (count trailing zeros), which gives
                        /// the number of zeros following the least significant one bit.
                        function ffs(uint256 x) internal pure returns (uint256 r) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                // Isolate the least significant bit.
                                x := and(x, add(not(x), 1))
                                // For the upper 3 bits of the result, use a De Bruijn-like lookup.
                                // Credit to adhusson: https://blog.adhusson.com/cheap-find-first-set-evm/
                                // forgefmt: disable-next-item
                                r := shl(5, shr(252, shl(shl(2, shr(250, mul(x,
                                    0xb6db6db6ddddddddd34d34d349249249210842108c6318c639ce739cffffffff))),
                                    0x8040405543005266443200005020610674053026020000107506200176117077)))
                                // For the lower 5 bits of the result, use a De Bruijn lookup.
                                // forgefmt: disable-next-item
                                r := or(r, byte(and(div(0xd76453e0, shr(r, x)), 0x1f),
                                    0x001f0d1e100c1d070f090b19131c1706010e11080a1a141802121b1503160405))
                            }
                        }
                        /// @dev Returns the number of set bits in `x`.
                        function popCount(uint256 x) internal pure returns (uint256 c) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                let max := not(0)
                                let isMax := eq(x, max)
                                x := sub(x, and(shr(1, x), div(max, 3)))
                                x := add(and(x, div(max, 5)), and(shr(2, x), div(max, 5)))
                                x := and(add(x, shr(4, x)), div(max, 17))
                                c := or(shl(8, isMax), shr(248, mul(x, div(max, 255))))
                            }
                        }
                        /// @dev Returns whether `x` is a power of 2.
                        function isPo2(uint256 x) internal pure returns (bool result) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                // Equivalent to `x && !(x & (x - 1))`.
                                result := iszero(add(and(x, sub(x, 1)), iszero(x)))
                            }
                        }
                        /// @dev Returns `x` reversed at the bit level.
                        function reverseBits(uint256 x) internal pure returns (uint256 r) {
                            uint256 m0 = 0x0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f;
                            uint256 m1 = m0 ^ (m0 << 2);
                            uint256 m2 = m1 ^ (m1 << 1);
                            r = reverseBytes(x);
                            r = (m2 & (r >> 1)) | ((m2 & r) << 1);
                            r = (m1 & (r >> 2)) | ((m1 & r) << 2);
                            r = (m0 & (r >> 4)) | ((m0 & r) << 4);
                        }
                        /// @dev Returns `x` reversed at the byte level.
                        function reverseBytes(uint256 x) internal pure returns (uint256 r) {
                            unchecked {
                                // Computing masks on-the-fly reduces bytecode size by about 200 bytes.
                                uint256 m0 = 0x100000000000000000000000000000001 * (~toUint(x == uint256(0)) >> 192);
                                uint256 m1 = m0 ^ (m0 << 32);
                                uint256 m2 = m1 ^ (m1 << 16);
                                uint256 m3 = m2 ^ (m2 << 8);
                                r = (m3 & (x >> 8)) | ((m3 & x) << 8);
                                r = (m2 & (r >> 16)) | ((m2 & r) << 16);
                                r = (m1 & (r >> 32)) | ((m1 & r) << 32);
                                r = (m0 & (r >> 64)) | ((m0 & r) << 64);
                                r = (r >> 128) | (r << 128);
                            }
                        }
                        /// @dev Returns the common prefix of `x` and `y` at the bit level.
                        function commonBitPrefix(uint256 x, uint256 y) internal pure returns (uint256) {
                            unchecked {
                                uint256 s = 256 - clz(x ^ y);
                                return (x >> s) << s;
                            }
                        }
                        /// @dev Returns the common prefix of `x` and `y` at the nibble level.
                        function commonNibblePrefix(uint256 x, uint256 y) internal pure returns (uint256) {
                            unchecked {
                                uint256 s = (64 - (clz(x ^ y) >> 2)) << 2;
                                return (x >> s) << s;
                            }
                        }
                        /// @dev Returns the common prefix of `x` and `y` at the byte level.
                        function commonBytePrefix(uint256 x, uint256 y) internal pure returns (uint256) {
                            unchecked {
                                uint256 s = (32 - (clz(x ^ y) >> 3)) << 3;
                                return (x >> s) << s;
                            }
                        }
                        /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
                        /*                     BOOLEAN OPERATIONS                     */
                        /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
                        // A Solidity bool on the stack or memory is represented as a 256-bit word.
                        // Non-zero values are true, zero is false.
                        // A clean bool is either 0 (false) or 1 (true) under the hood.
                        // Usually, if not always, the bool result of a regular Solidity expression,
                        // or the argument of a public/external function will be a clean bool.
                        // You can usually use the raw variants for more performance.
                        // If uncertain, test (best with exact compiler settings).
                        // Or use the non-raw variants (compiler can sometimes optimize out the double `iszero`s).
                        /// @dev Returns `x & y`. Inputs must be clean.
                        function rawAnd(bool x, bool y) internal pure returns (bool z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := and(x, y)
                            }
                        }
                        /// @dev Returns `x & y`.
                        function and(bool x, bool y) internal pure returns (bool z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := and(iszero(iszero(x)), iszero(iszero(y)))
                            }
                        }
                        /// @dev Returns `x | y`. Inputs must be clean.
                        function rawOr(bool x, bool y) internal pure returns (bool z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := or(x, y)
                            }
                        }
                        /// @dev Returns `x | y`.
                        function or(bool x, bool y) internal pure returns (bool z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := or(iszero(iszero(x)), iszero(iszero(y)))
                            }
                        }
                        /// @dev Returns 1 if `b` is true, else 0. Input must be clean.
                        function rawToUint(bool b) internal pure returns (uint256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := b
                            }
                        }
                        /// @dev Returns 1 if `b` is true, else 0.
                        function toUint(bool b) internal pure returns (uint256 z) {
                            /// @solidity memory-safe-assembly
                            assembly {
                                z := iszero(iszero(b))
                            }
                        }
                    }
                    // SPDX-License-Identifier: UNLICENSED
                    pragma solidity =0.8.28;
                    // Exposes all the storage of a contract via view methods.
                    // Absent https://eips.ethereum.org/EIPS/eip-2330 this makes it easier to access specific pieces of state in the inheriting contract.
                    interface IExposedStorage {
                        // Loads each slot after the function selector from the contract's storage and returns all of them.
                        function sload() external view;
                        // Loads each slot after the function selector from the contract's transient storage and returns all of them.
                        function tload() external view;
                    }
                    // SPDX-License-Identifier: UNLICENSED
                    pragma solidity =0.8.28;
                    interface ILocker {
                        function locked(uint256 id) external;
                    }
                    interface IForwardee {
                        function forwarded(uint256 id, address originalLocker) external;
                    }
                    interface IPayer {
                        function payCallback(uint256 id, address token) external;
                    }
                    interface IFlashAccountant {
                        error NotLocked();
                        error LockerOnly();
                        error NoPaymentMade();
                        error DebtsNotZeroed(uint256 id);
                        // Thrown if the contract receives too much payment in the payment callback or from a direct native token transfer
                        error PaymentOverflow();
                        error PayReentrance();
                        // Create a lock context
                        // Any data passed after the function signature is passed through back to the caller after the locked function signature and data, with no additional encoding
                        // In addition, any data returned from ILocker#locked is also returned from this function exactly as is, i.e. with no additional encoding or decoding
                        // Reverts are also bubbled up
                        function lock() external;
                        // Forward the lock from the current locker to the given address
                        // Any additional calldata is also passed through to the forwardee, with no additional encoding
                        // In addition, any data returned from IForwardee#forwarded is also returned from this function exactly as is, i.e. with no additional encoding or decoding
                        // Reverts are also bubbled up
                        function forward(address to) external;
                        // Pays the given amount of token, by calling the payCallback function on the caller to afford them the opportunity to make the payment.
                        // This function, unlike lock and forward, does not return any of the returndata from the callback.
                        // This function also cannot be re-entered like lock and forward.
                        // Must be locked, as the contract accounts the payment against the current locker's debts.
                        // Token must not be the NATIVE_TOKEN_ADDRESS, as the `balanceOf` calls will fail.
                        // If you want to pay in the chain's native token, simply transfer it to this contract using a call.
                        // The payer must implement payCallback in which they must transfer the token to Core.
                        function pay(address token) external returns (uint128 payment);
                        // Withdraws a token amount from the accountant to the given recipient.
                        // The contract must be locked, as it tracks the withdrawn amount against the current locker's delta.
                        function withdraw(address token, address recipient, uint128 amount) external;
                        // This contract can receive ETH as a payment as well
                        receive() external payable;
                    }
                    

                    File 4 of 9: TransparentUpgradeableProxy
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.8.0;
                    import "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol";
                    import "@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol";
                    import "@openzeppelin/contracts/proxy/transparent/ProxyAdmin.sol";
                    // Kept for backwards compatibility with older versions of Hardhat and Truffle plugins.
                    contract AdminUpgradeabilityProxy is TransparentUpgradeableProxy {
                        constructor(address logic, address admin, bytes memory data) payable TransparentUpgradeableProxy(logic, admin, data) {}
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.8.0;
                    import "../Proxy.sol";
                    import "./ERC1967Upgrade.sol";
                    /**
                     * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
                     * implementation address that can be changed. This address is stored in storage in the location specified by
                     * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
                     * implementation behind the proxy.
                     */
                    contract ERC1967Proxy is Proxy, ERC1967Upgrade {
                        /**
                         * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
                         *
                         * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded
                         * function call, and allows initializating the storage of the proxy like a Solidity constructor.
                         */
                        constructor(address _logic, bytes memory _data) payable {
                            assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
                            _upgradeToAndCall(_logic, _data, false);
                        }
                        /**
                         * @dev Returns the current implementation address.
                         */
                        function _implementation() internal view virtual override returns (address impl) {
                            return ERC1967Upgrade._getImplementation();
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.8.0;
                    import "../ERC1967/ERC1967Proxy.sol";
                    /**
                     * @dev This contract implements a proxy that is upgradeable by an admin.
                     *
                     * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector
                     * clashing], which can potentially be used in an attack, this contract uses the
                     * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two
                     * things that go hand in hand:
                     *
                     * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if
                     * that call matches one of the admin functions exposed by the proxy itself.
                     * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the
                     * implementation. If the admin tries to call a function on the implementation it will fail with an error that says
                     * "admin cannot fallback to proxy target".
                     *
                     * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing
                     * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due
                     * to sudden errors when trying to call a function from the proxy implementation.
                     *
                     * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way,
                     * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.
                     */
                    contract TransparentUpgradeableProxy is ERC1967Proxy {
                        /**
                         * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and
                         * optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}.
                         */
                        constructor(address _logic, address admin_, bytes memory _data) payable ERC1967Proxy(_logic, _data) {
                            assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1));
                            _changeAdmin(admin_);
                        }
                        /**
                         * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin.
                         */
                        modifier ifAdmin() {
                            if (msg.sender == _getAdmin()) {
                                _;
                            } else {
                                _fallback();
                            }
                        }
                        /**
                         * @dev Returns the current admin.
                         *
                         * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}.
                         *
                         * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
                         * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
                         * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
                         */
                        function admin() external ifAdmin returns (address admin_) {
                            admin_ = _getAdmin();
                        }
                        /**
                         * @dev Returns the current implementation.
                         *
                         * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}.
                         *
                         * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
                         * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
                         * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
                         */
                        function implementation() external ifAdmin returns (address implementation_) {
                            implementation_ = _implementation();
                        }
                        /**
                         * @dev Changes the admin of the proxy.
                         *
                         * Emits an {AdminChanged} event.
                         *
                         * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}.
                         */
                        function changeAdmin(address newAdmin) external virtual ifAdmin {
                            _changeAdmin(newAdmin);
                        }
                        /**
                         * @dev Upgrade the implementation of the proxy.
                         *
                         * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}.
                         */
                        function upgradeTo(address newImplementation) external ifAdmin {
                            _upgradeToAndCall(newImplementation, bytes(""), false);
                        }
                        /**
                         * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified
                         * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the
                         * proxied contract.
                         *
                         * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}.
                         */
                        function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin {
                            _upgradeToAndCall(newImplementation, data, true);
                        }
                        /**
                         * @dev Returns the current admin.
                         */
                        function _admin() internal view virtual returns (address) {
                            return _getAdmin();
                        }
                        /**
                         * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}.
                         */
                        function _beforeFallback() internal virtual override {
                            require(msg.sender != _getAdmin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target");
                            super._beforeFallback();
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.8.0;
                    import "./TransparentUpgradeableProxy.sol";
                    import "../../access/Ownable.sol";
                    /**
                     * @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an
                     * explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}.
                     */
                    contract ProxyAdmin is Ownable {
                        /**
                         * @dev Returns the current implementation of `proxy`.
                         *
                         * Requirements:
                         *
                         * - This contract must be the admin of `proxy`.
                         */
                        function getProxyImplementation(TransparentUpgradeableProxy proxy) public view virtual returns (address) {
                            // We need to manually run the static call since the getter cannot be flagged as view
                            // bytes4(keccak256("implementation()")) == 0x5c60da1b
                            (bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b");
                            require(success);
                            return abi.decode(returndata, (address));
                        }
                        /**
                         * @dev Returns the current admin of `proxy`.
                         *
                         * Requirements:
                         *
                         * - This contract must be the admin of `proxy`.
                         */
                        function getProxyAdmin(TransparentUpgradeableProxy proxy) public view virtual returns (address) {
                            // We need to manually run the static call since the getter cannot be flagged as view
                            // bytes4(keccak256("admin()")) == 0xf851a440
                            (bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440");
                            require(success);
                            return abi.decode(returndata, (address));
                        }
                        /**
                         * @dev Changes the admin of `proxy` to `newAdmin`.
                         *
                         * Requirements:
                         *
                         * - This contract must be the current admin of `proxy`.
                         */
                        function changeProxyAdmin(TransparentUpgradeableProxy proxy, address newAdmin) public virtual onlyOwner {
                            proxy.changeAdmin(newAdmin);
                        }
                        /**
                         * @dev Upgrades `proxy` to `implementation`. See {TransparentUpgradeableProxy-upgradeTo}.
                         *
                         * Requirements:
                         *
                         * - This contract must be the admin of `proxy`.
                         */
                        function upgrade(TransparentUpgradeableProxy proxy, address implementation) public virtual onlyOwner {
                            proxy.upgradeTo(implementation);
                        }
                        /**
                         * @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. See
                         * {TransparentUpgradeableProxy-upgradeToAndCall}.
                         *
                         * Requirements:
                         *
                         * - This contract must be the admin of `proxy`.
                         */
                        function upgradeAndCall(TransparentUpgradeableProxy proxy, address implementation, bytes memory data) public payable virtual onlyOwner {
                            proxy.upgradeToAndCall{value: msg.value}(implementation, data);
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.8.0;
                    /**
                     * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
                     * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
                     * be specified by overriding the virtual {_implementation} function.
                     *
                     * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
                     * different contract through the {_delegate} function.
                     *
                     * The success and return data of the delegated call will be returned back to the caller of the proxy.
                     */
                    abstract contract Proxy {
                        /**
                         * @dev Delegates the current call to `implementation`.
                         *
                         * This function does not return to its internall call site, it will return directly to the external caller.
                         */
                        function _delegate(address implementation) internal virtual {
                            // solhint-disable-next-line no-inline-assembly
                            assembly {
                                // Copy msg.data. We take full control of memory in this inline assembly
                                // block because it will not return to Solidity code. We overwrite the
                                // Solidity scratch pad at memory position 0.
                                calldatacopy(0, 0, calldatasize())
                                // Call the implementation.
                                // out and outsize are 0 because we don't know the size yet.
                                let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
                                // Copy the returned data.
                                returndatacopy(0, 0, returndatasize())
                                switch result
                                // delegatecall returns 0 on error.
                                case 0 { revert(0, returndatasize()) }
                                default { return(0, returndatasize()) }
                            }
                        }
                        /**
                         * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
                         * and {_fallback} should delegate.
                         */
                        function _implementation() internal view virtual returns (address);
                        /**
                         * @dev Delegates the current call to the address returned by `_implementation()`.
                         *
                         * This function does not return to its internall call site, it will return directly to the external caller.
                         */
                        function _fallback() internal virtual {
                            _beforeFallback();
                            _delegate(_implementation());
                        }
                        /**
                         * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
                         * function in the contract matches the call data.
                         */
                        fallback () external payable virtual {
                            _fallback();
                        }
                        /**
                         * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
                         * is empty.
                         */
                        receive () external payable virtual {
                            _fallback();
                        }
                        /**
                         * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
                         * call, or as part of the Solidity `fallback` or `receive` functions.
                         *
                         * If overriden should call `super._beforeFallback()`.
                         */
                        function _beforeFallback() internal virtual {
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.8.2;
                    import "../beacon/IBeacon.sol";
                    import "../../utils/Address.sol";
                    import "../../utils/StorageSlot.sol";
                    /**
                     * @dev This abstract contract provides getters and event emitting update functions for
                     * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
                     *
                     * _Available since v4.1._
                     *
                     * @custom:oz-upgrades-unsafe-allow delegatecall
                     */
                    abstract contract ERC1967Upgrade {
                        // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
                        bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
                        /**
                         * @dev Storage slot with the address of the current implementation.
                         * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
                         * validated in the constructor.
                         */
                        bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
                        /**
                         * @dev Emitted when the implementation is upgraded.
                         */
                        event Upgraded(address indexed implementation);
                        /**
                         * @dev Returns the current implementation address.
                         */
                        function _getImplementation() internal view returns (address) {
                            return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
                        }
                        /**
                         * @dev Stores a new address in the EIP1967 implementation slot.
                         */
                        function _setImplementation(address newImplementation) private {
                            require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
                            StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
                        }
                        /**
                         * @dev Perform implementation upgrade
                         *
                         * Emits an {Upgraded} event.
                         */
                        function _upgradeTo(address newImplementation) internal {
                            _setImplementation(newImplementation);
                            emit Upgraded(newImplementation);
                        }
                        /**
                         * @dev Perform implementation upgrade with additional setup call.
                         *
                         * Emits an {Upgraded} event.
                         */
                        function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal {
                            _setImplementation(newImplementation);
                            emit Upgraded(newImplementation);
                            if (data.length > 0 || forceCall) {
                                Address.functionDelegateCall(newImplementation, data);
                            }
                        }
                        /**
                         * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
                         *
                         * Emits an {Upgraded} event.
                         */
                        function _upgradeToAndCallSecure(address newImplementation, bytes memory data, bool forceCall) internal {
                            address oldImplementation = _getImplementation();
                            // Initial upgrade and setup call
                            _setImplementation(newImplementation);
                            if (data.length > 0 || forceCall) {
                                Address.functionDelegateCall(newImplementation, data);
                            }
                            // Perform rollback test if not already in progress
                            StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot(_ROLLBACK_SLOT);
                            if (!rollbackTesting.value) {
                                // Trigger rollback using upgradeTo from the new implementation
                                rollbackTesting.value = true;
                                Address.functionDelegateCall(
                                    newImplementation,
                                    abi.encodeWithSignature(
                                        "upgradeTo(address)",
                                        oldImplementation
                                    )
                                );
                                rollbackTesting.value = false;
                                // Check rollback was effective
                                require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
                                // Finally reset to the new implementation and log the upgrade
                                _setImplementation(newImplementation);
                                emit Upgraded(newImplementation);
                            }
                        }
                        /**
                         * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
                         * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
                         *
                         * Emits a {BeaconUpgraded} event.
                         */
                        function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal {
                            _setBeacon(newBeacon);
                            emit BeaconUpgraded(newBeacon);
                            if (data.length > 0 || forceCall) {
                                Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
                            }
                        }
                        /**
                         * @dev Storage slot with the admin of the contract.
                         * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
                         * validated in the constructor.
                         */
                        bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
                        /**
                         * @dev Emitted when the admin account has changed.
                         */
                        event AdminChanged(address previousAdmin, address newAdmin);
                        /**
                         * @dev Returns the current admin.
                         */
                        function _getAdmin() internal view returns (address) {
                            return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
                        }
                        /**
                         * @dev Stores a new address in the EIP1967 admin slot.
                         */
                        function _setAdmin(address newAdmin) private {
                            require(newAdmin != address(0), "ERC1967: new admin is the zero address");
                            StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
                        }
                        /**
                         * @dev Changes the admin of the proxy.
                         *
                         * Emits an {AdminChanged} event.
                         */
                        function _changeAdmin(address newAdmin) internal {
                            emit AdminChanged(_getAdmin(), newAdmin);
                            _setAdmin(newAdmin);
                        }
                        /**
                         * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
                         * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
                         */
                        bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
                        /**
                         * @dev Emitted when the beacon is upgraded.
                         */
                        event BeaconUpgraded(address indexed beacon);
                        /**
                         * @dev Returns the current beacon.
                         */
                        function _getBeacon() internal view returns (address) {
                            return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
                        }
                        /**
                         * @dev Stores a new beacon in the EIP1967 beacon slot.
                         */
                        function _setBeacon(address newBeacon) private {
                            require(
                                Address.isContract(newBeacon),
                                "ERC1967: new beacon is not a contract"
                            );
                            require(
                                Address.isContract(IBeacon(newBeacon).implementation()),
                                "ERC1967: beacon implementation is not a contract"
                            );
                            StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.8.0;
                    /**
                     * @dev This is the interface that {BeaconProxy} expects of its beacon.
                     */
                    interface IBeacon {
                        /**
                         * @dev Must return an address that can be used as a delegate call target.
                         *
                         * {BeaconProxy} will check that this address is a contract.
                         */
                        function implementation() external view returns (address);
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.8.0;
                    /**
                     * @dev Collection of functions related to the address type
                     */
                    library Address {
                        /**
                         * @dev Returns true if `account` is a contract.
                         *
                         * [IMPORTANT]
                         * ====
                         * It is unsafe to assume that an address for which this function returns
                         * false is an externally-owned account (EOA) and not a contract.
                         *
                         * Among others, `isContract` will return false for the following
                         * types of addresses:
                         *
                         *  - an externally-owned account
                         *  - a contract in construction
                         *  - an address where a contract will be created
                         *  - an address where a contract lived, but was destroyed
                         * ====
                         */
                        function isContract(address account) internal view returns (bool) {
                            // This method relies on extcodesize, which returns 0 for contracts in
                            // construction, since the code is only stored at the end of the
                            // constructor execution.
                            uint256 size;
                            // solhint-disable-next-line no-inline-assembly
                            assembly { size := extcodesize(account) }
                            return size > 0;
                        }
                        /**
                         * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
                         * `recipient`, forwarding all available gas and reverting on errors.
                         *
                         * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
                         * of certain opcodes, possibly making contracts go over the 2300 gas limit
                         * imposed by `transfer`, making them unable to receive funds via
                         * `transfer`. {sendValue} removes this limitation.
                         *
                         * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
                         *
                         * IMPORTANT: because control is transferred to `recipient`, care must be
                         * taken to not create reentrancy vulnerabilities. Consider using
                         * {ReentrancyGuard} or the
                         * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                         */
                        function sendValue(address payable recipient, uint256 amount) internal {
                            require(address(this).balance >= amount, "Address: insufficient balance");
                            // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
                            (bool success, ) = recipient.call{ value: amount }("");
                            require(success, "Address: unable to send value, recipient may have reverted");
                        }
                        /**
                         * @dev Performs a Solidity function call using a low level `call`. A
                         * plain`call` is an unsafe replacement for a function call: use this
                         * function instead.
                         *
                         * If `target` reverts with a revert reason, it is bubbled up by this
                         * function (like regular Solidity function calls).
                         *
                         * Returns the raw returned data. To convert to the expected return value,
                         * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
                         *
                         * Requirements:
                         *
                         * - `target` must be a contract.
                         * - calling `target` with `data` must not revert.
                         *
                         * _Available since v3.1._
                         */
                        function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                          return functionCall(target, data, "Address: low-level call failed");
                        }
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
                         * `errorMessage` as a fallback revert reason when `target` reverts.
                         *
                         * _Available since v3.1._
                         */
                        function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
                            return functionCallWithValue(target, data, 0, errorMessage);
                        }
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                         * but also transferring `value` wei to `target`.
                         *
                         * Requirements:
                         *
                         * - the calling contract must have an ETH balance of at least `value`.
                         * - the called Solidity function must be `payable`.
                         *
                         * _Available since v3.1._
                         */
                        function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
                            return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
                        }
                        /**
                         * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
                         * with `errorMessage` as a fallback revert reason when `target` reverts.
                         *
                         * _Available since v3.1._
                         */
                        function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
                            require(address(this).balance >= value, "Address: insufficient balance for call");
                            require(isContract(target), "Address: call to non-contract");
                            // solhint-disable-next-line avoid-low-level-calls
                            (bool success, bytes memory returndata) = target.call{ value: value }(data);
                            return _verifyCallResult(success, returndata, errorMessage);
                        }
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                         * but performing a static call.
                         *
                         * _Available since v3.3._
                         */
                        function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                            return functionStaticCall(target, data, "Address: low-level static call failed");
                        }
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                         * but performing a static call.
                         *
                         * _Available since v3.3._
                         */
                        function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
                            require(isContract(target), "Address: static call to non-contract");
                            // solhint-disable-next-line avoid-low-level-calls
                            (bool success, bytes memory returndata) = target.staticcall(data);
                            return _verifyCallResult(success, returndata, errorMessage);
                        }
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                         * but performing a delegate call.
                         *
                         * _Available since v3.4._
                         */
                        function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                            return functionDelegateCall(target, data, "Address: low-level delegate call failed");
                        }
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                         * but performing a delegate call.
                         *
                         * _Available since v3.4._
                         */
                        function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
                            require(isContract(target), "Address: delegate call to non-contract");
                            // solhint-disable-next-line avoid-low-level-calls
                            (bool success, bytes memory returndata) = target.delegatecall(data);
                            return _verifyCallResult(success, returndata, errorMessage);
                        }
                        function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
                            if (success) {
                                return returndata;
                            } else {
                                // Look for revert reason and bubble it up if present
                                if (returndata.length > 0) {
                                    // The easiest way to bubble the revert reason is using memory via assembly
                                    // solhint-disable-next-line no-inline-assembly
                                    assembly {
                                        let returndata_size := mload(returndata)
                                        revert(add(32, returndata), returndata_size)
                                    }
                                } else {
                                    revert(errorMessage);
                                }
                            }
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.8.0;
                    /**
                     * @dev Library for reading and writing primitive types to specific storage slots.
                     *
                     * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
                     * This library helps with reading and writing to such slots without the need for inline assembly.
                     *
                     * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
                     *
                     * Example usage to set ERC1967 implementation slot:
                     * ```
                     * contract ERC1967 {
                     *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
                     *
                     *     function _getImplementation() internal view returns (address) {
                     *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
                     *     }
                     *
                     *     function _setImplementation(address newImplementation) internal {
                     *         require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
                     *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
                     *     }
                     * }
                     * ```
                     *
                     * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
                     */
                    library StorageSlot {
                        struct AddressSlot {
                            address value;
                        }
                        struct BooleanSlot {
                            bool value;
                        }
                        struct Bytes32Slot {
                            bytes32 value;
                        }
                        struct Uint256Slot {
                            uint256 value;
                        }
                        /**
                         * @dev Returns an `AddressSlot` with member `value` located at `slot`.
                         */
                        function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
                            assembly {
                                r.slot := slot
                            }
                        }
                        /**
                         * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
                         */
                        function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
                            assembly {
                                r.slot := slot
                            }
                        }
                        /**
                         * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
                         */
                        function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
                            assembly {
                                r.slot := slot
                            }
                        }
                        /**
                         * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
                         */
                        function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
                            assembly {
                                r.slot := slot
                            }
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.8.0;
                    import "../utils/Context.sol";
                    /**
                     * @dev Contract module which provides a basic access control mechanism, where
                     * there is an account (an owner) that can be granted exclusive access to
                     * specific functions.
                     *
                     * By default, the owner account will be the one that deploys the contract. This
                     * can later be changed with {transferOwnership}.
                     *
                     * This module is used through inheritance. It will make available the modifier
                     * `onlyOwner`, which can be applied to your functions to restrict their use to
                     * the owner.
                     */
                    abstract contract Ownable is Context {
                        address private _owner;
                        event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                        /**
                         * @dev Initializes the contract setting the deployer as the initial owner.
                         */
                        constructor () {
                            address msgSender = _msgSender();
                            _owner = msgSender;
                            emit OwnershipTransferred(address(0), msgSender);
                        }
                        /**
                         * @dev Returns the address of the current owner.
                         */
                        function owner() public view virtual returns (address) {
                            return _owner;
                        }
                        /**
                         * @dev Throws if called by any account other than the owner.
                         */
                        modifier onlyOwner() {
                            require(owner() == _msgSender(), "Ownable: caller is not the owner");
                            _;
                        }
                        /**
                         * @dev Leaves the contract without owner. It will not be possible to call
                         * `onlyOwner` functions anymore. Can only be called by the current owner.
                         *
                         * NOTE: Renouncing ownership will leave the contract without an owner,
                         * thereby removing any functionality that is only available to the owner.
                         */
                        function renounceOwnership() public virtual onlyOwner {
                            emit OwnershipTransferred(_owner, address(0));
                            _owner = address(0);
                        }
                        /**
                         * @dev Transfers ownership of the contract to a new account (`newOwner`).
                         * Can only be called by the current owner.
                         */
                        function transferOwnership(address newOwner) public virtual onlyOwner {
                            require(newOwner != address(0), "Ownable: new owner is the zero address");
                            emit OwnershipTransferred(_owner, newOwner);
                            _owner = newOwner;
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.8.0;
                    /*
                     * @dev Provides information about the current execution context, including the
                     * sender of the transaction and its data. While these are generally available
                     * via msg.sender and msg.data, they should not be accessed in such a direct
                     * manner, since when dealing with meta-transactions the account sending and
                     * paying for execution may not be the actual sender (as far as an application
                     * is concerned).
                     *
                     * This contract is only required for intermediate, library-like contracts.
                     */
                    abstract contract Context {
                        function _msgSender() internal view virtual returns (address) {
                            return msg.sender;
                        }
                        function _msgData() internal view virtual returns (bytes calldata) {
                            this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
                            return msg.data;
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.8.0;
                    import "../ERC1967/ERC1967Upgrade.sol";
                    /**
                     * @dev Base contract for building openzeppelin-upgrades compatible implementations for the {ERC1967Proxy}. It includes
                     * publicly available upgrade functions that are called by the plugin and by the secure upgrade mechanism to verify
                     * continuation of the upgradability.
                     *
                     * The {_authorizeUpgrade} function MUST be overridden to include access restriction to the upgrade mechanism.
                     *
                     * _Available since v4.1._
                     */
                    abstract contract UUPSUpgradeable is ERC1967Upgrade {
                        function upgradeTo(address newImplementation) external virtual {
                            _authorizeUpgrade(newImplementation);
                            _upgradeToAndCallSecure(newImplementation, bytes(""), false);
                        }
                        function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual {
                            _authorizeUpgrade(newImplementation);
                            _upgradeToAndCallSecure(newImplementation, data, true);
                        }
                        function _authorizeUpgrade(address newImplementation) internal virtual;
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.8.2;
                    import "@openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol";
                    abstract contract Proxiable is UUPSUpgradeable {
                        function _authorizeUpgrade(address newImplementation) internal override {
                            _beforeUpgrade(newImplementation);
                        }
                        function _beforeUpgrade(address newImplementation) internal virtual;
                    }
                    contract ChildOfProxiable is Proxiable {
                        function _beforeUpgrade(address newImplementation) internal virtual override {}
                    }
                    

                    File 5 of 9: BridgeV2
                    // SPDX-License-Identifier: GPL-3.0
                    pragma solidity ^0.8.4;
                    import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
                    import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
                    import "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";
                    import "../../utils/AdminableUpgradeable.sol";
                    import "../../utils/RevertMessageParser.sol";
                    contract BridgeV2 is Initializable, AdminableUpgradeable {
                        /// ** PUBLIC states **
                        address public newMPC;
                        address public oldMPC;
                        uint256 public newMPCEffectiveTime;
                        mapping(address => bool) public isTransmitter;
                        /// ** EVENTS **
                        event LogChangeMPC(
                            address indexed oldMPC,
                            address indexed newMPC,
                            uint256 indexed effectiveTime,
                            uint256 chainId
                        );
                        event SetTransmitterStatus(address indexed transmitter, bool status);
                        event OracleRequest(
                            address bridge,
                            bytes callData,
                            address receiveSide,
                            address oppositeBridge,
                            uint256 chainId
                        );
                        /// ** MODIFIERs **
                        modifier onlyMPC() {
                            require(msg.sender == mpc(), "BridgeV2: forbidden");
                            _;
                        }
                        modifier onlyTransmitter() {
                            require(isTransmitter[msg.sender], "BridgeV2: not a transmitter");
                            _;
                        }
                        modifier onlyOwnerOrMPC() {
                            require(
                                mpc() == msg.sender || owner() == msg.sender,
                                "BridgeV2: only owner or MPC can call"
                            );
                            _;
                        }
                        modifier onlySignedByMPC(bytes32 hash, bytes memory signature) {
                            require(SignatureChecker.isValidSignatureNow(mpc(), hash, signature), "BridgeV2: invalid signature");
                            _;
                        }
                        /// ** INITIALIZER **
                        function initialize(address _mpc) public virtual initializer {
                            __Ownable_init();
                            newMPC = _mpc;
                            newMPCEffectiveTime = block.timestamp;
                        }
                        /// ** VIEW functions **
                        /**
                         * @notice Returns MPC
                         */
                        function mpc() public view returns (address) {
                            if (block.timestamp >= newMPCEffectiveTime) {
                                return newMPC;
                            }
                            return oldMPC;
                        }
                        /**
                         * @notice Returns chain ID of block
                         */
                        function currentChainId() public view returns (uint256) {
                            return block.chainid;
                        }
                        /// ** MPC functions **
                        /**
                         * @notice Receives requests
                         */
                        function receiveRequestV2(bytes memory _callData, address _receiveSide)
                        external
                        onlyMPC
                        {
                            _processRequest(_callData, _receiveSide);
                        }
                        /**
                         * @notice Receives requests
                         */
                        function receiveRequestV2Signed(bytes memory _callData, address _receiveSide, bytes memory signature)
                        external
                        onlySignedByMPC(keccak256(bytes.concat("receiveRequestV2", _callData, bytes20(_receiveSide),
                            bytes32(block.chainid), bytes20(address(this)))), signature)
                        {
                            _processRequest(_callData, _receiveSide);
                        }
                        /// ** TRANSMITTER functions **
                        /**
                         * @notice transmits request
                         */
                        function transmitRequestV2(
                            bytes memory _callData,
                            address _receiveSide,
                            address _oppositeBridge,
                            uint256 _chainId
                        ) public onlyTransmitter {
                            emit OracleRequest(
                                address(this),
                                _callData,
                                _receiveSide,
                                _oppositeBridge,
                                _chainId
                            );
                        }
                        /// ** OWNER functions **
                        /**
                         * @notice Sets transmitter status
                         */
                        function setTransmitterStatus(address _transmitter, bool _status)
                        external
                        onlyOwner
                        {
                            isTransmitter[_transmitter] = _status;
                            emit SetTransmitterStatus(_transmitter, _status);
                        }
                        /**
                         * @notice Changes MPC by owner or MPC
                         */
                        function changeMPC(address _newMPC) external onlyOwnerOrMPC returns (bool) {
                            return _changeMPC(_newMPC);
                        }
                        /**
                         * @notice Changes MPC with signature
                         */
                        function changeMPCSigned(address _newMPC, bytes memory signature)
                        external
                        onlySignedByMPC(keccak256(bytes.concat("changeMPC", bytes20(_newMPC), bytes32(block.chainid),
                            bytes20(address(this)))), signature)
                        returns (bool)
                        {
                            return _changeMPC(_newMPC);
                        }
                        /**
                         * @notice Withdraw fee by owner or admin
                         */
                        function withdrawFee(address token, address to, uint256 amount) external onlyOwnerOrAdmin returns (bool) {
                            TransferHelper.safeTransfer(token, to, amount);
                            return true;
                        }
                        /// ** Private functions **
                        /**
                         * @notice Private function that handles request processing
                         */
                        function _processRequest(bytes memory _callData, address _receiveSide)
                        private
                        {
                            require(isTransmitter[_receiveSide], "BridgeV2: untrusted transmitter");
                            (bool success, bytes memory data) = _receiveSide.call(_callData);
                            if (!success) {
                                revert(RevertMessageParser.getRevertMessage(data, "BridgeV2: call failed"));
                            }
                        }
                        /**
                         * @notice Private function that changes MPC
                         */
                        function _changeMPC(address _newMPC) private returns (bool) {
                            require(_newMPC != address(0), "BridgeV2: address(0x0)");
                            oldMPC = mpc();
                            newMPC = _newMPC;
                            newMPCEffectiveTime = block.timestamp;
                            emit LogChangeMPC(
                                oldMPC,
                                newMPC,
                                newMPCEffectiveTime,
                                currentChainId()
                            );
                            return true;
                        }
                    }// SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
                    pragma solidity ^0.8.0;
                    import "../../utils/AddressUpgradeable.sol";
                    /**
                     * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
                     * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
                     * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
                     * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
                     *
                     * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
                     * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
                     *
                     * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
                     * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
                     *
                     * [CAUTION]
                     * ====
                     * Avoid leaving a contract uninitialized.
                     *
                     * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
                     * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
                     * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
                     *
                     * [.hljs-theme-light.nopadding]
                     * ```
                     * /// @custom:oz-upgrades-unsafe-allow constructor
                     * constructor() initializer {}
                     * ```
                     * ====
                     */
                    abstract contract Initializable {
                        /**
                         * @dev Indicates that the contract has been initialized.
                         */
                        bool private _initialized;
                        /**
                         * @dev Indicates that the contract is in the process of being initialized.
                         */
                        bool private _initializing;
                        /**
                         * @dev Modifier to protect an initializer function from being invoked twice.
                         */
                        modifier initializer() {
                            // If the contract is initializing we ignore whether _initialized is set in order to support multiple
                            // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
                            // contract may have been reentered.
                            require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
                            bool isTopLevelCall = !_initializing;
                            if (isTopLevelCall) {
                                _initializing = true;
                                _initialized = true;
                            }
                            _;
                            if (isTopLevelCall) {
                                _initializing = false;
                            }
                        }
                        /**
                         * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
                         * {initializer} modifier, directly or indirectly.
                         */
                        modifier onlyInitializing() {
                            require(_initializing, "Initializable: contract is not initializing");
                            _;
                        }
                        function _isConstructor() private view returns (bool) {
                            return !AddressUpgradeable.isContract(address(this));
                        }
                    }
                    // SPDX-License-Identifier: GPL-3.0-or-later
                    pragma solidity >=0.6.0;
                    // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
                    library TransferHelper {
                        function safeApprove(
                            address token,
                            address to,
                            uint256 value
                        ) internal {
                            // bytes4(keccak256(bytes('approve(address,uint256)')));
                            (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
                            require(
                                success && (data.length == 0 || abi.decode(data, (bool))),
                                'TransferHelper::safeApprove: approve failed'
                            );
                        }
                        function safeTransfer(
                            address token,
                            address to,
                            uint256 value
                        ) internal {
                            // bytes4(keccak256(bytes('transfer(address,uint256)')));
                            (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
                            require(
                                success && (data.length == 0 || abi.decode(data, (bool))),
                                'TransferHelper::safeTransfer: transfer failed'
                            );
                        }
                        function safeTransferFrom(
                            address token,
                            address from,
                            address to,
                            uint256 value
                        ) internal {
                            // bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
                            (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
                            require(
                                success && (data.length == 0 || abi.decode(data, (bool))),
                                'TransferHelper::transferFrom: transferFrom failed'
                            );
                        }
                        function safeTransferETH(address to, uint256 value) internal {
                            (bool success, ) = to.call{value: value}(new bytes(0));
                            require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts v4.4.1 (utils/cryptography/SignatureChecker.sol)
                    pragma solidity ^0.8.0;
                    import "./ECDSA.sol";
                    import "../Address.sol";
                    import "../../interfaces/IERC1271.sol";
                    /**
                     * @dev Signature verification helper: Provide a single mechanism to verify both private-key (EOA) ECDSA signature and
                     * ERC1271 contract signatures. Using this instead of ECDSA.recover in your contract will make them compatible with
                     * smart contract wallets such as Argent and Gnosis.
                     *
                     * Note: unlike ECDSA signatures, contract signature's are revocable, and the outcome of this function can thus change
                     * through time. It could return true at block N and false at block N+1 (or the opposite).
                     *
                     * _Available since v4.1._
                     */
                    library SignatureChecker {
                        function isValidSignatureNow(
                            address signer,
                            bytes32 hash,
                            bytes memory signature
                        ) internal view returns (bool) {
                            (address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(hash, signature);
                            if (error == ECDSA.RecoverError.NoError && recovered == signer) {
                                return true;
                            }
                            (bool success, bytes memory result) = signer.staticcall(
                                abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature)
                            );
                            return (success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271.isValidSignature.selector);
                        }
                    }
                    // SPDX-License-Identifier: GPL-3.0
                    pragma solidity ^0.8.0;
                    import '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol';
                    abstract contract AdminableUpgradeable is OwnableUpgradeable {
                        mapping(address => bool) public isAdmin;
                        event SetAdminPermission(address indexed admin, bool permission);
                        modifier onlyAdmin {
                            require(isAdmin[msg.sender], "Only admin can call");
                            _;
                        }
                        modifier onlyOwnerOrAdmin {
                            require((owner() == msg.sender) || isAdmin[msg.sender], "Only owner or admin can call");
                            _;
                        }
                        function __Adminable_init() internal onlyInitializing {
                            __Ownable_init();
                        }
                        function setAdminPermission(address _user, bool _permission) external onlyOwner {
                            isAdmin[_user] = _permission;
                            emit SetAdminPermission(_user, _permission);
                        }
                    }// SPDX-License-Identifier: GPL-3.0
                    pragma solidity ^0.8.0;
                    library RevertMessageParser {
                        function getRevertMessage(bytes memory _data, string memory _defaultMessage) internal pure returns (string memory) {
                            // If the _data length is less than 68, then the transaction failed silently (without a revert message)
                            if (_data.length < 68) return _defaultMessage;
                            assembly {
                                // Slice the sighash
                                _data := add(_data, 0x04)
                            }
                            return abi.decode(_data, (string));
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
                    pragma solidity ^0.8.0;
                    /**
                     * @dev Collection of functions related to the address type
                     */
                    library AddressUpgradeable {
                        /**
                         * @dev Returns true if `account` is a contract.
                         *
                         * [IMPORTANT]
                         * ====
                         * It is unsafe to assume that an address for which this function returns
                         * false is an externally-owned account (EOA) and not a contract.
                         *
                         * Among others, `isContract` will return false for the following
                         * types of addresses:
                         *
                         *  - an externally-owned account
                         *  - a contract in construction
                         *  - an address where a contract will be created
                         *  - an address where a contract lived, but was destroyed
                         * ====
                         */
                        function isContract(address account) internal view returns (bool) {
                            // This method relies on extcodesize, which returns 0 for contracts in
                            // construction, since the code is only stored at the end of the
                            // constructor execution.
                            uint256 size;
                            assembly {
                                size := extcodesize(account)
                            }
                            return size > 0;
                        }
                        /**
                         * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
                         * `recipient`, forwarding all available gas and reverting on errors.
                         *
                         * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
                         * of certain opcodes, possibly making contracts go over the 2300 gas limit
                         * imposed by `transfer`, making them unable to receive funds via
                         * `transfer`. {sendValue} removes this limitation.
                         *
                         * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
                         *
                         * IMPORTANT: because control is transferred to `recipient`, care must be
                         * taken to not create reentrancy vulnerabilities. Consider using
                         * {ReentrancyGuard} or the
                         * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                         */
                        function sendValue(address payable recipient, uint256 amount) internal {
                            require(address(this).balance >= amount, "Address: insufficient balance");
                            (bool success, ) = recipient.call{value: amount}("");
                            require(success, "Address: unable to send value, recipient may have reverted");
                        }
                        /**
                         * @dev Performs a Solidity function call using a low level `call`. A
                         * plain `call` is an unsafe replacement for a function call: use this
                         * function instead.
                         *
                         * If `target` reverts with a revert reason, it is bubbled up by this
                         * function (like regular Solidity function calls).
                         *
                         * Returns the raw returned data. To convert to the expected return value,
                         * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
                         *
                         * Requirements:
                         *
                         * - `target` must be a contract.
                         * - calling `target` with `data` must not revert.
                         *
                         * _Available since v3.1._
                         */
                        function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                            return functionCall(target, data, "Address: low-level call failed");
                        }
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
                         * `errorMessage` as a fallback revert reason when `target` reverts.
                         *
                         * _Available since v3.1._
                         */
                        function functionCall(
                            address target,
                            bytes memory data,
                            string memory errorMessage
                        ) internal returns (bytes memory) {
                            return functionCallWithValue(target, data, 0, errorMessage);
                        }
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                         * but also transferring `value` wei to `target`.
                         *
                         * Requirements:
                         *
                         * - the calling contract must have an ETH balance of at least `value`.
                         * - the called Solidity function must be `payable`.
                         *
                         * _Available since v3.1._
                         */
                        function functionCallWithValue(
                            address target,
                            bytes memory data,
                            uint256 value
                        ) internal returns (bytes memory) {
                            return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
                        }
                        /**
                         * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
                         * with `errorMessage` as a fallback revert reason when `target` reverts.
                         *
                         * _Available since v3.1._
                         */
                        function functionCallWithValue(
                            address target,
                            bytes memory data,
                            uint256 value,
                            string memory errorMessage
                        ) internal returns (bytes memory) {
                            require(address(this).balance >= value, "Address: insufficient balance for call");
                            require(isContract(target), "Address: call to non-contract");
                            (bool success, bytes memory returndata) = target.call{value: value}(data);
                            return verifyCallResult(success, returndata, errorMessage);
                        }
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                         * but performing a static call.
                         *
                         * _Available since v3.3._
                         */
                        function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                            return functionStaticCall(target, data, "Address: low-level static call failed");
                        }
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                         * but performing a static call.
                         *
                         * _Available since v3.3._
                         */
                        function functionStaticCall(
                            address target,
                            bytes memory data,
                            string memory errorMessage
                        ) internal view returns (bytes memory) {
                            require(isContract(target), "Address: static call to non-contract");
                            (bool success, bytes memory returndata) = target.staticcall(data);
                            return verifyCallResult(success, returndata, errorMessage);
                        }
                        /**
                         * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
                         * revert reason using the provided one.
                         *
                         * _Available since v4.3._
                         */
                        function verifyCallResult(
                            bool success,
                            bytes memory returndata,
                            string memory errorMessage
                        ) internal pure returns (bytes memory) {
                            if (success) {
                                return returndata;
                            } else {
                                // Look for revert reason and bubble it up if present
                                if (returndata.length > 0) {
                                    // The easiest way to bubble the revert reason is using memory via assembly
                                    assembly {
                                        let returndata_size := mload(returndata)
                                        revert(add(32, returndata), returndata_size)
                                    }
                                } else {
                                    revert(errorMessage);
                                }
                            }
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol)
                    pragma solidity ^0.8.0;
                    import "../Strings.sol";
                    /**
                     * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
                     *
                     * These functions can be used to verify that a message was signed by the holder
                     * of the private keys of a given address.
                     */
                    library ECDSA {
                        enum RecoverError {
                            NoError,
                            InvalidSignature,
                            InvalidSignatureLength,
                            InvalidSignatureS,
                            InvalidSignatureV
                        }
                        function _throwError(RecoverError error) private pure {
                            if (error == RecoverError.NoError) {
                                return; // no error: do nothing
                            } else if (error == RecoverError.InvalidSignature) {
                                revert("ECDSA: invalid signature");
                            } else if (error == RecoverError.InvalidSignatureLength) {
                                revert("ECDSA: invalid signature length");
                            } else if (error == RecoverError.InvalidSignatureS) {
                                revert("ECDSA: invalid signature 's' value");
                            } else if (error == RecoverError.InvalidSignatureV) {
                                revert("ECDSA: invalid signature 'v' value");
                            }
                        }
                        /**
                         * @dev Returns the address that signed a hashed message (`hash`) with
                         * `signature` or error string. This address can then be used for verification purposes.
                         *
                         * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
                         * this function rejects them by requiring the `s` value to be in the lower
                         * half order, and the `v` value to be either 27 or 28.
                         *
                         * IMPORTANT: `hash` _must_ be the result of a hash operation for the
                         * verification to be secure: it is possible to craft signatures that
                         * recover to arbitrary addresses for non-hashed data. A safe way to ensure
                         * this is by receiving a hash of the original message (which may otherwise
                         * be too long), and then calling {toEthSignedMessageHash} on it.
                         *
                         * Documentation for signature generation:
                         * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
                         * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
                         *
                         * _Available since v4.3._
                         */
                        function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
                            // Check the signature length
                            // - case 65: r,s,v signature (standard)
                            // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
                            if (signature.length == 65) {
                                bytes32 r;
                                bytes32 s;
                                uint8 v;
                                // ecrecover takes the signature parameters, and the only way to get them
                                // currently is to use assembly.
                                assembly {
                                    r := mload(add(signature, 0x20))
                                    s := mload(add(signature, 0x40))
                                    v := byte(0, mload(add(signature, 0x60)))
                                }
                                return tryRecover(hash, v, r, s);
                            } else if (signature.length == 64) {
                                bytes32 r;
                                bytes32 vs;
                                // ecrecover takes the signature parameters, and the only way to get them
                                // currently is to use assembly.
                                assembly {
                                    r := mload(add(signature, 0x20))
                                    vs := mload(add(signature, 0x40))
                                }
                                return tryRecover(hash, r, vs);
                            } else {
                                return (address(0), RecoverError.InvalidSignatureLength);
                            }
                        }
                        /**
                         * @dev Returns the address that signed a hashed message (`hash`) with
                         * `signature`. This address can then be used for verification purposes.
                         *
                         * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
                         * this function rejects them by requiring the `s` value to be in the lower
                         * half order, and the `v` value to be either 27 or 28.
                         *
                         * IMPORTANT: `hash` _must_ be the result of a hash operation for the
                         * verification to be secure: it is possible to craft signatures that
                         * recover to arbitrary addresses for non-hashed data. A safe way to ensure
                         * this is by receiving a hash of the original message (which may otherwise
                         * be too long), and then calling {toEthSignedMessageHash} on it.
                         */
                        function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
                            (address recovered, RecoverError error) = tryRecover(hash, signature);
                            _throwError(error);
                            return recovered;
                        }
                        /**
                         * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
                         *
                         * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
                         *
                         * _Available since v4.3._
                         */
                        function tryRecover(
                            bytes32 hash,
                            bytes32 r,
                            bytes32 vs
                        ) internal pure returns (address, RecoverError) {
                            bytes32 s;
                            uint8 v;
                            assembly {
                                s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
                                v := add(shr(255, vs), 27)
                            }
                            return tryRecover(hash, v, r, s);
                        }
                        /**
                         * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
                         *
                         * _Available since v4.2._
                         */
                        function recover(
                            bytes32 hash,
                            bytes32 r,
                            bytes32 vs
                        ) internal pure returns (address) {
                            (address recovered, RecoverError error) = tryRecover(hash, r, vs);
                            _throwError(error);
                            return recovered;
                        }
                        /**
                         * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
                         * `r` and `s` signature fields separately.
                         *
                         * _Available since v4.3._
                         */
                        function tryRecover(
                            bytes32 hash,
                            uint8 v,
                            bytes32 r,
                            bytes32 s
                        ) internal pure returns (address, RecoverError) {
                            // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
                            // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
                            // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
                            // signatures from current libraries generate a unique signature with an s-value in the lower half order.
                            //
                            // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
                            // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
                            // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
                            // these malleable signatures as well.
                            if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
                                return (address(0), RecoverError.InvalidSignatureS);
                            }
                            if (v != 27 && v != 28) {
                                return (address(0), RecoverError.InvalidSignatureV);
                            }
                            // If the signature is valid (and not malleable), return the signer address
                            address signer = ecrecover(hash, v, r, s);
                            if (signer == address(0)) {
                                return (address(0), RecoverError.InvalidSignature);
                            }
                            return (signer, RecoverError.NoError);
                        }
                        /**
                         * @dev Overload of {ECDSA-recover} that receives the `v`,
                         * `r` and `s` signature fields separately.
                         */
                        function recover(
                            bytes32 hash,
                            uint8 v,
                            bytes32 r,
                            bytes32 s
                        ) internal pure returns (address) {
                            (address recovered, RecoverError error) = tryRecover(hash, v, r, s);
                            _throwError(error);
                            return recovered;
                        }
                        /**
                         * @dev Returns an Ethereum Signed Message, created from a `hash`. This
                         * produces hash corresponding to the one signed with the
                         * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
                         * JSON-RPC method as part of EIP-191.
                         *
                         * See {recover}.
                         */
                        function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
                            // 32 is the length in bytes of hash,
                            // enforced by the type signature above
                            return keccak256(abi.encodePacked("\\x19Ethereum Signed Message:\
                    32", hash));
                        }
                        /**
                         * @dev Returns an Ethereum Signed Message, created from `s`. This
                         * produces hash corresponding to the one signed with the
                         * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
                         * JSON-RPC method as part of EIP-191.
                         *
                         * See {recover}.
                         */
                        function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
                            return keccak256(abi.encodePacked("\\x19Ethereum Signed Message:\
                    ", Strings.toString(s.length), s));
                        }
                        /**
                         * @dev Returns an Ethereum Signed Typed Data, created from a
                         * `domainSeparator` and a `structHash`. This produces hash corresponding
                         * to the one signed with the
                         * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
                         * JSON-RPC method as part of EIP-712.
                         *
                         * See {recover}.
                         */
                        function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
                            return keccak256(abi.encodePacked("\\x19\\x01", domainSeparator, structHash));
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
                    pragma solidity ^0.8.0;
                    /**
                     * @dev Collection of functions related to the address type
                     */
                    library Address {
                        /**
                         * @dev Returns true if `account` is a contract.
                         *
                         * [IMPORTANT]
                         * ====
                         * It is unsafe to assume that an address for which this function returns
                         * false is an externally-owned account (EOA) and not a contract.
                         *
                         * Among others, `isContract` will return false for the following
                         * types of addresses:
                         *
                         *  - an externally-owned account
                         *  - a contract in construction
                         *  - an address where a contract will be created
                         *  - an address where a contract lived, but was destroyed
                         * ====
                         */
                        function isContract(address account) internal view returns (bool) {
                            // This method relies on extcodesize, which returns 0 for contracts in
                            // construction, since the code is only stored at the end of the
                            // constructor execution.
                            uint256 size;
                            assembly {
                                size := extcodesize(account)
                            }
                            return size > 0;
                        }
                        /**
                         * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
                         * `recipient`, forwarding all available gas and reverting on errors.
                         *
                         * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
                         * of certain opcodes, possibly making contracts go over the 2300 gas limit
                         * imposed by `transfer`, making them unable to receive funds via
                         * `transfer`. {sendValue} removes this limitation.
                         *
                         * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
                         *
                         * IMPORTANT: because control is transferred to `recipient`, care must be
                         * taken to not create reentrancy vulnerabilities. Consider using
                         * {ReentrancyGuard} or the
                         * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                         */
                        function sendValue(address payable recipient, uint256 amount) internal {
                            require(address(this).balance >= amount, "Address: insufficient balance");
                            (bool success, ) = recipient.call{value: amount}("");
                            require(success, "Address: unable to send value, recipient may have reverted");
                        }
                        /**
                         * @dev Performs a Solidity function call using a low level `call`. A
                         * plain `call` is an unsafe replacement for a function call: use this
                         * function instead.
                         *
                         * If `target` reverts with a revert reason, it is bubbled up by this
                         * function (like regular Solidity function calls).
                         *
                         * Returns the raw returned data. To convert to the expected return value,
                         * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
                         *
                         * Requirements:
                         *
                         * - `target` must be a contract.
                         * - calling `target` with `data` must not revert.
                         *
                         * _Available since v3.1._
                         */
                        function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                            return functionCall(target, data, "Address: low-level call failed");
                        }
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
                         * `errorMessage` as a fallback revert reason when `target` reverts.
                         *
                         * _Available since v3.1._
                         */
                        function functionCall(
                            address target,
                            bytes memory data,
                            string memory errorMessage
                        ) internal returns (bytes memory) {
                            return functionCallWithValue(target, data, 0, errorMessage);
                        }
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                         * but also transferring `value` wei to `target`.
                         *
                         * Requirements:
                         *
                         * - the calling contract must have an ETH balance of at least `value`.
                         * - the called Solidity function must be `payable`.
                         *
                         * _Available since v3.1._
                         */
                        function functionCallWithValue(
                            address target,
                            bytes memory data,
                            uint256 value
                        ) internal returns (bytes memory) {
                            return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
                        }
                        /**
                         * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
                         * with `errorMessage` as a fallback revert reason when `target` reverts.
                         *
                         * _Available since v3.1._
                         */
                        function functionCallWithValue(
                            address target,
                            bytes memory data,
                            uint256 value,
                            string memory errorMessage
                        ) internal returns (bytes memory) {
                            require(address(this).balance >= value, "Address: insufficient balance for call");
                            require(isContract(target), "Address: call to non-contract");
                            (bool success, bytes memory returndata) = target.call{value: value}(data);
                            return verifyCallResult(success, returndata, errorMessage);
                        }
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                         * but performing a static call.
                         *
                         * _Available since v3.3._
                         */
                        function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                            return functionStaticCall(target, data, "Address: low-level static call failed");
                        }
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                         * but performing a static call.
                         *
                         * _Available since v3.3._
                         */
                        function functionStaticCall(
                            address target,
                            bytes memory data,
                            string memory errorMessage
                        ) internal view returns (bytes memory) {
                            require(isContract(target), "Address: static call to non-contract");
                            (bool success, bytes memory returndata) = target.staticcall(data);
                            return verifyCallResult(success, returndata, errorMessage);
                        }
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                         * but performing a delegate call.
                         *
                         * _Available since v3.4._
                         */
                        function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                            return functionDelegateCall(target, data, "Address: low-level delegate call failed");
                        }
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                         * but performing a delegate call.
                         *
                         * _Available since v3.4._
                         */
                        function functionDelegateCall(
                            address target,
                            bytes memory data,
                            string memory errorMessage
                        ) internal returns (bytes memory) {
                            require(isContract(target), "Address: delegate call to non-contract");
                            (bool success, bytes memory returndata) = target.delegatecall(data);
                            return verifyCallResult(success, returndata, errorMessage);
                        }
                        /**
                         * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
                         * revert reason using the provided one.
                         *
                         * _Available since v4.3._
                         */
                        function verifyCallResult(
                            bool success,
                            bytes memory returndata,
                            string memory errorMessage
                        ) internal pure returns (bytes memory) {
                            if (success) {
                                return returndata;
                            } else {
                                // Look for revert reason and bubble it up if present
                                if (returndata.length > 0) {
                                    // The easiest way to bubble the revert reason is using memory via assembly
                                    assembly {
                                        let returndata_size := mload(returndata)
                                        revert(add(32, returndata), returndata_size)
                                    }
                                } else {
                                    revert(errorMessage);
                                }
                            }
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol)
                    pragma solidity ^0.8.0;
                    /**
                     * @dev Interface of the ERC1271 standard signature validation method for
                     * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
                     *
                     * _Available since v4.1._
                     */
                    interface IERC1271 {
                        /**
                         * @dev Should return whether the signature provided is valid for the provided data
                         * @param hash      Hash of the data to be signed
                         * @param signature Signature byte array associated with _data
                         */
                        function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
                    }
                    // SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
                    pragma solidity ^0.8.0;
                    /**
                     * @dev String operations.
                     */
                    library Strings {
                        bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
                        /**
                         * @dev Converts a `uint256` to its ASCII `string` decimal representation.
                         */
                        function toString(uint256 value) internal pure returns (string memory) {
                            // Inspired by OraclizeAPI's implementation - MIT licence
                            // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
                            if (value == 0) {
                                return "0";
                            }
                            uint256 temp = value;
                            uint256 digits;
                            while (temp != 0) {
                                digits++;
                                temp /= 10;
                            }
                            bytes memory buffer = new bytes(digits);
                            while (value != 0) {
                                digits -= 1;
                                buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
                                value /= 10;
                            }
                            return string(buffer);
                        }
                        /**
                         * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
                         */
                        function toHexString(uint256 value) internal pure returns (string memory) {
                            if (value == 0) {
                                return "0x00";
                            }
                            uint256 temp = value;
                            uint256 length = 0;
                            while (temp != 0) {
                                length++;
                                temp >>= 8;
                            }
                            return toHexString(value, length);
                        }
                        /**
                         * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
                         */
                        function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
                            bytes memory buffer = new bytes(2 * length + 2);
                            buffer[0] = "0";
                            buffer[1] = "x";
                            for (uint256 i = 2 * length + 1; i > 1; --i) {
                                buffer[i] = _HEX_SYMBOLS[value & 0xf];
                                value >>= 4;
                            }
                            require(value == 0, "Strings: hex length insufficient");
                            return string(buffer);
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
                    pragma solidity ^0.8.0;
                    import "../utils/ContextUpgradeable.sol";
                    import "../proxy/utils/Initializable.sol";
                    /**
                     * @dev Contract module which provides a basic access control mechanism, where
                     * there is an account (an owner) that can be granted exclusive access to
                     * specific functions.
                     *
                     * By default, the owner account will be the one that deploys the contract. This
                     * can later be changed with {transferOwnership}.
                     *
                     * This module is used through inheritance. It will make available the modifier
                     * `onlyOwner`, which can be applied to your functions to restrict their use to
                     * the owner.
                     */
                    abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
                        address private _owner;
                        event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                        /**
                         * @dev Initializes the contract setting the deployer as the initial owner.
                         */
                        function __Ownable_init() internal onlyInitializing {
                            __Context_init_unchained();
                            __Ownable_init_unchained();
                        }
                        function __Ownable_init_unchained() internal onlyInitializing {
                            _transferOwnership(_msgSender());
                        }
                        /**
                         * @dev Returns the address of the current owner.
                         */
                        function owner() public view virtual returns (address) {
                            return _owner;
                        }
                        /**
                         * @dev Throws if called by any account other than the owner.
                         */
                        modifier onlyOwner() {
                            require(owner() == _msgSender(), "Ownable: caller is not the owner");
                            _;
                        }
                        /**
                         * @dev Leaves the contract without owner. It will not be possible to call
                         * `onlyOwner` functions anymore. Can only be called by the current owner.
                         *
                         * NOTE: Renouncing ownership will leave the contract without an owner,
                         * thereby removing any functionality that is only available to the owner.
                         */
                        function renounceOwnership() public virtual onlyOwner {
                            _transferOwnership(address(0));
                        }
                        /**
                         * @dev Transfers ownership of the contract to a new account (`newOwner`).
                         * Can only be called by the current owner.
                         */
                        function transferOwnership(address newOwner) public virtual onlyOwner {
                            require(newOwner != address(0), "Ownable: new owner is the zero address");
                            _transferOwnership(newOwner);
                        }
                        /**
                         * @dev Transfers ownership of the contract to a new account (`newOwner`).
                         * Internal function without access restriction.
                         */
                        function _transferOwnership(address newOwner) internal virtual {
                            address oldOwner = _owner;
                            _owner = newOwner;
                            emit OwnershipTransferred(oldOwner, newOwner);
                        }
                        uint256[49] private __gap;
                    }
                    // SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
                    pragma solidity ^0.8.0;
                    import "../proxy/utils/Initializable.sol";
                    /**
                     * @dev Provides information about the current execution context, including the
                     * sender of the transaction and its data. While these are generally available
                     * via msg.sender and msg.data, they should not be accessed in such a direct
                     * manner, since when dealing with meta-transactions the account sending and
                     * paying for execution may not be the actual sender (as far as an application
                     * is concerned).
                     *
                     * This contract is only required for intermediate, library-like contracts.
                     */
                    abstract contract ContextUpgradeable is Initializable {
                        function __Context_init() internal onlyInitializing {
                            __Context_init_unchained();
                        }
                        function __Context_init_unchained() internal onlyInitializing {
                        }
                        function _msgSender() internal view virtual returns (address) {
                            return msg.sender;
                        }
                        function _msgData() internal view virtual returns (bytes calldata) {
                            return msg.data;
                        }
                        uint256[50] private __gap;
                    }
                    

                    File 6 of 9: Portal
                    // SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
                    pragma solidity ^0.8.0;
                    import "../utils/ContextUpgradeable.sol";
                    import "../proxy/utils/Initializable.sol";
                    /**
                     * @dev Contract module which provides a basic access control mechanism, where
                     * there is an account (an owner) that can be granted exclusive access to
                     * specific functions.
                     *
                     * By default, the owner account will be the one that deploys the contract. This
                     * can later be changed with {transferOwnership}.
                     *
                     * This module is used through inheritance. It will make available the modifier
                     * `onlyOwner`, which can be applied to your functions to restrict their use to
                     * the owner.
                     */
                    abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
                        address private _owner;
                        event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                        /**
                         * @dev Initializes the contract setting the deployer as the initial owner.
                         */
                        function __Ownable_init() internal onlyInitializing {
                            __Context_init_unchained();
                            __Ownable_init_unchained();
                        }
                        function __Ownable_init_unchained() internal onlyInitializing {
                            _transferOwnership(_msgSender());
                        }
                        /**
                         * @dev Returns the address of the current owner.
                         */
                        function owner() public view virtual returns (address) {
                            return _owner;
                        }
                        /**
                         * @dev Throws if called by any account other than the owner.
                         */
                        modifier onlyOwner() {
                            require(owner() == _msgSender(), "Ownable: caller is not the owner");
                            _;
                        }
                        /**
                         * @dev Leaves the contract without owner. It will not be possible to call
                         * `onlyOwner` functions anymore. Can only be called by the current owner.
                         *
                         * NOTE: Renouncing ownership will leave the contract without an owner,
                         * thereby removing any functionality that is only available to the owner.
                         */
                        function renounceOwnership() public virtual onlyOwner {
                            _transferOwnership(address(0));
                        }
                        /**
                         * @dev Transfers ownership of the contract to a new account (`newOwner`).
                         * Can only be called by the current owner.
                         */
                        function transferOwnership(address newOwner) public virtual onlyOwner {
                            require(newOwner != address(0), "Ownable: new owner is the zero address");
                            _transferOwnership(newOwner);
                        }
                        /**
                         * @dev Transfers ownership of the contract to a new account (`newOwner`).
                         * Internal function without access restriction.
                         */
                        function _transferOwnership(address newOwner) internal virtual {
                            address oldOwner = _owner;
                            _owner = newOwner;
                            emit OwnershipTransferred(oldOwner, newOwner);
                        }
                        uint256[49] private __gap;
                    }
                    // SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
                    pragma solidity ^0.8.0;
                    import "../../utils/AddressUpgradeable.sol";
                    /**
                     * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
                     * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
                     * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
                     * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
                     *
                     * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
                     * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
                     *
                     * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
                     * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
                     *
                     * [CAUTION]
                     * ====
                     * Avoid leaving a contract uninitialized.
                     *
                     * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
                     * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
                     * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
                     *
                     * [.hljs-theme-light.nopadding]
                     * ```
                     * /// @custom:oz-upgrades-unsafe-allow constructor
                     * constructor() initializer {}
                     * ```
                     * ====
                     */
                    abstract contract Initializable {
                        /**
                         * @dev Indicates that the contract has been initialized.
                         */
                        bool private _initialized;
                        /**
                         * @dev Indicates that the contract is in the process of being initialized.
                         */
                        bool private _initializing;
                        /**
                         * @dev Modifier to protect an initializer function from being invoked twice.
                         */
                        modifier initializer() {
                            // If the contract is initializing we ignore whether _initialized is set in order to support multiple
                            // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
                            // contract may have been reentered.
                            require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
                            bool isTopLevelCall = !_initializing;
                            if (isTopLevelCall) {
                                _initializing = true;
                                _initialized = true;
                            }
                            _;
                            if (isTopLevelCall) {
                                _initializing = false;
                            }
                        }
                        /**
                         * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
                         * {initializer} modifier, directly or indirectly.
                         */
                        modifier onlyInitializing() {
                            require(_initializing, "Initializable: contract is not initializing");
                            _;
                        }
                        function _isConstructor() private view returns (bool) {
                            return !AddressUpgradeable.isContract(address(this));
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
                    pragma solidity ^0.8.0;
                    /**
                     * @dev Collection of functions related to the address type
                     */
                    library AddressUpgradeable {
                        /**
                         * @dev Returns true if `account` is a contract.
                         *
                         * [IMPORTANT]
                         * ====
                         * It is unsafe to assume that an address for which this function returns
                         * false is an externally-owned account (EOA) and not a contract.
                         *
                         * Among others, `isContract` will return false for the following
                         * types of addresses:
                         *
                         *  - an externally-owned account
                         *  - a contract in construction
                         *  - an address where a contract will be created
                         *  - an address where a contract lived, but was destroyed
                         * ====
                         */
                        function isContract(address account) internal view returns (bool) {
                            // This method relies on extcodesize, which returns 0 for contracts in
                            // construction, since the code is only stored at the end of the
                            // constructor execution.
                            uint256 size;
                            assembly {
                                size := extcodesize(account)
                            }
                            return size > 0;
                        }
                        /**
                         * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
                         * `recipient`, forwarding all available gas and reverting on errors.
                         *
                         * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
                         * of certain opcodes, possibly making contracts go over the 2300 gas limit
                         * imposed by `transfer`, making them unable to receive funds via
                         * `transfer`. {sendValue} removes this limitation.
                         *
                         * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
                         *
                         * IMPORTANT: because control is transferred to `recipient`, care must be
                         * taken to not create reentrancy vulnerabilities. Consider using
                         * {ReentrancyGuard} or the
                         * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                         */
                        function sendValue(address payable recipient, uint256 amount) internal {
                            require(address(this).balance >= amount, "Address: insufficient balance");
                            (bool success, ) = recipient.call{value: amount}("");
                            require(success, "Address: unable to send value, recipient may have reverted");
                        }
                        /**
                         * @dev Performs a Solidity function call using a low level `call`. A
                         * plain `call` is an unsafe replacement for a function call: use this
                         * function instead.
                         *
                         * If `target` reverts with a revert reason, it is bubbled up by this
                         * function (like regular Solidity function calls).
                         *
                         * Returns the raw returned data. To convert to the expected return value,
                         * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
                         *
                         * Requirements:
                         *
                         * - `target` must be a contract.
                         * - calling `target` with `data` must not revert.
                         *
                         * _Available since v3.1._
                         */
                        function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                            return functionCall(target, data, "Address: low-level call failed");
                        }
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
                         * `errorMessage` as a fallback revert reason when `target` reverts.
                         *
                         * _Available since v3.1._
                         */
                        function functionCall(
                            address target,
                            bytes memory data,
                            string memory errorMessage
                        ) internal returns (bytes memory) {
                            return functionCallWithValue(target, data, 0, errorMessage);
                        }
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                         * but also transferring `value` wei to `target`.
                         *
                         * Requirements:
                         *
                         * - the calling contract must have an ETH balance of at least `value`.
                         * - the called Solidity function must be `payable`.
                         *
                         * _Available since v3.1._
                         */
                        function functionCallWithValue(
                            address target,
                            bytes memory data,
                            uint256 value
                        ) internal returns (bytes memory) {
                            return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
                        }
                        /**
                         * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
                         * with `errorMessage` as a fallback revert reason when `target` reverts.
                         *
                         * _Available since v3.1._
                         */
                        function functionCallWithValue(
                            address target,
                            bytes memory data,
                            uint256 value,
                            string memory errorMessage
                        ) internal returns (bytes memory) {
                            require(address(this).balance >= value, "Address: insufficient balance for call");
                            require(isContract(target), "Address: call to non-contract");
                            (bool success, bytes memory returndata) = target.call{value: value}(data);
                            return verifyCallResult(success, returndata, errorMessage);
                        }
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                         * but performing a static call.
                         *
                         * _Available since v3.3._
                         */
                        function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                            return functionStaticCall(target, data, "Address: low-level static call failed");
                        }
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                         * but performing a static call.
                         *
                         * _Available since v3.3._
                         */
                        function functionStaticCall(
                            address target,
                            bytes memory data,
                            string memory errorMessage
                        ) internal view returns (bytes memory) {
                            require(isContract(target), "Address: static call to non-contract");
                            (bool success, bytes memory returndata) = target.staticcall(data);
                            return verifyCallResult(success, returndata, errorMessage);
                        }
                        /**
                         * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
                         * revert reason using the provided one.
                         *
                         * _Available since v4.3._
                         */
                        function verifyCallResult(
                            bool success,
                            bytes memory returndata,
                            string memory errorMessage
                        ) internal pure returns (bytes memory) {
                            if (success) {
                                return returndata;
                            } else {
                                // Look for revert reason and bubble it up if present
                                if (returndata.length > 0) {
                                    // The easiest way to bubble the revert reason is using memory via assembly
                                    assembly {
                                        let returndata_size := mload(returndata)
                                        revert(add(32, returndata), returndata_size)
                                    }
                                } else {
                                    revert(errorMessage);
                                }
                            }
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
                    pragma solidity ^0.8.0;
                    import "../proxy/utils/Initializable.sol";
                    /**
                     * @dev Provides information about the current execution context, including the
                     * sender of the transaction and its data. While these are generally available
                     * via msg.sender and msg.data, they should not be accessed in such a direct
                     * manner, since when dealing with meta-transactions the account sending and
                     * paying for execution may not be the actual sender (as far as an application
                     * is concerned).
                     *
                     * This contract is only required for intermediate, library-like contracts.
                     */
                    abstract contract ContextUpgradeable is Initializable {
                        function __Context_init() internal onlyInitializing {
                            __Context_init_unchained();
                        }
                        function __Context_init_unchained() internal onlyInitializing {
                        }
                        function _msgSender() internal view virtual returns (address) {
                            return msg.sender;
                        }
                        function _msgData() internal view virtual returns (bytes calldata) {
                            return msg.data;
                        }
                        uint256[50] private __gap;
                    }
                    // SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
                    pragma solidity ^0.8.0;
                    import "../utils/Context.sol";
                    /**
                     * @dev Contract module which provides a basic access control mechanism, where
                     * there is an account (an owner) that can be granted exclusive access to
                     * specific functions.
                     *
                     * By default, the owner account will be the one that deploys the contract. This
                     * can later be changed with {transferOwnership}.
                     *
                     * This module is used through inheritance. It will make available the modifier
                     * `onlyOwner`, which can be applied to your functions to restrict their use to
                     * the owner.
                     */
                    abstract contract Ownable is Context {
                        address private _owner;
                        event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                        /**
                         * @dev Initializes the contract setting the deployer as the initial owner.
                         */
                        constructor() {
                            _transferOwnership(_msgSender());
                        }
                        /**
                         * @dev Returns the address of the current owner.
                         */
                        function owner() public view virtual returns (address) {
                            return _owner;
                        }
                        /**
                         * @dev Throws if called by any account other than the owner.
                         */
                        modifier onlyOwner() {
                            require(owner() == _msgSender(), "Ownable: caller is not the owner");
                            _;
                        }
                        /**
                         * @dev Leaves the contract without owner. It will not be possible to call
                         * `onlyOwner` functions anymore. Can only be called by the current owner.
                         *
                         * NOTE: Renouncing ownership will leave the contract without an owner,
                         * thereby removing any functionality that is only available to the owner.
                         */
                        function renounceOwnership() public virtual onlyOwner {
                            _transferOwnership(address(0));
                        }
                        /**
                         * @dev Transfers ownership of the contract to a new account (`newOwner`).
                         * Can only be called by the current owner.
                         */
                        function transferOwnership(address newOwner) public virtual onlyOwner {
                            require(newOwner != address(0), "Ownable: new owner is the zero address");
                            _transferOwnership(newOwner);
                        }
                        /**
                         * @dev Transfers ownership of the contract to a new account (`newOwner`).
                         * Internal function without access restriction.
                         */
                        function _transferOwnership(address newOwner) internal virtual {
                            address oldOwner = _owner;
                            _owner = newOwner;
                            emit OwnershipTransferred(oldOwner, newOwner);
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
                    pragma solidity ^0.8.0;
                    /**
                     * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
                     * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
                     *
                     * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
                     * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
                     * need to send a transaction, and thus is not required to hold Ether at all.
                     */
                    interface IERC20Permit {
                        /**
                         * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
                         * given ``owner``'s signed approval.
                         *
                         * IMPORTANT: The same issues {IERC20-approve} has related to transaction
                         * ordering also apply here.
                         *
                         * Emits an {Approval} event.
                         *
                         * Requirements:
                         *
                         * - `spender` cannot be the zero address.
                         * - `deadline` must be a timestamp in the future.
                         * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
                         * over the EIP712-formatted function arguments.
                         * - the signature must use ``owner``'s current nonce (see {nonces}).
                         *
                         * For more information on the signature format, see the
                         * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
                         * section].
                         */
                        function permit(
                            address owner,
                            address spender,
                            uint256 value,
                            uint256 deadline,
                            uint8 v,
                            bytes32 r,
                            bytes32 s
                        ) external;
                        /**
                         * @dev Returns the current nonce for `owner`. This value must be
                         * included whenever a signature is generated for {permit}.
                         *
                         * Every successful call to {permit} increases ``owner``'s nonce by one. This
                         * prevents a signature from being used multiple times.
                         */
                        function nonces(address owner) external view returns (uint256);
                        /**
                         * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
                         */
                        // solhint-disable-next-line func-name-mixedcase
                        function DOMAIN_SEPARATOR() external view returns (bytes32);
                    }
                    // SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
                    pragma solidity ^0.8.0;
                    /**
                     * @dev Interface of the ERC20 standard as defined in the EIP.
                     */
                    interface IERC20 {
                        /**
                         * @dev Returns the amount of tokens in existence.
                         */
                        function totalSupply() external view returns (uint256);
                        /**
                         * @dev Returns the amount of tokens owned by `account`.
                         */
                        function balanceOf(address account) external view returns (uint256);
                        /**
                         * @dev Moves `amount` tokens from the caller's account to `recipient`.
                         *
                         * Returns a boolean value indicating whether the operation succeeded.
                         *
                         * Emits a {Transfer} event.
                         */
                        function transfer(address recipient, uint256 amount) external returns (bool);
                        /**
                         * @dev Returns the remaining number of tokens that `spender` will be
                         * allowed to spend on behalf of `owner` through {transferFrom}. This is
                         * zero by default.
                         *
                         * This value changes when {approve} or {transferFrom} are called.
                         */
                        function allowance(address owner, address spender) external view returns (uint256);
                        /**
                         * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
                         *
                         * Returns a boolean value indicating whether the operation succeeded.
                         *
                         * IMPORTANT: Beware that changing an allowance with this method brings the risk
                         * that someone may use both the old and the new allowance by unfortunate
                         * transaction ordering. One possible solution to mitigate this race
                         * condition is to first reduce the spender's allowance to 0 and set the
                         * desired value afterwards:
                         * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                         *
                         * Emits an {Approval} event.
                         */
                        function approve(address spender, uint256 amount) external returns (bool);
                        /**
                         * @dev Moves `amount` tokens from `sender` to `recipient` using the
                         * allowance mechanism. `amount` is then deducted from the caller's
                         * allowance.
                         *
                         * Returns a boolean value indicating whether the operation succeeded.
                         *
                         * Emits a {Transfer} event.
                         */
                        function transferFrom(
                            address sender,
                            address recipient,
                            uint256 amount
                        ) external returns (bool);
                        /**
                         * @dev Emitted when `value` tokens are moved from one account (`from`) to
                         * another (`to`).
                         *
                         * Note that `value` may be zero.
                         */
                        event Transfer(address indexed from, address indexed to, uint256 value);
                        /**
                         * @dev Emitted when the allowance of a `spender` for an `owner` is set by
                         * a call to {approve}. `value` is the new allowance.
                         */
                        event Approval(address indexed owner, address indexed spender, uint256 value);
                    }
                    // SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
                    pragma solidity ^0.8.0;
                    /**
                     * @dev Provides information about the current execution context, including the
                     * sender of the transaction and its data. While these are generally available
                     * via msg.sender and msg.data, they should not be accessed in such a direct
                     * manner, since when dealing with meta-transactions the account sending and
                     * paying for execution may not be the actual sender (as far as an application
                     * is concerned).
                     *
                     * This contract is only required for intermediate, library-like contracts.
                     */
                    abstract contract Context {
                        function _msgSender() internal view virtual returns (address) {
                            return msg.sender;
                        }
                        function _msgData() internal view virtual returns (bytes calldata) {
                            return msg.data;
                        }
                    }
                    // SPDX-License-Identifier: GPL-3.0-or-later
                    pragma solidity >=0.6.0;
                    // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
                    library TransferHelper {
                        function safeApprove(
                            address token,
                            address to,
                            uint256 value
                        ) internal {
                            // bytes4(keccak256(bytes('approve(address,uint256)')));
                            (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
                            require(
                                success && (data.length == 0 || abi.decode(data, (bool))),
                                'TransferHelper::safeApprove: approve failed'
                            );
                        }
                        function safeTransfer(
                            address token,
                            address to,
                            uint256 value
                        ) internal {
                            // bytes4(keccak256(bytes('transfer(address,uint256)')));
                            (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
                            require(
                                success && (data.length == 0 || abi.decode(data, (bool))),
                                'TransferHelper::safeTransfer: transfer failed'
                            );
                        }
                        function safeTransferFrom(
                            address token,
                            address from,
                            address to,
                            uint256 value
                        ) internal {
                            // bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
                            (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
                            require(
                                success && (data.length == 0 || abi.decode(data, (bool))),
                                'TransferHelper::transferFrom: transferFrom failed'
                            );
                        }
                        function safeTransferETH(address to, uint256 value) internal {
                            (bool success, ) = to.call{value: value}(new bytes(0));
                            require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
                        }
                    }
                    // SPDX-License-Identifier: GPL-3.0
                    pragma solidity ^0.8.0;
                    interface IBridge {
                      function transmitRequestV2(
                        bytes memory _callData,
                        address _receiveSide,
                        address _oppositeBridge,
                        uint256 _chainId
                      ) external;
                      
                      function receiveRequestV2(
                        bytes memory _callData,
                        address _receiveSide
                      ) external;
                    }
                    // SPDX-License-Identifier: GPL-3.0
                    pragma solidity ^0.8.0;
                    interface IWrapper {
                        function deposit() external payable;
                        function withdraw(uint256 amount) external;
                    }
                    // SPDX-License-Identifier: GPL-3.0
                    pragma solidity ^0.8.0;
                    import "../MetaRouteStructs.sol";
                    interface IMetaRouter {
                        function metaRoute(
                            MetaRouteStructs.MetaRouteTransaction calldata _metarouteTransaction
                        ) external payable;
                        function externalCall(
                            address _token,
                            uint256 _amount,
                            address _receiveSide,
                            bytes calldata _calldata,
                            uint256 _offset,
                            address _revertableAddress
                        ) external;
                        function returnSwap(
                            address _token,
                            uint256 _amount,
                            address _router,
                            bytes calldata _swapCalldata,
                            address _burnToken,
                            address _synthesis,
                            bytes calldata _burnCalldata
                        ) external;
                        function metaMintSwap(
                            MetaRouteStructs.MetaMintTransaction calldata _metaMintTransaction
                        ) external;
                    }
                    // SPDX-License-Identifier: GPL-3.0
                    pragma solidity ^0.8.0;
                    library MetaRouteStructs {
                        struct MetaBurnTransaction {
                            uint256 stableBridgingFee;
                            uint256 amount;
                            bytes32 crossChainID;
                            address syntCaller;
                            address finalReceiveSide;
                            address sToken;
                            bytes finalCallData;
                            uint256 finalOffset;
                            address chain2address;
                            address receiveSide;
                            address oppositeBridge;
                            address revertableAddress;
                            uint256 chainID;
                            bytes32 clientID;
                        }
                        struct MetaMintTransaction {
                            uint256 stableBridgingFee;
                            uint256 amount;
                            bytes32 crossChainID;
                            bytes32 externalID;
                            address tokenReal;
                            uint256 chainID;
                            address to;
                            address[] swapTokens;
                            address secondDexRouter;
                            bytes secondSwapCalldata;
                            address finalReceiveSide;
                            bytes finalCalldata;
                            uint256 finalOffset;
                        }
                        struct MetaRouteTransaction {
                            bytes firstSwapCalldata;
                            bytes secondSwapCalldata;
                            address[] approvedTokens;
                            address firstDexRouter;
                            address secondDexRouter;
                            uint256 amount;
                            bool nativeIn;
                            address relayRecipient;
                            bytes otherSideCalldata;
                        }
                        struct MetaSynthesizeTransaction {
                            uint256 stableBridgingFee;
                            uint256 amount;
                            address rtoken;
                            address chain2address;
                            address receiveSide;
                            address oppositeBridge;
                            address syntCaller;
                            uint256 chainID;
                            address[] swapTokens;
                            address secondDexRouter;
                            bytes secondSwapCalldata;
                            address finalReceiveSide;
                            bytes finalCalldata;
                            uint256 finalOffset;
                            address revertableAddress;
                            bytes32 clientID;
                        }
                        struct MetaRevertTransaction {
                            uint256 stableBridgingFee;
                            bytes32 internalID;
                            address receiveSide;
                            address managerChainBridge;
                            address sourceChainBridge;
                            uint256 managerChainId;
                            uint256 sourceChainId;
                            address router;
                            bytes swapCalldata;
                            address sourceChainSynthesis;
                            address burnToken;
                            bytes burnCalldata;
                            bytes32 clientID;
                        }
                    }
                    // SPDX-License-Identifier: GPL-3.0
                    pragma solidity ^0.8.0;
                    import "@openzeppelin/contracts/access/Ownable.sol";
                    import "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol";
                    import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
                    import "./interfaces/IBridge.sol";
                    import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
                    import "../utils/RelayRecipientUpgradeable.sol";
                    import "./interfaces/IWrapper.sol";
                    import "./metarouter/interfaces/IMetaRouter.sol";
                    /**
                     * @title A contract that synthesizes tokens
                     * @notice In order to create a synthetic representation on another network, the user must call synthesize function here
                     * @dev All function calls are currently implemented without side effects
                     */
                    contract Portal is RelayRecipientUpgradeable {
                        /// ** PUBLIC states **
                        address public wrapper;
                        address public bridge;
                        uint256 public requestCount;
                        bool public paused;
                        mapping(bytes32 => TxState) public requests;
                        mapping(bytes32 => UnsynthesizeState) public unsynthesizeStates;
                        mapping(address => uint256) public balanceOf;
                        mapping(address => uint256) public tokenThreshold;
                        mapping(address => bool) public tokenWhitelist;
                        IMetaRouter public metaRouter;
                        /// ** STRUCTS **
                        enum RequestState {
                            Default,
                            Sent,
                            Reverted
                        }
                        enum UnsynthesizeState {
                            Default,
                            Unsynthesized,
                            RevertRequest
                        }
                        struct TxState {
                            address recipient;
                            address chain2address;
                            uint256 amount;
                            address rtoken;
                            RequestState state;
                        }
                        struct SynthesizeWithPermitTransaction {
                            uint256 stableBridgingFee;
                            bytes approvalData;
                            address token;
                            uint256 amount;
                            address chain2address;
                            address receiveSide;
                            address oppositeBridge;
                            address revertableAddress;
                            uint256 chainID;
                            bytes32 clientID;
                        }
                        /// ** EVENTS **
                        event SynthesizeRequest(
                            bytes32 id, // todo it wasn't indexed
                            address indexed from,
                            uint256 indexed chainID,
                            address indexed revertableAddress, // todo it was indexed
                            address to,
                            uint256 amount,
                            address token
                        );
                        event RevertBurnRequest(bytes32 indexed id, address indexed to);
                        event ClientIdLog(bytes32 requestId, bytes32 indexed clientId);
                        event MetaRevertRequest(bytes32 indexed id, address indexed to);
                        event BurnCompleted(
                            bytes32 indexed id,
                            bytes32 indexed crossChainID,
                            address indexed to,
                            uint256 amount,
                            uint256 bridgingFee,
                            address token
                        );
                        event RevertSynthesizeCompleted(
                            bytes32 indexed id,
                            address indexed to,
                            uint256 amount,
                            uint256 bridgingFee,
                            address token
                        );
                        event Paused(address account);
                        event Unpaused(address account);
                        event SetWhitelistToken(address token, bool activate);
                        event SetTokenThreshold(address token, uint256 threshold);
                        event SetMetaRouter(address metaRouter);
                        event SetWrapper(address wrapper);
                        event SetBalanceOf(address[] tokens);
                        /// ** MODIFIERs **
                        modifier onlyBridge() {
                            require(bridge == msg.sender, "Symb: caller is not the bridge");
                            _;
                        }
                        modifier whenNotPaused() {
                            require(!paused, "Symb: paused");
                            _;
                        }
                        /// ** INITIALIZER **
                        /**
                         * init
                         */
                        function initialize(
                            address _bridge,
                            address _trustedForwarder,
                            address _wrapper,
                            address _whitelistedToken,
                            IMetaRouter _metaRouter
                        ) public virtual initializer {
                            __RelayRecipient_init(_trustedForwarder);
                            bridge = _bridge;
                            wrapper = _wrapper;
                            metaRouter = _metaRouter;
                            if (_whitelistedToken != address(0)) {
                                tokenWhitelist[_whitelistedToken] = true;
                            }
                        }
                        /// ** EXTERNAL PURE functions **
                        /**
                         * @notice Returns version
                         */
                        function versionRecipient() external pure returns (string memory) {
                            return "2.0.1";
                        }
                        // ** EXTERNAL functions **
                        /**
                         * @notice Sends synthesize request
                         * @dev Token -> sToken on a second chain
                         * @param _stableBridgingFee Bridging fee on another network
                         * @param _token The address of the token that the user wants to synthesize
                         * @param _amount Number of tokens to synthesize
                         * @param _chain2address The address to which the user wants to receive the synth asset on another network
                         * @param _receiveSide Synthesis address on another network
                         * @param _oppositeBridge Bridge address on another network
                         * @param _revertableAddress An address on another network that allows the user to revert a stuck request
                         * @param _chainID Chain id of the network where synthesization will take place
                         */
                        function synthesize(
                            uint256 _stableBridgingFee,
                            address _token,
                            uint256 _amount,
                            address _chain2address,
                            address _receiveSide,
                            address _oppositeBridge,
                            address _revertableAddress,
                            uint256 _chainID,
                            bytes32 _clientID
                        ) external whenNotPaused returns (bytes32) {
                            require(tokenWhitelist[_token], "Symb: unauthorized token");
                            require(_amount >= tokenThreshold[_token], "Symb: amount under threshold");
                            TransferHelper.safeTransferFrom(
                                _token,
                                _msgSender(),
                                address(this),
                                _amount
                            );
                            return
                            sendSynthesizeRequest(
                                _stableBridgingFee,
                                _token,
                                _amount,
                                _chain2address,
                                _receiveSide,
                                _oppositeBridge,
                                _revertableAddress,
                                _chainID,
                                _clientID
                            );
                        }
                        /**
                         * @notice Sends metaSynthesizeOffchain request
                         * @dev Token -> sToken on a second chain -> final token on a second chain
                         * @param _metaSynthesizeTransaction metaSynthesize offchain transaction data
                         */
                        function metaSynthesize(
                            MetaRouteStructs.MetaSynthesizeTransaction
                            memory _metaSynthesizeTransaction
                        ) external whenNotPaused returns (bytes32) {
                            require(tokenWhitelist[_metaSynthesizeTransaction.rtoken], "Symb: unauthorized token");
                            require(_metaSynthesizeTransaction.amount >= tokenThreshold[_metaSynthesizeTransaction.rtoken],
                                "Symb: amount under threshold");
                            TransferHelper.safeTransferFrom(
                                _metaSynthesizeTransaction.rtoken,
                                _msgSender(),
                                address(this),
                                _metaSynthesizeTransaction.amount
                            );
                            return sendMetaSynthesizeRequest(_metaSynthesizeTransaction);
                        }
                        /**
                         * @notice Emergency unsynthesize
                         * @dev Can called only by bridge after initiation on a second chain
                         * @dev If a transaction arrives at the synthesization chain with an already completed revert synthesize contract will fail this transaction,
                         * since the state was changed during the call to the desynthesis request
                         * @param _stableBridgingFee Bridging fee
                         * @param _externalID the synthesize transaction that was received from the event when it was originally called synthesize on the Portal contract
                         */
                        function revertSynthesize(uint256 _stableBridgingFee, bytes32 _externalID) external onlyBridge whenNotPaused {
                            TxState storage txState = requests[_externalID];
                            require(
                                txState.state == RequestState.Sent,
                                "Symb: state not open or tx does not exist"
                            );
                            txState.state = RequestState.Reverted;
                            // close
                            balanceOf[txState.rtoken] = balanceOf[txState.rtoken] - txState.amount;
                            TransferHelper.safeTransfer(
                                txState.rtoken,
                                txState.recipient,
                                txState.amount - _stableBridgingFee
                            );
                            TransferHelper.safeTransfer(
                                txState.rtoken,
                                bridge,
                                _stableBridgingFee
                            );
                            emit RevertSynthesizeCompleted(
                                _externalID,
                                txState.recipient,
                                txState.amount - _stableBridgingFee,
                                _stableBridgingFee,
                                txState.rtoken
                            );
                        }
                        /**
                         * @notice Revert synthesize
                         * @dev After revertSynthesizeRequest in Synthesis this method is called
                         * @param _stableBridgingFee Bridging fee
                         * @param _externalID the burn transaction that was received from the event when it was originally called burn on the Synthesis contract
                         * @param _token The address of the token to unsynthesize
                         * @param _amount Number of tokens to unsynthesize
                         * @param _to The address to receive tokens
                         */
                        function unsynthesize(
                            uint256 _stableBridgingFee,
                            bytes32 _externalID,
                            bytes32 _crossChainID,
                            address _token,
                            uint256 _amount,
                            address _to
                        ) external onlyBridge whenNotPaused {
                            require(
                                unsynthesizeStates[_externalID] == UnsynthesizeState.Default,
                                "Symb: synthetic tokens emergencyUnburn"
                            );
                            balanceOf[_token] = balanceOf[_token] - _amount;
                            unsynthesizeStates[_externalID] = UnsynthesizeState.Unsynthesized;
                            TransferHelper.safeTransfer(_token, _to, _amount - _stableBridgingFee);
                            TransferHelper.safeTransfer(_token, bridge, _stableBridgingFee);
                            emit BurnCompleted(_externalID, _crossChainID, _to, _amount - _stableBridgingFee, _stableBridgingFee, _token);
                        }
                        /**
                         * @notice Unsynthesize and final call on second chain
                         * @dev Token -> sToken on a first chain -> final token on a second chain
                         * @param _stableBridgingFee Number of tokens to send to bridge (fee)
                         * @param _externalID the metaBurn transaction that was received from the event when it was originally called metaBurn on the Synthesis contract
                         * @param _to The address to receive tokens
                         * @param _amount Number of tokens to unsynthesize
                         * @param _rToken The address of the token to unsynthesize
                         * @param _finalReceiveSide router for final call
                         * @param _finalCalldata encoded call of a final function
                         * @param _finalOffset offset to patch _amount to _finalCalldata
                         */
                        function metaUnsynthesize(
                            uint256 _stableBridgingFee,
                            bytes32 _crossChainID,
                            bytes32 _externalID,
                            address _to,
                            uint256 _amount,
                            address _rToken,
                            address _finalReceiveSide,
                            bytes memory _finalCalldata,
                            uint256 _finalOffset
                        ) external onlyBridge whenNotPaused {
                            require(
                                unsynthesizeStates[_externalID] == UnsynthesizeState.Default,
                                "Symb: synthetic tokens emergencyUnburn"
                            );
                            balanceOf[_rToken] = balanceOf[_rToken] - _amount;
                            unsynthesizeStates[_externalID] = UnsynthesizeState.Unsynthesized;
                            TransferHelper.safeTransfer(_rToken, bridge, _stableBridgingFee);
                            _amount = _amount - _stableBridgingFee;
                            if (_finalCalldata.length == 0) {
                                TransferHelper.safeTransfer(_rToken, _to, _amount);
                                emit BurnCompleted(_externalID, _crossChainID, _to, _amount, _stableBridgingFee, _rToken);
                                return;
                            }
                            // transfer ERC20 tokens to MetaRouter
                            TransferHelper.safeTransfer(
                                _rToken,
                                address(metaRouter),
                                _amount
                            );
                            // metaRouter call
                            metaRouter.externalCall(_rToken, _amount, _finalReceiveSide, _finalCalldata, _finalOffset, _to);
                            emit BurnCompleted(_externalID, _crossChainID, _to, _amount, _stableBridgingFee, _rToken);
                        }
                        /**
                         * @notice Revert burnSyntheticToken() operation
                         * @dev Can called only by bridge after initiation on a second chain
                         * @dev Further, this transaction also enters the relay network and is called on the other side under the method "revertBurn"
                         * @param _stableBridgingFee Bridging fee on another network
                         * @param _internalID the synthesize transaction that was received from the event when it was originally called burn on the Synthesize contract
                         * @param _receiveSide Synthesis address on another network
                         * @param _oppositeBridge Bridge address on another network
                         * @param _chainId Chain id of the network
                         */
                        function revertBurnRequest(
                            uint256 _stableBridgingFee,
                            bytes32 _internalID,
                            address _receiveSide,
                            address _oppositeBridge,
                            uint256 _chainId,
                            bytes32 _clientID
                        ) external whenNotPaused {
                            bytes32 externalID = keccak256(abi.encodePacked(_internalID, address(this), _msgSender(), block.chainid));
                            require(
                                unsynthesizeStates[externalID] != UnsynthesizeState.Unsynthesized,
                                "Symb: Real tokens already transfered"
                            );
                            unsynthesizeStates[externalID] = UnsynthesizeState.RevertRequest;
                            {
                                bytes memory out = abi.encodeWithSelector(
                                    bytes4(keccak256(bytes("revertBurn(uint256,bytes32)"))),
                                    _stableBridgingFee,
                                    externalID
                                );
                                IBridge(bridge).transmitRequestV2(
                                    out,
                                    _receiveSide,
                                    _oppositeBridge,
                                    _chainId
                                );
                            }
                            emit RevertBurnRequest(_internalID, _msgSender());
                            emit ClientIdLog(_internalID, _clientID);
                        }
                        function metaRevertRequest(
                            MetaRouteStructs.MetaRevertTransaction memory _metaRevertTransaction
                        ) external whenNotPaused {
                            if (_metaRevertTransaction.swapCalldata.length != 0){
                                bytes32 externalID = keccak256(abi.encodePacked(_metaRevertTransaction.internalID, address(this), _msgSender(), block.chainid));
                                require(
                                    unsynthesizeStates[externalID] != UnsynthesizeState.Unsynthesized,
                                    "Symb: Real tokens already transfered"
                                );
                                unsynthesizeStates[externalID] = UnsynthesizeState.RevertRequest;
                                {
                                    bytes memory out = abi.encodeWithSelector(
                                        bytes4(keccak256(bytes("revertMetaBurn(uint256,bytes32,address,bytes,address,address,bytes)"))),
                                        _metaRevertTransaction.stableBridgingFee,
                                        externalID,
                                        _metaRevertTransaction.router,
                                        _metaRevertTransaction.swapCalldata,
                                        _metaRevertTransaction.sourceChainSynthesis,
                                        _metaRevertTransaction.burnToken,
                                        _metaRevertTransaction.burnCalldata
                                    );
                                    IBridge(bridge).transmitRequestV2(
                                        out,
                                        _metaRevertTransaction.receiveSide,
                                        _metaRevertTransaction.managerChainBridge,
                                        _metaRevertTransaction.managerChainId
                                    );
                                    emit RevertBurnRequest(_metaRevertTransaction.internalID, _msgSender());
                                    emit ClientIdLog(_metaRevertTransaction.internalID, _metaRevertTransaction.clientID);
                                }
                            } else {
                                if (_metaRevertTransaction.burnCalldata.length != 0){
                                    bytes32 externalID = keccak256(abi.encodePacked(_metaRevertTransaction.internalID, address(this), _msgSender(), block.chainid));
                                    require(
                                        unsynthesizeStates[externalID] != UnsynthesizeState.Unsynthesized,
                                        "Symb: Real tokens already transfered"
                                    );
                                    unsynthesizeStates[externalID] = UnsynthesizeState.RevertRequest;
                                    bytes memory out = abi.encodeWithSelector(
                                        bytes4(keccak256(bytes("revertBurnAndBurn(uint256,bytes32,address,address,uint256,address)"))),
                                        _metaRevertTransaction.stableBridgingFee,
                                        externalID,
                                        address(this),
                                        _metaRevertTransaction.sourceChainBridge,
                                        block.chainid,
                                        _msgSender()
                                    );
                                    IBridge(bridge).transmitRequestV2(
                                        out,
                                        _metaRevertTransaction.sourceChainSynthesis,
                                        _metaRevertTransaction.managerChainBridge,
                                        _metaRevertTransaction.managerChainId
                                    );
                                    emit RevertBurnRequest(_metaRevertTransaction.internalID, _msgSender());
                                    emit ClientIdLog(_metaRevertTransaction.internalID, _metaRevertTransaction.clientID);
                                } else {
                                    bytes memory out = abi.encodeWithSelector(
                                        bytes4(keccak256(bytes("revertSynthesizeRequestByBridge(uint256,bytes32,address,address,uint256,address,bytes32)"))),
                                        _metaRevertTransaction.stableBridgingFee,
                                        _metaRevertTransaction.internalID,
                                        _metaRevertTransaction.receiveSide,
                                        _metaRevertTransaction.sourceChainBridge,
                                        block.chainid,
                                        _msgSender(),
                                        _metaRevertTransaction.clientID
                                    );
                                    IBridge(bridge).transmitRequestV2(
                                        out,
                                        _metaRevertTransaction.sourceChainSynthesis,
                                        _metaRevertTransaction.managerChainBridge,
                                        _metaRevertTransaction.managerChainId
                                    );
                                }
                            }
                            emit MetaRevertRequest(_metaRevertTransaction.internalID, _msgSender());
                        }
                        // ** ONLYOWNER functions **
                        /**
                         * @notice Set paused flag to true
                         */
                        function pause() external onlyOwner {
                            paused = true;
                            emit Paused(_msgSender());
                        }
                        /**
                         * @notice Set paused flag to false
                         */
                        function unpause() external onlyOwner {
                            paused = false;
                            emit Unpaused(_msgSender());
                        }
                        /**
                         * @notice Sets token to tokenWhitelist
                         * @param _token Address of token to add to whitelist
                         * @param _activate true - add to whitelist, false - remove from whitelist
                         */
                        function setWhitelistToken(address _token, bool _activate) external onlyOwner {
                            tokenWhitelist[_token] = _activate;
                            emit SetWhitelistToken(_token, _activate);
                        }
                        /**
                         * @notice Sets minimal price for token
                         * @param _token Address of token to set threshold
                         * @param _threshold threshold to set
                         */
                        function setTokenThreshold(address _token, uint256 _threshold) external onlyOwner {
                            tokenThreshold[_token] = _threshold;
                            emit SetTokenThreshold(_token, _threshold);
                        }
                        function setWrapper(address _wrapper) external onlyOwner {
                            wrapper = _wrapper;
                            emit SetWrapper(_wrapper);
                        }
                        function setBalanceOf(address[] memory _tokens) external onlyOwner {
                            for (uint256 i = 0; i < _tokens.length; i++) {
                                require(tokenWhitelist[_tokens[i]], "Symb: unauthorized token");
                                balanceOf[_tokens[i]] = IERC20(_tokens[i]).balanceOf(address(this));
                            }
                            emit SetBalanceOf(_tokens);
                        }
                        /**
                         * @notice Sets MetaRouter address
                         * @param _metaRouter Address of metaRouter
                         */
                        function setMetaRouter(IMetaRouter _metaRouter) external onlyOwner {
                            require(address(_metaRouter) != address(0), "Symb: metaRouter cannot be zero address");
                            metaRouter = _metaRouter;
                            emit SetMetaRouter(address(_metaRouter));
                        }
                        /// ** INTERNAL functions **
                        /**
                         * @dev Sends synthesize request
                         * @dev Internal function used in synthesize, synthesizeNative, synthesizeWithPermit
                         */
                        function sendSynthesizeRequest(
                            uint256 _stableBridgingFee,
                            address _token,
                            uint256 _amount,
                            address _chain2address,
                            address _receiveSide,
                            address _oppositeBridge,
                            address _revertableAddress,
                            uint256 _chainID,
                            bytes32 _clientID
                        ) internal returns (bytes32 internalID) {
                            balanceOf[_token] = balanceOf[_token] + _amount;
                            if (_revertableAddress == address(0)) {
                                _revertableAddress = _chain2address;
                            }
                            internalID = keccak256(abi.encodePacked(this, requestCount, block.chainid));
                            {
                                bytes32 externalID = keccak256(abi.encodePacked(internalID, _receiveSide, _revertableAddress, _chainID));
                                {
                                    bytes memory out = abi.encodeWithSelector(
                                        bytes4(
                                            keccak256(
                                                bytes(
                                                    "mintSyntheticToken(uint256,bytes32,bytes32,address,uint256,uint256,address)"
                                                )
                                            )
                                        ),
                                        _stableBridgingFee,
                                        externalID,
                                        internalID,
                                        _token,
                                        block.chainid,
                                        _amount,
                                        _chain2address
                                    );
                                    requests[externalID] = TxState({
                                        recipient : _msgSender(),
                                        chain2address : _chain2address,
                                        rtoken : _token,
                                        amount : _amount,
                                        state : RequestState.Sent
                                    });
                                    requestCount++;
                                    IBridge(bridge).transmitRequestV2(
                                        out,
                                        _receiveSide,
                                        _oppositeBridge,
                                        _chainID
                                    );
                                }
                            }
                            emit SynthesizeRequest(
                                internalID,
                                _msgSender(),
                                _chainID,
                                _revertableAddress,
                                _chain2address,
                                _amount,
                                _token
                            );
                            emit ClientIdLog(internalID, _clientID);
                        }
                        /**
                         * @dev Sends metaSynthesizeOffchain request
                         * @dev Internal function used in metaSynthesizeOffchain
                         */
                        function sendMetaSynthesizeRequest(
                            MetaRouteStructs.MetaSynthesizeTransaction
                            memory _metaSynthesizeTransaction
                        ) internal returns (bytes32 internalID) {
                            balanceOf[_metaSynthesizeTransaction.rtoken] =
                            balanceOf[_metaSynthesizeTransaction.rtoken] +
                            _metaSynthesizeTransaction.amount;
                            if (_metaSynthesizeTransaction.revertableAddress == address(0)) {
                                _metaSynthesizeTransaction.revertableAddress = _metaSynthesizeTransaction.chain2address;
                            }
                            internalID = keccak256(abi.encodePacked(this, requestCount, block.chainid));
                            bytes32 externalID = keccak256(
                                abi.encodePacked(internalID, _metaSynthesizeTransaction.receiveSide, _metaSynthesizeTransaction.revertableAddress, _metaSynthesizeTransaction.chainID)
                            );
                            MetaRouteStructs.MetaMintTransaction
                            memory _metaMintTransaction = MetaRouteStructs.MetaMintTransaction(
                                _metaSynthesizeTransaction.stableBridgingFee,
                                _metaSynthesizeTransaction.amount,
                                internalID,
                                externalID,
                                _metaSynthesizeTransaction.rtoken,
                                block.chainid,
                                _metaSynthesizeTransaction.chain2address,
                                _metaSynthesizeTransaction.swapTokens,
                                _metaSynthesizeTransaction.secondDexRouter,
                                _metaSynthesizeTransaction.secondSwapCalldata,
                                _metaSynthesizeTransaction.finalReceiveSide,
                                _metaSynthesizeTransaction.finalCalldata,
                                _metaSynthesizeTransaction.finalOffset
                            );
                            {
                                bytes memory out = abi.encodeWithSignature(
                                    "metaMintSyntheticToken((uint256,uint256,bytes32,bytes32,address,uint256,address,address[],"
                                    "address,bytes,address,bytes,uint256))",
                                    _metaMintTransaction
                                );
                                requests[externalID] = TxState({
                                    recipient : _metaSynthesizeTransaction.syntCaller,
                                    chain2address : _metaSynthesizeTransaction.chain2address,
                                    rtoken : _metaSynthesizeTransaction.rtoken,
                                    amount : _metaSynthesizeTransaction.amount,
                                    state : RequestState.Sent
                                });
                                requestCount++;
                                IBridge(bridge).transmitRequestV2(
                                    out,
                                    _metaSynthesizeTransaction.receiveSide,
                                    _metaSynthesizeTransaction.oppositeBridge,
                                    _metaSynthesizeTransaction.chainID
                                );
                            }
                            emit SynthesizeRequest(
                                internalID,
                                _metaSynthesizeTransaction.syntCaller,
                                _metaSynthesizeTransaction.chainID,
                                _metaSynthesizeTransaction.revertableAddress,
                                _metaSynthesizeTransaction.chain2address,
                                _metaSynthesizeTransaction.amount,
                                _metaSynthesizeTransaction.rtoken
                            );
                            emit ClientIdLog(internalID, _metaSynthesizeTransaction.clientID);
                        }
                    }
                    // SPDX-License-Identifier: GPL-3.0
                    pragma solidity ^0.8.0;
                    import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
                    abstract contract RelayRecipientUpgradeable is OwnableUpgradeable {
                        address private _trustedForwarder;
                        function __RelayRecipient_init(address trustedForwarder)
                            internal
                            onlyInitializing
                        {
                            __Ownable_init();
                            _trustedForwarder = trustedForwarder;
                        }
                        function isTrustedForwarder(address forwarder)
                            public
                            view
                            virtual
                            returns (bool)
                        {
                            return forwarder == _trustedForwarder;
                        }
                        function _msgSender()
                            internal
                            view
                            virtual
                            override
                            returns (address sender)
                        {
                            if (isTrustedForwarder(msg.sender)) {
                                // The assembly code is more direct than the Solidity version using `abi.decode`.
                                assembly {
                                    sender := shr(96, calldataload(sub(calldatasize(), 20)))
                                }
                            } else {
                                return super._msgSender();
                            }
                        }
                        function _msgData()
                            internal
                            view
                            virtual
                            override
                            returns (bytes calldata)
                        {
                            if (isTrustedForwarder(msg.sender)) {
                                return msg.data[:msg.data.length - 20];
                            } else {
                                return super._msgData();
                            }
                        }
                    }
                    

                    File 7 of 9: FiatTokenV2_2
                    /**
                     * SPDX-License-Identifier: Apache-2.0
                     *
                     * Copyright (c) 2023, Circle Internet Financial, LLC.
                     *
                     * Licensed under the Apache License, Version 2.0 (the "License");
                     * you may not use this file except in compliance with the License.
                     * You may obtain a copy of the License at
                     *
                     * http://www.apache.org/licenses/LICENSE-2.0
                     *
                     * Unless required by applicable law or agreed to in writing, software
                     * distributed under the License is distributed on an "AS IS" BASIS,
                     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                     * See the License for the specific language governing permissions and
                     * limitations under the License.
                     */
                    pragma solidity 0.6.12;
                    import { EIP712Domain } from "./EIP712Domain.sol"; // solhint-disable-line no-unused-import
                    import { Blacklistable } from "../v1/Blacklistable.sol"; // solhint-disable-line no-unused-import
                    import { FiatTokenV1 } from "../v1/FiatTokenV1.sol"; // solhint-disable-line no-unused-import
                    import { FiatTokenV2 } from "./FiatTokenV2.sol"; // solhint-disable-line no-unused-import
                    import { FiatTokenV2_1 } from "./FiatTokenV2_1.sol";
                    import { EIP712 } from "../util/EIP712.sol";
                    // solhint-disable func-name-mixedcase
                    /**
                     * @title FiatToken V2.2
                     * @notice ERC20 Token backed by fiat reserves, version 2.2
                     */
                    contract FiatTokenV2_2 is FiatTokenV2_1 {
                        /**
                         * @notice Initialize v2.2
                         * @param accountsToBlacklist   A list of accounts to migrate from the old blacklist
                         * @param newSymbol             New token symbol
                         * data structure to the new blacklist data structure.
                         */
                        function initializeV2_2(
                            address[] calldata accountsToBlacklist,
                            string calldata newSymbol
                        ) external {
                            // solhint-disable-next-line reason-string
                            require(_initializedVersion == 2);
                            // Update fiat token symbol
                            symbol = newSymbol;
                            // Add previously blacklisted accounts to the new blacklist data structure
                            // and remove them from the old blacklist data structure.
                            for (uint256 i = 0; i < accountsToBlacklist.length; i++) {
                                require(
                                    _deprecatedBlacklisted[accountsToBlacklist[i]],
                                    "FiatTokenV2_2: Blacklisting previously unblacklisted account!"
                                );
                                _blacklist(accountsToBlacklist[i]);
                                delete _deprecatedBlacklisted[accountsToBlacklist[i]];
                            }
                            _blacklist(address(this));
                            delete _deprecatedBlacklisted[address(this)];
                            _initializedVersion = 3;
                        }
                        /**
                         * @dev Internal function to get the current chain id.
                         * @return The current chain id.
                         */
                        function _chainId() internal virtual view returns (uint256) {
                            uint256 chainId;
                            assembly {
                                chainId := chainid()
                            }
                            return chainId;
                        }
                        /**
                         * @inheritdoc EIP712Domain
                         */
                        function _domainSeparator() internal override view returns (bytes32) {
                            return EIP712.makeDomainSeparator(name, "2", _chainId());
                        }
                        /**
                         * @notice Update allowance with a signed permit
                         * @dev EOA wallet signatures should be packed in the order of r, s, v.
                         * @param owner       Token owner's address (Authorizer)
                         * @param spender     Spender's address
                         * @param value       Amount of allowance
                         * @param deadline    The time at which the signature expires (unix time), or max uint256 value to signal no expiration
                         * @param signature   Signature bytes signed by an EOA wallet or a contract wallet
                         */
                        function permit(
                            address owner,
                            address spender,
                            uint256 value,
                            uint256 deadline,
                            bytes memory signature
                        ) external whenNotPaused {
                            _permit(owner, spender, value, deadline, signature);
                        }
                        /**
                         * @notice Execute a transfer with a signed authorization
                         * @dev EOA wallet signatures should be packed in the order of r, s, v.
                         * @param from          Payer's address (Authorizer)
                         * @param to            Payee's address
                         * @param value         Amount to be transferred
                         * @param validAfter    The time after which this is valid (unix time)
                         * @param validBefore   The time before which this is valid (unix time)
                         * @param nonce         Unique nonce
                         * @param signature     Signature bytes signed by an EOA wallet or a contract wallet
                         */
                        function transferWithAuthorization(
                            address from,
                            address to,
                            uint256 value,
                            uint256 validAfter,
                            uint256 validBefore,
                            bytes32 nonce,
                            bytes memory signature
                        ) external whenNotPaused notBlacklisted(from) notBlacklisted(to) {
                            _transferWithAuthorization(
                                from,
                                to,
                                value,
                                validAfter,
                                validBefore,
                                nonce,
                                signature
                            );
                        }
                        /**
                         * @notice Receive a transfer with a signed authorization from the payer
                         * @dev This has an additional check to ensure that the payee's address
                         * matches the caller of this function to prevent front-running attacks.
                         * EOA wallet signatures should be packed in the order of r, s, v.
                         * @param from          Payer's address (Authorizer)
                         * @param to            Payee's address
                         * @param value         Amount to be transferred
                         * @param validAfter    The time after which this is valid (unix time)
                         * @param validBefore   The time before which this is valid (unix time)
                         * @param nonce         Unique nonce
                         * @param signature     Signature bytes signed by an EOA wallet or a contract wallet
                         */
                        function receiveWithAuthorization(
                            address from,
                            address to,
                            uint256 value,
                            uint256 validAfter,
                            uint256 validBefore,
                            bytes32 nonce,
                            bytes memory signature
                        ) external whenNotPaused notBlacklisted(from) notBlacklisted(to) {
                            _receiveWithAuthorization(
                                from,
                                to,
                                value,
                                validAfter,
                                validBefore,
                                nonce,
                                signature
                            );
                        }
                        /**
                         * @notice Attempt to cancel an authorization
                         * @dev Works only if the authorization is not yet used.
                         * EOA wallet signatures should be packed in the order of r, s, v.
                         * @param authorizer    Authorizer's address
                         * @param nonce         Nonce of the authorization
                         * @param signature     Signature bytes signed by an EOA wallet or a contract wallet
                         */
                        function cancelAuthorization(
                            address authorizer,
                            bytes32 nonce,
                            bytes memory signature
                        ) external whenNotPaused {
                            _cancelAuthorization(authorizer, nonce, signature);
                        }
                        /**
                         * @dev Helper method that sets the blacklist state of an account on balanceAndBlacklistStates.
                         * If _shouldBlacklist is true, we apply a (1 << 255) bitmask with an OR operation on the
                         * account's balanceAndBlacklistState. This flips the high bit for the account to 1,
                         * indicating that the account is blacklisted.
                         *
                         * If _shouldBlacklist if false, we reset the account's balanceAndBlacklistStates to their
                         * balances. This clears the high bit for the account, indicating that the account is unblacklisted.
                         * @param _account         The address of the account.
                         * @param _shouldBlacklist True if the account should be blacklisted, false if the account should be unblacklisted.
                         */
                        function _setBlacklistState(address _account, bool _shouldBlacklist)
                            internal
                            override
                        {
                            balanceAndBlacklistStates[_account] = _shouldBlacklist
                                ? balanceAndBlacklistStates[_account] | (1 << 255)
                                : _balanceOf(_account);
                        }
                        /**
                         * @dev Helper method that sets the balance of an account on balanceAndBlacklistStates.
                         * Since balances are stored in the last 255 bits of the balanceAndBlacklistStates value,
                         * we need to ensure that the updated balance does not exceed (2^255 - 1).
                         * Since blacklisted accounts' balances cannot be updated, the method will also
                         * revert if the account is blacklisted
                         * @param _account The address of the account.
                         * @param _balance The new fiat token balance of the account (max: (2^255 - 1)).
                         */
                        function _setBalance(address _account, uint256 _balance) internal override {
                            require(
                                _balance <= ((1 << 255) - 1),
                                "FiatTokenV2_2: Balance exceeds (2^255 - 1)"
                            );
                            require(
                                !_isBlacklisted(_account),
                                "FiatTokenV2_2: Account is blacklisted"
                            );
                            balanceAndBlacklistStates[_account] = _balance;
                        }
                        /**
                         * @inheritdoc Blacklistable
                         */
                        function _isBlacklisted(address _account)
                            internal
                            override
                            view
                            returns (bool)
                        {
                            return balanceAndBlacklistStates[_account] >> 255 == 1;
                        }
                        /**
                         * @dev Helper method to obtain the balance of an account. Since balances
                         * are stored in the last 255 bits of the balanceAndBlacklistStates value,
                         * we apply a ((1 << 255) - 1) bit bitmask with an AND operation on the
                         * balanceAndBlacklistState to obtain the balance.
                         * @param _account  The address of the account.
                         * @return          The fiat token balance of the account.
                         */
                        function _balanceOf(address _account)
                            internal
                            override
                            view
                            returns (uint256)
                        {
                            return balanceAndBlacklistStates[_account] & ((1 << 255) - 1);
                        }
                        /**
                         * @inheritdoc FiatTokenV1
                         */
                        function approve(address spender, uint256 value)
                            external
                            override
                            whenNotPaused
                            returns (bool)
                        {
                            _approve(msg.sender, spender, value);
                            return true;
                        }
                        /**
                         * @inheritdoc FiatTokenV2
                         */
                        function permit(
                            address owner,
                            address spender,
                            uint256 value,
                            uint256 deadline,
                            uint8 v,
                            bytes32 r,
                            bytes32 s
                        ) external override whenNotPaused {
                            _permit(owner, spender, value, deadline, v, r, s);
                        }
                        /**
                         * @inheritdoc FiatTokenV2
                         */
                        function increaseAllowance(address spender, uint256 increment)
                            external
                            override
                            whenNotPaused
                            returns (bool)
                        {
                            _increaseAllowance(msg.sender, spender, increment);
                            return true;
                        }
                        /**
                         * @inheritdoc FiatTokenV2
                         */
                        function decreaseAllowance(address spender, uint256 decrement)
                            external
                            override
                            whenNotPaused
                            returns (bool)
                        {
                            _decreaseAllowance(msg.sender, spender, decrement);
                            return true;
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity >=0.6.2 <0.8.0;
                    /**
                     * @dev Collection of functions related to the address type
                     */
                    library Address {
                        /**
                         * @dev Returns true if `account` is a contract.
                         *
                         * [IMPORTANT]
                         * ====
                         * It is unsafe to assume that an address for which this function returns
                         * false is an externally-owned account (EOA) and not a contract.
                         *
                         * Among others, `isContract` will return false for the following
                         * types of addresses:
                         *
                         *  - an externally-owned account
                         *  - a contract in construction
                         *  - an address where a contract will be created
                         *  - an address where a contract lived, but was destroyed
                         * ====
                         */
                        function isContract(address account) internal view returns (bool) {
                            // This method relies on extcodesize, which returns 0 for contracts in
                            // construction, since the code is only stored at the end of the
                            // constructor execution.
                            uint256 size;
                            // solhint-disable-next-line no-inline-assembly
                            assembly { size := extcodesize(account) }
                            return size > 0;
                        }
                        /**
                         * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
                         * `recipient`, forwarding all available gas and reverting on errors.
                         *
                         * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
                         * of certain opcodes, possibly making contracts go over the 2300 gas limit
                         * imposed by `transfer`, making them unable to receive funds via
                         * `transfer`. {sendValue} removes this limitation.
                         *
                         * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
                         *
                         * IMPORTANT: because control is transferred to `recipient`, care must be
                         * taken to not create reentrancy vulnerabilities. Consider using
                         * {ReentrancyGuard} or the
                         * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                         */
                        function sendValue(address payable recipient, uint256 amount) internal {
                            require(address(this).balance >= amount, "Address: insufficient balance");
                            // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
                            (bool success, ) = recipient.call{ value: amount }("");
                            require(success, "Address: unable to send value, recipient may have reverted");
                        }
                        /**
                         * @dev Performs a Solidity function call using a low level `call`. A
                         * plain`call` is an unsafe replacement for a function call: use this
                         * function instead.
                         *
                         * If `target` reverts with a revert reason, it is bubbled up by this
                         * function (like regular Solidity function calls).
                         *
                         * Returns the raw returned data. To convert to the expected return value,
                         * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
                         *
                         * Requirements:
                         *
                         * - `target` must be a contract.
                         * - calling `target` with `data` must not revert.
                         *
                         * _Available since v3.1._
                         */
                        function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                          return functionCall(target, data, "Address: low-level call failed");
                        }
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
                         * `errorMessage` as a fallback revert reason when `target` reverts.
                         *
                         * _Available since v3.1._
                         */
                        function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
                            return functionCallWithValue(target, data, 0, errorMessage);
                        }
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                         * but also transferring `value` wei to `target`.
                         *
                         * Requirements:
                         *
                         * - the calling contract must have an ETH balance of at least `value`.
                         * - the called Solidity function must be `payable`.
                         *
                         * _Available since v3.1._
                         */
                        function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
                            return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
                        }
                        /**
                         * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
                         * with `errorMessage` as a fallback revert reason when `target` reverts.
                         *
                         * _Available since v3.1._
                         */
                        function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
                            require(address(this).balance >= value, "Address: insufficient balance for call");
                            require(isContract(target), "Address: call to non-contract");
                            // solhint-disable-next-line avoid-low-level-calls
                            (bool success, bytes memory returndata) = target.call{ value: value }(data);
                            return _verifyCallResult(success, returndata, errorMessage);
                        }
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                         * but performing a static call.
                         *
                         * _Available since v3.3._
                         */
                        function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                            return functionStaticCall(target, data, "Address: low-level static call failed");
                        }
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                         * but performing a static call.
                         *
                         * _Available since v3.3._
                         */
                        function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
                            require(isContract(target), "Address: static call to non-contract");
                            // solhint-disable-next-line avoid-low-level-calls
                            (bool success, bytes memory returndata) = target.staticcall(data);
                            return _verifyCallResult(success, returndata, errorMessage);
                        }
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                         * but performing a delegate call.
                         *
                         * _Available since v3.4._
                         */
                        function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                            return functionDelegateCall(target, data, "Address: low-level delegate call failed");
                        }
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                         * but performing a delegate call.
                         *
                         * _Available since v3.4._
                         */
                        function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
                            require(isContract(target), "Address: delegate call to non-contract");
                            // solhint-disable-next-line avoid-low-level-calls
                            (bool success, bytes memory returndata) = target.delegatecall(data);
                            return _verifyCallResult(success, returndata, errorMessage);
                        }
                        function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
                            if (success) {
                                return returndata;
                            } else {
                                // Look for revert reason and bubble it up if present
                                if (returndata.length > 0) {
                                    // The easiest way to bubble the revert reason is using memory via assembly
                                    // solhint-disable-next-line no-inline-assembly
                                    assembly {
                                        let returndata_size := mload(returndata)
                                        revert(add(32, returndata), returndata_size)
                                    }
                                } else {
                                    revert(errorMessage);
                                }
                            }
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity >=0.6.0 <0.8.0;
                    import "./IERC20.sol";
                    import "../../math/SafeMath.sol";
                    import "../../utils/Address.sol";
                    /**
                     * @title SafeERC20
                     * @dev Wrappers around ERC20 operations that throw on failure (when the token
                     * contract returns false). Tokens that return no value (and instead revert or
                     * throw on failure) are also supported, non-reverting calls are assumed to be
                     * successful.
                     * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
                     * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
                     */
                    library SafeERC20 {
                        using SafeMath for uint256;
                        using Address for address;
                        function safeTransfer(IERC20 token, address to, uint256 value) internal {
                            _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
                        }
                        function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
                            _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
                        }
                        /**
                         * @dev Deprecated. This function has issues similar to the ones found in
                         * {IERC20-approve}, and its usage is discouraged.
                         *
                         * Whenever possible, use {safeIncreaseAllowance} and
                         * {safeDecreaseAllowance} instead.
                         */
                        function safeApprove(IERC20 token, address spender, uint256 value) internal {
                            // safeApprove should only be called when setting an initial allowance,
                            // or when resetting it to zero. To increase and decrease it, use
                            // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
                            // solhint-disable-next-line max-line-length
                            require((value == 0) || (token.allowance(address(this), spender) == 0),
                                "SafeERC20: approve from non-zero to non-zero allowance"
                            );
                            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
                        }
                        function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                            uint256 newAllowance = token.allowance(address(this), spender).add(value);
                            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                        }
                        function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                            uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
                            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                        }
                        /**
                         * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
                         * on the return value: the return value is optional (but if data is returned, it must not be false).
                         * @param token The token targeted by the call.
                         * @param data The call data (encoded using abi.encode or one of its variants).
                         */
                        function _callOptionalReturn(IERC20 token, bytes memory data) private {
                            // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                            // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
                            // the target address contains contract code and also asserts for success in the low-level call.
                            bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
                            if (returndata.length > 0) { // Return data is optional
                                // solhint-disable-next-line max-line-length
                                require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
                            }
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity >=0.6.0 <0.8.0;
                    /**
                     * @dev Interface of the ERC20 standard as defined in the EIP.
                     */
                    interface IERC20 {
                        /**
                         * @dev Returns the amount of tokens in existence.
                         */
                        function totalSupply() external view returns (uint256);
                        /**
                         * @dev Returns the amount of tokens owned by `account`.
                         */
                        function balanceOf(address account) external view returns (uint256);
                        /**
                         * @dev Moves `amount` tokens from the caller's account to `recipient`.
                         *
                         * Returns a boolean value indicating whether the operation succeeded.
                         *
                         * Emits a {Transfer} event.
                         */
                        function transfer(address recipient, uint256 amount) external returns (bool);
                        /**
                         * @dev Returns the remaining number of tokens that `spender` will be
                         * allowed to spend on behalf of `owner` through {transferFrom}. This is
                         * zero by default.
                         *
                         * This value changes when {approve} or {transferFrom} are called.
                         */
                        function allowance(address owner, address spender) external view returns (uint256);
                        /**
                         * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
                         *
                         * Returns a boolean value indicating whether the operation succeeded.
                         *
                         * IMPORTANT: Beware that changing an allowance with this method brings the risk
                         * that someone may use both the old and the new allowance by unfortunate
                         * transaction ordering. One possible solution to mitigate this race
                         * condition is to first reduce the spender's allowance to 0 and set the
                         * desired value afterwards:
                         * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                         *
                         * Emits an {Approval} event.
                         */
                        function approve(address spender, uint256 amount) external returns (bool);
                        /**
                         * @dev Moves `amount` tokens from `sender` to `recipient` using the
                         * allowance mechanism. `amount` is then deducted from the caller's
                         * allowance.
                         *
                         * Returns a boolean value indicating whether the operation succeeded.
                         *
                         * Emits a {Transfer} event.
                         */
                        function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
                        /**
                         * @dev Emitted when `value` tokens are moved from one account (`from`) to
                         * another (`to`).
                         *
                         * Note that `value` may be zero.
                         */
                        event Transfer(address indexed from, address indexed to, uint256 value);
                        /**
                         * @dev Emitted when the allowance of a `spender` for an `owner` is set by
                         * a call to {approve}. `value` is the new allowance.
                         */
                        event Approval(address indexed owner, address indexed spender, uint256 value);
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity >=0.6.0 <0.8.0;
                    /**
                     * @dev Wrappers over Solidity's arithmetic operations with added overflow
                     * checks.
                     *
                     * Arithmetic operations in Solidity wrap on overflow. This can easily result
                     * in bugs, because programmers usually assume that an overflow raises an
                     * error, which is the standard behavior in high level programming languages.
                     * `SafeMath` restores this intuition by reverting the transaction when an
                     * operation overflows.
                     *
                     * Using this library instead of the unchecked operations eliminates an entire
                     * class of bugs, so it's recommended to use it always.
                     */
                    library SafeMath {
                        /**
                         * @dev Returns the addition of two unsigned integers, with an overflow flag.
                         *
                         * _Available since v3.4._
                         */
                        function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                            uint256 c = a + b;
                            if (c < a) return (false, 0);
                            return (true, c);
                        }
                        /**
                         * @dev Returns the substraction of two unsigned integers, with an overflow flag.
                         *
                         * _Available since v3.4._
                         */
                        function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                            if (b > a) return (false, 0);
                            return (true, a - b);
                        }
                        /**
                         * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
                         *
                         * _Available since v3.4._
                         */
                        function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
                            // benefit is lost if 'b' is also tested.
                            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
                            if (a == 0) return (true, 0);
                            uint256 c = a * b;
                            if (c / a != b) return (false, 0);
                            return (true, c);
                        }
                        /**
                         * @dev Returns the division of two unsigned integers, with a division by zero flag.
                         *
                         * _Available since v3.4._
                         */
                        function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                            if (b == 0) return (false, 0);
                            return (true, a / b);
                        }
                        /**
                         * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
                         *
                         * _Available since v3.4._
                         */
                        function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                            if (b == 0) return (false, 0);
                            return (true, a % b);
                        }
                        /**
                         * @dev Returns the addition of two unsigned integers, reverting on
                         * overflow.
                         *
                         * Counterpart to Solidity's `+` operator.
                         *
                         * Requirements:
                         *
                         * - Addition cannot overflow.
                         */
                        function add(uint256 a, uint256 b) internal pure returns (uint256) {
                            uint256 c = a + b;
                            require(c >= a, "SafeMath: addition overflow");
                            return c;
                        }
                        /**
                         * @dev Returns the subtraction of two unsigned integers, reverting on
                         * overflow (when the result is negative).
                         *
                         * Counterpart to Solidity's `-` operator.
                         *
                         * Requirements:
                         *
                         * - Subtraction cannot overflow.
                         */
                        function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                            require(b <= a, "SafeMath: subtraction overflow");
                            return a - b;
                        }
                        /**
                         * @dev Returns the multiplication of two unsigned integers, reverting on
                         * overflow.
                         *
                         * Counterpart to Solidity's `*` operator.
                         *
                         * Requirements:
                         *
                         * - Multiplication cannot overflow.
                         */
                        function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                            if (a == 0) return 0;
                            uint256 c = a * b;
                            require(c / a == b, "SafeMath: multiplication overflow");
                            return c;
                        }
                        /**
                         * @dev Returns the integer division of two unsigned integers, reverting on
                         * division by zero. The result is rounded towards zero.
                         *
                         * Counterpart to Solidity's `/` operator. Note: this function uses a
                         * `revert` opcode (which leaves remaining gas untouched) while Solidity
                         * uses an invalid opcode to revert (consuming all remaining gas).
                         *
                         * Requirements:
                         *
                         * - The divisor cannot be zero.
                         */
                        function div(uint256 a, uint256 b) internal pure returns (uint256) {
                            require(b > 0, "SafeMath: division by zero");
                            return a / b;
                        }
                        /**
                         * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                         * reverting when dividing by zero.
                         *
                         * Counterpart to Solidity's `%` operator. This function uses a `revert`
                         * opcode (which leaves remaining gas untouched) while Solidity uses an
                         * invalid opcode to revert (consuming all remaining gas).
                         *
                         * Requirements:
                         *
                         * - The divisor cannot be zero.
                         */
                        function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                            require(b > 0, "SafeMath: modulo by zero");
                            return a % b;
                        }
                        /**
                         * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
                         * overflow (when the result is negative).
                         *
                         * CAUTION: This function is deprecated because it requires allocating memory for the error
                         * message unnecessarily. For custom revert reasons use {trySub}.
                         *
                         * Counterpart to Solidity's `-` operator.
                         *
                         * Requirements:
                         *
                         * - Subtraction cannot overflow.
                         */
                        function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                            require(b <= a, errorMessage);
                            return a - b;
                        }
                        /**
                         * @dev Returns the integer division of two unsigned integers, reverting with custom message on
                         * division by zero. The result is rounded towards zero.
                         *
                         * CAUTION: This function is deprecated because it requires allocating memory for the error
                         * message unnecessarily. For custom revert reasons use {tryDiv}.
                         *
                         * Counterpart to Solidity's `/` operator. Note: this function uses a
                         * `revert` opcode (which leaves remaining gas untouched) while Solidity
                         * uses an invalid opcode to revert (consuming all remaining gas).
                         *
                         * Requirements:
                         *
                         * - The divisor cannot be zero.
                         */
                        function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                            require(b > 0, errorMessage);
                            return a / b;
                        }
                        /**
                         * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                         * reverting with custom message when dividing by zero.
                         *
                         * CAUTION: This function is deprecated because it requires allocating memory for the error
                         * message unnecessarily. For custom revert reasons use {tryMod}.
                         *
                         * Counterpart to Solidity's `%` operator. This function uses a `revert`
                         * opcode (which leaves remaining gas untouched) while Solidity uses an
                         * invalid opcode to revert (consuming all remaining gas).
                         *
                         * Requirements:
                         *
                         * - The divisor cannot be zero.
                         */
                        function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                            require(b > 0, errorMessage);
                            return a % b;
                        }
                    }
                    /**
                     * SPDX-License-Identifier: Apache-2.0
                     *
                     * Copyright (c) 2023, Circle Internet Financial, LLC.
                     *
                     * Licensed under the Apache License, Version 2.0 (the "License");
                     * you may not use this file except in compliance with the License.
                     * You may obtain a copy of the License at
                     *
                     * http://www.apache.org/licenses/LICENSE-2.0
                     *
                     * Unless required by applicable law or agreed to in writing, software
                     * distributed under the License is distributed on an "AS IS" BASIS,
                     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                     * See the License for the specific language governing permissions and
                     * limitations under the License.
                     */
                    pragma solidity 0.6.12;
                    import { FiatTokenV2 } from "./FiatTokenV2.sol";
                    // solhint-disable func-name-mixedcase
                    /**
                     * @title FiatToken V2.1
                     * @notice ERC20 Token backed by fiat reserves, version 2.1
                     */
                    contract FiatTokenV2_1 is FiatTokenV2 {
                        /**
                         * @notice Initialize v2.1
                         * @param lostAndFound  The address to which the locked funds are sent
                         */
                        function initializeV2_1(address lostAndFound) external {
                            // solhint-disable-next-line reason-string
                            require(_initializedVersion == 1);
                            uint256 lockedAmount = _balanceOf(address(this));
                            if (lockedAmount > 0) {
                                _transfer(address(this), lostAndFound, lockedAmount);
                            }
                            _blacklist(address(this));
                            _initializedVersion = 2;
                        }
                        /**
                         * @notice Version string for the EIP712 domain separator
                         * @return Version string
                         */
                        function version() external pure returns (string memory) {
                            return "2";
                        }
                    }
                    /**
                     * SPDX-License-Identifier: Apache-2.0
                     *
                     * Copyright (c) 2023, Circle Internet Financial, LLC.
                     *
                     * Licensed under the Apache License, Version 2.0 (the "License");
                     * you may not use this file except in compliance with the License.
                     * You may obtain a copy of the License at
                     *
                     * http://www.apache.org/licenses/LICENSE-2.0
                     *
                     * Unless required by applicable law or agreed to in writing, software
                     * distributed under the License is distributed on an "AS IS" BASIS,
                     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                     * See the License for the specific language governing permissions and
                     * limitations under the License.
                     */
                    pragma solidity 0.6.12;
                    import { FiatTokenV1_1 } from "../v1.1/FiatTokenV1_1.sol";
                    import { EIP712 } from "../util/EIP712.sol";
                    import { EIP3009 } from "./EIP3009.sol";
                    import { EIP2612 } from "./EIP2612.sol";
                    /**
                     * @title FiatToken V2
                     * @notice ERC20 Token backed by fiat reserves, version 2
                     */
                    contract FiatTokenV2 is FiatTokenV1_1, EIP3009, EIP2612 {
                        uint8 internal _initializedVersion;
                        /**
                         * @notice Initialize v2
                         * @param newName   New token name
                         */
                        function initializeV2(string calldata newName) external {
                            // solhint-disable-next-line reason-string
                            require(initialized && _initializedVersion == 0);
                            name = newName;
                            _DEPRECATED_CACHED_DOMAIN_SEPARATOR = EIP712.makeDomainSeparator(
                                newName,
                                "2"
                            );
                            _initializedVersion = 1;
                        }
                        /**
                         * @notice Increase the allowance by a given increment
                         * @param spender   Spender's address
                         * @param increment Amount of increase in allowance
                         * @return True if successful
                         */
                        function increaseAllowance(address spender, uint256 increment)
                            external
                            virtual
                            whenNotPaused
                            notBlacklisted(msg.sender)
                            notBlacklisted(spender)
                            returns (bool)
                        {
                            _increaseAllowance(msg.sender, spender, increment);
                            return true;
                        }
                        /**
                         * @notice Decrease the allowance by a given decrement
                         * @param spender   Spender's address
                         * @param decrement Amount of decrease in allowance
                         * @return True if successful
                         */
                        function decreaseAllowance(address spender, uint256 decrement)
                            external
                            virtual
                            whenNotPaused
                            notBlacklisted(msg.sender)
                            notBlacklisted(spender)
                            returns (bool)
                        {
                            _decreaseAllowance(msg.sender, spender, decrement);
                            return true;
                        }
                        /**
                         * @notice Execute a transfer with a signed authorization
                         * @param from          Payer's address (Authorizer)
                         * @param to            Payee's address
                         * @param value         Amount to be transferred
                         * @param validAfter    The time after which this is valid (unix time)
                         * @param validBefore   The time before which this is valid (unix time)
                         * @param nonce         Unique nonce
                         * @param v             v of the signature
                         * @param r             r of the signature
                         * @param s             s of the signature
                         */
                        function transferWithAuthorization(
                            address from,
                            address to,
                            uint256 value,
                            uint256 validAfter,
                            uint256 validBefore,
                            bytes32 nonce,
                            uint8 v,
                            bytes32 r,
                            bytes32 s
                        ) external whenNotPaused notBlacklisted(from) notBlacklisted(to) {
                            _transferWithAuthorization(
                                from,
                                to,
                                value,
                                validAfter,
                                validBefore,
                                nonce,
                                v,
                                r,
                                s
                            );
                        }
                        /**
                         * @notice Receive a transfer with a signed authorization from the payer
                         * @dev This has an additional check to ensure that the payee's address
                         * matches the caller of this function to prevent front-running attacks.
                         * @param from          Payer's address (Authorizer)
                         * @param to            Payee's address
                         * @param value         Amount to be transferred
                         * @param validAfter    The time after which this is valid (unix time)
                         * @param validBefore   The time before which this is valid (unix time)
                         * @param nonce         Unique nonce
                         * @param v             v of the signature
                         * @param r             r of the signature
                         * @param s             s of the signature
                         */
                        function receiveWithAuthorization(
                            address from,
                            address to,
                            uint256 value,
                            uint256 validAfter,
                            uint256 validBefore,
                            bytes32 nonce,
                            uint8 v,
                            bytes32 r,
                            bytes32 s
                        ) external whenNotPaused notBlacklisted(from) notBlacklisted(to) {
                            _receiveWithAuthorization(
                                from,
                                to,
                                value,
                                validAfter,
                                validBefore,
                                nonce,
                                v,
                                r,
                                s
                            );
                        }
                        /**
                         * @notice Attempt to cancel an authorization
                         * @dev Works only if the authorization is not yet used.
                         * @param authorizer    Authorizer's address
                         * @param nonce         Nonce of the authorization
                         * @param v             v of the signature
                         * @param r             r of the signature
                         * @param s             s of the signature
                         */
                        function cancelAuthorization(
                            address authorizer,
                            bytes32 nonce,
                            uint8 v,
                            bytes32 r,
                            bytes32 s
                        ) external whenNotPaused {
                            _cancelAuthorization(authorizer, nonce, v, r, s);
                        }
                        /**
                         * @notice Update allowance with a signed permit
                         * @param owner       Token owner's address (Authorizer)
                         * @param spender     Spender's address
                         * @param value       Amount of allowance
                         * @param deadline    The time at which the signature expires (unix time), or max uint256 value to signal no expiration
                         * @param v           v of the signature
                         * @param r           r of the signature
                         * @param s           s of the signature
                         */
                        function permit(
                            address owner,
                            address spender,
                            uint256 value,
                            uint256 deadline,
                            uint8 v,
                            bytes32 r,
                            bytes32 s
                        )
                            external
                            virtual
                            whenNotPaused
                            notBlacklisted(owner)
                            notBlacklisted(spender)
                        {
                            _permit(owner, spender, value, deadline, v, r, s);
                        }
                        /**
                         * @dev Internal function to increase the allowance by a given increment
                         * @param owner     Token owner's address
                         * @param spender   Spender's address
                         * @param increment Amount of increase
                         */
                        function _increaseAllowance(
                            address owner,
                            address spender,
                            uint256 increment
                        ) internal override {
                            _approve(owner, spender, allowed[owner][spender].add(increment));
                        }
                        /**
                         * @dev Internal function to decrease the allowance by a given decrement
                         * @param owner     Token owner's address
                         * @param spender   Spender's address
                         * @param decrement Amount of decrease
                         */
                        function _decreaseAllowance(
                            address owner,
                            address spender,
                            uint256 decrement
                        ) internal override {
                            _approve(
                                owner,
                                spender,
                                allowed[owner][spender].sub(
                                    decrement,
                                    "ERC20: decreased allowance below zero"
                                )
                            );
                        }
                    }
                    /**
                     * SPDX-License-Identifier: Apache-2.0
                     *
                     * Copyright (c) 2023, Circle Internet Financial, LLC.
                     *
                     * Licensed under the Apache License, Version 2.0 (the "License");
                     * you may not use this file except in compliance with the License.
                     * You may obtain a copy of the License at
                     *
                     * http://www.apache.org/licenses/LICENSE-2.0
                     *
                     * Unless required by applicable law or agreed to in writing, software
                     * distributed under the License is distributed on an "AS IS" BASIS,
                     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                     * See the License for the specific language governing permissions and
                     * limitations under the License.
                     */
                    pragma solidity 0.6.12;
                    // solhint-disable func-name-mixedcase
                    /**
                     * @title EIP712 Domain
                     */
                    contract EIP712Domain {
                        // was originally DOMAIN_SEPARATOR
                        // but that has been moved to a method so we can override it in V2_2+
                        bytes32 internal _DEPRECATED_CACHED_DOMAIN_SEPARATOR;
                        /**
                         * @notice Get the EIP712 Domain Separator.
                         * @return The bytes32 EIP712 domain separator.
                         */
                        function DOMAIN_SEPARATOR() external view returns (bytes32) {
                            return _domainSeparator();
                        }
                        /**
                         * @dev Internal method to get the EIP712 Domain Separator.
                         * @return The bytes32 EIP712 domain separator.
                         */
                        function _domainSeparator() internal virtual view returns (bytes32) {
                            return _DEPRECATED_CACHED_DOMAIN_SEPARATOR;
                        }
                    }
                    /**
                     * SPDX-License-Identifier: Apache-2.0
                     *
                     * Copyright (c) 2023, Circle Internet Financial, LLC.
                     *
                     * Licensed under the Apache License, Version 2.0 (the "License");
                     * you may not use this file except in compliance with the License.
                     * You may obtain a copy of the License at
                     *
                     * http://www.apache.org/licenses/LICENSE-2.0
                     *
                     * Unless required by applicable law or agreed to in writing, software
                     * distributed under the License is distributed on an "AS IS" BASIS,
                     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                     * See the License for the specific language governing permissions and
                     * limitations under the License.
                     */
                    pragma solidity 0.6.12;
                    import { AbstractFiatTokenV2 } from "./AbstractFiatTokenV2.sol";
                    import { EIP712Domain } from "./EIP712Domain.sol";
                    import { SignatureChecker } from "../util/SignatureChecker.sol";
                    import { MessageHashUtils } from "../util/MessageHashUtils.sol";
                    /**
                     * @title EIP-3009
                     * @notice Provide internal implementation for gas-abstracted transfers
                     * @dev Contracts that inherit from this must wrap these with publicly
                     * accessible functions, optionally adding modifiers where necessary
                     */
                    abstract contract EIP3009 is AbstractFiatTokenV2, EIP712Domain {
                        // keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)")
                        bytes32
                            public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267;
                        // keccak256("ReceiveWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)")
                        bytes32
                            public constant RECEIVE_WITH_AUTHORIZATION_TYPEHASH = 0xd099cc98ef71107a616c4f0f941f04c322d8e254fe26b3c6668db87aae413de8;
                        // keccak256("CancelAuthorization(address authorizer,bytes32 nonce)")
                        bytes32
                            public constant CANCEL_AUTHORIZATION_TYPEHASH = 0x158b0a9edf7a828aad02f63cd515c68ef2f50ba807396f6d12842833a1597429;
                        /**
                         * @dev authorizer address => nonce => bool (true if nonce is used)
                         */
                        mapping(address => mapping(bytes32 => bool)) private _authorizationStates;
                        event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce);
                        event AuthorizationCanceled(
                            address indexed authorizer,
                            bytes32 indexed nonce
                        );
                        /**
                         * @notice Returns the state of an authorization
                         * @dev Nonces are randomly generated 32-byte data unique to the
                         * authorizer's address
                         * @param authorizer    Authorizer's address
                         * @param nonce         Nonce of the authorization
                         * @return True if the nonce is used
                         */
                        function authorizationState(address authorizer, bytes32 nonce)
                            external
                            view
                            returns (bool)
                        {
                            return _authorizationStates[authorizer][nonce];
                        }
                        /**
                         * @notice Execute a transfer with a signed authorization
                         * @param from          Payer's address (Authorizer)
                         * @param to            Payee's address
                         * @param value         Amount to be transferred
                         * @param validAfter    The time after which this is valid (unix time)
                         * @param validBefore   The time before which this is valid (unix time)
                         * @param nonce         Unique nonce
                         * @param v             v of the signature
                         * @param r             r of the signature
                         * @param s             s of the signature
                         */
                        function _transferWithAuthorization(
                            address from,
                            address to,
                            uint256 value,
                            uint256 validAfter,
                            uint256 validBefore,
                            bytes32 nonce,
                            uint8 v,
                            bytes32 r,
                            bytes32 s
                        ) internal {
                            _transferWithAuthorization(
                                from,
                                to,
                                value,
                                validAfter,
                                validBefore,
                                nonce,
                                abi.encodePacked(r, s, v)
                            );
                        }
                        /**
                         * @notice Execute a transfer with a signed authorization
                         * @dev EOA wallet signatures should be packed in the order of r, s, v.
                         * @param from          Payer's address (Authorizer)
                         * @param to            Payee's address
                         * @param value         Amount to be transferred
                         * @param validAfter    The time after which this is valid (unix time)
                         * @param validBefore   The time before which this is valid (unix time)
                         * @param nonce         Unique nonce
                         * @param signature     Signature byte array produced by an EOA wallet or a contract wallet
                         */
                        function _transferWithAuthorization(
                            address from,
                            address to,
                            uint256 value,
                            uint256 validAfter,
                            uint256 validBefore,
                            bytes32 nonce,
                            bytes memory signature
                        ) internal {
                            _requireValidAuthorization(from, nonce, validAfter, validBefore);
                            _requireValidSignature(
                                from,
                                keccak256(
                                    abi.encode(
                                        TRANSFER_WITH_AUTHORIZATION_TYPEHASH,
                                        from,
                                        to,
                                        value,
                                        validAfter,
                                        validBefore,
                                        nonce
                                    )
                                ),
                                signature
                            );
                            _markAuthorizationAsUsed(from, nonce);
                            _transfer(from, to, value);
                        }
                        /**
                         * @notice Receive a transfer with a signed authorization from the payer
                         * @dev This has an additional check to ensure that the payee's address
                         * matches the caller of this function to prevent front-running attacks.
                         * @param from          Payer's address (Authorizer)
                         * @param to            Payee's address
                         * @param value         Amount to be transferred
                         * @param validAfter    The time after which this is valid (unix time)
                         * @param validBefore   The time before which this is valid (unix time)
                         * @param nonce         Unique nonce
                         * @param v             v of the signature
                         * @param r             r of the signature
                         * @param s             s of the signature
                         */
                        function _receiveWithAuthorization(
                            address from,
                            address to,
                            uint256 value,
                            uint256 validAfter,
                            uint256 validBefore,
                            bytes32 nonce,
                            uint8 v,
                            bytes32 r,
                            bytes32 s
                        ) internal {
                            _receiveWithAuthorization(
                                from,
                                to,
                                value,
                                validAfter,
                                validBefore,
                                nonce,
                                abi.encodePacked(r, s, v)
                            );
                        }
                        /**
                         * @notice Receive a transfer with a signed authorization from the payer
                         * @dev This has an additional check to ensure that the payee's address
                         * matches the caller of this function to prevent front-running attacks.
                         * EOA wallet signatures should be packed in the order of r, s, v.
                         * @param from          Payer's address (Authorizer)
                         * @param to            Payee's address
                         * @param value         Amount to be transferred
                         * @param validAfter    The time after which this is valid (unix time)
                         * @param validBefore   The time before which this is valid (unix time)
                         * @param nonce         Unique nonce
                         * @param signature     Signature byte array produced by an EOA wallet or a contract wallet
                         */
                        function _receiveWithAuthorization(
                            address from,
                            address to,
                            uint256 value,
                            uint256 validAfter,
                            uint256 validBefore,
                            bytes32 nonce,
                            bytes memory signature
                        ) internal {
                            require(to == msg.sender, "FiatTokenV2: caller must be the payee");
                            _requireValidAuthorization(from, nonce, validAfter, validBefore);
                            _requireValidSignature(
                                from,
                                keccak256(
                                    abi.encode(
                                        RECEIVE_WITH_AUTHORIZATION_TYPEHASH,
                                        from,
                                        to,
                                        value,
                                        validAfter,
                                        validBefore,
                                        nonce
                                    )
                                ),
                                signature
                            );
                            _markAuthorizationAsUsed(from, nonce);
                            _transfer(from, to, value);
                        }
                        /**
                         * @notice Attempt to cancel an authorization
                         * @param authorizer    Authorizer's address
                         * @param nonce         Nonce of the authorization
                         * @param v             v of the signature
                         * @param r             r of the signature
                         * @param s             s of the signature
                         */
                        function _cancelAuthorization(
                            address authorizer,
                            bytes32 nonce,
                            uint8 v,
                            bytes32 r,
                            bytes32 s
                        ) internal {
                            _cancelAuthorization(authorizer, nonce, abi.encodePacked(r, s, v));
                        }
                        /**
                         * @notice Attempt to cancel an authorization
                         * @dev EOA wallet signatures should be packed in the order of r, s, v.
                         * @param authorizer    Authorizer's address
                         * @param nonce         Nonce of the authorization
                         * @param signature     Signature byte array produced by an EOA wallet or a contract wallet
                         */
                        function _cancelAuthorization(
                            address authorizer,
                            bytes32 nonce,
                            bytes memory signature
                        ) internal {
                            _requireUnusedAuthorization(authorizer, nonce);
                            _requireValidSignature(
                                authorizer,
                                keccak256(
                                    abi.encode(CANCEL_AUTHORIZATION_TYPEHASH, authorizer, nonce)
                                ),
                                signature
                            );
                            _authorizationStates[authorizer][nonce] = true;
                            emit AuthorizationCanceled(authorizer, nonce);
                        }
                        /**
                         * @notice Validates that signature against input data struct
                         * @param signer        Signer's address
                         * @param dataHash      Hash of encoded data struct
                         * @param signature     Signature byte array produced by an EOA wallet or a contract wallet
                         */
                        function _requireValidSignature(
                            address signer,
                            bytes32 dataHash,
                            bytes memory signature
                        ) private view {
                            require(
                                SignatureChecker.isValidSignatureNow(
                                    signer,
                                    MessageHashUtils.toTypedDataHash(_domainSeparator(), dataHash),
                                    signature
                                ),
                                "FiatTokenV2: invalid signature"
                            );
                        }
                        /**
                         * @notice Check that an authorization is unused
                         * @param authorizer    Authorizer's address
                         * @param nonce         Nonce of the authorization
                         */
                        function _requireUnusedAuthorization(address authorizer, bytes32 nonce)
                            private
                            view
                        {
                            require(
                                !_authorizationStates[authorizer][nonce],
                                "FiatTokenV2: authorization is used or canceled"
                            );
                        }
                        /**
                         * @notice Check that authorization is valid
                         * @param authorizer    Authorizer's address
                         * @param nonce         Nonce of the authorization
                         * @param validAfter    The time after which this is valid (unix time)
                         * @param validBefore   The time before which this is valid (unix time)
                         */
                        function _requireValidAuthorization(
                            address authorizer,
                            bytes32 nonce,
                            uint256 validAfter,
                            uint256 validBefore
                        ) private view {
                            require(
                                now > validAfter,
                                "FiatTokenV2: authorization is not yet valid"
                            );
                            require(now < validBefore, "FiatTokenV2: authorization is expired");
                            _requireUnusedAuthorization(authorizer, nonce);
                        }
                        /**
                         * @notice Mark an authorization as used
                         * @param authorizer    Authorizer's address
                         * @param nonce         Nonce of the authorization
                         */
                        function _markAuthorizationAsUsed(address authorizer, bytes32 nonce)
                            private
                        {
                            _authorizationStates[authorizer][nonce] = true;
                            emit AuthorizationUsed(authorizer, nonce);
                        }
                    }
                    /**
                     * SPDX-License-Identifier: Apache-2.0
                     *
                     * Copyright (c) 2023, Circle Internet Financial, LLC.
                     *
                     * Licensed under the Apache License, Version 2.0 (the "License");
                     * you may not use this file except in compliance with the License.
                     * You may obtain a copy of the License at
                     *
                     * http://www.apache.org/licenses/LICENSE-2.0
                     *
                     * Unless required by applicable law or agreed to in writing, software
                     * distributed under the License is distributed on an "AS IS" BASIS,
                     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                     * See the License for the specific language governing permissions and
                     * limitations under the License.
                     */
                    pragma solidity 0.6.12;
                    import { AbstractFiatTokenV2 } from "./AbstractFiatTokenV2.sol";
                    import { EIP712Domain } from "./EIP712Domain.sol";
                    import { MessageHashUtils } from "../util/MessageHashUtils.sol";
                    import { SignatureChecker } from "../util/SignatureChecker.sol";
                    /**
                     * @title EIP-2612
                     * @notice Provide internal implementation for gas-abstracted approvals
                     */
                    abstract contract EIP2612 is AbstractFiatTokenV2, EIP712Domain {
                        // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")
                        bytes32
                            public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
                        mapping(address => uint256) private _permitNonces;
                        /**
                         * @notice Nonces for permit
                         * @param owner Token owner's address (Authorizer)
                         * @return Next nonce
                         */
                        function nonces(address owner) external view returns (uint256) {
                            return _permitNonces[owner];
                        }
                        /**
                         * @notice Verify a signed approval permit and execute if valid
                         * @param owner     Token owner's address (Authorizer)
                         * @param spender   Spender's address
                         * @param value     Amount of allowance
                         * @param deadline  The time at which the signature expires (unix time), or max uint256 value to signal no expiration
                         * @param v         v of the signature
                         * @param r         r of the signature
                         * @param s         s of the signature
                         */
                        function _permit(
                            address owner,
                            address spender,
                            uint256 value,
                            uint256 deadline,
                            uint8 v,
                            bytes32 r,
                            bytes32 s
                        ) internal {
                            _permit(owner, spender, value, deadline, abi.encodePacked(r, s, v));
                        }
                        /**
                         * @notice Verify a signed approval permit and execute if valid
                         * @dev EOA wallet signatures should be packed in the order of r, s, v.
                         * @param owner      Token owner's address (Authorizer)
                         * @param spender    Spender's address
                         * @param value      Amount of allowance
                         * @param deadline   The time at which the signature expires (unix time), or max uint256 value to signal no expiration
                         * @param signature  Signature byte array signed by an EOA wallet or a contract wallet
                         */
                        function _permit(
                            address owner,
                            address spender,
                            uint256 value,
                            uint256 deadline,
                            bytes memory signature
                        ) internal {
                            require(
                                deadline == type(uint256).max || deadline >= now,
                                "FiatTokenV2: permit is expired"
                            );
                            bytes32 typedDataHash = MessageHashUtils.toTypedDataHash(
                                _domainSeparator(),
                                keccak256(
                                    abi.encode(
                                        PERMIT_TYPEHASH,
                                        owner,
                                        spender,
                                        value,
                                        _permitNonces[owner]++,
                                        deadline
                                    )
                                )
                            );
                            require(
                                SignatureChecker.isValidSignatureNow(
                                    owner,
                                    typedDataHash,
                                    signature
                                ),
                                "EIP2612: invalid signature"
                            );
                            _approve(owner, spender, value);
                        }
                    }
                    /**
                     * SPDX-License-Identifier: Apache-2.0
                     *
                     * Copyright (c) 2023, Circle Internet Financial, LLC.
                     *
                     * Licensed under the Apache License, Version 2.0 (the "License");
                     * you may not use this file except in compliance with the License.
                     * You may obtain a copy of the License at
                     *
                     * http://www.apache.org/licenses/LICENSE-2.0
                     *
                     * Unless required by applicable law or agreed to in writing, software
                     * distributed under the License is distributed on an "AS IS" BASIS,
                     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                     * See the License for the specific language governing permissions and
                     * limitations under the License.
                     */
                    pragma solidity 0.6.12;
                    import { AbstractFiatTokenV1 } from "../v1/AbstractFiatTokenV1.sol";
                    abstract contract AbstractFiatTokenV2 is AbstractFiatTokenV1 {
                        function _increaseAllowance(
                            address owner,
                            address spender,
                            uint256 increment
                        ) internal virtual;
                        function _decreaseAllowance(
                            address owner,
                            address spender,
                            uint256 decrement
                        ) internal virtual;
                    }
                    /**
                     * SPDX-License-Identifier: MIT
                     *
                     * Copyright (c) 2016 Smart Contract Solutions, Inc.
                     * Copyright (c) 2018-2020 CENTRE SECZ
                     *
                     * Permission is hereby granted, free of charge, to any person obtaining a copy
                     * of this software and associated documentation files (the "Software"), to deal
                     * in the Software without restriction, including without limitation the rights
                     * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                     * copies of the Software, and to permit persons to whom the Software is
                     * furnished to do so, subject to the following conditions:
                     *
                     * The above copyright notice and this permission notice shall be included in
                     * copies or substantial portions of the Software.
                     *
                     * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                     * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                     * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                     * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                     * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                     * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
                     * SOFTWARE.
                     */
                    pragma solidity 0.6.12;
                    import { Ownable } from "./Ownable.sol";
                    /**
                     * @notice Base contract which allows children to implement an emergency stop
                     * mechanism
                     * @dev Forked from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/feb665136c0dae9912e08397c1a21c4af3651ef3/contracts/lifecycle/Pausable.sol
                     * Modifications:
                     * 1. Added pauser role, switched pause/unpause to be onlyPauser (6/14/2018)
                     * 2. Removed whenNotPause/whenPaused from pause/unpause (6/14/2018)
                     * 3. Removed whenPaused (6/14/2018)
                     * 4. Switches ownable library to use ZeppelinOS (7/12/18)
                     * 5. Remove constructor (7/13/18)
                     * 6. Reformat, conform to Solidity 0.6 syntax and add error messages (5/13/20)
                     * 7. Make public functions external (5/27/20)
                     */
                    contract Pausable is Ownable {
                        event Pause();
                        event Unpause();
                        event PauserChanged(address indexed newAddress);
                        address public pauser;
                        bool public paused = false;
                        /**
                         * @dev Modifier to make a function callable only when the contract is not paused.
                         */
                        modifier whenNotPaused() {
                            require(!paused, "Pausable: paused");
                            _;
                        }
                        /**
                         * @dev throws if called by any account other than the pauser
                         */
                        modifier onlyPauser() {
                            require(msg.sender == pauser, "Pausable: caller is not the pauser");
                            _;
                        }
                        /**
                         * @dev called by the owner to pause, triggers stopped state
                         */
                        function pause() external onlyPauser {
                            paused = true;
                            emit Pause();
                        }
                        /**
                         * @dev called by the owner to unpause, returns to normal state
                         */
                        function unpause() external onlyPauser {
                            paused = false;
                            emit Unpause();
                        }
                        /**
                         * @notice Updates the pauser address.
                         * @param _newPauser The address of the new pauser.
                         */
                        function updatePauser(address _newPauser) external onlyOwner {
                            require(
                                _newPauser != address(0),
                                "Pausable: new pauser is the zero address"
                            );
                            pauser = _newPauser;
                            emit PauserChanged(pauser);
                        }
                    }
                    /**
                     * SPDX-License-Identifier: MIT
                     *
                     * Copyright (c) 2018 zOS Global Limited.
                     * Copyright (c) 2018-2020 CENTRE SECZ
                     *
                     * Permission is hereby granted, free of charge, to any person obtaining a copy
                     * of this software and associated documentation files (the "Software"), to deal
                     * in the Software without restriction, including without limitation the rights
                     * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                     * copies of the Software, and to permit persons to whom the Software is
                     * furnished to do so, subject to the following conditions:
                     *
                     * The above copyright notice and this permission notice shall be included in
                     * copies or substantial portions of the Software.
                     *
                     * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                     * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                     * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                     * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                     * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                     * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
                     * SOFTWARE.
                     */
                    pragma solidity 0.6.12;
                    /**
                     * @notice The Ownable contract has an owner address, and provides basic
                     * authorization control functions
                     * @dev Forked from https://github.com/OpenZeppelin/openzeppelin-labs/blob/3887ab77b8adafba4a26ace002f3a684c1a3388b/upgradeability_ownership/contracts/ownership/Ownable.sol
                     * Modifications:
                     * 1. Consolidate OwnableStorage into this contract (7/13/18)
                     * 2. Reformat, conform to Solidity 0.6 syntax, and add error messages (5/13/20)
                     * 3. Make public functions external (5/27/20)
                     */
                    contract Ownable {
                        // Owner of the contract
                        address private _owner;
                        /**
                         * @dev Event to show ownership has been transferred
                         * @param previousOwner representing the address of the previous owner
                         * @param newOwner representing the address of the new owner
                         */
                        event OwnershipTransferred(address previousOwner, address newOwner);
                        /**
                         * @dev The constructor sets the original owner of the contract to the sender account.
                         */
                        constructor() public {
                            setOwner(msg.sender);
                        }
                        /**
                         * @dev Tells the address of the owner
                         * @return the address of the owner
                         */
                        function owner() external view returns (address) {
                            return _owner;
                        }
                        /**
                         * @dev Sets a new owner address
                         */
                        function setOwner(address newOwner) internal {
                            _owner = newOwner;
                        }
                        /**
                         * @dev Throws if called by any account other than the owner.
                         */
                        modifier onlyOwner() {
                            require(msg.sender == _owner, "Ownable: caller is not the owner");
                            _;
                        }
                        /**
                         * @dev Allows the current owner to transfer control of the contract to a newOwner.
                         * @param newOwner The address to transfer ownership to.
                         */
                        function transferOwnership(address newOwner) external onlyOwner {
                            require(
                                newOwner != address(0),
                                "Ownable: new owner is the zero address"
                            );
                            emit OwnershipTransferred(_owner, newOwner);
                            setOwner(newOwner);
                        }
                    }
                    /**
                     * SPDX-License-Identifier: Apache-2.0
                     *
                     * Copyright (c) 2023, Circle Internet Financial, LLC.
                     *
                     * Licensed under the Apache License, Version 2.0 (the "License");
                     * you may not use this file except in compliance with the License.
                     * You may obtain a copy of the License at
                     *
                     * http://www.apache.org/licenses/LICENSE-2.0
                     *
                     * Unless required by applicable law or agreed to in writing, software
                     * distributed under the License is distributed on an "AS IS" BASIS,
                     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                     * See the License for the specific language governing permissions and
                     * limitations under the License.
                     */
                    pragma solidity 0.6.12;
                    import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
                    import { AbstractFiatTokenV1 } from "./AbstractFiatTokenV1.sol";
                    import { Ownable } from "./Ownable.sol";
                    import { Pausable } from "./Pausable.sol";
                    import { Blacklistable } from "./Blacklistable.sol";
                    /**
                     * @title FiatToken
                     * @dev ERC20 Token backed by fiat reserves
                     */
                    contract FiatTokenV1 is AbstractFiatTokenV1, Ownable, Pausable, Blacklistable {
                        using SafeMath for uint256;
                        string public name;
                        string public symbol;
                        uint8 public decimals;
                        string public currency;
                        address public masterMinter;
                        bool internal initialized;
                        /// @dev A mapping that stores the balance and blacklist states for a given address.
                        /// The first bit defines whether the address is blacklisted (1 if blacklisted, 0 otherwise).
                        /// The last 255 bits define the balance for the address.
                        mapping(address => uint256) internal balanceAndBlacklistStates;
                        mapping(address => mapping(address => uint256)) internal allowed;
                        uint256 internal totalSupply_ = 0;
                        mapping(address => bool) internal minters;
                        mapping(address => uint256) internal minterAllowed;
                        event Mint(address indexed minter, address indexed to, uint256 amount);
                        event Burn(address indexed burner, uint256 amount);
                        event MinterConfigured(address indexed minter, uint256 minterAllowedAmount);
                        event MinterRemoved(address indexed oldMinter);
                        event MasterMinterChanged(address indexed newMasterMinter);
                        /**
                         * @notice Initializes the fiat token contract.
                         * @param tokenName       The name of the fiat token.
                         * @param tokenSymbol     The symbol of the fiat token.
                         * @param tokenCurrency   The fiat currency that the token represents.
                         * @param tokenDecimals   The number of decimals that the token uses.
                         * @param newMasterMinter The masterMinter address for the fiat token.
                         * @param newPauser       The pauser address for the fiat token.
                         * @param newBlacklister  The blacklister address for the fiat token.
                         * @param newOwner        The owner of the fiat token.
                         */
                        function initialize(
                            string memory tokenName,
                            string memory tokenSymbol,
                            string memory tokenCurrency,
                            uint8 tokenDecimals,
                            address newMasterMinter,
                            address newPauser,
                            address newBlacklister,
                            address newOwner
                        ) public {
                            require(!initialized, "FiatToken: contract is already initialized");
                            require(
                                newMasterMinter != address(0),
                                "FiatToken: new masterMinter is the zero address"
                            );
                            require(
                                newPauser != address(0),
                                "FiatToken: new pauser is the zero address"
                            );
                            require(
                                newBlacklister != address(0),
                                "FiatToken: new blacklister is the zero address"
                            );
                            require(
                                newOwner != address(0),
                                "FiatToken: new owner is the zero address"
                            );
                            name = tokenName;
                            symbol = tokenSymbol;
                            currency = tokenCurrency;
                            decimals = tokenDecimals;
                            masterMinter = newMasterMinter;
                            pauser = newPauser;
                            blacklister = newBlacklister;
                            setOwner(newOwner);
                            initialized = true;
                        }
                        /**
                         * @dev Throws if called by any account other than a minter.
                         */
                        modifier onlyMinters() {
                            require(minters[msg.sender], "FiatToken: caller is not a minter");
                            _;
                        }
                        /**
                         * @notice Mints fiat tokens to an address.
                         * @param _to The address that will receive the minted tokens.
                         * @param _amount The amount of tokens to mint. Must be less than or equal
                         * to the minterAllowance of the caller.
                         * @return True if the operation was successful.
                         */
                        function mint(address _to, uint256 _amount)
                            external
                            whenNotPaused
                            onlyMinters
                            notBlacklisted(msg.sender)
                            notBlacklisted(_to)
                            returns (bool)
                        {
                            require(_to != address(0), "FiatToken: mint to the zero address");
                            require(_amount > 0, "FiatToken: mint amount not greater than 0");
                            uint256 mintingAllowedAmount = minterAllowed[msg.sender];
                            require(
                                _amount <= mintingAllowedAmount,
                                "FiatToken: mint amount exceeds minterAllowance"
                            );
                            totalSupply_ = totalSupply_.add(_amount);
                            _setBalance(_to, _balanceOf(_to).add(_amount));
                            minterAllowed[msg.sender] = mintingAllowedAmount.sub(_amount);
                            emit Mint(msg.sender, _to, _amount);
                            emit Transfer(address(0), _to, _amount);
                            return true;
                        }
                        /**
                         * @dev Throws if called by any account other than the masterMinter
                         */
                        modifier onlyMasterMinter() {
                            require(
                                msg.sender == masterMinter,
                                "FiatToken: caller is not the masterMinter"
                            );
                            _;
                        }
                        /**
                         * @notice Gets the minter allowance for an account.
                         * @param minter The address to check.
                         * @return The remaining minter allowance for the account.
                         */
                        function minterAllowance(address minter) external view returns (uint256) {
                            return minterAllowed[minter];
                        }
                        /**
                         * @notice Checks if an account is a minter.
                         * @param account The address to check.
                         * @return True if the account is a minter, false if the account is not a minter.
                         */
                        function isMinter(address account) external view returns (bool) {
                            return minters[account];
                        }
                        /**
                         * @notice Gets the remaining amount of fiat tokens a spender is allowed to transfer on
                         * behalf of the token owner.
                         * @param owner   The token owner's address.
                         * @param spender The spender's address.
                         * @return The remaining allowance.
                         */
                        function allowance(address owner, address spender)
                            external
                            override
                            view
                            returns (uint256)
                        {
                            return allowed[owner][spender];
                        }
                        /**
                         * @notice Gets the totalSupply of the fiat token.
                         * @return The totalSupply of the fiat token.
                         */
                        function totalSupply() external override view returns (uint256) {
                            return totalSupply_;
                        }
                        /**
                         * @notice Gets the fiat token balance of an account.
                         * @param account  The address to check.
                         * @return balance The fiat token balance of the account.
                         */
                        function balanceOf(address account)
                            external
                            override
                            view
                            returns (uint256)
                        {
                            return _balanceOf(account);
                        }
                        /**
                         * @notice Sets a fiat token allowance for a spender to spend on behalf of the caller.
                         * @param spender The spender's address.
                         * @param value   The allowance amount.
                         * @return True if the operation was successful.
                         */
                        function approve(address spender, uint256 value)
                            external
                            virtual
                            override
                            whenNotPaused
                            notBlacklisted(msg.sender)
                            notBlacklisted(spender)
                            returns (bool)
                        {
                            _approve(msg.sender, spender, value);
                            return true;
                        }
                        /**
                         * @dev Internal function to set allowance.
                         * @param owner     Token owner's address.
                         * @param spender   Spender's address.
                         * @param value     Allowance amount.
                         */
                        function _approve(
                            address owner,
                            address spender,
                            uint256 value
                        ) internal override {
                            require(owner != address(0), "ERC20: approve from the zero address");
                            require(spender != address(0), "ERC20: approve to the zero address");
                            allowed[owner][spender] = value;
                            emit Approval(owner, spender, value);
                        }
                        /**
                         * @notice Transfers tokens from an address to another by spending the caller's allowance.
                         * @dev The caller must have some fiat token allowance on the payer's tokens.
                         * @param from  Payer's address.
                         * @param to    Payee's address.
                         * @param value Transfer amount.
                         * @return True if the operation was successful.
                         */
                        function transferFrom(
                            address from,
                            address to,
                            uint256 value
                        )
                            external
                            override
                            whenNotPaused
                            notBlacklisted(msg.sender)
                            notBlacklisted(from)
                            notBlacklisted(to)
                            returns (bool)
                        {
                            require(
                                value <= allowed[from][msg.sender],
                                "ERC20: transfer amount exceeds allowance"
                            );
                            _transfer(from, to, value);
                            allowed[from][msg.sender] = allowed[from][msg.sender].sub(value);
                            return true;
                        }
                        /**
                         * @notice Transfers tokens from the caller.
                         * @param to    Payee's address.
                         * @param value Transfer amount.
                         * @return True if the operation was successful.
                         */
                        function transfer(address to, uint256 value)
                            external
                            override
                            whenNotPaused
                            notBlacklisted(msg.sender)
                            notBlacklisted(to)
                            returns (bool)
                        {
                            _transfer(msg.sender, to, value);
                            return true;
                        }
                        /**
                         * @dev Internal function to process transfers.
                         * @param from  Payer's address.
                         * @param to    Payee's address.
                         * @param value Transfer amount.
                         */
                        function _transfer(
                            address from,
                            address to,
                            uint256 value
                        ) internal override {
                            require(from != address(0), "ERC20: transfer from the zero address");
                            require(to != address(0), "ERC20: transfer to the zero address");
                            require(
                                value <= _balanceOf(from),
                                "ERC20: transfer amount exceeds balance"
                            );
                            _setBalance(from, _balanceOf(from).sub(value));
                            _setBalance(to, _balanceOf(to).add(value));
                            emit Transfer(from, to, value);
                        }
                        /**
                         * @notice Adds or updates a new minter with a mint allowance.
                         * @param minter The address of the minter.
                         * @param minterAllowedAmount The minting amount allowed for the minter.
                         * @return True if the operation was successful.
                         */
                        function configureMinter(address minter, uint256 minterAllowedAmount)
                            external
                            whenNotPaused
                            onlyMasterMinter
                            returns (bool)
                        {
                            minters[minter] = true;
                            minterAllowed[minter] = minterAllowedAmount;
                            emit MinterConfigured(minter, minterAllowedAmount);
                            return true;
                        }
                        /**
                         * @notice Removes a minter.
                         * @param minter The address of the minter to remove.
                         * @return True if the operation was successful.
                         */
                        function removeMinter(address minter)
                            external
                            onlyMasterMinter
                            returns (bool)
                        {
                            minters[minter] = false;
                            minterAllowed[minter] = 0;
                            emit MinterRemoved(minter);
                            return true;
                        }
                        /**
                         * @notice Allows a minter to burn some of its own tokens.
                         * @dev The caller must be a minter, must not be blacklisted, and the amount to burn
                         * should be less than or equal to the account's balance.
                         * @param _amount the amount of tokens to be burned.
                         */
                        function burn(uint256 _amount)
                            external
                            whenNotPaused
                            onlyMinters
                            notBlacklisted(msg.sender)
                        {
                            uint256 balance = _balanceOf(msg.sender);
                            require(_amount > 0, "FiatToken: burn amount not greater than 0");
                            require(balance >= _amount, "FiatToken: burn amount exceeds balance");
                            totalSupply_ = totalSupply_.sub(_amount);
                            _setBalance(msg.sender, balance.sub(_amount));
                            emit Burn(msg.sender, _amount);
                            emit Transfer(msg.sender, address(0), _amount);
                        }
                        /**
                         * @notice Updates the master minter address.
                         * @param _newMasterMinter The address of the new master minter.
                         */
                        function updateMasterMinter(address _newMasterMinter) external onlyOwner {
                            require(
                                _newMasterMinter != address(0),
                                "FiatToken: new masterMinter is the zero address"
                            );
                            masterMinter = _newMasterMinter;
                            emit MasterMinterChanged(masterMinter);
                        }
                        /**
                         * @inheritdoc Blacklistable
                         */
                        function _blacklist(address _account) internal override {
                            _setBlacklistState(_account, true);
                        }
                        /**
                         * @inheritdoc Blacklistable
                         */
                        function _unBlacklist(address _account) internal override {
                            _setBlacklistState(_account, false);
                        }
                        /**
                         * @dev Helper method that sets the blacklist state of an account.
                         * @param _account         The address of the account.
                         * @param _shouldBlacklist True if the account should be blacklisted, false if the account should be unblacklisted.
                         */
                        function _setBlacklistState(address _account, bool _shouldBlacklist)
                            internal
                            virtual
                        {
                            _deprecatedBlacklisted[_account] = _shouldBlacklist;
                        }
                        /**
                         * @dev Helper method that sets the balance of an account.
                         * @param _account The address of the account.
                         * @param _balance The new fiat token balance of the account.
                         */
                        function _setBalance(address _account, uint256 _balance) internal virtual {
                            balanceAndBlacklistStates[_account] = _balance;
                        }
                        /**
                         * @inheritdoc Blacklistable
                         */
                        function _isBlacklisted(address _account)
                            internal
                            virtual
                            override
                            view
                            returns (bool)
                        {
                            return _deprecatedBlacklisted[_account];
                        }
                        /**
                         * @dev Helper method to obtain the balance of an account.
                         * @param _account  The address of the account.
                         * @return          The fiat token balance of the account.
                         */
                        function _balanceOf(address _account)
                            internal
                            virtual
                            view
                            returns (uint256)
                        {
                            return balanceAndBlacklistStates[_account];
                        }
                    }
                    /**
                     * SPDX-License-Identifier: Apache-2.0
                     *
                     * Copyright (c) 2023, Circle Internet Financial, LLC.
                     *
                     * Licensed under the Apache License, Version 2.0 (the "License");
                     * you may not use this file except in compliance with the License.
                     * You may obtain a copy of the License at
                     *
                     * http://www.apache.org/licenses/LICENSE-2.0
                     *
                     * Unless required by applicable law or agreed to in writing, software
                     * distributed under the License is distributed on an "AS IS" BASIS,
                     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                     * See the License for the specific language governing permissions and
                     * limitations under the License.
                     */
                    pragma solidity 0.6.12;
                    import { Ownable } from "./Ownable.sol";
                    /**
                     * @title Blacklistable Token
                     * @dev Allows accounts to be blacklisted by a "blacklister" role
                     */
                    abstract contract Blacklistable is Ownable {
                        address public blacklister;
                        mapping(address => bool) internal _deprecatedBlacklisted;
                        event Blacklisted(address indexed _account);
                        event UnBlacklisted(address indexed _account);
                        event BlacklisterChanged(address indexed newBlacklister);
                        /**
                         * @dev Throws if called by any account other than the blacklister.
                         */
                        modifier onlyBlacklister() {
                            require(
                                msg.sender == blacklister,
                                "Blacklistable: caller is not the blacklister"
                            );
                            _;
                        }
                        /**
                         * @dev Throws if argument account is blacklisted.
                         * @param _account The address to check.
                         */
                        modifier notBlacklisted(address _account) {
                            require(
                                !_isBlacklisted(_account),
                                "Blacklistable: account is blacklisted"
                            );
                            _;
                        }
                        /**
                         * @notice Checks if account is blacklisted.
                         * @param _account The address to check.
                         * @return True if the account is blacklisted, false if the account is not blacklisted.
                         */
                        function isBlacklisted(address _account) external view returns (bool) {
                            return _isBlacklisted(_account);
                        }
                        /**
                         * @notice Adds account to blacklist.
                         * @param _account The address to blacklist.
                         */
                        function blacklist(address _account) external onlyBlacklister {
                            _blacklist(_account);
                            emit Blacklisted(_account);
                        }
                        /**
                         * @notice Removes account from blacklist.
                         * @param _account The address to remove from the blacklist.
                         */
                        function unBlacklist(address _account) external onlyBlacklister {
                            _unBlacklist(_account);
                            emit UnBlacklisted(_account);
                        }
                        /**
                         * @notice Updates the blacklister address.
                         * @param _newBlacklister The address of the new blacklister.
                         */
                        function updateBlacklister(address _newBlacklister) external onlyOwner {
                            require(
                                _newBlacklister != address(0),
                                "Blacklistable: new blacklister is the zero address"
                            );
                            blacklister = _newBlacklister;
                            emit BlacklisterChanged(blacklister);
                        }
                        /**
                         * @dev Checks if account is blacklisted.
                         * @param _account The address to check.
                         * @return true if the account is blacklisted, false otherwise.
                         */
                        function _isBlacklisted(address _account)
                            internal
                            virtual
                            view
                            returns (bool);
                        /**
                         * @dev Helper method that blacklists an account.
                         * @param _account The address to blacklist.
                         */
                        function _blacklist(address _account) internal virtual;
                        /**
                         * @dev Helper method that unblacklists an account.
                         * @param _account The address to unblacklist.
                         */
                        function _unBlacklist(address _account) internal virtual;
                    }
                    /**
                     * SPDX-License-Identifier: Apache-2.0
                     *
                     * Copyright (c) 2023, Circle Internet Financial, LLC.
                     *
                     * Licensed under the Apache License, Version 2.0 (the "License");
                     * you may not use this file except in compliance with the License.
                     * You may obtain a copy of the License at
                     *
                     * http://www.apache.org/licenses/LICENSE-2.0
                     *
                     * Unless required by applicable law or agreed to in writing, software
                     * distributed under the License is distributed on an "AS IS" BASIS,
                     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                     * See the License for the specific language governing permissions and
                     * limitations under the License.
                     */
                    pragma solidity 0.6.12;
                    import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
                    abstract contract AbstractFiatTokenV1 is IERC20 {
                        function _approve(
                            address owner,
                            address spender,
                            uint256 value
                        ) internal virtual;
                        function _transfer(
                            address from,
                            address to,
                            uint256 value
                        ) internal virtual;
                    }
                    /**
                     * SPDX-License-Identifier: Apache-2.0
                     *
                     * Copyright (c) 2023, Circle Internet Financial, LLC.
                     *
                     * Licensed under the Apache License, Version 2.0 (the "License");
                     * you may not use this file except in compliance with the License.
                     * You may obtain a copy of the License at
                     *
                     * http://www.apache.org/licenses/LICENSE-2.0
                     *
                     * Unless required by applicable law or agreed to in writing, software
                     * distributed under the License is distributed on an "AS IS" BASIS,
                     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                     * See the License for the specific language governing permissions and
                     * limitations under the License.
                     */
                    pragma solidity 0.6.12;
                    import { Ownable } from "../v1/Ownable.sol";
                    import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
                    import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
                    contract Rescuable is Ownable {
                        using SafeERC20 for IERC20;
                        address private _rescuer;
                        event RescuerChanged(address indexed newRescuer);
                        /**
                         * @notice Returns current rescuer
                         * @return Rescuer's address
                         */
                        function rescuer() external view returns (address) {
                            return _rescuer;
                        }
                        /**
                         * @notice Revert if called by any account other than the rescuer.
                         */
                        modifier onlyRescuer() {
                            require(msg.sender == _rescuer, "Rescuable: caller is not the rescuer");
                            _;
                        }
                        /**
                         * @notice Rescue ERC20 tokens locked up in this contract.
                         * @param tokenContract ERC20 token contract address
                         * @param to        Recipient address
                         * @param amount    Amount to withdraw
                         */
                        function rescueERC20(
                            IERC20 tokenContract,
                            address to,
                            uint256 amount
                        ) external onlyRescuer {
                            tokenContract.safeTransfer(to, amount);
                        }
                        /**
                         * @notice Updates the rescuer address.
                         * @param newRescuer The address of the new rescuer.
                         */
                        function updateRescuer(address newRescuer) external onlyOwner {
                            require(
                                newRescuer != address(0),
                                "Rescuable: new rescuer is the zero address"
                            );
                            _rescuer = newRescuer;
                            emit RescuerChanged(newRescuer);
                        }
                    }
                    /**
                     * SPDX-License-Identifier: Apache-2.0
                     *
                     * Copyright (c) 2023, Circle Internet Financial, LLC.
                     *
                     * Licensed under the Apache License, Version 2.0 (the "License");
                     * you may not use this file except in compliance with the License.
                     * You may obtain a copy of the License at
                     *
                     * http://www.apache.org/licenses/LICENSE-2.0
                     *
                     * Unless required by applicable law or agreed to in writing, software
                     * distributed under the License is distributed on an "AS IS" BASIS,
                     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                     * See the License for the specific language governing permissions and
                     * limitations under the License.
                     */
                    pragma solidity 0.6.12;
                    import { FiatTokenV1 } from "../v1/FiatTokenV1.sol";
                    import { Rescuable } from "./Rescuable.sol";
                    /**
                     * @title FiatTokenV1_1
                     * @dev ERC20 Token backed by fiat reserves
                     */
                    contract FiatTokenV1_1 is FiatTokenV1, Rescuable {
                    }
                    /**
                     * SPDX-License-Identifier: Apache-2.0
                     *
                     * Copyright (c) 2023, Circle Internet Financial, LLC.
                     *
                     * Licensed under the Apache License, Version 2.0 (the "License");
                     * you may not use this file except in compliance with the License.
                     * You may obtain a copy of the License at
                     *
                     * http://www.apache.org/licenses/LICENSE-2.0
                     *
                     * Unless required by applicable law or agreed to in writing, software
                     * distributed under the License is distributed on an "AS IS" BASIS,
                     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                     * See the License for the specific language governing permissions and
                     * limitations under the License.
                     */
                    pragma solidity 0.6.12;
                    import { ECRecover } from "./ECRecover.sol";
                    import { IERC1271 } from "../interface/IERC1271.sol";
                    /**
                     * @dev Signature verification helper that can be used instead of `ECRecover.recover` to seamlessly support both ECDSA
                     * signatures from externally owned accounts (EOAs) as well as ERC1271 signatures from smart contract wallets.
                     *
                     * Adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/21bb89ef5bfc789b9333eb05e3ba2b7b284ac77c/contracts/utils/cryptography/SignatureChecker.sol
                     */
                    library SignatureChecker {
                        /**
                         * @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the
                         * signature is validated against that smart contract using ERC1271, otherwise it's validated using `ECRecover.recover`.
                         * @param signer        Address of the claimed signer
                         * @param digest        Keccak-256 hash digest of the signed message
                         * @param signature     Signature byte array associated with hash
                         */
                        function isValidSignatureNow(
                            address signer,
                            bytes32 digest,
                            bytes memory signature
                        ) external view returns (bool) {
                            if (!isContract(signer)) {
                                return ECRecover.recover(digest, signature) == signer;
                            }
                            return isValidERC1271SignatureNow(signer, digest, signature);
                        }
                        /**
                         * @dev Checks if a signature is valid for a given signer and data hash. The signature is validated
                         * against the signer smart contract using ERC1271.
                         * @param signer        Address of the claimed signer
                         * @param digest        Keccak-256 hash digest of the signed message
                         * @param signature     Signature byte array associated with hash
                         *
                         * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
                         * change through time. It could return true at block N and false at block N+1 (or the opposite).
                         */
                        function isValidERC1271SignatureNow(
                            address signer,
                            bytes32 digest,
                            bytes memory signature
                        ) internal view returns (bool) {
                            (bool success, bytes memory result) = signer.staticcall(
                                abi.encodeWithSelector(
                                    IERC1271.isValidSignature.selector,
                                    digest,
                                    signature
                                )
                            );
                            return (success &&
                                result.length >= 32 &&
                                abi.decode(result, (bytes32)) ==
                                bytes32(IERC1271.isValidSignature.selector));
                        }
                        /**
                         * @dev Checks if the input address is a smart contract.
                         */
                        function isContract(address addr) internal view returns (bool) {
                            uint256 size;
                            assembly {
                                size := extcodesize(addr)
                            }
                            return size > 0;
                        }
                    }
                    /**
                     * SPDX-License-Identifier: Apache-2.0
                     *
                     * Copyright (c) 2023, Circle Internet Financial, LLC.
                     *
                     * Licensed under the Apache License, Version 2.0 (the "License");
                     * you may not use this file except in compliance with the License.
                     * You may obtain a copy of the License at
                     *
                     * http://www.apache.org/licenses/LICENSE-2.0
                     *
                     * Unless required by applicable law or agreed to in writing, software
                     * distributed under the License is distributed on an "AS IS" BASIS,
                     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                     * See the License for the specific language governing permissions and
                     * limitations under the License.
                     */
                    pragma solidity 0.6.12;
                    /**
                     * @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
                     *
                     * The library provides methods for generating a hash of a message that conforms to the
                     * https://eips.ethereum.org/EIPS/eip-191[EIP 191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
                     * specifications.
                     */
                    library MessageHashUtils {
                        /**
                         * @dev Returns the keccak256 digest of an EIP-712 typed data (EIP-191 version `0x01`).
                         * Adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/21bb89ef5bfc789b9333eb05e3ba2b7b284ac77c/contracts/utils/cryptography/MessageHashUtils.sol
                         *
                         * The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
                         * `\\x19\\x01` and hashing the result. It corresponds to the hash signed by the
                         * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
                         *
                         * @param domainSeparator    Domain separator
                         * @param structHash         Hashed EIP-712 data struct
                         * @return digest            The keccak256 digest of an EIP-712 typed data
                         */
                        function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash)
                            internal
                            pure
                            returns (bytes32 digest)
                        {
                            assembly {
                                let ptr := mload(0x40)
                                mstore(ptr, "\\x19\\x01")
                                mstore(add(ptr, 0x02), domainSeparator)
                                mstore(add(ptr, 0x22), structHash)
                                digest := keccak256(ptr, 0x42)
                            }
                        }
                    }
                    /**
                     * SPDX-License-Identifier: Apache-2.0
                     *
                     * Copyright (c) 2023, Circle Internet Financial, LLC.
                     *
                     * Licensed under the Apache License, Version 2.0 (the "License");
                     * you may not use this file except in compliance with the License.
                     * You may obtain a copy of the License at
                     *
                     * http://www.apache.org/licenses/LICENSE-2.0
                     *
                     * Unless required by applicable law or agreed to in writing, software
                     * distributed under the License is distributed on an "AS IS" BASIS,
                     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                     * See the License for the specific language governing permissions and
                     * limitations under the License.
                     */
                    pragma solidity 0.6.12;
                    /**
                     * @title EIP712
                     * @notice A library that provides EIP712 helper functions
                     */
                    library EIP712 {
                        /**
                         * @notice Make EIP712 domain separator
                         * @param name      Contract name
                         * @param version   Contract version
                         * @param chainId   Blockchain ID
                         * @return Domain separator
                         */
                        function makeDomainSeparator(
                            string memory name,
                            string memory version,
                            uint256 chainId
                        ) internal view returns (bytes32) {
                            return
                                keccak256(
                                    abi.encode(
                                        // keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")
                                        0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f,
                                        keccak256(bytes(name)),
                                        keccak256(bytes(version)),
                                        chainId,
                                        address(this)
                                    )
                                );
                        }
                        /**
                         * @notice Make EIP712 domain separator
                         * @param name      Contract name
                         * @param version   Contract version
                         * @return Domain separator
                         */
                        function makeDomainSeparator(string memory name, string memory version)
                            internal
                            view
                            returns (bytes32)
                        {
                            uint256 chainId;
                            assembly {
                                chainId := chainid()
                            }
                            return makeDomainSeparator(name, version, chainId);
                        }
                    }
                    /**
                     * SPDX-License-Identifier: Apache-2.0
                     *
                     * Copyright (c) 2023, Circle Internet Financial, LLC.
                     *
                     * Licensed under the Apache License, Version 2.0 (the "License");
                     * you may not use this file except in compliance with the License.
                     * You may obtain a copy of the License at
                     *
                     * http://www.apache.org/licenses/LICENSE-2.0
                     *
                     * Unless required by applicable law or agreed to in writing, software
                     * distributed under the License is distributed on an "AS IS" BASIS,
                     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                     * See the License for the specific language governing permissions and
                     * limitations under the License.
                     */
                    pragma solidity 0.6.12;
                    /**
                     * @title ECRecover
                     * @notice A library that provides a safe ECDSA recovery function
                     */
                    library ECRecover {
                        /**
                         * @notice Recover signer's address from a signed message
                         * @dev Adapted from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/65e4ffde586ec89af3b7e9140bdc9235d1254853/contracts/cryptography/ECDSA.sol
                         * Modifications: Accept v, r, and s as separate arguments
                         * @param digest    Keccak-256 hash digest of the signed message
                         * @param v         v of the signature
                         * @param r         r of the signature
                         * @param s         s of the signature
                         * @return Signer address
                         */
                        function recover(
                            bytes32 digest,
                            uint8 v,
                            bytes32 r,
                            bytes32 s
                        ) internal pure returns (address) {
                            // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
                            // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
                            // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
                            // signatures from current libraries generate a unique signature with an s-value in the lower half order.
                            //
                            // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
                            // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
                            // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
                            // these malleable signatures as well.
                            if (
                                uint256(s) >
                                0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0
                            ) {
                                revert("ECRecover: invalid signature 's' value");
                            }
                            if (v != 27 && v != 28) {
                                revert("ECRecover: invalid signature 'v' value");
                            }
                            // If the signature is valid (and not malleable), return the signer address
                            address signer = ecrecover(digest, v, r, s);
                            require(signer != address(0), "ECRecover: invalid signature");
                            return signer;
                        }
                        /**
                         * @notice Recover signer's address from a signed message
                         * @dev Adapted from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/0053ee040a7ff1dbc39691c9e67a69f564930a88/contracts/utils/cryptography/ECDSA.sol
                         * @param digest    Keccak-256 hash digest of the signed message
                         * @param signature Signature byte array associated with hash
                         * @return Signer address
                         */
                        function recover(bytes32 digest, bytes memory signature)
                            internal
                            pure
                            returns (address)
                        {
                            require(signature.length == 65, "ECRecover: invalid signature length");
                            bytes32 r;
                            bytes32 s;
                            uint8 v;
                            // ecrecover takes the signature parameters, and the only way to get them
                            // currently is to use assembly.
                            /// @solidity memory-safe-assembly
                            assembly {
                                r := mload(add(signature, 0x20))
                                s := mload(add(signature, 0x40))
                                v := byte(0, mload(add(signature, 0x60)))
                            }
                            return recover(digest, v, r, s);
                        }
                    }
                    /**
                     * SPDX-License-Identifier: Apache-2.0
                     *
                     * Copyright (c) 2023, Circle Internet Financial, LLC.
                     *
                     * Licensed under the Apache License, Version 2.0 (the "License");
                     * you may not use this file except in compliance with the License.
                     * You may obtain a copy of the License at
                     *
                     * http://www.apache.org/licenses/LICENSE-2.0
                     *
                     * Unless required by applicable law or agreed to in writing, software
                     * distributed under the License is distributed on an "AS IS" BASIS,
                     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                     * See the License for the specific language governing permissions and
                     * limitations under the License.
                     */
                    pragma solidity 0.6.12;
                    /**
                     * @dev Interface of the ERC1271 standard signature validation method for
                     * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
                     */
                    interface IERC1271 {
                        /**
                         * @dev Should return whether the signature provided is valid for the provided data
                         * @param hash          Hash of the data to be signed
                         * @param signature     Signature byte array associated with the provided data hash
                         * @return magicValue   bytes4 magic value 0x1626ba7e when function passes
                         */
                        function isValidSignature(bytes32 hash, bytes memory signature)
                            external
                            view
                            returns (bytes4 magicValue);
                    }
                    

                    File 8 of 9: MetaRouter
                    // SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
                    pragma solidity ^0.8.0;
                    /**
                     * @dev Interface of the ERC20 standard as defined in the EIP.
                     */
                    interface IERC20 {
                        /**
                         * @dev Returns the amount of tokens in existence.
                         */
                        function totalSupply() external view returns (uint256);
                        /**
                         * @dev Returns the amount of tokens owned by `account`.
                         */
                        function balanceOf(address account) external view returns (uint256);
                        /**
                         * @dev Moves `amount` tokens from the caller's account to `recipient`.
                         *
                         * Returns a boolean value indicating whether the operation succeeded.
                         *
                         * Emits a {Transfer} event.
                         */
                        function transfer(address recipient, uint256 amount) external returns (bool);
                        /**
                         * @dev Returns the remaining number of tokens that `spender` will be
                         * allowed to spend on behalf of `owner` through {transferFrom}. This is
                         * zero by default.
                         *
                         * This value changes when {approve} or {transferFrom} are called.
                         */
                        function allowance(address owner, address spender) external view returns (uint256);
                        /**
                         * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
                         *
                         * Returns a boolean value indicating whether the operation succeeded.
                         *
                         * IMPORTANT: Beware that changing an allowance with this method brings the risk
                         * that someone may use both the old and the new allowance by unfortunate
                         * transaction ordering. One possible solution to mitigate this race
                         * condition is to first reduce the spender's allowance to 0 and set the
                         * desired value afterwards:
                         * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                         *
                         * Emits an {Approval} event.
                         */
                        function approve(address spender, uint256 amount) external returns (bool);
                        /**
                         * @dev Moves `amount` tokens from `sender` to `recipient` using the
                         * allowance mechanism. `amount` is then deducted from the caller's
                         * allowance.
                         *
                         * Returns a boolean value indicating whether the operation succeeded.
                         *
                         * Emits a {Transfer} event.
                         */
                        function transferFrom(
                            address sender,
                            address recipient,
                            uint256 amount
                        ) external returns (bool);
                        /**
                         * @dev Emitted when `value` tokens are moved from one account (`from`) to
                         * another (`to`).
                         *
                         * Note that `value` may be zero.
                         */
                        event Transfer(address indexed from, address indexed to, uint256 value);
                        /**
                         * @dev Emitted when the allowance of a `spender` for an `owner` is set by
                         * a call to {approve}. `value` is the new allowance.
                         */
                        event Approval(address indexed owner, address indexed spender, uint256 value);
                    }
                    // SPDX-License-Identifier: MIT
                    // OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
                    pragma solidity ^0.8.0;
                    /**
                     * @dev Provides information about the current execution context, including the
                     * sender of the transaction and its data. While these are generally available
                     * via msg.sender and msg.data, they should not be accessed in such a direct
                     * manner, since when dealing with meta-transactions the account sending and
                     * paying for execution may not be the actual sender (as far as an application
                     * is concerned).
                     *
                     * This contract is only required for intermediate, library-like contracts.
                     */
                    abstract contract Context {
                        function _msgSender() internal view virtual returns (address) {
                            return msg.sender;
                        }
                        function _msgData() internal view virtual returns (bytes calldata) {
                            return msg.data;
                        }
                    }
                    // SPDX-License-Identifier: GPL-3.0-or-later
                    pragma solidity >=0.6.0;
                    // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
                    library TransferHelper {
                        function safeApprove(
                            address token,
                            address to,
                            uint256 value
                        ) internal {
                            // bytes4(keccak256(bytes('approve(address,uint256)')));
                            (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
                            require(
                                success && (data.length == 0 || abi.decode(data, (bool))),
                                'TransferHelper::safeApprove: approve failed'
                            );
                        }
                        function safeTransfer(
                            address token,
                            address to,
                            uint256 value
                        ) internal {
                            // bytes4(keccak256(bytes('transfer(address,uint256)')));
                            (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
                            require(
                                success && (data.length == 0 || abi.decode(data, (bool))),
                                'TransferHelper::safeTransfer: transfer failed'
                            );
                        }
                        function safeTransferFrom(
                            address token,
                            address from,
                            address to,
                            uint256 value
                        ) internal {
                            // bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
                            (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
                            require(
                                success && (data.length == 0 || abi.decode(data, (bool))),
                                'TransferHelper::transferFrom: transferFrom failed'
                            );
                        }
                        function safeTransferETH(address to, uint256 value) internal {
                            (bool success, ) = to.call{value: value}(new bytes(0));
                            require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
                        }
                    }
                    // SPDX-License-Identifier: GPL-3.0
                    // uni -> stable -> uni scheme
                    pragma solidity ^0.8.0;
                    import "@openzeppelin/contracts/utils/Context.sol";
                    import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
                    import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
                    import "./MetaRouteStructs.sol";
                    import "./MetaRouterGateway.sol";
                    import "../../utils/RevertMessageParser.sol";
                    /**
                     * @title MetaRouterV3
                     * @notice Users must give approve on their tokens to `MetaRoutetGateway` contract,
                     * not to `MetaRouter` contract.
                     */
                    contract MetaRouter is Context {
                        MetaRouterGateway public immutable metaRouterGateway;
                        event TransitTokenSent(
                            address to,
                            uint256 amount,
                            address token
                        );
                        constructor() {
                            metaRouterGateway = new MetaRouterGateway(address(this));
                        }
                        /**
                         * @notice Method that starts the Meta Routing
                         * @dev external + internal swap for burn scheme, only external for synth scheme
                         * @dev calls the next method on the other side
                         * @param _metarouteTransaction metaRoute offchain transaction data
                         */
                        function metaRoute(
                            MetaRouteStructs.MetaRouteTransaction calldata _metarouteTransaction
                        ) external payable {
                            uint256 approvedTokensLength = _metarouteTransaction.approvedTokens.length;
                            if (!_metarouteTransaction.nativeIn) {
                                metaRouterGateway.claimTokens(
                                    _metarouteTransaction.approvedTokens[0],
                                    _msgSender(),
                                    _metarouteTransaction.amount
                                );
                            }
                            uint256 secondSwapAmountIn = _metarouteTransaction.amount;
                            if (_metarouteTransaction.firstSwapCalldata.length != 0) {
                                if (!_metarouteTransaction.nativeIn) {
                                    _lazyApprove(
                                        _metarouteTransaction.approvedTokens[0],
                                        _metarouteTransaction.firstDexRouter,
                                        _metarouteTransaction.amount
                                    );
                                }
                                require(
                                    _metarouteTransaction.firstDexRouter != address(metaRouterGateway),
                                    "MetaRouter: invalid first router"
                                );
                                {
                                    uint256 size;
                                    address toCheck = _metarouteTransaction.firstDexRouter;
                                    assembly {
                                        size := extcodesize(toCheck)
                                    }
                                    require(size != 0, "MetaRouter: call for a non-contract account");
                                }
                                (bool firstSwapSuccess, bytes memory swapData) = _metarouteTransaction.firstDexRouter.call{value: msg.value}(
                                    _metarouteTransaction.firstSwapCalldata
                                );
                                if (!firstSwapSuccess) {
                                    revert(RevertMessageParser.getRevertMessage(swapData, "MetaRouter: first swap failed"));
                                }
                                secondSwapAmountIn = IERC20(_metarouteTransaction.approvedTokens[1]).balanceOf(address(this));
                            }
                            uint256 finalSwapAmountIn = secondSwapAmountIn;
                            if (_metarouteTransaction.secondSwapCalldata.length != 0) {
                                bytes memory secondSwapCalldata = _metarouteTransaction.secondSwapCalldata;
                                assembly {
                                    mstore(add(secondSwapCalldata, 36), secondSwapAmountIn)
                                }
                                _lazyApprove(
                                    _metarouteTransaction.approvedTokens[approvedTokensLength - 2],
                                    _metarouteTransaction.secondDexRouter,
                                    secondSwapAmountIn
                                );
                                require(
                                    _metarouteTransaction.secondDexRouter != address(metaRouterGateway),
                                    "MetaRouter: invalid second router"
                                );
                                {
                                    uint256 size;
                                    address toCheck = _metarouteTransaction.secondDexRouter;
                                    assembly {
                                        size := extcodesize(toCheck)
                                    }
                                    require(size != 0, "MetaRouter: call for a non-contract account");
                                }
                                (bool secondSwapSuccess, bytes memory swapData) = _metarouteTransaction.secondDexRouter.call(secondSwapCalldata);
                                if (!secondSwapSuccess) {
                                    revert(RevertMessageParser.getRevertMessage(swapData, "MetaRouter: second swap failed"));
                                }
                                finalSwapAmountIn = IERC20(
                                    _metarouteTransaction.approvedTokens[approvedTokensLength - 1]
                                ).balanceOf(address(this));
                            }
                            _lazyApprove(
                                _metarouteTransaction.approvedTokens[approvedTokensLength - 1],
                                _metarouteTransaction.relayRecipient,
                                finalSwapAmountIn
                            );
                            bytes memory otherSideCalldata = _metarouteTransaction.otherSideCalldata;
                            assembly {
                                mstore(add(otherSideCalldata, 100), finalSwapAmountIn)
                            }
                            require(
                                _metarouteTransaction.relayRecipient != address(metaRouterGateway),
                                "MetaRouter: invalid recipient"
                            );
                            {
                                uint256 size;
                                address toCheck = _metarouteTransaction.relayRecipient;
                                assembly {
                                    size := extcodesize(toCheck)
                                }
                                require(size != 0, "MetaRouter: call for a non-contract account");
                            }
                            (bool otherSideCallSuccess, bytes memory data) = _metarouteTransaction.relayRecipient.call(otherSideCalldata);
                            if (!otherSideCallSuccess) {
                                revert(RevertMessageParser.getRevertMessage(data, "MetaRouter: other side call failed"));
                            }
                        }
                        /**
                         * @notice Implements an external call on some contract
                         * @dev called by Portal in metaUnsynthesize() method
                         * @param _token address of token
                         * @param _amount amount of _token
                         * @param _receiveSide contract on which call will take place
                         * @param _calldata encoded method to call
                         * @param _offset shift to patch the amount to calldata
                         */
                        function externalCall(
                            address _token,
                            uint256 _amount,
                            address _receiveSide,
                            bytes calldata _calldata,
                            uint256 _offset,
                            address _to
                        ) external {
                            (bool success,) = _externalCall(_token, _amount, _receiveSide, _calldata, _offset);
                            if (!success) {
                                TransferHelper.safeTransfer(
                                    _token,
                                    _to,
                                    _amount
                                );
                                emit TransitTokenSent(_to, _amount, _token);
                            }
                        }
                        function returnSwap(
                            address _token,
                            uint256 _amount,
                            address _router,
                            bytes calldata _swapCalldata,
                            address _burnToken,
                            address _synthesis,
                            bytes calldata _burnCalldata
                        ) external {
                            (bool success, bytes memory data) = _externalCall(_token, _amount, _router, _swapCalldata, 36);
                            if (!success) {
                                revert(RevertMessageParser.getRevertMessage(data, "MetaRouterV2: internal swap failed"));
                            }
                            uint256 internalSwapAmountOut = IERC20(_burnToken).balanceOf(address(this));
                            bytes memory burnCalldata = _burnCalldata;
                            assembly {
                                mstore(add(burnCalldata, 100), internalSwapAmountOut)
                            }
                            require(
                                _synthesis != address(metaRouterGateway),
                                "MetaRouterV2: invalid recipient"
                            );
                            {
                                uint256 size;
                                address toCheck = _synthesis;
                                assembly {
                                    size := extcodesize(toCheck)
                                }
                                require(size != 0, "MetaRouter: call for a non-contract account");
                            }
                            (bool otherSideCallSuccess, bytes memory burnData) = _synthesis.call(burnCalldata);
                            if (!otherSideCallSuccess) {
                                revert(RevertMessageParser.getRevertMessage(burnData, "MetaRouterV2: revertSynthesizeRequest call failed"));
                            }
                        }
                        /**
                         * @notice Implements an internal swap on stable router and final method call
                         * @dev called by Synthesis in metaMint() method
                         * @param _metaMintTransaction metaMint offchain transaction data
                         */
                        function metaMintSwap(
                            MetaRouteStructs.MetaMintTransaction calldata _metaMintTransaction
                        ) external {
                            address finalCallToken = _metaMintTransaction.swapTokens[0];
                            if (_metaMintTransaction.secondSwapCalldata.length != 0) {
                                // internal swap
                                (bool internalSwapSuccess, bytes memory internalSwapData) = _externalCall(
                                    _metaMintTransaction.swapTokens[0],
                                    _metaMintTransaction.amount,
                                    _metaMintTransaction.secondDexRouter,
                                    _metaMintTransaction.secondSwapCalldata,
                                    36
                                );
                                if (!internalSwapSuccess) {
                                    revert(RevertMessageParser.getRevertMessage(internalSwapData, "MetaRouter: internal swap failed"));
                                }
                                finalCallToken = _metaMintTransaction.swapTokens[1];
                            }
                            if (_metaMintTransaction.finalCalldata.length != 0) {
                                // patch crossChainID
                                bytes32 crossChainID = _metaMintTransaction.crossChainID;
                                bytes memory calldata_ = _metaMintTransaction.finalCalldata;
                                assembly {
                                    mstore(add(calldata_, 132), crossChainID)
                                }
                                uint256 finalAmountIn = IERC20(finalCallToken).balanceOf(address(this));
                                // external call
                                (bool finalSuccess, bytes memory finalData) = _externalCall(
                                    finalCallToken,
                                    finalAmountIn,
                                    _metaMintTransaction.finalReceiveSide,
                                    calldata_,
                                    _metaMintTransaction.finalOffset
                                );
                                if (!finalSuccess) {
                                    revert(RevertMessageParser.getRevertMessage(finalData, "MetaRouter: final call failed"));
                                }
                            }
                            uint256 amountOut = IERC20(_metaMintTransaction.swapTokens[_metaMintTransaction.swapTokens.length - 1]).balanceOf(address(this));
                            if (amountOut != 0) {
                                TransferHelper.safeTransfer(
                                    _metaMintTransaction.swapTokens[_metaMintTransaction.swapTokens.length - 1],
                                    _metaMintTransaction.to,
                                    amountOut
                                );
                            }
                        }
                        /**
                         * @notice Implements call of some operation with token
                         * @dev Internal function used in metaMintSwap() and externalCall()
                         * @param _token token address
                         * @param _amount amount of _token
                         * @param _receiveSide address of contract on which method will be called
                         * @param _calldata encoded method call
                         * @param _offset shift to patch the _amount to calldata
                         */
                        function _externalCall(
                            address _token,
                            uint256 _amount,
                            address _receiveSide,
                            bytes memory _calldata,
                            uint256 _offset
                        ) internal returns (bool success, bytes memory data) {
                            require(_receiveSide != address(metaRouterGateway), "MetaRouter: invalid receiveSide");
                            _lazyApprove(_token, _receiveSide, _amount);
                            assembly {
                                mstore(add(_calldata, _offset), _amount)
                            }
                            {
                                uint256 size;
                                address toCheck = _receiveSide;
                                assembly {
                                    size := extcodesize(toCheck)
                                }
                                require(size != 0, "MetaRouter: call for a non-contract account");
                            }
                            (success, data) = _receiveSide.call(_calldata);
                        }
                        /**
                         * @notice Implements approve
                         * @dev Internal function used to approve the token spending
                         * @param _token token address
                         * @param _to address to approve
                         * @param _amount amount for which approve will be given
                         */
                        function _lazyApprove(address _token, address _to, uint256 _amount) internal {
                            if (IERC20(_token).allowance(address(this), _to) < _amount) {
                                TransferHelper.safeApprove(_token, _to, type(uint256).max);
                            }
                        }
                    }
                    // SPDX-License-Identifier: GPL-3.0
                    pragma solidity ^0.8.0;
                    import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
                    /**
                     * @title MetaRouterGateway
                     * @notice During the `metaRoute` transaction `MetaRouter` (only) claims user's tokens
                     * from `MetaRoutetGateway` contract and then operates with them.
                     */
                    contract MetaRouterGateway {
                        address public immutable metaRouter;
                        modifier onlyMetarouter() {
                            require(metaRouter == msg.sender, "Symb: caller is not the metarouter");
                            _;
                        }
                        constructor(address _metaRouter) {
                            metaRouter = _metaRouter;
                        }
                        function claimTokens(
                            address _token,
                            address _from,
                            uint256 _amount
                        ) external onlyMetarouter {
                            TransferHelper.safeTransferFrom(_token, _from, metaRouter, _amount);
                        }
                    }
                    // SPDX-License-Identifier: GPL-3.0
                    pragma solidity ^0.8.0;
                    library MetaRouteStructs {
                        struct MetaBurnTransaction {
                            uint256 stableBridgingFee;
                            uint256 amount;
                            bytes32 crossChainID;
                            address syntCaller;
                            address finalReceiveSide;
                            address sToken;
                            bytes finalCallData;
                            uint256 finalOffset;
                            address chain2address;
                            address receiveSide;
                            address oppositeBridge;
                            address revertableAddress;
                            uint256 chainID;
                            bytes32 clientID;
                        }
                        struct MetaMintTransaction {
                            uint256 stableBridgingFee;
                            uint256 amount;
                            bytes32 crossChainID;
                            bytes32 externalID;
                            address tokenReal;
                            uint256 chainID;
                            address to;
                            address[] swapTokens;
                            address secondDexRouter;
                            bytes secondSwapCalldata;
                            address finalReceiveSide;
                            bytes finalCalldata;
                            uint256 finalOffset;
                        }
                        struct MetaRouteTransaction {
                            bytes firstSwapCalldata;
                            bytes secondSwapCalldata;
                            address[] approvedTokens;
                            address firstDexRouter;
                            address secondDexRouter;
                            uint256 amount;
                            bool nativeIn;
                            address relayRecipient;
                            bytes otherSideCalldata;
                        }
                        struct MetaSynthesizeTransaction {
                            uint256 stableBridgingFee;
                            uint256 amount;
                            address rtoken;
                            address chain2address;
                            address receiveSide;
                            address oppositeBridge;
                            address syntCaller;
                            uint256 chainID;
                            address[] swapTokens;
                            address secondDexRouter;
                            bytes secondSwapCalldata;
                            address finalReceiveSide;
                            bytes finalCalldata;
                            uint256 finalOffset;
                            address revertableAddress;
                            bytes32 clientID;
                        }
                        struct MetaRevertTransaction {
                            uint256 stableBridgingFee;
                            bytes32 internalID;
                            address receiveSide;
                            address managerChainBridge;
                            address sourceChainBridge;
                            uint256 managerChainId;
                            uint256 sourceChainId;
                            address router;
                            bytes swapCalldata;
                            address sourceChainSynthesis;
                            address burnToken;
                            bytes burnCalldata;
                            bytes32 clientID;
                        }
                    }
                    // SPDX-License-Identifier: GPL-3.0
                    pragma solidity ^0.8.0;
                    library RevertMessageParser {
                        function getRevertMessage(bytes memory _data, string memory _defaultMessage) internal pure returns (string memory) {
                            // If the _data length is less than 68, then the transaction failed silently (without a revert message)
                            if (_data.length < 68) return _defaultMessage;
                            assembly {
                                // Slice the sighash
                                _data := add(_data, 0x04)
                            }
                            return abi.decode(_data, (string));
                        }
                    }
                    

                    File 9 of 9: AggregationRouterV5
                    /*
                                                                               ,▄▓▓██▌   ,╓▄▄▓▓▓▓▓▓▓▓▄▄▄,,
                                                                            ,▓██▓███▓▄▓███▓╬╬╬╬╬╬╬╬╬╬╬╬╬▓███▓▄,
                                                                      ▄█   ▓██╬╣███████╬▓▀╬╬▓▓▓████████████▓█████▄,
                                                                     ▓██▌ ▓██╬╣██████╬▓▌  ██████████████████████▌╙╙▀ⁿ
                                                                    ▐████████╬▓████▓▓█╨ ▄ ╟█████████▓▓╬╬╬╬╬▓▓█████▓▄
                                                      └▀▓▓▄╓        ╟█▓╣█████▓██████▀ ╓█▌ ███████▓▓▓▓▓╬╬╬╬╬╬╬╬╬╬╬╬▓██▓▄
                                                         └▀████▓▄╥  ▐██╬╬██████████╙ Æ▀─ ▓███▀╚╠╬╩▀▀███████▓▓╬╬╬╬╬╬╬╬╬██▄
                                                            └▀██▓▀▀█████▓╬▓██████▀     ▄█████▒╠"      └╙▓██████▓╬╬╬╬╬╬╬╬██▄
                                                               └▀██▄,└╙▀▀████▌└╙    ^"▀╙╙╙"╙██      @▄    ╙▀███████╬╬╬╬╬╬╬██µ
                                                                  └▀██▓▄, ██▌       ╒       ╙█▓     ]▓█▓╔    ▀███████▓╬╬╬╬╬▓█▌
                                                                      ▀█████       ▓         ╟█▌    ]╠██▓░▒╓   ▀████████╬╬╬╬╣█▌
                                                                      ▐████      ╓█▀█▌      ,██▌    ╚Å███▓▒▒╠╓  ╙█████████╬╬╬╣█▌
                                                                      └████     ▓█░░▓█      ▀▀▀    φ▒╫████▒▒▒▒╠╓  █████████▓╬╬▓█µ
                                                                       ╘███µ ▌▄█▓▄▓▀`     ,▀    ,╔╠░▓██████▌╠▒▒▒φ  ██████████╬╬██
                                                                       ▐████µ╙▓▀`     ,▀╙,╔╔φφφ╠░▄▓███████▌░▓╙▒▒▒╠ └██╬███████╬▓█⌐
                                                                       ╫██ ▓▌         ▌φ▒▒░▓██████████████▌▒░▓╚▒▒▒╠ ▓██╬▓██████╣█▌
                                                                       ██▌           ▌╔▒▒▄████████████████▒▒▒░▌╠▒▒▒≥▐██▓╬╬███████▌
                                                                       ██▌      ,╓φ╠▓«▒▒▓████▀  ▀█████████▌▒▒▒╟░▒▒▒▒▐███╬╬╣████▓█▌
                                                                      ▐██      ╠▒▄▓▓███▓████└     ▀████████▌▒▒░▌╚▒▒▒▐███▓╬╬████ ╙▌
                                                                      ███  )  ╠▒░░░▒░╬████▀        └████████░▒▒░╬∩▒▒▓████╬╬╣███
                                                                     ▓██    ╠╠▒▒▐█▀▀▌`░╫██           ███████▒▒▒▒░▒▒½█████╬╬╣███
                                                                    ███ ,█▄ ╠▒▒▒╫▌,▄▀,▒╫██           ╟██████▒▒▒░╣⌠▒▓█████╬╬╣██▌
                                                                   ╘██µ ██` ╠▒▒░██╬φ╠▄▓██`            ██████░░▌φ╠░▓█████▓╬╬▓██
                                                                    ╟██  .φ╠▒░▄█▀░░▄██▀└              █████▌▒╣φ▒░▓██████╬╬╣██
                                                                     ▀██▄▄▄╓▄███████▀                ▐█████░▓φ▒▄███████▓╬╣██
                                                                       ╙▀▀▀██▀└                      ████▓▄▀φ▄▓████████╬▓█▀
                                                                                                    ▓███╬╩╔╣██████████▓██└
                                                                                                  ╓████▀▄▓████████▀████▀
                                                                                                ,▓███████████████─]██╙
                                                                                             ,▄▓██████████████▀└  ╙
                                                                                        ,╓▄▓███████████████▀╙
                                                                                 `"▀▀▀████████▀▀▀▀`▄███▀▀└
                                                                                                  └└
                    
                    
                    
                                        11\   11\                     11\             11\   11\            11\                                       11\
                                      1111 |  \__|                    11 |            111\  11 |           11 |                                      11 |
                                      \_11 |  11\ 1111111\   1111111\ 1111111\        1111\ 11 | 111111\ 111111\   11\  11\  11\  111111\   111111\  11 |  11\
                                        11 |  11 |11  __11\ 11  _____|11  __11\       11 11\11 |11  __11\\_11  _|  11 | 11 | 11 |11  __11\ 11  __11\ 11 | 11  |
                                        11 |  11 |11 |  11 |11 /      11 |  11 |      11 \1111 |11111111 | 11 |    11 | 11 | 11 |11 /  11 |11 |  \__|111111  /
                                        11 |  11 |11 |  11 |11 |      11 |  11 |      11 |\111 |11   ____| 11 |11\ 11 | 11 | 11 |11 |  11 |11 |      11  _11<
                                      111111\ 11 |11 |  11 |\1111111\ 11 |  11 |      11 | \11 |\1111111\  \1111  |\11111\1111  |\111111  |11 |      11 | \11\
                                      \______|\__|\__|  \__| \_______|\__|  \__|      \__|  \__| \_______|  \____/  \_____\____/  \______/ \__|      \__|  \__|
                    
                    
                    
                                                   111111\                                                               11\     11\
                                                  11  __11\                                                              11 |    \__|
                                                  11 /  11 | 111111\   111111\   111111\   111111\   111111\   111111\ 111111\   11\  111111\  1111111\
                                                  11111111 |11  __11\ 11  __11\ 11  __11\ 11  __11\ 11  __11\  \____11\\_11  _|  11 |11  __11\ 11  __11\
                                                  11  __11 |11 /  11 |11 /  11 |11 |  \__|11111111 |11 /  11 | 1111111 | 11 |    11 |11 /  11 |11 |  11 |
                                                  11 |  11 |11 |  11 |11 |  11 |11 |      11   ____|11 |  11 |11  __11 | 11 |11\ 11 |11 |  11 |11 |  11 |
                                                  11 |  11 |\1111111 |\1111111 |11 |      \1111111\ \1111111 |\1111111 | \1111  |11 |\111111  |11 |  11 |
                                                  \__|  \__| \____11 | \____11 |\__|       \_______| \____11 | \_______|  \____/ \__| \______/ \__|  \__|
                                                            11\   11 |11\   11 |                    11\   11 |
                                                            \111111  |\111111  |                    \111111  |
                                                             \______/  \______/                      \______/
                                                                    1111111\                        11\
                                                                    11  __11\                       11 |
                                                                    11 |  11 | 111111\  11\   11\ 111111\    111111\   111111\
                                                                    1111111  |11  __11\ 11 |  11 |\_11  _|  11  __11\ 11  __11\
                                                                    11  __11< 11 /  11 |11 |  11 |  11 |    11111111 |11 |  \__|
                                                                    11 |  11 |11 |  11 |11 |  11 |  11 |11\ 11   ____|11 |
                                                                    11 |  11 |\111111  |\111111  |  \1111  |\1111111\ 11 |
                                                                    \__|  \__| \______/  \______/    \____/  \_______|\__|
                    */
                    
                    // SPDX-License-Identifier: MIT
                    
                    // File contracts/interfaces/IClipperExchangeInterface.sol
                    
                    
                    pragma solidity 0.8.17;
                    
                    /// @title Clipper interface subset used in swaps
                    interface IClipperExchangeInterface {
                        struct Signature {
                            uint8 v;
                            bytes32 r;
                            bytes32 s;
                        }
                    
                        function sellEthForToken(address outputToken, uint256 inputAmount, uint256 outputAmount, uint256 goodUntil, address destinationAddress, Signature calldata theSignature, bytes calldata auxiliaryData) external payable;
                        function sellTokenForEth(address inputToken, uint256 inputAmount, uint256 outputAmount, uint256 goodUntil, address destinationAddress, Signature calldata theSignature, bytes calldata auxiliaryData) external;
                        function swap(address inputToken, address outputToken, uint256 inputAmount, uint256 outputAmount, uint256 goodUntil, address destinationAddress, Signature calldata theSignature, bytes calldata auxiliaryData) external;
                    }
                    
                    
                    // File contracts/helpers/RouterErrors.sol
                    
                    
                    pragma solidity 0.8.17;
                    
                    library RouterErrors {
                        error ReturnAmountIsNotEnough();
                        error InvalidMsgValue();
                        error ERC20TransferFailed();
                    }
                    
                    
                    // File @1inch/solidity-utils/contracts/[email protected]
                    
                    
                    pragma solidity ^0.8.0;
                    
                    abstract contract EthReceiver {
                        error EthDepositRejected();
                    
                        receive() external payable {
                            _receive();
                        }
                    
                        function _receive() internal virtual {
                            // solhint-disable-next-line avoid-tx-origin
                            if (msg.sender == tx.origin) revert EthDepositRejected();
                        }
                    }
                    
                    
                    // File @openzeppelin/contracts/token/ERC20/[email protected]
                    
                    // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
                    
                    pragma solidity ^0.8.0;
                    
                    /**
                     * @dev Interface of the ERC20 standard as defined in the EIP.
                     */
                    interface IERC20 {
                        /**
                         * @dev Emitted when `value` tokens are moved from one account (`from`) to
                         * another (`to`).
                         *
                         * Note that `value` may be zero.
                         */
                        event Transfer(address indexed from, address indexed to, uint256 value);
                    
                        /**
                         * @dev Emitted when the allowance of a `spender` for an `owner` is set by
                         * a call to {approve}. `value` is the new allowance.
                         */
                        event Approval(address indexed owner, address indexed spender, uint256 value);
                    
                        /**
                         * @dev Returns the amount of tokens in existence.
                         */
                        function totalSupply() external view returns (uint256);
                    
                        /**
                         * @dev Returns the amount of tokens owned by `account`.
                         */
                        function balanceOf(address account) external view returns (uint256);
                    
                        /**
                         * @dev Moves `amount` tokens from the caller's account to `to`.
                         *
                         * Returns a boolean value indicating whether the operation succeeded.
                         *
                         * Emits a {Transfer} event.
                         */
                        function transfer(address to, uint256 amount) external returns (bool);
                    
                        /**
                         * @dev Returns the remaining number of tokens that `spender` will be
                         * allowed to spend on behalf of `owner` through {transferFrom}. This is
                         * zero by default.
                         *
                         * This value changes when {approve} or {transferFrom} are called.
                         */
                        function allowance(address owner, address spender) external view returns (uint256);
                    
                        /**
                         * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
                         *
                         * Returns a boolean value indicating whether the operation succeeded.
                         *
                         * IMPORTANT: Beware that changing an allowance with this method brings the risk
                         * that someone may use both the old and the new allowance by unfortunate
                         * transaction ordering. One possible solution to mitigate this race
                         * condition is to first reduce the spender's allowance to 0 and set the
                         * desired value afterwards:
                         * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                         *
                         * Emits an {Approval} event.
                         */
                        function approve(address spender, uint256 amount) external returns (bool);
                    
                        /**
                         * @dev Moves `amount` tokens from `from` to `to` using the
                         * allowance mechanism. `amount` is then deducted from the caller's
                         * allowance.
                         *
                         * Returns a boolean value indicating whether the operation succeeded.
                         *
                         * Emits a {Transfer} event.
                         */
                        function transferFrom(
                            address from,
                            address to,
                            uint256 amount
                        ) external returns (bool);
                    }
                    
                    
                    // File @1inch/solidity-utils/contracts/interfaces/[email protected]
                    
                    
                    pragma solidity ^0.8.0;
                    
                    
                    interface IDaiLikePermit {
                        function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external;
                    }
                    
                    
                    // File @1inch/solidity-utils/contracts/libraries/[email protected]
                    
                    
                    pragma solidity ^0.8.0;
                    
                    library RevertReasonForwarder {
                        function reRevert() internal pure {
                            // bubble up revert reason from latest external call
                            /// @solidity memory-safe-assembly
                            assembly { // solhint-disable-line no-inline-assembly
                                let ptr := mload(0x40)
                                returndatacopy(ptr, 0, returndatasize())
                                revert(ptr, returndatasize())
                            }
                        }
                    }
                    
                    
                    // File @openzeppelin/contracts/token/ERC20/extensions/[email protected]
                    
                    // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
                    
                    pragma solidity ^0.8.0;
                    
                    /**
                     * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
                     * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
                     *
                     * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
                     * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
                     * need to send a transaction, and thus is not required to hold Ether at all.
                     */
                    interface IERC20Permit {
                        /**
                         * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
                         * given ``owner``'s signed approval.
                         *
                         * IMPORTANT: The same issues {IERC20-approve} has related to transaction
                         * ordering also apply here.
                         *
                         * Emits an {Approval} event.
                         *
                         * Requirements:
                         *
                         * - `spender` cannot be the zero address.
                         * - `deadline` must be a timestamp in the future.
                         * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
                         * over the EIP712-formatted function arguments.
                         * - the signature must use ``owner``'s current nonce (see {nonces}).
                         *
                         * For more information on the signature format, see the
                         * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
                         * section].
                         */
                        function permit(
                            address owner,
                            address spender,
                            uint256 value,
                            uint256 deadline,
                            uint8 v,
                            bytes32 r,
                            bytes32 s
                        ) external;
                    
                        /**
                         * @dev Returns the current nonce for `owner`. This value must be
                         * included whenever a signature is generated for {permit}.
                         *
                         * Every successful call to {permit} increases ``owner``'s nonce by one. This
                         * prevents a signature from being used multiple times.
                         */
                        function nonces(address owner) external view returns (uint256);
                    
                        /**
                         * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
                         */
                        // solhint-disable-next-line func-name-mixedcase
                        function DOMAIN_SEPARATOR() external view returns (bytes32);
                    }
                    
                    
                    // File @1inch/solidity-utils/contracts/libraries/[email protected]
                    
                    
                    pragma solidity ^0.8.0;
                    
                    
                    
                    
                    library SafeERC20 {
                        error SafeTransferFailed();
                        error SafeTransferFromFailed();
                        error ForceApproveFailed();
                        error SafeIncreaseAllowanceFailed();
                        error SafeDecreaseAllowanceFailed();
                        error SafePermitBadLength();
                    
                        // Ensures method do not revert or return boolean `true`, admits call to non-smart-contract
                        function safeTransferFrom(IERC20 token, address from, address to, uint256 amount) internal {
                            bytes4 selector = token.transferFrom.selector;
                            bool success;
                            /// @solidity memory-safe-assembly
                            assembly { // solhint-disable-line no-inline-assembly
                                let data := mload(0x40)
                    
                                mstore(data, selector)
                                mstore(add(data, 0x04), from)
                                mstore(add(data, 0x24), to)
                                mstore(add(data, 0x44), amount)
                                success := call(gas(), token, 0, data, 100, 0x0, 0x20)
                                if success {
                                    switch returndatasize()
                                    case 0 { success := gt(extcodesize(token), 0) }
                                    default { success := and(gt(returndatasize(), 31), eq(mload(0), 1)) }
                                }
                            }
                            if (!success) revert SafeTransferFromFailed();
                        }
                    
                        // Ensures method do not revert or return boolean `true`, admits call to non-smart-contract
                        function safeTransfer(IERC20 token, address to, uint256 value) internal {
                            if (!_makeCall(token, token.transfer.selector, to, value)) {
                                revert SafeTransferFailed();
                            }
                        }
                    
                        // If `approve(from, to, amount)` fails, try to `approve(from, to, 0)` before retry
                        function forceApprove(IERC20 token, address spender, uint256 value) internal {
                            if (!_makeCall(token, token.approve.selector, spender, value)) {
                                if (!_makeCall(token, token.approve.selector, spender, 0) ||
                                    !_makeCall(token, token.approve.selector, spender, value))
                                {
                                    revert ForceApproveFailed();
                                }
                            }
                        }
                    
                        function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                            uint256 allowance = token.allowance(address(this), spender);
                            if (value > type(uint256).max - allowance) revert SafeIncreaseAllowanceFailed();
                            forceApprove(token, spender, allowance + value);
                        }
                    
                        function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                            uint256 allowance = token.allowance(address(this), spender);
                            if (value > allowance) revert SafeDecreaseAllowanceFailed();
                            forceApprove(token, spender, allowance - value);
                        }
                    
                        function safePermit(IERC20 token, bytes calldata permit) internal {
                            bool success;
                            if (permit.length == 32 * 7) {
                                success = _makeCalldataCall(token, IERC20Permit.permit.selector, permit);
                            } else if (permit.length == 32 * 8) {
                                success = _makeCalldataCall(token, IDaiLikePermit.permit.selector, permit);
                            } else {
                                revert SafePermitBadLength();
                            }
                            if (!success) RevertReasonForwarder.reRevert();
                        }
                    
                        function _makeCall(IERC20 token, bytes4 selector, address to, uint256 amount) private returns(bool success) {
                            /// @solidity memory-safe-assembly
                            assembly { // solhint-disable-line no-inline-assembly
                                let data := mload(0x40)
                    
                                mstore(data, selector)
                                mstore(add(data, 0x04), to)
                                mstore(add(data, 0x24), amount)
                                success := call(gas(), token, 0, data, 0x44, 0x0, 0x20)
                                if success {
                                    switch returndatasize()
                                    case 0 { success := gt(extcodesize(token), 0) }
                                    default { success := and(gt(returndatasize(), 31), eq(mload(0), 1)) }
                                }
                            }
                        }
                    
                        function _makeCalldataCall(IERC20 token, bytes4 selector, bytes calldata args) private returns(bool success) {
                            /// @solidity memory-safe-assembly
                            assembly { // solhint-disable-line no-inline-assembly
                                let len := add(4, args.length)
                                let data := mload(0x40)
                    
                                mstore(data, selector)
                                calldatacopy(add(data, 0x04), args.offset, args.length)
                                success := call(gas(), token, 0, data, len, 0x0, 0x20)
                                if success {
                                    switch returndatasize()
                                    case 0 { success := gt(extcodesize(token), 0) }
                                    default { success := and(gt(returndatasize(), 31), eq(mload(0), 1)) }
                                }
                            }
                        }
                    }
                    
                    
                    // File @1inch/solidity-utils/contracts/interfaces/[email protected]
                    
                    
                    pragma solidity ^0.8.0;
                    
                    interface IWETH is IERC20 {
                        function deposit() external payable;
                        function withdraw(uint256 amount) external;
                    }
                    
                    
                    // File contracts/routers/ClipperRouter.sol
                    
                    
                    pragma solidity 0.8.17;
                    
                    
                    
                    
                    
                    
                    /// @title Clipper router that allows to use `ClipperExchangeInterface` for swaps
                    contract ClipperRouter is EthReceiver {
                        using SafeERC20 for IERC20;
                    
                        uint256 private constant _SIGNATURE_S_MASK = 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
                        uint256 private constant _SIGNATURE_V_SHIFT = 255;
                        bytes6 private constant _INCH_TAG_WITH_LENGTH_PREFIX = "\x051INCH";
                        IERC20 private constant _ETH = IERC20(address(0));
                        IWETH private immutable _WETH;  // solhint-disable-line var-name-mixedcase
                    
                        constructor(IWETH weth) {
                            _WETH = weth;
                        }
                    
                        /// @notice Same as `clipperSwapTo` but calls permit first,
                        /// allowing to approve token spending and make a swap in one transaction.
                        /// @dev See tests for examples
                        /// @param recipient Address that will receive swap funds
                        /// @param srcToken Source token
                        /// @param dstToken Destination token
                        /// @param inputAmount Amount of source tokens to swap
                        /// @param outputAmount Amount of destination tokens to receive
                        /// @param goodUntil Timestamp until the swap will be valid
                        /// @param r Clipper order signature (r part)
                        /// @param vs Clipper order signature (vs part)
                        /// @param permit Should contain valid permit that can be used in `IERC20Permit.permit` calls.
                        /// @return returnAmount Amount of destination tokens received
                        function clipperSwapToWithPermit(
                            IClipperExchangeInterface clipperExchange,
                            address payable recipient,
                            IERC20 srcToken,
                            IERC20 dstToken,
                            uint256 inputAmount,
                            uint256 outputAmount,
                            uint256 goodUntil,
                            bytes32 r,
                            bytes32 vs,
                            bytes calldata permit
                        ) external returns(uint256 returnAmount) {
                            srcToken.safePermit(permit);
                            return clipperSwapTo(clipperExchange, recipient, srcToken, dstToken, inputAmount, outputAmount, goodUntil, r, vs);
                        }
                    
                        /// @notice Same as `clipperSwapTo` but uses `msg.sender` as recipient
                        /// @param srcToken Source token
                        /// @param dstToken Destination token
                        /// @param inputAmount Amount of source tokens to swap
                        /// @param outputAmount Amount of destination tokens to receive
                        /// @param goodUntil Timestamp until the swap will be valid
                        /// @param r Clipper order signature (r part)
                        /// @param vs Clipper order signature (vs part)
                        /// @return returnAmount Amount of destination tokens received
                        function clipperSwap(
                            IClipperExchangeInterface clipperExchange,
                            IERC20 srcToken,
                            IERC20 dstToken,
                            uint256 inputAmount,
                            uint256 outputAmount,
                            uint256 goodUntil,
                            bytes32 r,
                            bytes32 vs
                        ) external payable returns(uint256 returnAmount) {
                            return clipperSwapTo(clipperExchange, payable(msg.sender), srcToken, dstToken, inputAmount, outputAmount, goodUntil, r, vs);
                        }
                    
                        /// @notice Performs swap using Clipper exchange. Wraps and unwraps ETH if required.
                        /// Sending non-zero `msg.value` for anything but ETH swaps is prohibited
                        /// @param recipient Address that will receive swap funds
                        /// @param srcToken Source token
                        /// @param dstToken Destination token
                        /// @param inputAmount Amount of source tokens to swap
                        /// @param outputAmount Amount of destination tokens to receive
                        /// @param goodUntil Timestamp until the swap will be valid
                        /// @param r Clipper order signature (r part)
                        /// @param vs Clipper order signature (vs part)
                        /// @return returnAmount Amount of destination tokens received
                        function clipperSwapTo(
                            IClipperExchangeInterface clipperExchange,
                            address payable recipient,
                            IERC20 srcToken,
                            IERC20 dstToken,
                            uint256 inputAmount,
                            uint256 outputAmount,
                            uint256 goodUntil,
                            bytes32 r,
                            bytes32 vs
                        ) public payable returns(uint256 returnAmount) {
                            bool srcETH = srcToken == _ETH;
                            if (srcETH) {
                                if (msg.value != inputAmount) revert RouterErrors.InvalidMsgValue();
                            } else if (srcToken == _WETH) {
                                srcETH = true;
                                if (msg.value != 0) revert RouterErrors.InvalidMsgValue();
                                // _WETH.transferFrom(msg.sender, address(this), inputAmount);
                                // _WETH.withdraw(inputAmount);
                                address weth = address(_WETH);
                                bytes4 transferFromSelector = _WETH.transferFrom.selector;
                                bytes4 withdrawSelector = _WETH.withdraw.selector;
                                /// @solidity memory-safe-assembly
                                assembly { // solhint-disable-line no-inline-assembly
                                    let ptr := mload(0x40)
                    
                                    mstore(ptr, transferFromSelector)
                                    mstore(add(ptr, 0x04), caller())
                                    mstore(add(ptr, 0x24), address())
                                    mstore(add(ptr, 0x44), inputAmount)
                                    if iszero(call(gas(), weth, 0, ptr, 0x64, 0, 0)) {
                                        returndatacopy(ptr, 0, returndatasize())
                                        revert(ptr, returndatasize())
                                    }
                    
                                    mstore(ptr, withdrawSelector)
                                    mstore(add(ptr, 0x04), inputAmount)
                                    if iszero(call(gas(), weth, 0, ptr, 0x24, 0, 0)) {
                                        returndatacopy(ptr, 0, returndatasize())
                                        revert(ptr, returndatasize())
                                    }
                                }
                            } else {
                                if (msg.value != 0) revert RouterErrors.InvalidMsgValue();
                                srcToken.safeTransferFrom(msg.sender, address(clipperExchange), inputAmount);
                            }
                    
                            if (srcETH) {
                                // clipperExchange.sellEthForToken{value: inputAmount}(address(dstToken), inputAmount, outputAmount, goodUntil, recipient, signature, _INCH_TAG);
                                address clipper = address(clipperExchange);
                                bytes4 selector = clipperExchange.sellEthForToken.selector;
                                /// @solidity memory-safe-assembly
                                assembly { // solhint-disable-line no-inline-assembly
                                    let ptr := mload(0x40)
                    
                                    mstore(ptr, selector)
                                    mstore(add(ptr, 0x04), dstToken)
                                    mstore(add(ptr, 0x24), inputAmount)
                                    mstore(add(ptr, 0x44), outputAmount)
                                    mstore(add(ptr, 0x64), goodUntil)
                                    mstore(add(ptr, 0x84), recipient)
                                    mstore(add(ptr, 0xa4), add(27, shr(_SIGNATURE_V_SHIFT, vs)))
                                    mstore(add(ptr, 0xc4), r)
                                    mstore(add(ptr, 0xe4), and(vs, _SIGNATURE_S_MASK))
                                    mstore(add(ptr, 0x104), 0x120)
                                    mstore(add(ptr, 0x143), _INCH_TAG_WITH_LENGTH_PREFIX)
                                    if iszero(call(gas(), clipper, inputAmount, ptr, 0x149, 0, 0)) {
                                        returndatacopy(ptr, 0, returndatasize())
                                        revert(ptr, returndatasize())
                                    }
                                }
                            } else if (dstToken == _ETH || dstToken == _WETH) {
                                // clipperExchange.sellTokenForEth(address(srcToken), inputAmount, outputAmount, goodUntil, recipient, signature, _INCH_TAG);
                                address clipper = address(clipperExchange);
                                bytes4 selector = clipperExchange.sellTokenForEth.selector;
                                /// @solidity memory-safe-assembly
                                assembly { // solhint-disable-line no-inline-assembly
                                    let ptr := mload(0x40)
                    
                                    mstore(ptr, selector)
                                    mstore(add(ptr, 0x04), srcToken)
                                    mstore(add(ptr, 0x24), inputAmount)
                                    mstore(add(ptr, 0x44), outputAmount)
                                    mstore(add(ptr, 0x64), goodUntil)
                                    switch iszero(dstToken)
                                    case 1 {
                                        mstore(add(ptr, 0x84), recipient)
                                    }
                                    default {
                                        mstore(add(ptr, 0x84), address())
                                    }
                                    mstore(add(ptr, 0xa4), add(27, shr(_SIGNATURE_V_SHIFT, vs)))
                                    mstore(add(ptr, 0xc4), r)
                                    mstore(add(ptr, 0xe4), and(vs, _SIGNATURE_S_MASK))
                                    mstore(add(ptr, 0x104), 0x120)
                                    mstore(add(ptr, 0x143), _INCH_TAG_WITH_LENGTH_PREFIX)
                                    if iszero(call(gas(), clipper, 0, ptr, 0x149, 0, 0)) {
                                        returndatacopy(ptr, 0, returndatasize())
                                        revert(ptr, returndatasize())
                                    }
                                }
                    
                                if (dstToken == _WETH) {
                                    // _WETH.deposit{value: outputAmount}();
                                    // _WETH.transfer(recipient, outputAmount);
                                    address weth = address(_WETH);
                                    bytes4 depositSelector = _WETH.deposit.selector;
                                    bytes4 transferSelector = _WETH.transfer.selector;
                                    /// @solidity memory-safe-assembly
                                    assembly { // solhint-disable-line no-inline-assembly
                                        let ptr := mload(0x40)
                    
                                        mstore(ptr, depositSelector)
                                        if iszero(call(gas(), weth, outputAmount, ptr, 0x04, 0, 0)) {
                                            returndatacopy(ptr, 0, returndatasize())
                                            revert(ptr, returndatasize())
                                        }
                    
                                        mstore(ptr, transferSelector)
                                        mstore(add(ptr, 0x04), recipient)
                                        mstore(add(ptr, 0x24), outputAmount)
                                        if iszero(call(gas(), weth, 0, ptr, 0x44, 0, 0)) {
                                            returndatacopy(ptr, 0, returndatasize())
                                            revert(ptr, returndatasize())
                                        }
                                    }
                                }
                            } else {
                                // clipperExchange.swap(address(srcToken), address(dstToken), inputAmount, outputAmount, goodUntil, recipient, signature, _INCH_TAG);
                                address clipper = address(clipperExchange);
                                bytes4 selector = clipperExchange.swap.selector;
                                /// @solidity memory-safe-assembly
                                assembly { // solhint-disable-line no-inline-assembly
                                    let ptr := mload(0x40)
                    
                                    mstore(ptr, selector)
                                    mstore(add(ptr, 0x04), srcToken)
                                    mstore(add(ptr, 0x24), dstToken)
                                    mstore(add(ptr, 0x44), inputAmount)
                                    mstore(add(ptr, 0x64), outputAmount)
                                    mstore(add(ptr, 0x84), goodUntil)
                                    mstore(add(ptr, 0xa4), recipient)
                                    mstore(add(ptr, 0xc4), add(27, shr(_SIGNATURE_V_SHIFT, vs)))
                                    mstore(add(ptr, 0xe4), r)
                                    mstore(add(ptr, 0x104), and(vs, _SIGNATURE_S_MASK))
                                    mstore(add(ptr, 0x124), 0x140)
                                    mstore(add(ptr, 0x163), _INCH_TAG_WITH_LENGTH_PREFIX)
                                    if iszero(call(gas(), clipper, 0, ptr, 0x169, 0, 0)) {
                                        returndatacopy(ptr, 0, returndatasize())
                                        revert(ptr, returndatasize())
                                    }
                                }
                            }
                    
                            return outputAmount;
                        }
                    }
                    
                    
                    // File contracts/interfaces/IAggregationExecutor.sol
                    
                    
                    pragma solidity 0.8.17;
                    
                    /// @title Interface for making arbitrary calls during swap
                    interface IAggregationExecutor {
                        /// @notice propagates information about original msg.sender and executes arbitrary data
                        function execute(address msgSender) external payable;  // 0x4b64e492
                    }
                    
                    
                    // File @1inch/solidity-utils/contracts/interfaces/[email protected]
                    
                    
                    pragma solidity ^0.8.0;
                    
                    
                    interface IERC20MetadataUppercase {
                        function NAME() external view returns (string memory);  // solhint-disable-line func-name-mixedcase
                        function SYMBOL() external view returns (string memory);  // solhint-disable-line func-name-mixedcase
                    }
                    
                    
                    // File @1inch/solidity-utils/contracts/libraries/[email protected]
                    
                    
                    pragma solidity ^0.8.0;
                    
                    /// @title Library with gas-efficient string operations
                    library StringUtil {
                        function toHex(uint256 value) internal pure returns (string memory) {
                            return toHex(abi.encodePacked(value));
                        }
                    
                        function toHex(address value) internal pure returns (string memory) {
                            return toHex(abi.encodePacked(value));
                        }
                    
                        function toHex(bytes memory data) internal pure returns (string memory result) {
                            /// @solidity memory-safe-assembly
                            assembly { // solhint-disable-line no-inline-assembly
                                function _toHex16(input) -> output {
                                    output := or(
                                        and(input, 0xFFFFFFFFFFFFFFFF000000000000000000000000000000000000000000000000),
                                        shr(64, and(input, 0x0000000000000000FFFFFFFFFFFFFFFF00000000000000000000000000000000))
                                    )
                                    output := or(
                                        and(output, 0xFFFFFFFF000000000000000000000000FFFFFFFF000000000000000000000000),
                                        shr(32, and(output, 0x00000000FFFFFFFF000000000000000000000000FFFFFFFF0000000000000000))
                                    )
                                    output := or(
                                        and(output, 0xFFFF000000000000FFFF000000000000FFFF000000000000FFFF000000000000),
                                        shr(16, and(output, 0x0000FFFF000000000000FFFF000000000000FFFF000000000000FFFF00000000))
                                    )
                                    output := or(
                                        and(output, 0xFF000000FF000000FF000000FF000000FF000000FF000000FF000000FF000000),
                                        shr(8, and(output, 0x00FF000000FF000000FF000000FF000000FF000000FF000000FF000000FF0000))
                                    )
                                    output := or(
                                        shr(4, and(output, 0xF000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000)),
                                        shr(8, and(output, 0x0F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F00))
                                    )
                                    output := add(
                                        add(0x3030303030303030303030303030303030303030303030303030303030303030, output),
                                        mul(
                                            and(
                                                shr(4, add(output, 0x0606060606060606060606060606060606060606060606060606060606060606)),
                                                0x0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F
                                            ),
                                            7   // Change 7 to 39 for lower case output
                                        )
                                    )
                                }
                    
                                result := mload(0x40)
                                let length := mload(data)
                                let resultLength := shl(1, length)
                                let toPtr := add(result, 0x22)          // 32 bytes for length + 2 bytes for '0x'
                                mstore(0x40, add(toPtr, resultLength))  // move free memory pointer
                                mstore(add(result, 2), 0x3078)          // 0x3078 is right aligned so we write to `result + 2`
                                                                        // to store the last 2 bytes in the beginning of the string
                                mstore(result, add(resultLength, 2))    // extra 2 bytes for '0x'
                    
                                for {
                                    let fromPtr := add(data, 0x20)
                                    let endPtr := add(fromPtr, length)
                                } lt(fromPtr, endPtr) {
                                    fromPtr := add(fromPtr, 0x20)
                                } {
                                    let rawData := mload(fromPtr)
                                    let hexData := _toHex16(rawData)
                                    mstore(toPtr, hexData)
                                    toPtr := add(toPtr, 0x20)
                                    hexData := _toHex16(shl(128, rawData))
                                    mstore(toPtr, hexData)
                                    toPtr := add(toPtr, 0x20)
                                }
                            }
                        }
                    }
                    
                    
                    // File @openzeppelin/contracts/token/ERC20/extensions/[email protected]
                    
                    // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
                    
                    pragma solidity ^0.8.0;
                    
                    /**
                     * @dev Interface for the optional metadata functions from the ERC20 standard.
                     *
                     * _Available since v4.1._
                     */
                    interface IERC20Metadata is IERC20 {
                        /**
                         * @dev Returns the name of the token.
                         */
                        function name() external view returns (string memory);
                    
                        /**
                         * @dev Returns the symbol of the token.
                         */
                        function symbol() external view returns (string memory);
                    
                        /**
                         * @dev Returns the decimals places of the token.
                         */
                        function decimals() external view returns (uint8);
                    }
                    
                    
                    // File @1inch/solidity-utils/contracts/libraries/[email protected]
                    
                    
                    pragma solidity ^0.8.0;
                    
                    
                    
                    
                    
                    library UniERC20 {
                        using SafeERC20 for IERC20;
                    
                        error InsufficientBalance();
                        error ApproveCalledOnETH();
                        error NotEnoughValue();
                        error FromIsNotSender();
                        error ToIsNotThis();
                        error ETHTransferFailed();
                    
                        uint256 private constant _RAW_CALL_GAS_LIMIT = 5000;
                        IERC20 private constant _ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
                        IERC20 private constant _ZERO_ADDRESS = IERC20(address(0));
                    
                        function isETH(IERC20 token) internal pure returns (bool) {
                            return (token == _ZERO_ADDRESS || token == _ETH_ADDRESS);
                        }
                    
                        function uniBalanceOf(IERC20 token, address account) internal view returns (uint256) {
                            if (isETH(token)) {
                                return account.balance;
                            } else {
                                return token.balanceOf(account);
                            }
                        }
                    
                        /// @dev note that this function does nothing in case of zero amount
                        function uniTransfer(IERC20 token, address payable to, uint256 amount) internal {
                            if (amount > 0) {
                                if (isETH(token)) {
                                    if (address(this).balance < amount) revert InsufficientBalance();
                                    // solhint-disable-next-line avoid-low-level-calls
                                    (bool success, ) = to.call{value: amount, gas: _RAW_CALL_GAS_LIMIT}("");
                                    if (!success) revert ETHTransferFailed();
                                } else {
                                    token.safeTransfer(to, amount);
                                }
                            }
                        }
                    
                        /// @dev note that this function does nothing in case of zero amount
                        function uniTransferFrom(IERC20 token, address payable from, address to, uint256 amount) internal {
                            if (amount > 0) {
                                if (isETH(token)) {
                                    if (msg.value < amount) revert NotEnoughValue();
                                    if (from != msg.sender) revert FromIsNotSender();
                                    if (to != address(this)) revert ToIsNotThis();
                                    if (msg.value > amount) {
                                        // Return remainder if exist
                                        unchecked {
                                            // solhint-disable-next-line avoid-low-level-calls
                                            (bool success, ) = from.call{value: msg.value - amount, gas: _RAW_CALL_GAS_LIMIT}("");
                                            if (!success) revert ETHTransferFailed();
                                        }
                                    }
                                } else {
                                    token.safeTransferFrom(from, to, amount);
                                }
                            }
                        }
                    
                        function uniSymbol(IERC20 token) internal view returns(string memory) {
                            return _uniDecode(token, IERC20Metadata.symbol.selector, IERC20MetadataUppercase.SYMBOL.selector);
                        }
                    
                        function uniName(IERC20 token) internal view returns(string memory) {
                            return _uniDecode(token, IERC20Metadata.name.selector, IERC20MetadataUppercase.NAME.selector);
                        }
                    
                        function uniApprove(IERC20 token, address to, uint256 amount) internal {
                            if (isETH(token)) revert ApproveCalledOnETH();
                    
                            token.forceApprove(to, amount);
                        }
                    
                        /// 20K gas is provided to account for possible implementations of name/symbol
                        /// (token implementation might be behind proxy or store the value in storage)
                        function _uniDecode(IERC20 token, bytes4 lowerCaseSelector, bytes4 upperCaseSelector) private view returns(string memory result) {
                            if (isETH(token)) {
                                return "ETH";
                            }
                    
                            (bool success, bytes memory data) = address(token).staticcall{ gas: 20000 }(
                                abi.encodeWithSelector(lowerCaseSelector)
                            );
                            if (!success) {
                                (success, data) = address(token).staticcall{ gas: 20000 }(
                                    abi.encodeWithSelector(upperCaseSelector)
                                );
                            }
                    
                            if (success && data.length >= 0x40) {
                                (uint256 offset, uint256 len) = abi.decode(data, (uint256, uint256));
                                if (offset == 0x20 && len > 0 && data.length == 0x40 + len) {
                                    /// @solidity memory-safe-assembly
                                    assembly { // solhint-disable-line no-inline-assembly
                                        result := add(data, 0x20)
                                    }
                                    return result;
                                }
                            }
                    
                            if (success && data.length == 32) {
                                uint256 len = 0;
                                while (len < data.length && data[len] >= 0x20 && data[len] <= 0x7E) {
                                    unchecked {
                                        len++;
                                    }
                                }
                    
                                if (len > 0) {
                                    /// @solidity memory-safe-assembly
                                    assembly { // solhint-disable-line no-inline-assembly
                                        mstore(data, len)
                                    }
                                    return string(data);
                                }
                            }
                    
                            return StringUtil.toHex(address(token));
                        }
                    }
                    
                    
                    // File contracts/routers/GenericRouter.sol
                    
                    
                    pragma solidity 0.8.17;
                    
                    
                    
                    
                    
                    contract GenericRouter is EthReceiver {
                        using UniERC20 for IERC20;
                        using SafeERC20 for IERC20;
                    
                        error ZeroMinReturn();
                        error ZeroReturnAmount();
                    
                        uint256 private constant _PARTIAL_FILL = 1 << 0;
                        uint256 private constant _REQUIRES_EXTRA_ETH = 1 << 1;
                    
                        struct SwapDescription {
                            IERC20 srcToken;
                            IERC20 dstToken;
                            address payable srcReceiver;
                            address payable dstReceiver;
                            uint256 amount;
                            uint256 minReturnAmount;
                            uint256 flags;
                        }
                    
                        /// @notice Performs a swap, delegating all calls encoded in `data` to `executor`. See tests for usage examples
                        /// @dev router keeps 1 wei of every token on the contract balance for gas optimisations reasons. This affects first swap of every token by leaving 1 wei on the contract.
                        /// @param executor Aggregation executor that executes calls described in `data`
                        /// @param desc Swap description
                        /// @param permit Should contain valid permit that can be used in `IERC20Permit.permit` calls.
                        /// @param data Encoded calls that `caller` should execute in between of swaps
                        /// @return returnAmount Resulting token amount
                        /// @return spentAmount Source token amount
                        function swap(
                            IAggregationExecutor executor,
                            SwapDescription calldata desc,
                            bytes calldata permit,
                            bytes calldata data
                        )
                            external
                            payable
                            returns (
                                uint256 returnAmount,
                                uint256 spentAmount
                            )
                        {
                            if (desc.minReturnAmount == 0) revert ZeroMinReturn();
                    
                            IERC20 srcToken = desc.srcToken;
                            IERC20 dstToken = desc.dstToken;
                    
                            bool srcETH = srcToken.isETH();
                            if (desc.flags & _REQUIRES_EXTRA_ETH != 0) {
                                if (msg.value <= (srcETH ? desc.amount : 0)) revert RouterErrors.InvalidMsgValue();
                            } else {
                                if (msg.value != (srcETH ? desc.amount : 0)) revert RouterErrors.InvalidMsgValue();
                            }
                    
                            if (!srcETH) {
                                if (permit.length > 0) {
                                    srcToken.safePermit(permit);
                                }
                                srcToken.safeTransferFrom(msg.sender, desc.srcReceiver, desc.amount);
                            }
                    
                            _execute(executor, msg.sender, desc.amount, data);
                    
                            spentAmount = desc.amount;
                            // we leave 1 wei on the router for gas optimisations reasons
                            returnAmount = dstToken.uniBalanceOf(address(this));
                            if (returnAmount == 0) revert ZeroReturnAmount();
                            unchecked { returnAmount--; }
                    
                            if (desc.flags & _PARTIAL_FILL != 0) {
                                uint256 unspentAmount = srcToken.uniBalanceOf(address(this));
                                if (unspentAmount > 1) {
                                    // we leave 1 wei on the router for gas optimisations reasons
                                    unchecked { unspentAmount--; }
                                    spentAmount -= unspentAmount;
                                    srcToken.uniTransfer(payable(msg.sender), unspentAmount);
                                }
                                if (returnAmount * desc.amount < desc.minReturnAmount * spentAmount) revert RouterErrors.ReturnAmountIsNotEnough();
                            } else {
                                if (returnAmount < desc.minReturnAmount) revert RouterErrors.ReturnAmountIsNotEnough();
                            }
                    
                            address payable dstReceiver = (desc.dstReceiver == address(0)) ? payable(msg.sender) : desc.dstReceiver;
                            dstToken.uniTransfer(dstReceiver, returnAmount);
                        }
                    
                        function _execute(
                            IAggregationExecutor executor,
                            address srcTokenOwner,
                            uint256 inputAmount,
                            bytes calldata data
                        ) private {
                            bytes4 executeSelector = executor.execute.selector;
                            /// @solidity memory-safe-assembly
                            assembly {  // solhint-disable-line no-inline-assembly
                                let ptr := mload(0x40)
                    
                                mstore(ptr, executeSelector)
                                mstore(add(ptr, 0x04), srcTokenOwner)
                                calldatacopy(add(ptr, 0x24), data.offset, data.length)
                                mstore(add(add(ptr, 0x24), data.length), inputAmount)
                    
                                if iszero(call(gas(), executor, callvalue(), ptr, add(0x44, data.length), 0, 0)) {
                                    returndatacopy(ptr, 0, returndatasize())
                                    revert(ptr, returndatasize())
                                }
                            }
                        }
                    }
                    
                    
                    // File contracts/routers/UnoswapRouter.sol
                    
                    
                    pragma solidity 0.8.17;
                    
                    
                    
                    
                    contract UnoswapRouter is EthReceiver {
                        using SafeERC20 for IERC20;
                    
                        error ReservesCallFailed();
                        error SwapAmountTooLarge();
                    
                        bytes4 private constant _TRANSFER_FROM_CALL_SELECTOR = 0x23b872dd;
                        bytes4 private constant _WETH_DEPOSIT_CALL_SELECTOR = 0xd0e30db0;
                        bytes4 private constant _WETH_WITHDRAW_CALL_SELECTOR = 0x2e1a7d4d;
                        bytes4 private constant _ERC20_TRANSFER_CALL_SELECTOR = 0xa9059cbb;
                        uint256 private constant _ADDRESS_MASK =   0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff;
                        uint256 private constant _REVERSE_MASK =   0x8000000000000000000000000000000000000000000000000000000000000000;
                        uint256 private constant _WETH_MASK =      0x4000000000000000000000000000000000000000000000000000000000000000;
                        uint256 private constant _NUMERATOR_MASK = 0x0000000000000000ffffffff0000000000000000000000000000000000000000;
                        /// @dev WETH address is network-specific and needs to be changed before deployment.
                        /// It can not be moved to immutable as immutables are not supported in assembly
                        address private constant _WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
                        bytes4 private constant _UNISWAP_PAIR_RESERVES_CALL_SELECTOR = 0x0902f1ac;
                        bytes4 private constant _UNISWAP_PAIR_SWAP_CALL_SELECTOR = 0x022c0d9f;
                        uint256 private constant _DENOMINATOR = 1e9;
                        uint256 private constant _NUMERATOR_OFFSET = 160;
                        uint256 private constant _MAX_SWAP_AMOUNT = (1 << 112) - 1;  // type(uint112).max;
                    
                        /// @notice Same as `unoswapTo` but calls permit first,
                        /// allowing to approve token spending and make a swap in one transaction.
                        /// @param recipient Address that will receive swapped funds
                        /// @param srcToken Source token
                        /// @param amount Amount of source tokens to swap
                        /// @param minReturn Minimal allowed returnAmount to make transaction commit
                        /// @param pools Pools chain used for swaps. Pools src and dst tokens should match to make swap happen
                        /// @param permit Should contain valid permit that can be used in `IERC20Permit.permit` calls.
                        /// See tests for examples
                        function unoswapToWithPermit(
                            address payable recipient,
                            IERC20 srcToken,
                            uint256 amount,
                            uint256 minReturn,
                            uint256[] calldata pools,
                            bytes calldata permit
                        ) external returns(uint256 returnAmount) {
                            srcToken.safePermit(permit);
                            return _unoswap(recipient, srcToken, amount, minReturn, pools);
                        }
                    
                        /// @notice Performs swap using Uniswap exchange. Wraps and unwraps ETH if required.
                        /// Sending non-zero `msg.value` for anything but ETH swaps is prohibited
                        /// @param recipient Address that will receive swapped funds
                        /// @param srcToken Source token
                        /// @param amount Amount of source tokens to swap
                        /// @param minReturn Minimal allowed returnAmount to make transaction commit
                        /// @param pools Pools chain used for swaps. Pools src and dst tokens should match to make swap happen
                        function unoswapTo(
                            address payable recipient,
                            IERC20 srcToken,
                            uint256 amount,
                            uint256 minReturn,
                            uint256[] calldata pools
                        ) external payable returns(uint256 returnAmount) {
                            return _unoswap(recipient, srcToken, amount, minReturn, pools);
                        }
                    
                        /// @notice Performs swap using Uniswap exchange. Wraps and unwraps ETH if required.
                        /// Sending non-zero `msg.value` for anything but ETH swaps is prohibited
                        /// @param srcToken Source token
                        /// @param amount Amount of source tokens to swap
                        /// @param minReturn Minimal allowed returnAmount to make transaction commit
                        /// @param pools Pools chain used for swaps. Pools src and dst tokens should match to make swap happen
                        function unoswap(
                            IERC20 srcToken,
                            uint256 amount,
                            uint256 minReturn,
                            uint256[] calldata pools
                        ) external payable returns(uint256 returnAmount) {
                            return _unoswap(payable(msg.sender), srcToken, amount, minReturn, pools);
                        }
                    
                        function _unoswap(
                            address payable recipient,
                            IERC20 srcToken,
                            uint256 amount,
                            uint256 minReturn,
                            uint256[] calldata pools
                        ) private returns(uint256 returnAmount) {
                            assembly {  // solhint-disable-line no-inline-assembly
                                function reRevert() {
                                    returndatacopy(0, 0, returndatasize())
                                    revert(0, returndatasize())
                                }
                    
                                function validateERC20Transfer(status) {
                                    if iszero(status) {
                                        reRevert()
                                    }
                                    let success := or(
                                        iszero(returndatasize()),                       // empty return data
                                        and(gt(returndatasize(), 31), eq(mload(0), 1))  // true in return data
                                    )
                                    if iszero(success) {
                                        mstore(0, 0xf27f64e400000000000000000000000000000000000000000000000000000000)  // ERC20TransferFailed()
                                        revert(0, 4)
                                    }
                                }
                    
                                function swap(emptyPtr, swapAmount, pair, reversed, numerator, to) -> ret {
                                    mstore(emptyPtr, _UNISWAP_PAIR_RESERVES_CALL_SELECTOR)
                                    if iszero(staticcall(gas(), pair, emptyPtr, 0x4, emptyPtr, 0x40)) {
                                        reRevert()
                                    }
                                    if iszero(eq(returndatasize(), 0x60)) {
                                        mstore(0, 0x85cd58dc00000000000000000000000000000000000000000000000000000000)  // ReservesCallFailed()
                                        revert(0, 4)
                                    }
                    
                                    let reserve0 := mload(emptyPtr)
                                    let reserve1 := mload(add(emptyPtr, 0x20))
                                    if reversed {
                                        let tmp := reserve0
                                        reserve0 := reserve1
                                        reserve1 := tmp
                                    }
                                    // this will not overflow as reserve0, reserve1 and ret fit to 112 bit and numerator and _DENOMINATOR fit to 32 bit
                                    ret := mul(swapAmount, numerator)
                                    ret := div(mul(ret, reserve1), add(ret, mul(reserve0, _DENOMINATOR)))
                    
                                    mstore(emptyPtr, _UNISWAP_PAIR_SWAP_CALL_SELECTOR)
                                    reversed := iszero(reversed)
                                    mstore(add(emptyPtr, 0x04), mul(ret, iszero(reversed)))
                                    mstore(add(emptyPtr, 0x24), mul(ret, reversed))
                                    mstore(add(emptyPtr, 0x44), to)
                                    mstore(add(emptyPtr, 0x64), 0x80)
                                    mstore(add(emptyPtr, 0x84), 0)
                                    if iszero(call(gas(), pair, 0, emptyPtr, 0xa4, 0, 0)) {
                                        reRevert()
                                    }
                                }
                    
                                // make sure that input amount fits in 112 bit
                                if gt(amount, _MAX_SWAP_AMOUNT) {
                                    mstore(0, 0xcf0b4d3a00000000000000000000000000000000000000000000000000000000)  // SwapAmountTooLarge()
                                    revert(0, 4)
                                }
                    
                                let emptyPtr := mload(0x40)
                                mstore(0x40, add(emptyPtr, 0xc0))
                    
                                let poolsEndOffset := add(pools.offset, shl(5, pools.length))
                                let rawPair := calldataload(pools.offset)
                                switch srcToken
                                case 0 {
                                    if iszero(eq(amount, callvalue())) {
                                        mstore(0, 0x1841b4e100000000000000000000000000000000000000000000000000000000)  // InvalidMsgValue()
                                        revert(0, 4)
                                    }
                    
                                    mstore(emptyPtr, _WETH_DEPOSIT_CALL_SELECTOR)
                                    if iszero(call(gas(), _WETH, amount, emptyPtr, 0x4, 0, 0)) {
                                        reRevert()
                                    }
                    
                                    mstore(emptyPtr, _ERC20_TRANSFER_CALL_SELECTOR)
                                    mstore(add(emptyPtr, 0x4), and(rawPair, _ADDRESS_MASK))
                                    mstore(add(emptyPtr, 0x24), amount)
                                    if iszero(call(gas(), _WETH, 0, emptyPtr, 0x44, 0, 0)) {
                                        reRevert()
                                    }
                                }
                                default {
                                    if callvalue() {
                                        mstore(0, 0x1841b4e100000000000000000000000000000000000000000000000000000000)  // InvalidMsgValue()
                                        revert(0, 4)
                                    }
                    
                                    mstore(emptyPtr, _TRANSFER_FROM_CALL_SELECTOR)
                                    mstore(add(emptyPtr, 0x4), caller())
                                    mstore(add(emptyPtr, 0x24), and(rawPair, _ADDRESS_MASK))
                                    mstore(add(emptyPtr, 0x44), amount)
                                    validateERC20Transfer(
                                        call(gas(), srcToken, 0, emptyPtr, 0x64, 0, 0x20)
                                    )
                                }
                    
                                returnAmount := amount
                    
                                for {let i := add(pools.offset, 0x20)} lt(i, poolsEndOffset) {i := add(i, 0x20)} {
                                    let nextRawPair := calldataload(i)
                    
                                    returnAmount := swap(
                                        emptyPtr,
                                        returnAmount,
                                        and(rawPair, _ADDRESS_MASK),
                                        and(rawPair, _REVERSE_MASK),
                                        shr(_NUMERATOR_OFFSET, and(rawPair, _NUMERATOR_MASK)),
                                        and(nextRawPair, _ADDRESS_MASK)
                                    )
                    
                                    rawPair := nextRawPair
                                }
                    
                                switch and(rawPair, _WETH_MASK)
                                case 0 {
                                    returnAmount := swap(
                                        emptyPtr,
                                        returnAmount,
                                        and(rawPair, _ADDRESS_MASK),
                                        and(rawPair, _REVERSE_MASK),
                                        shr(_NUMERATOR_OFFSET, and(rawPair, _NUMERATOR_MASK)),
                                        recipient
                                    )
                                }
                                default {
                                    returnAmount := swap(
                                        emptyPtr,
                                        returnAmount,
                                        and(rawPair, _ADDRESS_MASK),
                                        and(rawPair, _REVERSE_MASK),
                                        shr(_NUMERATOR_OFFSET, and(rawPair, _NUMERATOR_MASK)),
                                        address()
                                    )
                    
                                    mstore(emptyPtr, _WETH_WITHDRAW_CALL_SELECTOR)
                                    mstore(add(emptyPtr, 0x04), returnAmount)
                                    if iszero(call(gas(), _WETH, 0, emptyPtr, 0x24, 0, 0)) {
                                        reRevert()
                                    }
                    
                                    if iszero(call(gas(), recipient, returnAmount, 0, 0, 0, 0)) {
                                        reRevert()
                                    }
                                }
                            }
                            if (returnAmount < minReturn) revert RouterErrors.ReturnAmountIsNotEnough();
                        }
                    }
                    
                    
                    // File contracts/interfaces/IUniswapV3Pool.sol
                    
                    pragma solidity 0.8.17;
                    
                    interface IUniswapV3Pool {
                        /// @notice Swap token0 for token1, or token1 for token0
                        /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
                        /// @param recipient The address to receive the output of the swap
                        /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
                        /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
                        /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
                        /// value after the swap. If one for zero, the price cannot be greater than this value after the swap
                        /// @param data Any data to be passed through to the callback
                        /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
                        /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
                        function swap(
                            address recipient,
                            bool zeroForOne,
                            int256 amountSpecified,
                            uint160 sqrtPriceLimitX96,
                            bytes calldata data
                        ) external returns (int256 amount0, int256 amount1);
                    
                        /// @notice The first of the two tokens of the pool, sorted by address
                        /// @return The token contract address
                        function token0() external view returns (address);
                    
                        /// @notice The second of the two tokens of the pool, sorted by address
                        /// @return The token contract address
                        function token1() external view returns (address);
                    
                        /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
                        /// @return The fee
                        function fee() external view returns (uint24);
                    }
                    
                    
                    // File contracts/interfaces/IUniswapV3SwapCallback.sol
                    
                    pragma solidity 0.8.17;
                    
                    /// @title Callback for IUniswapV3PoolActions#swap
                    /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
                    interface IUniswapV3SwapCallback {
                        /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
                        /// @dev In the implementation you must pay the pool tokens owed for the swap.
                        /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
                        /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
                        /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
                        /// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
                        /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
                        /// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
                        /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
                        function uniswapV3SwapCallback(
                            int256 amount0Delta,
                            int256 amount1Delta,
                            bytes calldata data
                        ) external;
                    }
                    
                    
                    // File @openzeppelin/contracts/utils/[email protected]
                    
                    // OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)
                    
                    pragma solidity ^0.8.1;
                    
                    /**
                     * @dev Collection of functions related to the address type
                     */
                    library Address {
                        /**
                         * @dev Returns true if `account` is a contract.
                         *
                         * [IMPORTANT]
                         * ====
                         * It is unsafe to assume that an address for which this function returns
                         * false is an externally-owned account (EOA) and not a contract.
                         *
                         * Among others, `isContract` will return false for the following
                         * types of addresses:
                         *
                         *  - an externally-owned account
                         *  - a contract in construction
                         *  - an address where a contract will be created
                         *  - an address where a contract lived, but was destroyed
                         * ====
                         *
                         * [IMPORTANT]
                         * ====
                         * You shouldn't rely on `isContract` to protect against flash loan attacks!
                         *
                         * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
                         * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
                         * constructor.
                         * ====
                         */
                        function isContract(address account) internal view returns (bool) {
                            // This method relies on extcodesize/address.code.length, which returns 0
                            // for contracts in construction, since the code is only stored at the end
                            // of the constructor execution.
                    
                            return account.code.length > 0;
                        }
                    
                        /**
                         * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
                         * `recipient`, forwarding all available gas and reverting on errors.
                         *
                         * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
                         * of certain opcodes, possibly making contracts go over the 2300 gas limit
                         * imposed by `transfer`, making them unable to receive funds via
                         * `transfer`. {sendValue} removes this limitation.
                         *
                         * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
                         *
                         * IMPORTANT: because control is transferred to `recipient`, care must be
                         * taken to not create reentrancy vulnerabilities. Consider using
                         * {ReentrancyGuard} or the
                         * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                         */
                        function sendValue(address payable recipient, uint256 amount) internal {
                            require(address(this).balance >= amount, "Address: insufficient balance");
                    
                            (bool success, ) = recipient.call{value: amount}("");
                            require(success, "Address: unable to send value, recipient may have reverted");
                        }
                    
                        /**
                         * @dev Performs a Solidity function call using a low level `call`. A
                         * plain `call` is an unsafe replacement for a function call: use this
                         * function instead.
                         *
                         * If `target` reverts with a revert reason, it is bubbled up by this
                         * function (like regular Solidity function calls).
                         *
                         * Returns the raw returned data. To convert to the expected return value,
                         * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
                         *
                         * Requirements:
                         *
                         * - `target` must be a contract.
                         * - calling `target` with `data` must not revert.
                         *
                         * _Available since v3.1._
                         */
                        function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                            return functionCall(target, data, "Address: low-level call failed");
                        }
                    
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
                         * `errorMessage` as a fallback revert reason when `target` reverts.
                         *
                         * _Available since v3.1._
                         */
                        function functionCall(
                            address target,
                            bytes memory data,
                            string memory errorMessage
                        ) internal returns (bytes memory) {
                            return functionCallWithValue(target, data, 0, errorMessage);
                        }
                    
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                         * but also transferring `value` wei to `target`.
                         *
                         * Requirements:
                         *
                         * - the calling contract must have an ETH balance of at least `value`.
                         * - the called Solidity function must be `payable`.
                         *
                         * _Available since v3.1._
                         */
                        function functionCallWithValue(
                            address target,
                            bytes memory data,
                            uint256 value
                        ) internal returns (bytes memory) {
                            return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
                        }
                    
                        /**
                         * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
                         * with `errorMessage` as a fallback revert reason when `target` reverts.
                         *
                         * _Available since v3.1._
                         */
                        function functionCallWithValue(
                            address target,
                            bytes memory data,
                            uint256 value,
                            string memory errorMessage
                        ) internal returns (bytes memory) {
                            require(address(this).balance >= value, "Address: insufficient balance for call");
                            require(isContract(target), "Address: call to non-contract");
                    
                            (bool success, bytes memory returndata) = target.call{value: value}(data);
                            return verifyCallResult(success, returndata, errorMessage);
                        }
                    
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                         * but performing a static call.
                         *
                         * _Available since v3.3._
                         */
                        function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                            return functionStaticCall(target, data, "Address: low-level static call failed");
                        }
                    
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                         * but performing a static call.
                         *
                         * _Available since v3.3._
                         */
                        function functionStaticCall(
                            address target,
                            bytes memory data,
                            string memory errorMessage
                        ) internal view returns (bytes memory) {
                            require(isContract(target), "Address: static call to non-contract");
                    
                            (bool success, bytes memory returndata) = target.staticcall(data);
                            return verifyCallResult(success, returndata, errorMessage);
                        }
                    
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                         * but performing a delegate call.
                         *
                         * _Available since v3.4._
                         */
                        function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                            return functionDelegateCall(target, data, "Address: low-level delegate call failed");
                        }
                    
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                         * but performing a delegate call.
                         *
                         * _Available since v3.4._
                         */
                        function functionDelegateCall(
                            address target,
                            bytes memory data,
                            string memory errorMessage
                        ) internal returns (bytes memory) {
                            require(isContract(target), "Address: delegate call to non-contract");
                    
                            (bool success, bytes memory returndata) = target.delegatecall(data);
                            return verifyCallResult(success, returndata, errorMessage);
                        }
                    
                        /**
                         * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
                         * revert reason using the provided one.
                         *
                         * _Available since v4.3._
                         */
                        function verifyCallResult(
                            bool success,
                            bytes memory returndata,
                            string memory errorMessage
                        ) internal pure returns (bytes memory) {
                            if (success) {
                                return returndata;
                            } else {
                                // Look for revert reason and bubble it up if present
                                if (returndata.length > 0) {
                                    // The easiest way to bubble the revert reason is using memory via assembly
                                    /// @solidity memory-safe-assembly
                                    assembly {
                                        let returndata_size := mload(returndata)
                                        revert(add(32, returndata), returndata_size)
                                    }
                                } else {
                                    revert(errorMessage);
                                }
                            }
                        }
                    }
                    
                    
                    // File @openzeppelin/contracts/utils/math/[email protected]
                    
                    // OpenZeppelin Contracts (last updated v4.7.0) (utils/math/SafeCast.sol)
                    
                    pragma solidity ^0.8.0;
                    
                    /**
                     * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
                     * checks.
                     *
                     * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
                     * easily result in undesired exploitation or bugs, since developers usually
                     * assume that overflows raise errors. `SafeCast` restores this intuition by
                     * reverting the transaction when such an operation overflows.
                     *
                     * Using this library instead of the unchecked operations eliminates an entire
                     * class of bugs, so it's recommended to use it always.
                     *
                     * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
                     * all math on `uint256` and `int256` and then downcasting.
                     */
                    library SafeCast {
                        /**
                         * @dev Returns the downcasted uint248 from uint256, reverting on
                         * overflow (when the input is greater than largest uint248).
                         *
                         * Counterpart to Solidity's `uint248` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 248 bits
                         *
                         * _Available since v4.7._
                         */
                        function toUint248(uint256 value) internal pure returns (uint248) {
                            require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits");
                            return uint248(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted uint240 from uint256, reverting on
                         * overflow (when the input is greater than largest uint240).
                         *
                         * Counterpart to Solidity's `uint240` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 240 bits
                         *
                         * _Available since v4.7._
                         */
                        function toUint240(uint256 value) internal pure returns (uint240) {
                            require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits");
                            return uint240(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted uint232 from uint256, reverting on
                         * overflow (when the input is greater than largest uint232).
                         *
                         * Counterpart to Solidity's `uint232` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 232 bits
                         *
                         * _Available since v4.7._
                         */
                        function toUint232(uint256 value) internal pure returns (uint232) {
                            require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits");
                            return uint232(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted uint224 from uint256, reverting on
                         * overflow (when the input is greater than largest uint224).
                         *
                         * Counterpart to Solidity's `uint224` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 224 bits
                         *
                         * _Available since v4.2._
                         */
                        function toUint224(uint256 value) internal pure returns (uint224) {
                            require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
                            return uint224(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted uint216 from uint256, reverting on
                         * overflow (when the input is greater than largest uint216).
                         *
                         * Counterpart to Solidity's `uint216` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 216 bits
                         *
                         * _Available since v4.7._
                         */
                        function toUint216(uint256 value) internal pure returns (uint216) {
                            require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits");
                            return uint216(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted uint208 from uint256, reverting on
                         * overflow (when the input is greater than largest uint208).
                         *
                         * Counterpart to Solidity's `uint208` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 208 bits
                         *
                         * _Available since v4.7._
                         */
                        function toUint208(uint256 value) internal pure returns (uint208) {
                            require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits");
                            return uint208(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted uint200 from uint256, reverting on
                         * overflow (when the input is greater than largest uint200).
                         *
                         * Counterpart to Solidity's `uint200` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 200 bits
                         *
                         * _Available since v4.7._
                         */
                        function toUint200(uint256 value) internal pure returns (uint200) {
                            require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits");
                            return uint200(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted uint192 from uint256, reverting on
                         * overflow (when the input is greater than largest uint192).
                         *
                         * Counterpart to Solidity's `uint192` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 192 bits
                         *
                         * _Available since v4.7._
                         */
                        function toUint192(uint256 value) internal pure returns (uint192) {
                            require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits");
                            return uint192(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted uint184 from uint256, reverting on
                         * overflow (when the input is greater than largest uint184).
                         *
                         * Counterpart to Solidity's `uint184` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 184 bits
                         *
                         * _Available since v4.7._
                         */
                        function toUint184(uint256 value) internal pure returns (uint184) {
                            require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits");
                            return uint184(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted uint176 from uint256, reverting on
                         * overflow (when the input is greater than largest uint176).
                         *
                         * Counterpart to Solidity's `uint176` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 176 bits
                         *
                         * _Available since v4.7._
                         */
                        function toUint176(uint256 value) internal pure returns (uint176) {
                            require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits");
                            return uint176(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted uint168 from uint256, reverting on
                         * overflow (when the input is greater than largest uint168).
                         *
                         * Counterpart to Solidity's `uint168` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 168 bits
                         *
                         * _Available since v4.7._
                         */
                        function toUint168(uint256 value) internal pure returns (uint168) {
                            require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits");
                            return uint168(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted uint160 from uint256, reverting on
                         * overflow (when the input is greater than largest uint160).
                         *
                         * Counterpart to Solidity's `uint160` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 160 bits
                         *
                         * _Available since v4.7._
                         */
                        function toUint160(uint256 value) internal pure returns (uint160) {
                            require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits");
                            return uint160(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted uint152 from uint256, reverting on
                         * overflow (when the input is greater than largest uint152).
                         *
                         * Counterpart to Solidity's `uint152` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 152 bits
                         *
                         * _Available since v4.7._
                         */
                        function toUint152(uint256 value) internal pure returns (uint152) {
                            require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits");
                            return uint152(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted uint144 from uint256, reverting on
                         * overflow (when the input is greater than largest uint144).
                         *
                         * Counterpart to Solidity's `uint144` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 144 bits
                         *
                         * _Available since v4.7._
                         */
                        function toUint144(uint256 value) internal pure returns (uint144) {
                            require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits");
                            return uint144(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted uint136 from uint256, reverting on
                         * overflow (when the input is greater than largest uint136).
                         *
                         * Counterpart to Solidity's `uint136` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 136 bits
                         *
                         * _Available since v4.7._
                         */
                        function toUint136(uint256 value) internal pure returns (uint136) {
                            require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits");
                            return uint136(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted uint128 from uint256, reverting on
                         * overflow (when the input is greater than largest uint128).
                         *
                         * Counterpart to Solidity's `uint128` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 128 bits
                         *
                         * _Available since v2.5._
                         */
                        function toUint128(uint256 value) internal pure returns (uint128) {
                            require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
                            return uint128(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted uint120 from uint256, reverting on
                         * overflow (when the input is greater than largest uint120).
                         *
                         * Counterpart to Solidity's `uint120` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 120 bits
                         *
                         * _Available since v4.7._
                         */
                        function toUint120(uint256 value) internal pure returns (uint120) {
                            require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits");
                            return uint120(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted uint112 from uint256, reverting on
                         * overflow (when the input is greater than largest uint112).
                         *
                         * Counterpart to Solidity's `uint112` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 112 bits
                         *
                         * _Available since v4.7._
                         */
                        function toUint112(uint256 value) internal pure returns (uint112) {
                            require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits");
                            return uint112(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted uint104 from uint256, reverting on
                         * overflow (when the input is greater than largest uint104).
                         *
                         * Counterpart to Solidity's `uint104` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 104 bits
                         *
                         * _Available since v4.7._
                         */
                        function toUint104(uint256 value) internal pure returns (uint104) {
                            require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits");
                            return uint104(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted uint96 from uint256, reverting on
                         * overflow (when the input is greater than largest uint96).
                         *
                         * Counterpart to Solidity's `uint96` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 96 bits
                         *
                         * _Available since v4.2._
                         */
                        function toUint96(uint256 value) internal pure returns (uint96) {
                            require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
                            return uint96(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted uint88 from uint256, reverting on
                         * overflow (when the input is greater than largest uint88).
                         *
                         * Counterpart to Solidity's `uint88` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 88 bits
                         *
                         * _Available since v4.7._
                         */
                        function toUint88(uint256 value) internal pure returns (uint88) {
                            require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits");
                            return uint88(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted uint80 from uint256, reverting on
                         * overflow (when the input is greater than largest uint80).
                         *
                         * Counterpart to Solidity's `uint80` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 80 bits
                         *
                         * _Available since v4.7._
                         */
                        function toUint80(uint256 value) internal pure returns (uint80) {
                            require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits");
                            return uint80(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted uint72 from uint256, reverting on
                         * overflow (when the input is greater than largest uint72).
                         *
                         * Counterpart to Solidity's `uint72` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 72 bits
                         *
                         * _Available since v4.7._
                         */
                        function toUint72(uint256 value) internal pure returns (uint72) {
                            require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits");
                            return uint72(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted uint64 from uint256, reverting on
                         * overflow (when the input is greater than largest uint64).
                         *
                         * Counterpart to Solidity's `uint64` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 64 bits
                         *
                         * _Available since v2.5._
                         */
                        function toUint64(uint256 value) internal pure returns (uint64) {
                            require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
                            return uint64(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted uint56 from uint256, reverting on
                         * overflow (when the input is greater than largest uint56).
                         *
                         * Counterpart to Solidity's `uint56` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 56 bits
                         *
                         * _Available since v4.7._
                         */
                        function toUint56(uint256 value) internal pure returns (uint56) {
                            require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits");
                            return uint56(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted uint48 from uint256, reverting on
                         * overflow (when the input is greater than largest uint48).
                         *
                         * Counterpart to Solidity's `uint48` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 48 bits
                         *
                         * _Available since v4.7._
                         */
                        function toUint48(uint256 value) internal pure returns (uint48) {
                            require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits");
                            return uint48(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted uint40 from uint256, reverting on
                         * overflow (when the input is greater than largest uint40).
                         *
                         * Counterpart to Solidity's `uint40` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 40 bits
                         *
                         * _Available since v4.7._
                         */
                        function toUint40(uint256 value) internal pure returns (uint40) {
                            require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits");
                            return uint40(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted uint32 from uint256, reverting on
                         * overflow (when the input is greater than largest uint32).
                         *
                         * Counterpart to Solidity's `uint32` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 32 bits
                         *
                         * _Available since v2.5._
                         */
                        function toUint32(uint256 value) internal pure returns (uint32) {
                            require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
                            return uint32(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted uint24 from uint256, reverting on
                         * overflow (when the input is greater than largest uint24).
                         *
                         * Counterpart to Solidity's `uint24` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 24 bits
                         *
                         * _Available since v4.7._
                         */
                        function toUint24(uint256 value) internal pure returns (uint24) {
                            require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits");
                            return uint24(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted uint16 from uint256, reverting on
                         * overflow (when the input is greater than largest uint16).
                         *
                         * Counterpart to Solidity's `uint16` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 16 bits
                         *
                         * _Available since v2.5._
                         */
                        function toUint16(uint256 value) internal pure returns (uint16) {
                            require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
                            return uint16(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted uint8 from uint256, reverting on
                         * overflow (when the input is greater than largest uint8).
                         *
                         * Counterpart to Solidity's `uint8` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 8 bits
                         *
                         * _Available since v2.5._
                         */
                        function toUint8(uint256 value) internal pure returns (uint8) {
                            require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
                            return uint8(value);
                        }
                    
                        /**
                         * @dev Converts a signed int256 into an unsigned uint256.
                         *
                         * Requirements:
                         *
                         * - input must be greater than or equal to 0.
                         *
                         * _Available since v3.0._
                         */
                        function toUint256(int256 value) internal pure returns (uint256) {
                            require(value >= 0, "SafeCast: value must be positive");
                            return uint256(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted int248 from int256, reverting on
                         * overflow (when the input is less than smallest int248 or
                         * greater than largest int248).
                         *
                         * Counterpart to Solidity's `int248` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 248 bits
                         *
                         * _Available since v4.7._
                         */
                        function toInt248(int256 value) internal pure returns (int248) {
                            require(value >= type(int248).min && value <= type(int248).max, "SafeCast: value doesn't fit in 248 bits");
                            return int248(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted int240 from int256, reverting on
                         * overflow (when the input is less than smallest int240 or
                         * greater than largest int240).
                         *
                         * Counterpart to Solidity's `int240` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 240 bits
                         *
                         * _Available since v4.7._
                         */
                        function toInt240(int256 value) internal pure returns (int240) {
                            require(value >= type(int240).min && value <= type(int240).max, "SafeCast: value doesn't fit in 240 bits");
                            return int240(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted int232 from int256, reverting on
                         * overflow (when the input is less than smallest int232 or
                         * greater than largest int232).
                         *
                         * Counterpart to Solidity's `int232` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 232 bits
                         *
                         * _Available since v4.7._
                         */
                        function toInt232(int256 value) internal pure returns (int232) {
                            require(value >= type(int232).min && value <= type(int232).max, "SafeCast: value doesn't fit in 232 bits");
                            return int232(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted int224 from int256, reverting on
                         * overflow (when the input is less than smallest int224 or
                         * greater than largest int224).
                         *
                         * Counterpart to Solidity's `int224` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 224 bits
                         *
                         * _Available since v4.7._
                         */
                        function toInt224(int256 value) internal pure returns (int224) {
                            require(value >= type(int224).min && value <= type(int224).max, "SafeCast: value doesn't fit in 224 bits");
                            return int224(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted int216 from int256, reverting on
                         * overflow (when the input is less than smallest int216 or
                         * greater than largest int216).
                         *
                         * Counterpart to Solidity's `int216` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 216 bits
                         *
                         * _Available since v4.7._
                         */
                        function toInt216(int256 value) internal pure returns (int216) {
                            require(value >= type(int216).min && value <= type(int216).max, "SafeCast: value doesn't fit in 216 bits");
                            return int216(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted int208 from int256, reverting on
                         * overflow (when the input is less than smallest int208 or
                         * greater than largest int208).
                         *
                         * Counterpart to Solidity's `int208` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 208 bits
                         *
                         * _Available since v4.7._
                         */
                        function toInt208(int256 value) internal pure returns (int208) {
                            require(value >= type(int208).min && value <= type(int208).max, "SafeCast: value doesn't fit in 208 bits");
                            return int208(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted int200 from int256, reverting on
                         * overflow (when the input is less than smallest int200 or
                         * greater than largest int200).
                         *
                         * Counterpart to Solidity's `int200` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 200 bits
                         *
                         * _Available since v4.7._
                         */
                        function toInt200(int256 value) internal pure returns (int200) {
                            require(value >= type(int200).min && value <= type(int200).max, "SafeCast: value doesn't fit in 200 bits");
                            return int200(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted int192 from int256, reverting on
                         * overflow (when the input is less than smallest int192 or
                         * greater than largest int192).
                         *
                         * Counterpart to Solidity's `int192` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 192 bits
                         *
                         * _Available since v4.7._
                         */
                        function toInt192(int256 value) internal pure returns (int192) {
                            require(value >= type(int192).min && value <= type(int192).max, "SafeCast: value doesn't fit in 192 bits");
                            return int192(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted int184 from int256, reverting on
                         * overflow (when the input is less than smallest int184 or
                         * greater than largest int184).
                         *
                         * Counterpart to Solidity's `int184` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 184 bits
                         *
                         * _Available since v4.7._
                         */
                        function toInt184(int256 value) internal pure returns (int184) {
                            require(value >= type(int184).min && value <= type(int184).max, "SafeCast: value doesn't fit in 184 bits");
                            return int184(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted int176 from int256, reverting on
                         * overflow (when the input is less than smallest int176 or
                         * greater than largest int176).
                         *
                         * Counterpart to Solidity's `int176` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 176 bits
                         *
                         * _Available since v4.7._
                         */
                        function toInt176(int256 value) internal pure returns (int176) {
                            require(value >= type(int176).min && value <= type(int176).max, "SafeCast: value doesn't fit in 176 bits");
                            return int176(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted int168 from int256, reverting on
                         * overflow (when the input is less than smallest int168 or
                         * greater than largest int168).
                         *
                         * Counterpart to Solidity's `int168` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 168 bits
                         *
                         * _Available since v4.7._
                         */
                        function toInt168(int256 value) internal pure returns (int168) {
                            require(value >= type(int168).min && value <= type(int168).max, "SafeCast: value doesn't fit in 168 bits");
                            return int168(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted int160 from int256, reverting on
                         * overflow (when the input is less than smallest int160 or
                         * greater than largest int160).
                         *
                         * Counterpart to Solidity's `int160` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 160 bits
                         *
                         * _Available since v4.7._
                         */
                        function toInt160(int256 value) internal pure returns (int160) {
                            require(value >= type(int160).min && value <= type(int160).max, "SafeCast: value doesn't fit in 160 bits");
                            return int160(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted int152 from int256, reverting on
                         * overflow (when the input is less than smallest int152 or
                         * greater than largest int152).
                         *
                         * Counterpart to Solidity's `int152` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 152 bits
                         *
                         * _Available since v4.7._
                         */
                        function toInt152(int256 value) internal pure returns (int152) {
                            require(value >= type(int152).min && value <= type(int152).max, "SafeCast: value doesn't fit in 152 bits");
                            return int152(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted int144 from int256, reverting on
                         * overflow (when the input is less than smallest int144 or
                         * greater than largest int144).
                         *
                         * Counterpart to Solidity's `int144` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 144 bits
                         *
                         * _Available since v4.7._
                         */
                        function toInt144(int256 value) internal pure returns (int144) {
                            require(value >= type(int144).min && value <= type(int144).max, "SafeCast: value doesn't fit in 144 bits");
                            return int144(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted int136 from int256, reverting on
                         * overflow (when the input is less than smallest int136 or
                         * greater than largest int136).
                         *
                         * Counterpart to Solidity's `int136` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 136 bits
                         *
                         * _Available since v4.7._
                         */
                        function toInt136(int256 value) internal pure returns (int136) {
                            require(value >= type(int136).min && value <= type(int136).max, "SafeCast: value doesn't fit in 136 bits");
                            return int136(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted int128 from int256, reverting on
                         * overflow (when the input is less than smallest int128 or
                         * greater than largest int128).
                         *
                         * Counterpart to Solidity's `int128` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 128 bits
                         *
                         * _Available since v3.1._
                         */
                        function toInt128(int256 value) internal pure returns (int128) {
                            require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
                            return int128(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted int120 from int256, reverting on
                         * overflow (when the input is less than smallest int120 or
                         * greater than largest int120).
                         *
                         * Counterpart to Solidity's `int120` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 120 bits
                         *
                         * _Available since v4.7._
                         */
                        function toInt120(int256 value) internal pure returns (int120) {
                            require(value >= type(int120).min && value <= type(int120).max, "SafeCast: value doesn't fit in 120 bits");
                            return int120(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted int112 from int256, reverting on
                         * overflow (when the input is less than smallest int112 or
                         * greater than largest int112).
                         *
                         * Counterpart to Solidity's `int112` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 112 bits
                         *
                         * _Available since v4.7._
                         */
                        function toInt112(int256 value) internal pure returns (int112) {
                            require(value >= type(int112).min && value <= type(int112).max, "SafeCast: value doesn't fit in 112 bits");
                            return int112(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted int104 from int256, reverting on
                         * overflow (when the input is less than smallest int104 or
                         * greater than largest int104).
                         *
                         * Counterpart to Solidity's `int104` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 104 bits
                         *
                         * _Available since v4.7._
                         */
                        function toInt104(int256 value) internal pure returns (int104) {
                            require(value >= type(int104).min && value <= type(int104).max, "SafeCast: value doesn't fit in 104 bits");
                            return int104(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted int96 from int256, reverting on
                         * overflow (when the input is less than smallest int96 or
                         * greater than largest int96).
                         *
                         * Counterpart to Solidity's `int96` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 96 bits
                         *
                         * _Available since v4.7._
                         */
                        function toInt96(int256 value) internal pure returns (int96) {
                            require(value >= type(int96).min && value <= type(int96).max, "SafeCast: value doesn't fit in 96 bits");
                            return int96(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted int88 from int256, reverting on
                         * overflow (when the input is less than smallest int88 or
                         * greater than largest int88).
                         *
                         * Counterpart to Solidity's `int88` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 88 bits
                         *
                         * _Available since v4.7._
                         */
                        function toInt88(int256 value) internal pure returns (int88) {
                            require(value >= type(int88).min && value <= type(int88).max, "SafeCast: value doesn't fit in 88 bits");
                            return int88(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted int80 from int256, reverting on
                         * overflow (when the input is less than smallest int80 or
                         * greater than largest int80).
                         *
                         * Counterpart to Solidity's `int80` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 80 bits
                         *
                         * _Available since v4.7._
                         */
                        function toInt80(int256 value) internal pure returns (int80) {
                            require(value >= type(int80).min && value <= type(int80).max, "SafeCast: value doesn't fit in 80 bits");
                            return int80(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted int72 from int256, reverting on
                         * overflow (when the input is less than smallest int72 or
                         * greater than largest int72).
                         *
                         * Counterpart to Solidity's `int72` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 72 bits
                         *
                         * _Available since v4.7._
                         */
                        function toInt72(int256 value) internal pure returns (int72) {
                            require(value >= type(int72).min && value <= type(int72).max, "SafeCast: value doesn't fit in 72 bits");
                            return int72(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted int64 from int256, reverting on
                         * overflow (when the input is less than smallest int64 or
                         * greater than largest int64).
                         *
                         * Counterpart to Solidity's `int64` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 64 bits
                         *
                         * _Available since v3.1._
                         */
                        function toInt64(int256 value) internal pure returns (int64) {
                            require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
                            return int64(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted int56 from int256, reverting on
                         * overflow (when the input is less than smallest int56 or
                         * greater than largest int56).
                         *
                         * Counterpart to Solidity's `int56` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 56 bits
                         *
                         * _Available since v4.7._
                         */
                        function toInt56(int256 value) internal pure returns (int56) {
                            require(value >= type(int56).min && value <= type(int56).max, "SafeCast: value doesn't fit in 56 bits");
                            return int56(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted int48 from int256, reverting on
                         * overflow (when the input is less than smallest int48 or
                         * greater than largest int48).
                         *
                         * Counterpart to Solidity's `int48` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 48 bits
                         *
                         * _Available since v4.7._
                         */
                        function toInt48(int256 value) internal pure returns (int48) {
                            require(value >= type(int48).min && value <= type(int48).max, "SafeCast: value doesn't fit in 48 bits");
                            return int48(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted int40 from int256, reverting on
                         * overflow (when the input is less than smallest int40 or
                         * greater than largest int40).
                         *
                         * Counterpart to Solidity's `int40` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 40 bits
                         *
                         * _Available since v4.7._
                         */
                        function toInt40(int256 value) internal pure returns (int40) {
                            require(value >= type(int40).min && value <= type(int40).max, "SafeCast: value doesn't fit in 40 bits");
                            return int40(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted int32 from int256, reverting on
                         * overflow (when the input is less than smallest int32 or
                         * greater than largest int32).
                         *
                         * Counterpart to Solidity's `int32` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 32 bits
                         *
                         * _Available since v3.1._
                         */
                        function toInt32(int256 value) internal pure returns (int32) {
                            require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
                            return int32(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted int24 from int256, reverting on
                         * overflow (when the input is less than smallest int24 or
                         * greater than largest int24).
                         *
                         * Counterpart to Solidity's `int24` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 24 bits
                         *
                         * _Available since v4.7._
                         */
                        function toInt24(int256 value) internal pure returns (int24) {
                            require(value >= type(int24).min && value <= type(int24).max, "SafeCast: value doesn't fit in 24 bits");
                            return int24(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted int16 from int256, reverting on
                         * overflow (when the input is less than smallest int16 or
                         * greater than largest int16).
                         *
                         * Counterpart to Solidity's `int16` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 16 bits
                         *
                         * _Available since v3.1._
                         */
                        function toInt16(int256 value) internal pure returns (int16) {
                            require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
                            return int16(value);
                        }
                    
                        /**
                         * @dev Returns the downcasted int8 from int256, reverting on
                         * overflow (when the input is less than smallest int8 or
                         * greater than largest int8).
                         *
                         * Counterpart to Solidity's `int8` operator.
                         *
                         * Requirements:
                         *
                         * - input must fit into 8 bits
                         *
                         * _Available since v3.1._
                         */
                        function toInt8(int256 value) internal pure returns (int8) {
                            require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
                            return int8(value);
                        }
                    
                        /**
                         * @dev Converts an unsigned uint256 into a signed int256.
                         *
                         * Requirements:
                         *
                         * - input must be less than or equal to maxInt256.
                         *
                         * _Available since v3.0._
                         */
                        function toInt256(uint256 value) internal pure returns (int256) {
                            // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
                            require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
                            return int256(value);
                        }
                    }
                    
                    
                    // File contracts/routers/UnoswapV3Router.sol
                    
                    
                    pragma solidity 0.8.17;
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    contract UnoswapV3Router is EthReceiver, IUniswapV3SwapCallback {
                        using Address for address payable;
                        using SafeERC20 for IERC20;
                    
                        error EmptyPools();
                        error BadPool();
                    
                        uint256 private constant _ONE_FOR_ZERO_MASK = 1 << 255;
                        uint256 private constant _WETH_UNWRAP_MASK = 1 << 253;
                        bytes32 private constant _POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;
                        bytes32 private constant _FF_FACTORY = 0xff1F98431c8aD98523631AE4a59f267346ea31F9840000000000000000000000;
                        // concatenation of token0(), token1() fee(), transfer() and transferFrom() selectors
                        bytes32 private constant _SELECTORS = 0x0dfe1681d21220a7ddca3f43a9059cbb23b872dd000000000000000000000000;
                        uint256 private constant _ADDRESS_MASK =   0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff;
                        /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
                        uint160 private constant _MIN_SQRT_RATIO = 4295128739 + 1;
                        /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
                        uint160 private constant _MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342 - 1;
                        IWETH private immutable _WETH;  // solhint-disable-line var-name-mixedcase
                    
                        constructor(IWETH weth) {
                            _WETH = weth;
                        }
                    
                        /// @notice Same as `uniswapV3SwapTo` but calls permit first,
                        /// allowing to approve token spending and make a swap in one transaction.
                        /// @param recipient Address that will receive swap funds
                        /// @param srcToken Source token
                        /// @param amount Amount of source tokens to swap
                        /// @param minReturn Minimal allowed returnAmount to make transaction commit
                        /// @param pools Pools chain used for swaps. Pools src and dst tokens should match to make swap happen
                        /// @param permit Should contain valid permit that can be used in `IERC20Permit.permit` calls.
                        /// See tests for examples
                        function uniswapV3SwapToWithPermit(
                            address payable recipient,
                            IERC20 srcToken,
                            uint256 amount,
                            uint256 minReturn,
                            uint256[] calldata pools,
                            bytes calldata permit
                        ) external returns(uint256 returnAmount) {
                            srcToken.safePermit(permit);
                            return _uniswapV3Swap(recipient, amount, minReturn, pools);
                        }
                    
                        /// @notice Same as `uniswapV3SwapTo` but uses `msg.sender` as recipient
                        /// @param amount Amount of source tokens to swap
                        /// @param minReturn Minimal allowed returnAmount to make transaction commit
                        /// @param pools Pools chain used for swaps. Pools src and dst tokens should match to make swap happen
                        function uniswapV3Swap(
                            uint256 amount,
                            uint256 minReturn,
                            uint256[] calldata pools
                        ) external payable returns(uint256 returnAmount) {
                            return _uniswapV3Swap(payable(msg.sender), amount, minReturn, pools);
                        }
                    
                        /// @notice Performs swap using Uniswap V3 exchange. Wraps and unwraps ETH if required.
                        /// Sending non-zero `msg.value` for anything but ETH swaps is prohibited
                        /// @param recipient Address that will receive swap funds
                        /// @param amount Amount of source tokens to swap
                        /// @param minReturn Minimal allowed returnAmount to make transaction commit
                        /// @param pools Pools chain used for swaps. Pools src and dst tokens should match to make swap happen
                        function uniswapV3SwapTo(
                            address payable recipient,
                            uint256 amount,
                            uint256 minReturn,
                            uint256[] calldata pools
                        ) external payable returns(uint256 returnAmount) {
                            return _uniswapV3Swap(recipient, amount, minReturn, pools);
                        }
                    
                        function _uniswapV3Swap(
                            address payable recipient,
                            uint256 amount,
                            uint256 minReturn,
                            uint256[] calldata pools
                        ) private returns(uint256 returnAmount) {
                            unchecked {
                                uint256 len = pools.length;
                                if (len == 0) revert EmptyPools();
                                uint256 lastIndex = len - 1;
                                returnAmount = amount;
                                bool wrapWeth = msg.value > 0;
                                bool unwrapWeth = pools[lastIndex] & _WETH_UNWRAP_MASK > 0;
                                if (wrapWeth) {
                                    if (msg.value != amount) revert RouterErrors.InvalidMsgValue();
                                    _WETH.deposit{value: amount}();
                                }
                                if (len > 1) {
                                    returnAmount = _makeSwap(address(this), wrapWeth ? address(this) : msg.sender, pools[0], returnAmount);
                    
                                    for (uint256 i = 1; i < lastIndex; i++) {
                                        returnAmount = _makeSwap(address(this), address(this), pools[i], returnAmount);
                                    }
                                    returnAmount = _makeSwap(unwrapWeth ? address(this) : recipient, address(this), pools[lastIndex], returnAmount);
                                } else {
                                    returnAmount = _makeSwap(unwrapWeth ? address(this) : recipient, wrapWeth ? address(this) : msg.sender, pools[0], returnAmount);
                                }
                    
                                if (returnAmount < minReturn) revert RouterErrors.ReturnAmountIsNotEnough();
                    
                                if (unwrapWeth) {
                                    _WETH.withdraw(returnAmount);
                                    recipient.sendValue(returnAmount);
                                }
                            }
                        }
                    
                        /// @inheritdoc IUniswapV3SwapCallback
                        function uniswapV3SwapCallback(
                            int256 amount0Delta,
                            int256 amount1Delta,
                            bytes calldata /* data */
                        ) external override {
                            assembly {  // solhint-disable-line no-inline-assembly
                                function reRevert() {
                                    returndatacopy(0, 0, returndatasize())
                                    revert(0, returndatasize())
                                }
                    
                                function validateERC20Transfer(status) {
                                    if iszero(status) {
                                        reRevert()
                                    }
                                    let success := or(
                                        iszero(returndatasize()),                       // empty return data
                                        and(gt(returndatasize(), 31), eq(mload(0), 1))  // true in return data
                                    )
                                    if iszero(success) {
                                        mstore(0, 0xf27f64e400000000000000000000000000000000000000000000000000000000)  // ERC20TransferFailed()
                                        revert(0, 4)
                                    }
                                }
                    
                                let emptyPtr := mload(0x40)
                                let resultPtr := add(emptyPtr, 0x15)  // 0x15 = _FF_FACTORY size
                    
                                mstore(emptyPtr, _SELECTORS)
                                if iszero(staticcall(gas(), caller(), emptyPtr, 0x4, resultPtr, 0x20)) {
                                    reRevert()
                                }
                                if iszero(staticcall(gas(), caller(), add(emptyPtr, 0x4), 0x4, add(resultPtr, 0x20), 0x20)) {
                                    reRevert()
                                }
                                if iszero(staticcall(gas(), caller(), add(emptyPtr, 0x8), 0x4, add(resultPtr, 0x40), 0x20)) {
                                    reRevert()
                                }
                    
                                let token
                                let amount
                                switch sgt(amount0Delta, 0)
                                case 1 {
                                    token := mload(resultPtr)
                                    amount := amount0Delta
                                }
                                default {
                                    token := mload(add(resultPtr, 0x20))
                                    amount := amount1Delta
                                }
                    
                                mstore(emptyPtr, _FF_FACTORY)
                                mstore(resultPtr, keccak256(resultPtr, 0x60)) // Compute the inner hash in-place
                                mstore(add(resultPtr, 0x20), _POOL_INIT_CODE_HASH)
                                let pool := and(keccak256(emptyPtr, 0x55), _ADDRESS_MASK)
                                if xor(pool, caller()) {
                                    mstore(0, 0xb2c0272200000000000000000000000000000000000000000000000000000000)  // BadPool()
                                    revert(0, 4)
                                }
                    
                                let payer := calldataload(0x84)
                                mstore(emptyPtr, _SELECTORS)
                                switch eq(payer, address())
                                case 1 {
                                    // token.safeTransfer(msg.sender,amount)
                                    mstore(add(emptyPtr, 0x10), caller())
                                    mstore(add(emptyPtr, 0x30), amount)
                                    validateERC20Transfer(
                                        call(gas(), token, 0, add(emptyPtr, 0x0c), 0x44, 0, 0x20)
                                    )
                                }
                                default {
                                    // token.safeTransferFrom(payer, msg.sender, amount);
                                    mstore(add(emptyPtr, 0x14), payer)
                                    mstore(add(emptyPtr, 0x34), caller())
                                    mstore(add(emptyPtr, 0x54), amount)
                                    validateERC20Transfer(
                                        call(gas(), token, 0, add(emptyPtr, 0x10), 0x64, 0, 0x20)
                                    )
                                }
                            }
                        }
                    
                        function _makeSwap(address recipient, address payer, uint256 pool, uint256 amount) private returns (uint256) {
                            bool zeroForOne = pool & _ONE_FOR_ZERO_MASK == 0;
                            if (zeroForOne) {
                                (, int256 amount1) = IUniswapV3Pool(address(uint160(pool))).swap(
                                    recipient,
                                    zeroForOne,
                                    SafeCast.toInt256(amount),
                                    _MIN_SQRT_RATIO,
                                    abi.encode(payer)
                                );
                                return SafeCast.toUint256(-amount1);
                            } else {
                                (int256 amount0,) = IUniswapV3Pool(address(uint160(pool))).swap(
                                    recipient,
                                    zeroForOne,
                                    SafeCast.toInt256(amount),
                                    _MAX_SQRT_RATIO,
                                    abi.encode(payer)
                                );
                                return SafeCast.toUint256(-amount0);
                            }
                        }
                    }
                    
                    
                    // File @1inch/solidity-utils/contracts/[email protected]
                    
                    
                    pragma solidity ^0.8.0;
                    
                    abstract contract OnlyWethReceiver is EthReceiver {
                        address private immutable _WETH;  // solhint-disable-line var-name-mixedcase
                    
                        constructor(address weth) {
                            _WETH = address(weth);
                        }
                    
                        function _receive() internal virtual override {
                            if (msg.sender != _WETH) revert EthDepositRejected();
                        }
                    }
                    
                    
                    // File @openzeppelin/contracts/interfaces/[email protected]
                    
                    // OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol)
                    
                    pragma solidity ^0.8.0;
                    
                    /**
                     * @dev Interface of the ERC1271 standard signature validation method for
                     * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
                     *
                     * _Available since v4.1._
                     */
                    interface IERC1271 {
                        /**
                         * @dev Should return whether the signature provided is valid for the provided data
                         * @param hash      Hash of the data to be signed
                         * @param signature Signature byte array associated with _data
                         */
                        function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
                    }
                    
                    
                    // File @1inch/solidity-utils/contracts/libraries/[email protected]
                    
                    
                    pragma solidity ^0.8.0;
                    
                    library ECDSA {
                        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
                        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
                        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
                        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
                        //
                        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
                        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
                        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
                        // these malleable signatures as well.
                        uint256 private constant _S_BOUNDARY = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0 + 1;
                        uint256 private constant _COMPACT_S_MASK = 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
                        uint256 private constant _COMPACT_V_SHIFT = 255;
                    
                        function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal view returns(address signer) {
                            /// @solidity memory-safe-assembly
                            assembly { // solhint-disable-line no-inline-assembly
                                if lt(s, _S_BOUNDARY) {
                                    let ptr := mload(0x40)
                    
                                    mstore(ptr, hash)
                                    mstore(add(ptr, 0x20), v)
                                    mstore(add(ptr, 0x40), r)
                                    mstore(add(ptr, 0x60), s)
                                    mstore(0, 0)
                                    pop(staticcall(gas(), 0x1, ptr, 0x80, 0, 0x20))
                                    signer := mload(0)
                                }
                            }
                        }
                    
                        function recover(bytes32 hash, bytes32 r, bytes32 vs) internal view returns(address signer) {
                            /// @solidity memory-safe-assembly
                            assembly { // solhint-disable-line no-inline-assembly
                                let s := and(vs, _COMPACT_S_MASK)
                                if lt(s, _S_BOUNDARY) {
                                    let ptr := mload(0x40)
                    
                                    mstore(ptr, hash)
                                    mstore(add(ptr, 0x20), add(27, shr(_COMPACT_V_SHIFT, vs)))
                                    mstore(add(ptr, 0x40), r)
                                    mstore(add(ptr, 0x60), s)
                                    mstore(0, 0)
                                    pop(staticcall(gas(), 0x1, ptr, 0x80, 0, 0x20))
                                    signer := mload(0)
                                }
                            }
                        }
                    
                        /// WARNING!!!
                        /// There is a known signature malleability issue with two representations of signatures!
                        /// Even though this function is able to verify both standard 65-byte and compact 64-byte EIP-2098 signatures
                        /// one should never use raw signatures for any kind of invalidation logic in their code.
                        /// As the standard and compact representations are interchangeable any invalidation logic that relies on
                        /// signature uniqueness will get rekt.
                        /// More info: https://github.com/OpenZeppelin/openzeppelin-contracts/security/advisories/GHSA-4h98-2769-gh6h
                        function recover(bytes32 hash, bytes calldata signature) internal view returns(address signer) {
                            /// @solidity memory-safe-assembly
                            assembly { // solhint-disable-line no-inline-assembly
                                let ptr := mload(0x40)
                    
                                // memory[ptr:ptr+0x80] = (hash, v, r, s)
                                switch signature.length
                                case 65 {
                                    // memory[ptr+0x20:ptr+0x80] = (v, r, s)
                                    mstore(add(ptr, 0x20), byte(0, calldataload(add(signature.offset, 0x40))))
                                    calldatacopy(add(ptr, 0x40), signature.offset, 0x40)
                                }
                                case 64 {
                                    // memory[ptr+0x20:ptr+0x80] = (v, r, s)
                                    let vs := calldataload(add(signature.offset, 0x20))
                                    mstore(add(ptr, 0x20), add(27, shr(_COMPACT_V_SHIFT, vs)))
                                    calldatacopy(add(ptr, 0x40), signature.offset, 0x20)
                                    mstore(add(ptr, 0x60), and(vs, _COMPACT_S_MASK))
                                }
                                default {
                                    ptr := 0
                                }
                    
                                if ptr {
                                    if lt(mload(add(ptr, 0x60)), _S_BOUNDARY) {
                                        // memory[ptr:ptr+0x20] = (hash)
                                        mstore(ptr, hash)
                    
                                        mstore(0, 0)
                                        pop(staticcall(gas(), 0x1, ptr, 0x80, 0, 0x20))
                                        signer := mload(0)
                                    }
                                }
                            }
                        }
                    
                        function recoverOrIsValidSignature(address signer, bytes32 hash, bytes calldata signature) internal view returns(bool success) {
                            if (signer == address(0)) return false;
                            if ((signature.length == 64 || signature.length == 65) && recover(hash, signature) == signer) {
                                return true;
                            }
                            return isValidSignature(signer, hash, signature);
                        }
                    
                        function recoverOrIsValidSignature(address signer, bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal view returns(bool success) {
                            if (signer == address(0)) return false;
                            if (recover(hash, v, r, s) == signer) {
                                return true;
                            }
                            return isValidSignature(signer, hash, v, r, s);
                        }
                    
                        function recoverOrIsValidSignature(address signer, bytes32 hash, bytes32 r, bytes32 vs) internal view returns(bool success) {
                            if (signer == address(0)) return false;
                            if (recover(hash, r, vs) == signer) {
                                return true;
                            }
                            return isValidSignature(signer, hash, r, vs);
                        }
                    
                        function recoverOrIsValidSignature65(address signer, bytes32 hash, bytes32 r, bytes32 vs) internal view returns(bool success) {
                            if (signer == address(0)) return false;
                            if (recover(hash, r, vs) == signer) {
                                return true;
                            }
                            return isValidSignature65(signer, hash, r, vs);
                        }
                    
                        function isValidSignature(address signer, bytes32 hash, bytes calldata signature) internal view returns(bool success) {
                            // (bool success, bytes memory data) = signer.staticcall(abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature));
                            // return success && data.length >= 4 && abi.decode(data, (bytes4)) == IERC1271.isValidSignature.selector;
                            bytes4 selector = IERC1271.isValidSignature.selector;
                            /// @solidity memory-safe-assembly
                            assembly { // solhint-disable-line no-inline-assembly
                                let ptr := mload(0x40)
                    
                                mstore(ptr, selector)
                                mstore(add(ptr, 0x04), hash)
                                mstore(add(ptr, 0x24), 0x40)
                                mstore(add(ptr, 0x44), signature.length)
                                calldatacopy(add(ptr, 0x64), signature.offset, signature.length)
                                if staticcall(gas(), signer, ptr, add(0x64, signature.length), 0, 0x20) {
                                    success := and(eq(selector, mload(0)), eq(returndatasize(), 0x20))
                                }
                            }
                        }
                    
                        function isValidSignature(address signer, bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal view returns(bool success) {
                            bytes4 selector = IERC1271.isValidSignature.selector;
                            /// @solidity memory-safe-assembly
                            assembly { // solhint-disable-line no-inline-assembly
                                let ptr := mload(0x40)
                    
                                mstore(ptr, selector)
                                mstore(add(ptr, 0x04), hash)
                                mstore(add(ptr, 0x24), 0x40)
                                mstore(add(ptr, 0x44), 65)
                                mstore(add(ptr, 0x64), r)
                                mstore(add(ptr, 0x84), s)
                                mstore8(add(ptr, 0xa4), v)
                                if staticcall(gas(), signer, ptr, 0xa5, 0, 0x20) {
                                    success := and(eq(selector, mload(0)), eq(returndatasize(), 0x20))
                                }
                            }
                        }
                    
                        function isValidSignature(address signer, bytes32 hash, bytes32 r, bytes32 vs) internal view returns(bool success) {
                            // (bool success, bytes memory data) = signer.staticcall(abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, abi.encodePacked(r, vs)));
                            // return success && data.length >= 4 && abi.decode(data, (bytes4)) == IERC1271.isValidSignature.selector;
                            bytes4 selector = IERC1271.isValidSignature.selector;
                            /// @solidity memory-safe-assembly
                            assembly { // solhint-disable-line no-inline-assembly
                                let ptr := mload(0x40)
                    
                                mstore(ptr, selector)
                                mstore(add(ptr, 0x04), hash)
                                mstore(add(ptr, 0x24), 0x40)
                                mstore(add(ptr, 0x44), 64)
                                mstore(add(ptr, 0x64), r)
                                mstore(add(ptr, 0x84), vs)
                                if staticcall(gas(), signer, ptr, 0xa4, 0, 0x20) {
                                    success := and(eq(selector, mload(0)), eq(returndatasize(), 0x20))
                                }
                            }
                        }
                    
                        function isValidSignature65(address signer, bytes32 hash, bytes32 r, bytes32 vs) internal view returns(bool success) {
                            // (bool success, bytes memory data) = signer.staticcall(abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, abi.encodePacked(r, vs & ~uint256(1 << 255), uint8(vs >> 255))));
                            // return success && data.length >= 4 && abi.decode(data, (bytes4)) == IERC1271.isValidSignature.selector;
                            bytes4 selector = IERC1271.isValidSignature.selector;
                            /// @solidity memory-safe-assembly
                            assembly { // solhint-disable-line no-inline-assembly
                                let ptr := mload(0x40)
                    
                                mstore(ptr, selector)
                                mstore(add(ptr, 0x04), hash)
                                mstore(add(ptr, 0x24), 0x40)
                                mstore(add(ptr, 0x44), 65)
                                mstore(add(ptr, 0x64), r)
                                mstore(add(ptr, 0x84), and(vs, _COMPACT_S_MASK))
                                mstore8(add(ptr, 0xa4), add(27, shr(_COMPACT_V_SHIFT, vs)))
                                if staticcall(gas(), signer, ptr, 0xa5, 0, 0x20) {
                                    success := and(eq(selector, mload(0)), eq(returndatasize(), 0x20))
                                }
                            }
                        }
                    
                        function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 res) {
                            // 32 is the length in bytes of hash, enforced by the type signature above
                            // return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
                            /// @solidity memory-safe-assembly
                            assembly { // solhint-disable-line no-inline-assembly
                                mstore(0, 0x19457468657265756d205369676e6564204d6573736167653a0a333200000000) // "\x19Ethereum Signed Message:\n32"
                                mstore(28, hash)
                                res := keccak256(0, 60)
                            }
                        }
                    
                        function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 res) {
                            // return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
                            /// @solidity memory-safe-assembly
                            assembly { // solhint-disable-line no-inline-assembly
                                let ptr := mload(0x40)
                                mstore(ptr, 0x1901000000000000000000000000000000000000000000000000000000000000) // "\x19\x01"
                                mstore(add(ptr, 0x02), domainSeparator)
                                mstore(add(ptr, 0x22), structHash)
                                res := keccak256(ptr, 66)
                            }
                        }
                    }
                    
                    
                    // File @1inch/limit-order-protocol/contracts/[email protected]
                    
                    
                    pragma solidity 0.8.17;
                    
                    library OrderRFQLib {
                        struct OrderRFQ {
                            uint256 info;  // lowest 64 bits is the order id, next 64 bits is the expiration timestamp
                            address makerAsset;
                            address takerAsset;
                            address maker;
                            address allowedSender;  // equals to Zero address on public orders
                            uint256 makingAmount;
                            uint256 takingAmount;
                        }
                    
                        bytes32 constant internal _LIMIT_ORDER_RFQ_TYPEHASH = keccak256(
                            "OrderRFQ("
                                "uint256 info,"
                                "address makerAsset,"
                                "address takerAsset,"
                                "address maker,"
                                "address allowedSender,"
                                "uint256 makingAmount,"
                                "uint256 takingAmount"
                            ")"
                        );
                    
                        function hash(OrderRFQ memory order, bytes32 domainSeparator) internal pure returns(bytes32 result) {
                            bytes32 typehash = _LIMIT_ORDER_RFQ_TYPEHASH;
                            bytes32 orderHash;
                            // this assembly is memory unsafe :(
                            assembly { // solhint-disable-line no-inline-assembly
                                let ptr := sub(order, 0x20)
                    
                                // keccak256(abi.encode(_LIMIT_ORDER_RFQ_TYPEHASH, order));
                                let tmp := mload(ptr)
                                mstore(ptr, typehash)
                                orderHash := keccak256(ptr, 0x100)
                                mstore(ptr, tmp)
                            }
                            return ECDSA.toTypedDataHash(domainSeparator, orderHash);
                        }
                    }
                    
                    
                    // File @openzeppelin/contracts/utils/[email protected]
                    
                    // OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)
                    
                    pragma solidity ^0.8.0;
                    
                    /**
                     * @dev String operations.
                     */
                    library Strings {
                        bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
                        uint8 private constant _ADDRESS_LENGTH = 20;
                    
                        /**
                         * @dev Converts a `uint256` to its ASCII `string` decimal representation.
                         */
                        function toString(uint256 value) internal pure returns (string memory) {
                            // Inspired by OraclizeAPI's implementation - MIT licence
                            // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
                    
                            if (value == 0) {
                                return "0";
                            }
                            uint256 temp = value;
                            uint256 digits;
                            while (temp != 0) {
                                digits++;
                                temp /= 10;
                            }
                            bytes memory buffer = new bytes(digits);
                            while (value != 0) {
                                digits -= 1;
                                buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
                                value /= 10;
                            }
                            return string(buffer);
                        }
                    
                        /**
                         * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
                         */
                        function toHexString(uint256 value) internal pure returns (string memory) {
                            if (value == 0) {
                                return "0x00";
                            }
                            uint256 temp = value;
                            uint256 length = 0;
                            while (temp != 0) {
                                length++;
                                temp >>= 8;
                            }
                            return toHexString(value, length);
                        }
                    
                        /**
                         * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
                         */
                        function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
                            bytes memory buffer = new bytes(2 * length + 2);
                            buffer[0] = "0";
                            buffer[1] = "x";
                            for (uint256 i = 2 * length + 1; i > 1; --i) {
                                buffer[i] = _HEX_SYMBOLS[value & 0xf];
                                value >>= 4;
                            }
                            require(value == 0, "Strings: hex length insufficient");
                            return string(buffer);
                        }
                    
                        /**
                         * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
                         */
                        function toHexString(address addr) internal pure returns (string memory) {
                            return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
                        }
                    }
                    
                    
                    // File @openzeppelin/contracts/utils/cryptography/[email protected]
                    
                    // OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol)
                    
                    pragma solidity ^0.8.0;
                    
                    /**
                     * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
                     *
                     * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
                     * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
                     * they need in their contracts using a combination of `abi.encode` and `keccak256`.
                     *
                     * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
                     * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
                     * ({_hashTypedDataV4}).
                     *
                     * The implementation of the domain separator was designed to be as efficient as possible while still properly updating
                     * the chain id to protect against replay attacks on an eventual fork of the chain.
                     *
                     * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
                     * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
                     *
                     * _Available since v3.4._
                     */
                    abstract contract EIP712 {
                        /* solhint-disable var-name-mixedcase */
                        // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
                        // invalidate the cached domain separator if the chain id changes.
                        bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
                        uint256 private immutable _CACHED_CHAIN_ID;
                        address private immutable _CACHED_THIS;
                    
                        bytes32 private immutable _HASHED_NAME;
                        bytes32 private immutable _HASHED_VERSION;
                        bytes32 private immutable _TYPE_HASH;
                    
                        /* solhint-enable var-name-mixedcase */
                    
                        /**
                         * @dev Initializes the domain separator and parameter caches.
                         *
                         * The meaning of `name` and `version` is specified in
                         * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
                         *
                         * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
                         * - `version`: the current major version of the signing domain.
                         *
                         * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
                         * contract upgrade].
                         */
                        constructor(string memory name, string memory version) {
                            bytes32 hashedName = keccak256(bytes(name));
                            bytes32 hashedVersion = keccak256(bytes(version));
                            bytes32 typeHash = keccak256(
                                "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
                            );
                            _HASHED_NAME = hashedName;
                            _HASHED_VERSION = hashedVersion;
                            _CACHED_CHAIN_ID = block.chainid;
                            _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
                            _CACHED_THIS = address(this);
                            _TYPE_HASH = typeHash;
                        }
                    
                        /**
                         * @dev Returns the domain separator for the current chain.
                         */
                        function _domainSeparatorV4() internal view returns (bytes32) {
                            if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) {
                                return _CACHED_DOMAIN_SEPARATOR;
                            } else {
                                return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
                            }
                        }
                    
                        function _buildDomainSeparator(
                            bytes32 typeHash,
                            bytes32 nameHash,
                            bytes32 versionHash
                        ) private view returns (bytes32) {
                            return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
                        }
                    
                        /**
                         * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
                         * function returns the hash of the fully encoded EIP712 message for this domain.
                         *
                         * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
                         *
                         * ```solidity
                         * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
                         *     keccak256("Mail(address to,string contents)"),
                         *     mailTo,
                         *     keccak256(bytes(mailContents))
                         * )));
                         * address signer = ECDSA.recover(digest, signature);
                         * ```
                         */
                        function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
                            return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
                        }
                    }
                    
                    
                    // File @1inch/limit-order-protocol/contracts/libraries/[email protected]
                    
                    
                    pragma solidity 0.8.17;
                    
                    library Errors {
                        error InvalidMsgValue();
                        error ETHTransferFailed();
                    }
                    
                    
                    // File @1inch/limit-order-protocol/contracts/helpers/[email protected]
                    
                    
                    pragma solidity 0.8.17;
                    
                    /// @title A helper contract for calculations related to order amounts
                    library AmountCalculator {
                        /// @notice Calculates maker amount
                        /// @return Result Floored maker amount
                        function getMakingAmount(uint256 orderMakerAmount, uint256 orderTakerAmount, uint256 swapTakerAmount) internal pure returns(uint256) {
                            return swapTakerAmount * orderMakerAmount / orderTakerAmount;
                        }
                    
                        /// @notice Calculates taker amount
                        /// @return Result Ceiled taker amount
                        function getTakingAmount(uint256 orderMakerAmount, uint256 orderTakerAmount, uint256 swapMakerAmount) internal pure returns(uint256) {
                            return (swapMakerAmount * orderTakerAmount + orderMakerAmount - 1) / orderMakerAmount;
                        }
                    }
                    
                    
                    // File @1inch/limit-order-protocol/contracts/[email protected]
                    
                    
                    pragma solidity 0.8.17;
                    
                    
                    
                    
                    
                    
                    
                    /// @title RFQ Limit Order mixin
                    abstract contract OrderRFQMixin is EIP712, OnlyWethReceiver {
                        using SafeERC20 for IERC20;
                        using OrderRFQLib for OrderRFQLib.OrderRFQ;
                    
                        error RFQZeroTargetIsForbidden();
                        error RFQPrivateOrder();
                        error RFQBadSignature();
                        error OrderExpired();
                        error MakingAmountExceeded();
                        error TakingAmountExceeded();
                        error RFQSwapWithZeroAmount();
                        error InvalidatedOrder();
                    
                        /**
                         * @notice Emitted when RFQ gets filled
                         * @param orderHash Hash of the order
                         * @param makingAmount Amount of the maker asset that was transferred from maker to taker
                         */
                        event OrderFilledRFQ(
                            bytes32 orderHash,
                            uint256 makingAmount
                        );
                    
                        uint256 private constant _RAW_CALL_GAS_LIMIT = 5000;
                        uint256 private constant _MAKER_AMOUNT_FLAG = 1 << 255;
                        uint256 private constant _SIGNER_SMART_CONTRACT_HINT = 1 << 254;
                        uint256 private constant _IS_VALID_SIGNATURE_65_BYTES = 1 << 253;
                        uint256 private constant _UNWRAP_WETH_FLAG = 1 << 252;
                        uint256 private constant _AMOUNT_MASK = ~(
                            _MAKER_AMOUNT_FLAG |
                            _SIGNER_SMART_CONTRACT_HINT |
                            _IS_VALID_SIGNATURE_65_BYTES |
                            _UNWRAP_WETH_FLAG
                        );
                    
                        IWETH private immutable _WETH;  // solhint-disable-line var-name-mixedcase
                        mapping(address => mapping(uint256 => uint256)) private _invalidator;
                    
                        constructor(IWETH weth) OnlyWethReceiver(address(weth)) {
                            _WETH = weth;
                        }
                    
                        /**
                         * @notice Returns bitmask for double-spend invalidators based on lowest byte of order.info and filled quotes
                         * @param maker Maker address
                         * @param slot Slot number to return bitmask for
                         * @return result Each bit represents whether corresponding was already invalidated
                         */
                        function invalidatorForOrderRFQ(address maker, uint256 slot) external view returns(uint256 /* result */) {
                            return _invalidator[maker][slot];
                        }
                    
                        /**
                         * @notice Cancels order's quote
                         * @param orderInfo Order info (only order id in lowest 64 bits is used)
                         */
                        function cancelOrderRFQ(uint256 orderInfo) external {
                            _invalidateOrder(msg.sender, orderInfo, 0);
                        }
                    
                        /// @notice Cancels multiple order's quotes
                        function cancelOrderRFQ(uint256 orderInfo, uint256 additionalMask) external {
                            _invalidateOrder(msg.sender, orderInfo, additionalMask);
                        }
                    
                        /**
                         * @notice Fills order's quote, fully or partially (whichever is possible)
                         * @param order Order quote to fill
                         * @param signature Signature to confirm quote ownership
                         * @param flagsAndAmount Fill configuration flags with amount packed in one slot
                         * @return filledMakingAmount Actual amount transferred from maker to taker
                         * @return filledTakingAmount Actual amount transferred from taker to maker
                         * @return orderHash Hash of the filled order
                         */
                        function fillOrderRFQ(
                            OrderRFQLib.OrderRFQ memory order,
                            bytes calldata signature,
                            uint256 flagsAndAmount
                        ) external payable returns(uint256 /* filledMakingAmount */, uint256 /* filledTakingAmount */, bytes32 /* orderHash */) {
                            return fillOrderRFQTo(order, signature, flagsAndAmount, msg.sender);
                        }
                    
                        /**
                         * @notice Fills order's quote, fully or partially, with compact signature
                         * @param order Order quote to fill
                         * @param r R component of signature
                         * @param vs VS component of signature
                         * @param flagsAndAmount Fill configuration flags with amount packed in one slot
                         * - Bits 0-252 contain the amount to fill
                         * - Bit 253 is used to indicate whether signature is 64-bit (0) or 65-bit (1)
                         * - Bit 254 is used to indicate whether smart contract (1) signed the order or not (0)
                         * - Bit 255 is used to indicate whether maker (1) or taker amount (0) is given in the amount parameter
                         * @return filledMakingAmount Actual amount transferred from maker to taker
                         * @return filledTakingAmount Actual amount transferred from taker to maker
                         * @return orderHash Hash of the filled order
                         */
                        function fillOrderRFQCompact(
                            OrderRFQLib.OrderRFQ memory order,
                            bytes32 r,
                            bytes32 vs,
                            uint256 flagsAndAmount
                        ) external payable returns(uint256 filledMakingAmount, uint256 filledTakingAmount, bytes32 orderHash) {
                            orderHash = order.hash(_domainSeparatorV4());
                            if (flagsAndAmount & _SIGNER_SMART_CONTRACT_HINT != 0) {
                                if (flagsAndAmount & _IS_VALID_SIGNATURE_65_BYTES != 0) {
                                    if (!ECDSA.isValidSignature65(order.maker, orderHash, r, vs)) revert RFQBadSignature();
                                } else {
                                    if (!ECDSA.isValidSignature(order.maker, orderHash, r, vs)) revert RFQBadSignature();
                                }
                            } else {
                                if(!ECDSA.recoverOrIsValidSignature(order.maker, orderHash, r, vs)) revert RFQBadSignature();
                            }
                    
                            (filledMakingAmount, filledTakingAmount) = _fillOrderRFQTo(order, flagsAndAmount, msg.sender);
                            emit OrderFilledRFQ(orderHash, filledMakingAmount);
                        }
                    
                        /**
                         * @notice Same as `fillOrderRFQTo` but calls permit first.
                         * It allows to approve token spending and make a swap in one transaction.
                         * Also allows to specify funds destination instead of `msg.sender`
                         * @param order Order quote to fill
                         * @param signature Signature to confirm quote ownership
                         * @param flagsAndAmount Fill configuration flags with amount packed in one slot
                         * @param target Address that will receive swap funds
                         * @param permit Should consist of abiencoded token address and encoded `IERC20Permit.permit` call.
                         * @return filledMakingAmount Actual amount transferred from maker to taker
                         * @return filledTakingAmount Actual amount transferred from taker to maker
                         * @return orderHash Hash of the filled order
                         * @dev See tests for examples
                         */
                        function fillOrderRFQToWithPermit(
                            OrderRFQLib.OrderRFQ memory order,
                            bytes calldata signature,
                            uint256 flagsAndAmount,
                            address target,
                            bytes calldata permit
                        ) external returns(uint256 /* filledMakingAmount */, uint256 /* filledTakingAmount */, bytes32 /* orderHash */) {
                            IERC20(order.takerAsset).safePermit(permit);
                            return fillOrderRFQTo(order, signature, flagsAndAmount, target);
                        }
                    
                        /**
                         * @notice Same as `fillOrderRFQ` but allows to specify funds destination instead of `msg.sender`
                         * @param order Order quote to fill
                         * @param signature Signature to confirm quote ownership
                         * @param flagsAndAmount Fill configuration flags with amount packed in one slot
                         * @param target Address that will receive swap funds
                         * @return filledMakingAmount Actual amount transferred from maker to taker
                         * @return filledTakingAmount Actual amount transferred from taker to maker
                         * @return orderHash Hash of the filled order
                         */
                        function fillOrderRFQTo(
                            OrderRFQLib.OrderRFQ memory order,
                            bytes calldata signature,
                            uint256 flagsAndAmount,
                            address target
                        ) public payable returns(uint256 filledMakingAmount, uint256 filledTakingAmount, bytes32 orderHash) {
                            orderHash = order.hash(_domainSeparatorV4());
                            if (flagsAndAmount & _SIGNER_SMART_CONTRACT_HINT != 0) {
                                if (flagsAndAmount & _IS_VALID_SIGNATURE_65_BYTES != 0 && signature.length != 65) revert RFQBadSignature();
                                if (!ECDSA.isValidSignature(order.maker, orderHash, signature)) revert RFQBadSignature();
                            } else {
                                if(!ECDSA.recoverOrIsValidSignature(order.maker, orderHash, signature)) revert RFQBadSignature();
                            }
                            (filledMakingAmount, filledTakingAmount) = _fillOrderRFQTo(order, flagsAndAmount, target);
                            emit OrderFilledRFQ(orderHash, filledMakingAmount);
                        }
                    
                        function _fillOrderRFQTo(
                            OrderRFQLib.OrderRFQ memory order,
                            uint256 flagsAndAmount,
                            address target
                        ) private returns(uint256 makingAmount, uint256 takingAmount) {
                            if (target == address(0)) revert RFQZeroTargetIsForbidden();
                    
                            address maker = order.maker;
                    
                            // Validate order
                            if (order.allowedSender != address(0) && order.allowedSender != msg.sender) revert RFQPrivateOrder();
                    
                            {  // Stack too deep
                                uint256 info = order.info;
                                // Check time expiration
                                uint256 expiration = uint128(info) >> 64;
                                if (expiration != 0 && block.timestamp > expiration) revert OrderExpired(); // solhint-disable-line not-rely-on-time
                                _invalidateOrder(maker, info, 0);
                            }
                    
                            {  // Stack too deep
                                uint256 orderMakingAmount = order.makingAmount;
                                uint256 orderTakingAmount = order.takingAmount;
                                uint256 amount = flagsAndAmount & _AMOUNT_MASK;
                                // Compute partial fill if needed
                                if (amount == 0) {
                                    // zero amount means whole order
                                    makingAmount = orderMakingAmount;
                                    takingAmount = orderTakingAmount;
                                }
                                else if (flagsAndAmount & _MAKER_AMOUNT_FLAG != 0) {
                                    if (amount > orderMakingAmount) revert MakingAmountExceeded();
                                    makingAmount = amount;
                                    takingAmount = AmountCalculator.getTakingAmount(orderMakingAmount, orderTakingAmount, makingAmount);
                                }
                                else {
                                    if (amount > orderTakingAmount) revert TakingAmountExceeded();
                                    takingAmount = amount;
                                    makingAmount = AmountCalculator.getMakingAmount(orderMakingAmount, orderTakingAmount, takingAmount);
                                }
                            }
                    
                            if (makingAmount == 0 || takingAmount == 0) revert RFQSwapWithZeroAmount();
                    
                            // Maker => Taker
                            if (order.makerAsset == address(_WETH) && flagsAndAmount & _UNWRAP_WETH_FLAG != 0) {
                                _WETH.transferFrom(maker, address(this), makingAmount);
                                _WETH.withdraw(makingAmount);
                                // solhint-disable-next-line avoid-low-level-calls
                                (bool success, ) = target.call{value: makingAmount, gas: _RAW_CALL_GAS_LIMIT}("");
                                if (!success) revert Errors.ETHTransferFailed();
                            } else {
                                IERC20(order.makerAsset).safeTransferFrom(maker, target, makingAmount);
                            }
                    
                            // Taker => Maker
                            if (order.takerAsset == address(_WETH) && msg.value > 0) {
                                if (msg.value != takingAmount) revert Errors.InvalidMsgValue();
                                _WETH.deposit{ value: takingAmount }();
                                _WETH.transfer(maker, takingAmount);
                            } else {
                                if (msg.value != 0) revert Errors.InvalidMsgValue();
                                IERC20(order.takerAsset).safeTransferFrom(msg.sender, maker, takingAmount);
                            }
                        }
                    
                        function _invalidateOrder(address maker, uint256 orderInfo, uint256 additionalMask) private {
                            uint256 invalidatorSlot = uint64(orderInfo) >> 8;
                            uint256 invalidatorBits = (1 << uint8(orderInfo)) | additionalMask;
                            mapping(uint256 => uint256) storage invalidatorStorage = _invalidator[maker];
                            uint256 invalidator = invalidatorStorage[invalidatorSlot];
                            if (invalidator & invalidatorBits == invalidatorBits) revert InvalidatedOrder();
                            invalidatorStorage[invalidatorSlot] = invalidator | invalidatorBits;
                        }
                    }
                    
                    
                    // File @1inch/limit-order-protocol/contracts/[email protected]
                    
                    
                    pragma solidity 0.8.17;
                    
                    library OrderLib {
                        struct Order {
                            uint256 salt;
                            address makerAsset;
                            address takerAsset;
                            address maker;
                            address receiver;
                            address allowedSender;  // equals to Zero address on public orders
                            uint256 makingAmount;
                            uint256 takingAmount;
                            uint256 offsets;
                            // bytes makerAssetData;
                            // bytes takerAssetData;
                            // bytes getMakingAmount; // this.staticcall(abi.encodePacked(bytes, swapTakerAmount)) => (swapMakerAmount)
                            // bytes getTakingAmount; // this.staticcall(abi.encodePacked(bytes, swapMakerAmount)) => (swapTakerAmount)
                            // bytes predicate;       // this.staticcall(bytes) => (bool)
                            // bytes permit;          // On first fill: permit.1.call(abi.encodePacked(permit.selector, permit.2))
                            // bytes preInteraction;
                            // bytes postInteraction;
                            bytes interactions; // concat(makerAssetData, takerAssetData, getMakingAmount, getTakingAmount, predicate, permit, preIntercation, postInteraction)
                        }
                    
                        bytes32 constant internal _LIMIT_ORDER_TYPEHASH = keccak256(
                            "Order("
                                "uint256 salt,"
                                "address makerAsset,"
                                "address takerAsset,"
                                "address maker,"
                                "address receiver,"
                                "address allowedSender,"
                                "uint256 makingAmount,"
                                "uint256 takingAmount,"
                                "uint256 offsets,"
                                "bytes interactions"
                            ")"
                        );
                    
                        enum DynamicField {
                            MakerAssetData,
                            TakerAssetData,
                            GetMakingAmount,
                            GetTakingAmount,
                            Predicate,
                            Permit,
                            PreInteraction,
                            PostInteraction
                        }
                    
                        function getterIsFrozen(bytes calldata getter) internal pure returns(bool) {
                            return getter.length == 1 && getter[0] == "x";
                        }
                    
                        function _get(Order calldata order, DynamicField field) private pure returns(bytes calldata) {
                            uint256 bitShift = uint256(field) << 5; // field * 32
                            return order.interactions[
                                uint32((order.offsets << 32) >> bitShift):
                                uint32(order.offsets >> bitShift)
                            ];
                        }
                    
                        function makerAssetData(Order calldata order) internal pure returns(bytes calldata) {
                            return _get(order, DynamicField.MakerAssetData);
                        }
                    
                        function takerAssetData(Order calldata order) internal pure returns(bytes calldata) {
                            return _get(order, DynamicField.TakerAssetData);
                        }
                    
                        function getMakingAmount(Order calldata order) internal pure returns(bytes calldata) {
                            return _get(order, DynamicField.GetMakingAmount);
                        }
                    
                        function getTakingAmount(Order calldata order) internal pure returns(bytes calldata) {
                            return _get(order, DynamicField.GetTakingAmount);
                        }
                    
                        function predicate(Order calldata order) internal pure returns(bytes calldata) {
                            return _get(order, DynamicField.Predicate);
                        }
                    
                        function permit(Order calldata order) internal pure returns(bytes calldata) {
                            return _get(order, DynamicField.Permit);
                        }
                    
                        function preInteraction(Order calldata order) internal pure returns(bytes calldata) {
                            return _get(order, DynamicField.PreInteraction);
                        }
                    
                        function postInteraction(Order calldata order) internal pure returns(bytes calldata) {
                            return _get(order, DynamicField.PostInteraction);
                        }
                    
                        function hash(Order calldata order, bytes32 domainSeparator) internal pure returns(bytes32 result) {
                            bytes calldata interactions = order.interactions;
                            bytes32 typehash = _LIMIT_ORDER_TYPEHASH;
                            /// @solidity memory-safe-assembly
                            assembly { // solhint-disable-line no-inline-assembly
                                let ptr := mload(0x40)
                    
                                // keccak256(abi.encode(_LIMIT_ORDER_TYPEHASH, orderWithoutInteractions, keccak256(order.interactions)));
                                calldatacopy(ptr, interactions.offset, interactions.length)
                                mstore(add(ptr, 0x140), keccak256(ptr, interactions.length))
                                calldatacopy(add(ptr, 0x20), order, 0x120)
                                mstore(ptr, typehash)
                                result := keccak256(ptr, 0x160)
                            }
                            result = ECDSA.toTypedDataHash(domainSeparator, result);
                        }
                    }
                    
                    
                    // File @1inch/limit-order-protocol/contracts/libraries/[email protected]
                    
                    
                    pragma solidity 0.8.17;
                    
                    /// @title Library with gas efficient alternatives to `abi.decode`
                    library ArgumentsDecoder {
                        error IncorrectDataLength();
                    
                        function decodeUint256(bytes calldata data, uint256 offset) internal pure returns(uint256 value) {
                            unchecked { if (data.length < offset + 32) revert IncorrectDataLength(); }
                            // no memory ops inside so this insertion is automatically memory safe
                            assembly { // solhint-disable-line no-inline-assembly
                                value := calldataload(add(data.offset, offset))
                            }
                        }
                    
                        function decodeSelector(bytes calldata data) internal pure returns(bytes4 value) {
                            if (data.length < 4) revert IncorrectDataLength();
                            // no memory ops inside so this insertion is automatically memory safe
                            assembly { // solhint-disable-line no-inline-assembly
                                value := calldataload(data.offset)
                            }
                        }
                    
                        function decodeTailCalldata(bytes calldata data, uint256 tailOffset) internal pure returns(bytes calldata args) {
                            if (data.length < tailOffset) revert IncorrectDataLength();
                            // no memory ops inside so this insertion is automatically memory safe
                            assembly {  // solhint-disable-line no-inline-assembly
                                args.offset := add(data.offset, tailOffset)
                                args.length := sub(data.length, tailOffset)
                            }
                        }
                    
                        function decodeTargetAndCalldata(bytes calldata data) internal pure returns(address target, bytes calldata args) {
                            if (data.length < 20) revert IncorrectDataLength();
                            // no memory ops inside so this insertion is automatically memory safe
                            assembly {  // solhint-disable-line no-inline-assembly
                                target := shr(96, calldataload(data.offset))
                                args.offset := add(data.offset, 20)
                                args.length := sub(data.length, 20)
                            }
                        }
                    }
                    
                    
                    // File @1inch/limit-order-protocol/contracts/helpers/[email protected]
                    
                    
                    pragma solidity 0.8.17;
                    
                    /// @title A helper contract for managing nonce of tx sender
                    contract NonceManager {
                        error AdvanceNonceFailed();
                        event NonceIncreased(address indexed maker, uint256 newNonce);
                    
                        mapping(address => uint256) public nonce;
                    
                        /// @notice Advances nonce by one
                        function increaseNonce() external {
                            advanceNonce(1);
                        }
                    
                        /// @notice Advances nonce by specified amount
                        function advanceNonce(uint8 amount) public {
                            if (amount == 0) revert AdvanceNonceFailed();
                            uint256 newNonce = nonce[msg.sender] + amount;
                            nonce[msg.sender] = newNonce;
                            emit NonceIncreased(msg.sender, newNonce);
                        }
                    
                        /// @notice Checks if `makerAddress` has specified `makerNonce`
                        /// @return Result True if `makerAddress` has specified nonce. Otherwise, false
                        function nonceEquals(address makerAddress, uint256 makerNonce) public view returns(bool) {
                            return nonce[makerAddress] == makerNonce;
                        }
                    }
                    
                    
                    // File @1inch/limit-order-protocol/contracts/helpers/[email protected]
                    
                    
                    pragma solidity 0.8.17;
                    
                    
                    /// @title A helper contract for executing boolean functions on arbitrary target call results
                    contract PredicateHelper is NonceManager {
                        using ArgumentsDecoder for bytes;
                    
                        error ArbitraryStaticCallFailed();
                    
                        /// @notice Calls every target with corresponding data
                        /// @return Result True if call to any target returned True. Otherwise, false
                        function or(uint256 offsets, bytes calldata data) public view returns(bool) {
                            uint256 current;
                            uint256 previous;
                            for (uint256 i = 0; (current = uint32(offsets >> i)) != 0; i += 32) {
                                (bool success, uint256 res) = _selfStaticCall(data[previous:current]);
                                if (success && res == 1) {
                                    return true;
                                }
                                previous = current;
                            }
                            return false;
                        }
                    
                        /// @notice Calls every target with corresponding data
                        /// @return Result True if calls to all targets returned True. Otherwise, false
                        function and(uint256 offsets, bytes calldata data) public view returns(bool) {
                            uint256 current;
                            uint256 previous;
                            for (uint256 i = 0; (current = uint32(offsets >> i)) != 0; i += 32) {
                                (bool success, uint256 res) = _selfStaticCall(data[previous:current]);
                                if (!success || res != 1) {
                                    return false;
                                }
                                previous = current;
                            }
                            return true;
                        }
                    
                        /// @notice Calls target with specified data and tests if it's equal to the value
                        /// @param value Value to test
                        /// @return Result True if call to target returns the same value as `value`. Otherwise, false
                        function eq(uint256 value, bytes calldata data) public view returns(bool) {
                            (bool success, uint256 res) = _selfStaticCall(data);
                            return success && res == value;
                        }
                    
                        /// @notice Calls target with specified data and tests if it's lower than value
                        /// @param value Value to test
                        /// @return Result True if call to target returns value which is lower than `value`. Otherwise, false
                        function lt(uint256 value, bytes calldata data) public view returns(bool) {
                            (bool success, uint256 res) = _selfStaticCall(data);
                            return success && res < value;
                        }
                    
                        /// @notice Calls target with specified data and tests if it's bigger than value
                        /// @param value Value to test
                        /// @return Result True if call to target returns value which is bigger than `value`. Otherwise, false
                        function gt(uint256 value, bytes calldata data) public view returns(bool) {
                            (bool success, uint256 res) = _selfStaticCall(data);
                            return success && res > value;
                        }
                    
                        /// @notice Checks passed time against block timestamp
                        /// @return Result True if current block timestamp is lower than `time`. Otherwise, false
                        function timestampBelow(uint256 time) public view returns(bool) {
                            return block.timestamp < time;  // solhint-disable-line not-rely-on-time
                        }
                    
                        /// @notice Performs an arbitrary call to target with data
                        /// @return Result Bytes transmuted to uint256
                        function arbitraryStaticCall(address target, bytes calldata data) public view returns(uint256) {
                            (bool success, uint256 res) = _staticcallForUint(target, data);
                            if (!success) revert ArbitraryStaticCallFailed();
                            return res;
                        }
                    
                        function timestampBelowAndNonceEquals(uint256 timeNonceAccount) public view returns(bool) {
                            uint256 _time = uint48(timeNonceAccount >> 208);
                            uint256 _nonce = uint48(timeNonceAccount >> 160);
                            address _account = address(uint160(timeNonceAccount));
                            return timestampBelow(_time) && nonceEquals(_account, _nonce);
                        }
                    
                        function _selfStaticCall(bytes calldata data) internal view returns(bool, uint256) {
                            uint256 selector = uint32(data.decodeSelector());
                            uint256 arg = data.decodeUint256(4);
                    
                            // special case for the most often used predicate
                            if (selector == uint32(this.timestampBelowAndNonceEquals.selector)) {  // 0x2cc2878d
                                return (true, timestampBelowAndNonceEquals(arg) ? 1 : 0);
                            }
                    
                            if (selector < uint32(this.arbitraryStaticCall.selector)) {  // 0xbf15fcd8
                                if (selector < uint32(this.eq.selector)) {  // 0x6fe7b0ba
                                    if (selector == uint32(this.gt.selector)) {  // 0x4f38e2b8
                                        return (true, gt(arg, data.decodeTailCalldata(100)) ? 1 : 0);
                                    } else if (selector == uint32(this.timestampBelow.selector)) {  // 0x63592c2b
                                        return (true, timestampBelow(arg) ? 1 : 0);
                                    }
                                } else {
                                    if (selector == uint32(this.eq.selector)) {  // 0x6fe7b0ba
                                        return (true, eq(arg, data.decodeTailCalldata(100)) ? 1 : 0);
                                    } else if (selector == uint32(this.or.selector)) {  // 0x74261145
                                        return (true, or(arg, data.decodeTailCalldata(100)) ? 1 : 0);
                                    }
                                }
                            } else {
                                if (selector < uint32(this.lt.selector)) {  // 0xca4ece22
                                    if (selector == uint32(this.arbitraryStaticCall.selector)) {  // 0xbf15fcd8
                                        return (true, arbitraryStaticCall(address(uint160(arg)), data.decodeTailCalldata(100)));
                                    } else if (selector == uint32(this.and.selector)) {  // 0xbfa75143
                                        return (true, and(arg, data.decodeTailCalldata(100)) ? 1 : 0);
                                    }
                                } else {
                                    if (selector == uint32(this.lt.selector)) {  // 0xca4ece22
                                        return (true, lt(arg, data.decodeTailCalldata(100)) ? 1 : 0);
                                    } else if (selector == uint32(this.nonceEquals.selector)) {  // 0xcf6fc6e3
                                        return (true, nonceEquals(address(uint160(arg)), data.decodeUint256(0x24)) ? 1 : 0);
                                    }
                                }
                            }
                    
                            return _staticcallForUint(address(this), data);
                        }
                    
                        function _staticcallForUint(address target, bytes calldata input) private view returns(bool success, uint256 res) {
                            /// @solidity memory-safe-assembly
                            assembly { // solhint-disable-line no-inline-assembly
                                let data := mload(0x40)
                    
                                calldatacopy(data, input.offset, input.length)
                                success := staticcall(gas(), target, data, input.length, 0x0, 0x20)
                                success := and(success, eq(returndatasize(), 32))
                                if success {
                                    res := mload(0)
                                }
                            }
                        }
                    }
                    
                    
                    // File @1inch/limit-order-protocol/contracts/interfaces/[email protected]
                    
                    
                    pragma solidity 0.8.17;
                    
                    interface IOrderMixin {
                        /**
                         * @notice Returns unfilled amount for order. Throws if order does not exist
                         * @param orderHash Order's hash. Can be obtained by the `hashOrder` function
                         * @return amount Unfilled amount
                         */
                        function remaining(bytes32 orderHash) external view returns(uint256 amount);
                    
                        /**
                         * @notice Returns unfilled amount for order
                         * @param orderHash Order's hash. Can be obtained by the `hashOrder` function
                         * @return rawAmount Unfilled amount of order plus one if order exists. Otherwise 0
                         */
                        function remainingRaw(bytes32 orderHash) external view returns(uint256 rawAmount);
                    
                        /**
                         * @notice Same as `remainingRaw` but for multiple orders
                         * @param orderHashes Array of hashes
                         * @return rawAmounts Array of amounts for each order plus one if order exists or 0 otherwise
                         */
                        function remainingsRaw(bytes32[] memory orderHashes) external view returns(uint256[] memory rawAmounts);
                    
                        /**
                         * @notice Checks order predicate
                         * @param order Order to check predicate for
                         * @return result Predicate evaluation result. True if predicate allows to fill the order, false otherwise
                         */
                        function checkPredicate(OrderLib.Order calldata order) external view returns(bool result);
                    
                        /**
                         * @notice Returns order hash according to EIP712 standard
                         * @param order Order to get hash for
                         * @return orderHash Hash of the order
                         */
                        function hashOrder(OrderLib.Order calldata order) external view returns(bytes32);
                    
                        /**
                         * @notice Delegates execution to custom implementation. Could be used to validate if `transferFrom` works properly
                         * @dev The function always reverts and returns the simulation results in revert data.
                         * @param target Addresses that will be delegated
                         * @param data Data that will be passed to delegatee
                         */
                        function simulate(address target, bytes calldata data) external;
                    
                        /**
                         * @notice Cancels order.
                         * @dev Order is cancelled by setting remaining amount to _ORDER_FILLED value
                         * @param order Order quote to cancel
                         * @return orderRemaining Unfilled amount of order before cancellation
                         * @return orderHash Hash of the filled order
                         */
                        function cancelOrder(OrderLib.Order calldata order) external returns(uint256 orderRemaining, bytes32 orderHash);
                    
                        /**
                         * @notice Fills an order. If one doesn't exist (first fill) it will be created using order.makerAssetData
                         * @param order Order quote to fill
                         * @param signature Signature to confirm quote ownership
                         * @param interaction A call data for InteractiveNotificationReceiver. Taker may execute interaction after getting maker assets and before sending taker assets.
                         * @param makingAmount Making amount
                         * @param takingAmount Taking amount
                         * @param skipPermitAndThresholdAmount Specifies maximum allowed takingAmount when takingAmount is zero, otherwise specifies minimum allowed makingAmount. Top-most bit specifies whether taker wants to skip maker's permit.
                         * @return actualMakingAmount Actual amount transferred from maker to taker
                         * @return actualTakingAmount Actual amount transferred from taker to maker
                         * @return orderHash Hash of the filled order
                         */
                        function fillOrder(
                            OrderLib.Order calldata order,
                            bytes calldata signature,
                            bytes calldata interaction,
                            uint256 makingAmount,
                            uint256 takingAmount,
                            uint256 skipPermitAndThresholdAmount
                        ) external payable returns(uint256 actualMakingAmount, uint256 actualTakingAmount, bytes32 orderHash);
                    
                        /**
                         * @notice Same as `fillOrderTo` but calls permit first,
                         * allowing to approve token spending and make a swap in one transaction.
                         * Also allows to specify funds destination instead of `msg.sender`
                         * @dev See tests for examples
                         * @param order Order quote to fill
                         * @param signature Signature to confirm quote ownership
                         * @param interaction A call data for InteractiveNotificationReceiver. Taker may execute interaction after getting maker assets and before sending taker assets.
                         * @param makingAmount Making amount
                         * @param takingAmount Taking amount
                         * @param skipPermitAndThresholdAmount Specifies maximum allowed takingAmount when takingAmount is zero, otherwise specifies minimum allowed makingAmount. Top-most bit specifies whether taker wants to skip maker's permit.
                         * @param target Address that will receive swap funds
                         * @param permit Should consist of abiencoded token address and encoded `IERC20Permit.permit` call.
                         * @return actualMakingAmount Actual amount transferred from maker to taker
                         * @return actualTakingAmount Actual amount transferred from taker to maker
                         * @return orderHash Hash of the filled order
                         */
                        function fillOrderToWithPermit(
                            OrderLib.Order calldata order,
                            bytes calldata signature,
                            bytes calldata interaction,
                            uint256 makingAmount,
                            uint256 takingAmount,
                            uint256 skipPermitAndThresholdAmount,
                            address target,
                            bytes calldata permit
                        ) external returns(uint256 actualMakingAmount, uint256 actualTakingAmount, bytes32 orderHash);
                    
                        /**
                         * @notice Same as `fillOrder` but allows to specify funds destination instead of `msg.sender`
                         * @param order_ Order quote to fill
                         * @param signature Signature to confirm quote ownership
                         * @param interaction A call data for InteractiveNotificationReceiver. Taker may execute interaction after getting maker assets and before sending taker assets.
                         * @param makingAmount Making amount
                         * @param takingAmount Taking amount
                         * @param skipPermitAndThresholdAmount Specifies maximum allowed takingAmount when takingAmount is zero, otherwise specifies minimum allowed makingAmount. Top-most bit specifies whether taker wants to skip maker's permit.
                         * @param target Address that will receive swap funds
                         * @return actualMakingAmount Actual amount transferred from maker to taker
                         * @return actualTakingAmount Actual amount transferred from taker to maker
                         * @return orderHash Hash of the filled order
                         */
                        function fillOrderTo(
                            OrderLib.Order calldata order_,
                            bytes calldata signature,
                            bytes calldata interaction,
                            uint256 makingAmount,
                            uint256 takingAmount,
                            uint256 skipPermitAndThresholdAmount,
                            address target
                        ) external payable returns(uint256 actualMakingAmount, uint256 actualTakingAmount, bytes32 orderHash);
                    }
                    
                    
                    // File @1inch/limit-order-protocol/contracts/interfaces/[email protected]
                    
                    
                    pragma solidity 0.8.17;
                    
                    /// @title Interface for interactor which acts between `maker => taker` and `taker => maker` transfers.
                    interface PreInteractionNotificationReceiver {
                        function fillOrderPreInteraction(
                            bytes32 orderHash,
                            address maker,
                            address taker,
                            uint256 makingAmount,
                            uint256 takingAmount,
                            uint256 remainingAmount,
                            bytes memory interactiveData
                        ) external;
                    }
                    
                    interface PostInteractionNotificationReceiver {
                        /// @notice Callback method that gets called after taker transferred funds to maker but before
                        /// the opposite transfer happened
                        function fillOrderPostInteraction(
                            bytes32 orderHash,
                            address maker,
                            address taker,
                            uint256 makingAmount,
                            uint256 takingAmount,
                            uint256 remainingAmount,
                            bytes memory interactiveData
                        ) external;
                    }
                    
                    interface InteractionNotificationReceiver {
                        function fillOrderInteraction(
                            address taker,
                            uint256 makingAmount,
                            uint256 takingAmount,
                            bytes memory interactiveData
                        ) external returns(uint256 offeredTakingAmount);
                    }
                    
                    
                    // File @1inch/limit-order-protocol/contracts/[email protected]
                    
                    
                    pragma solidity 0.8.17;
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    /// @title Regular Limit Order mixin
                    abstract contract OrderMixin is IOrderMixin, EIP712, PredicateHelper {
                        using SafeERC20 for IERC20;
                        using ArgumentsDecoder for bytes;
                        using OrderLib for OrderLib.Order;
                    
                        error UnknownOrder();
                        error AccessDenied();
                        error AlreadyFilled();
                        error PermitLengthTooLow();
                        error ZeroTargetIsForbidden();
                        error RemainingAmountIsZero();
                        error PrivateOrder();
                        error BadSignature();
                        error ReentrancyDetected();
                        error PredicateIsNotTrue();
                        error OnlyOneAmountShouldBeZero();
                        error TakingAmountTooHigh();
                        error MakingAmountTooLow();
                        error SwapWithZeroAmount();
                        error TransferFromMakerToTakerFailed();
                        error TransferFromTakerToMakerFailed();
                        error WrongAmount();
                        error WrongGetter();
                        error GetAmountCallFailed();
                        error TakingAmountIncreased();
                        error SimulationResults(bool success, bytes res);
                    
                        /// @notice Emitted every time order gets filled, including partial fills
                        event OrderFilled(
                            address indexed maker,
                            bytes32 orderHash,
                            uint256 remaining
                        );
                    
                        /// @notice Emitted when order gets cancelled
                        event OrderCanceled(
                            address indexed maker,
                            bytes32 orderHash,
                            uint256 remainingRaw
                        );
                    
                        uint256 constant private _ORDER_DOES_NOT_EXIST = 0;
                        uint256 constant private _ORDER_FILLED = 1;
                        uint256 constant private _SKIP_PERMIT_FLAG = 1 << 255;
                        uint256 constant private _THRESHOLD_MASK = ~_SKIP_PERMIT_FLAG;
                    
                        IWETH private immutable _WETH;  // solhint-disable-line var-name-mixedcase
                        /// @notice Stores unfilled amounts for each order plus one.
                        /// Therefore 0 means order doesn't exist and 1 means order was filled
                        mapping(bytes32 => uint256) private _remaining;
                    
                        constructor(IWETH weth) {
                            _WETH = weth;
                        }
                    
                        /**
                         * @notice See {IOrderMixin-remaining}.
                         */
                        function remaining(bytes32 orderHash) external view returns(uint256 /* amount */) {
                            uint256 amount = _remaining[orderHash];
                            if (amount == _ORDER_DOES_NOT_EXIST) revert UnknownOrder();
                            unchecked { return amount - 1; }
                        }
                    
                        /**
                         * @notice See {IOrderMixin-remainingRaw}.
                         */
                        function remainingRaw(bytes32 orderHash) external view returns(uint256 /* rawAmount */) {
                            return _remaining[orderHash];
                        }
                    
                        /**
                         * @notice See {IOrderMixin-remainingsRaw}.
                         */
                        function remainingsRaw(bytes32[] memory orderHashes) external view returns(uint256[] memory /* rawAmounts */) {
                            uint256[] memory results = new uint256[](orderHashes.length);
                            for (uint256 i = 0; i < orderHashes.length; i++) {
                                results[i] = _remaining[orderHashes[i]];
                            }
                            return results;
                        }
                    
                        /**
                         * @notice See {IOrderMixin-simulate}.
                         */
                        function simulate(address target, bytes calldata data) external {
                            // solhint-disable-next-line avoid-low-level-calls
                            (bool success, bytes memory result) = target.delegatecall(data);
                            revert SimulationResults(success, result);
                        }
                    
                        /**
                         * @notice See {IOrderMixin-cancelOrder}.
                         */
                        function cancelOrder(OrderLib.Order calldata order) external returns(uint256 orderRemaining, bytes32 orderHash) {
                            if (order.maker != msg.sender) revert AccessDenied();
                    
                            orderHash = hashOrder(order);
                            orderRemaining = _remaining[orderHash];
                            if (orderRemaining == _ORDER_FILLED) revert AlreadyFilled();
                            emit OrderCanceled(msg.sender, orderHash, orderRemaining);
                            _remaining[orderHash] = _ORDER_FILLED;
                        }
                    
                        /**
                         * @notice See {IOrderMixin-fillOrder}.
                         */
                        function fillOrder(
                            OrderLib.Order calldata order,
                            bytes calldata signature,
                            bytes calldata interaction,
                            uint256 makingAmount,
                            uint256 takingAmount,
                            uint256 skipPermitAndThresholdAmount
                        ) external payable returns(uint256 /* actualMakingAmount */, uint256 /* actualTakingAmount */, bytes32 /* orderHash */) {
                            return fillOrderTo(order, signature, interaction, makingAmount, takingAmount, skipPermitAndThresholdAmount, msg.sender);
                        }
                    
                        /**
                         * @notice See {IOrderMixin-fillOrderToWithPermit}.
                         */
                        function fillOrderToWithPermit(
                            OrderLib.Order calldata order,
                            bytes calldata signature,
                            bytes calldata interaction,
                            uint256 makingAmount,
                            uint256 takingAmount,
                            uint256 skipPermitAndThresholdAmount,
                            address target,
                            bytes calldata permit
                        ) external returns(uint256 /* actualMakingAmount */, uint256 /* actualTakingAmount */, bytes32 /* orderHash */) {
                            if (permit.length < 20) revert PermitLengthTooLow();
                            {  // Stack too deep
                                (address token, bytes calldata permitData) = permit.decodeTargetAndCalldata();
                                IERC20(token).safePermit(permitData);
                            }
                            return fillOrderTo(order, signature, interaction, makingAmount, takingAmount, skipPermitAndThresholdAmount, target);
                        }
                    
                        /**
                         * @notice See {IOrderMixin-fillOrderTo}.
                         */
                        function fillOrderTo(
                            OrderLib.Order calldata order_,
                            bytes calldata signature,
                            bytes calldata interaction,
                            uint256 makingAmount,
                            uint256 takingAmount,
                            uint256 skipPermitAndThresholdAmount,
                            address target
                        ) public payable returns(uint256 actualMakingAmount, uint256 actualTakingAmount, bytes32 orderHash) {
                            if (target == address(0)) revert ZeroTargetIsForbidden();
                            orderHash = hashOrder(order_);
                    
                            OrderLib.Order calldata order = order_; // Helps with "Stack too deep"
                            actualMakingAmount = makingAmount;
                            actualTakingAmount = takingAmount;
                    
                            uint256 remainingMakingAmount = _remaining[orderHash];
                            if (remainingMakingAmount == _ORDER_FILLED) revert RemainingAmountIsZero();
                            if (order.allowedSender != address(0) && order.allowedSender != msg.sender) revert PrivateOrder();
                            if (remainingMakingAmount == _ORDER_DOES_NOT_EXIST) {
                                // First fill: validate order and permit maker asset
                                if (!ECDSA.recoverOrIsValidSignature(order.maker, orderHash, signature)) revert BadSignature();
                                remainingMakingAmount = order.makingAmount;
                    
                                bytes calldata permit = order.permit();
                                if (skipPermitAndThresholdAmount & _SKIP_PERMIT_FLAG == 0 && permit.length >= 20) {
                                    // proceed only if taker is willing to execute permit and its length is enough to store address
                                    (address token, bytes calldata permitCalldata) = permit.decodeTargetAndCalldata();
                                    IERC20(token).safePermit(permitCalldata);
                                    if (_remaining[orderHash] != _ORDER_DOES_NOT_EXIST) revert ReentrancyDetected();
                                }
                            } else {
                                unchecked { remainingMakingAmount -= 1; }
                            }
                    
                            // Check if order is valid
                            if (order.predicate().length > 0) {
                                if (!checkPredicate(order)) revert PredicateIsNotTrue();
                            }
                    
                            // Compute maker and taker assets amount
                            if ((actualTakingAmount == 0) == (actualMakingAmount == 0)) {
                                revert OnlyOneAmountShouldBeZero();
                            } else if (actualTakingAmount == 0) {
                                if (actualMakingAmount > remainingMakingAmount) {
                                    actualMakingAmount = remainingMakingAmount;
                                }
                                actualTakingAmount = _getTakingAmount(order.getTakingAmount(), order.makingAmount, actualMakingAmount, order.takingAmount, remainingMakingAmount, orderHash);
                                uint256 thresholdAmount = skipPermitAndThresholdAmount & _THRESHOLD_MASK;
                                // check that actual rate is not worse than what was expected
                                // actualTakingAmount / actualMakingAmount <= thresholdAmount / makingAmount
                                if (actualTakingAmount * makingAmount > thresholdAmount * actualMakingAmount) revert TakingAmountTooHigh();
                            } else {
                                actualMakingAmount = _getMakingAmount(order.getMakingAmount(), order.takingAmount, actualTakingAmount, order.makingAmount, remainingMakingAmount, orderHash);
                                if (actualMakingAmount > remainingMakingAmount) {
                                    actualMakingAmount = remainingMakingAmount;
                                    actualTakingAmount = _getTakingAmount(order.getTakingAmount(), order.makingAmount, actualMakingAmount, order.takingAmount, remainingMakingAmount, orderHash);
                                    if (actualTakingAmount > takingAmount) revert TakingAmountIncreased();
                                }
                                uint256 thresholdAmount = skipPermitAndThresholdAmount & _THRESHOLD_MASK;
                                // check that actual rate is not worse than what was expected
                                // actualMakingAmount / actualTakingAmount >= thresholdAmount / takingAmount
                                if (actualMakingAmount * takingAmount < thresholdAmount * actualTakingAmount) revert MakingAmountTooLow();
                            }
                    
                            if (actualMakingAmount == 0 || actualTakingAmount == 0) revert SwapWithZeroAmount();
                    
                            // Update remaining amount in storage
                            unchecked {
                                remainingMakingAmount = remainingMakingAmount - actualMakingAmount;
                                _remaining[orderHash] = remainingMakingAmount + 1;
                            }
                            emit OrderFilled(order_.maker, orderHash, remainingMakingAmount);
                    
                            // Maker can handle funds interactively
                            if (order.preInteraction().length >= 20) {
                                // proceed only if interaction length is enough to store address
                                (address interactionTarget, bytes calldata interactionData) = order.preInteraction().decodeTargetAndCalldata();
                                PreInteractionNotificationReceiver(interactionTarget).fillOrderPreInteraction(
                                    orderHash, order.maker, msg.sender, actualMakingAmount, actualTakingAmount, remainingMakingAmount, interactionData
                                );
                            }
                    
                            // Maker => Taker
                            if (!_callTransferFrom(
                                order.makerAsset,
                                order.maker,
                                target,
                                actualMakingAmount,
                                order.makerAssetData()
                            )) revert TransferFromMakerToTakerFailed();
                    
                            if (interaction.length >= 20) {
                                // proceed only if interaction length is enough to store address
                                (address interactionTarget, bytes calldata interactionData) = interaction.decodeTargetAndCalldata();
                                uint256 offeredTakingAmount = InteractionNotificationReceiver(interactionTarget).fillOrderInteraction(
                                    msg.sender, actualMakingAmount, actualTakingAmount, interactionData
                                );
                    
                                if (offeredTakingAmount > actualTakingAmount &&
                                    !OrderLib.getterIsFrozen(order.getMakingAmount()) &&
                                    !OrderLib.getterIsFrozen(order.getTakingAmount()))
                                {
                                    actualTakingAmount = offeredTakingAmount;
                                }
                            }
                    
                            // Taker => Maker
                            if (order.takerAsset == address(_WETH) && msg.value > 0) {
                                if (msg.value < actualTakingAmount) revert Errors.InvalidMsgValue();
                                if (msg.value > actualTakingAmount) {
                                    unchecked {
                                        (bool success, ) = msg.sender.call{value: msg.value - actualTakingAmount}("");  // solhint-disable-line avoid-low-level-calls
                                        if (!success) revert Errors.ETHTransferFailed();
                                    }
                                }
                                _WETH.deposit{ value: actualTakingAmount }();
                                _WETH.transfer(order.receiver == address(0) ? order.maker : order.receiver, actualTakingAmount);
                            } else {
                                if (msg.value != 0) revert Errors.InvalidMsgValue();
                                if (!_callTransferFrom(
                                    order.takerAsset,
                                    msg.sender,
                                    order.receiver == address(0) ? order.maker : order.receiver,
                                    actualTakingAmount,
                                    order.takerAssetData()
                                )) revert TransferFromTakerToMakerFailed();
                            }
                    
                            // Maker can handle funds interactively
                            if (order.postInteraction().length >= 20) {
                                // proceed only if interaction length is enough to store address
                                (address interactionTarget, bytes calldata interactionData) = order.postInteraction().decodeTargetAndCalldata();
                                PostInteractionNotificationReceiver(interactionTarget).fillOrderPostInteraction(
                                     orderHash, order.maker, msg.sender, actualMakingAmount, actualTakingAmount, remainingMakingAmount, interactionData
                                );
                            }
                        }
                    
                        /**
                         * @notice See {IOrderMixin-checkPredicate}.
                         */
                        function checkPredicate(OrderLib.Order calldata order) public view returns(bool) {
                            (bool success, uint256 res) = _selfStaticCall(order.predicate());
                            return success && res == 1;
                        }
                    
                        /**
                         * @notice See {IOrderMixin-hashOrder}.
                         */
                        function hashOrder(OrderLib.Order calldata order) public view returns(bytes32) {
                            return order.hash(_domainSeparatorV4());
                        }
                    
                        function _callTransferFrom(address asset, address from, address to, uint256 amount, bytes calldata input) private returns(bool success) {
                            bytes4 selector = IERC20.transferFrom.selector;
                            /// @solidity memory-safe-assembly
                            assembly { // solhint-disable-line no-inline-assembly
                                let data := mload(0x40)
                    
                                mstore(data, selector)
                                mstore(add(data, 0x04), from)
                                mstore(add(data, 0x24), to)
                                mstore(add(data, 0x44), amount)
                                calldatacopy(add(data, 0x64), input.offset, input.length)
                                let status := call(gas(), asset, 0, data, add(0x64, input.length), 0x0, 0x20)
                                success := and(status, or(iszero(returndatasize()), and(gt(returndatasize(), 31), eq(mload(0), 1))))
                            }
                        }
                    
                        function _getMakingAmount(
                            bytes calldata getter,
                            uint256 orderTakingAmount,
                            uint256 requestedTakingAmount,
                            uint256 orderMakingAmount,
                            uint256 remainingMakingAmount,
                            bytes32 orderHash
                        ) private view returns(uint256) {
                            if (getter.length == 0) {
                                // Linear proportion
                                return AmountCalculator.getMakingAmount(orderMakingAmount, orderTakingAmount, requestedTakingAmount);
                            }
                            return _callGetter(getter, orderTakingAmount, requestedTakingAmount, orderMakingAmount, remainingMakingAmount, orderHash);
                        }
                    
                        function _getTakingAmount(
                            bytes calldata getter,
                            uint256 orderMakingAmount,
                            uint256 requestedMakingAmount,
                            uint256 orderTakingAmount,
                            uint256 remainingMakingAmount,
                            bytes32 orderHash
                        ) private view returns(uint256) {
                            if (getter.length == 0) {
                                // Linear proportion
                                return AmountCalculator.getTakingAmount(orderMakingAmount, orderTakingAmount, requestedMakingAmount);
                            }
                            return _callGetter(getter, orderMakingAmount, requestedMakingAmount, orderTakingAmount, remainingMakingAmount, orderHash);
                        }
                    
                        function _callGetter(
                            bytes calldata getter,
                            uint256 orderExpectedAmount,
                            uint256 requestedAmount,
                            uint256 orderResultAmount,
                            uint256 remainingMakingAmount,
                            bytes32 orderHash
                        ) private view returns(uint256) {
                            if (getter.length == 1) {
                                if (OrderLib.getterIsFrozen(getter)) {
                                    // On "x" getter calldata only exact amount is allowed
                                    if (requestedAmount != orderExpectedAmount) revert WrongAmount();
                                    return orderResultAmount;
                                } else {
                                    revert WrongGetter();
                                }
                            } else {
                                (address target, bytes calldata data) = getter.decodeTargetAndCalldata();
                                (bool success, bytes memory result) = target.staticcall(abi.encodePacked(data, requestedAmount, remainingMakingAmount, orderHash));
                                if (!success || result.length != 32) revert GetAmountCallFailed();
                                return abi.decode(result, (uint256));
                            }
                        }
                    }
                    
                    
                    // File @openzeppelin/contracts/utils/[email protected]
                    
                    // OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
                    
                    pragma solidity ^0.8.0;
                    
                    /**
                     * @dev Provides information about the current execution context, including the
                     * sender of the transaction and its data. While these are generally available
                     * via msg.sender and msg.data, they should not be accessed in such a direct
                     * manner, since when dealing with meta-transactions the account sending and
                     * paying for execution may not be the actual sender (as far as an application
                     * is concerned).
                     *
                     * This contract is only required for intermediate, library-like contracts.
                     */
                    abstract contract Context {
                        function _msgSender() internal view virtual returns (address) {
                            return msg.sender;
                        }
                    
                        function _msgData() internal view virtual returns (bytes calldata) {
                            return msg.data;
                        }
                    }
                    
                    
                    // File @openzeppelin/contracts/access/[email protected]
                    
                    // OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)
                    
                    pragma solidity ^0.8.0;
                    
                    /**
                     * @dev Contract module which provides a basic access control mechanism, where
                     * there is an account (an owner) that can be granted exclusive access to
                     * specific functions.
                     *
                     * By default, the owner account will be the one that deploys the contract. This
                     * can later be changed with {transferOwnership}.
                     *
                     * This module is used through inheritance. It will make available the modifier
                     * `onlyOwner`, which can be applied to your functions to restrict their use to
                     * the owner.
                     */
                    abstract contract Ownable is Context {
                        address private _owner;
                    
                        event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                    
                        /**
                         * @dev Initializes the contract setting the deployer as the initial owner.
                         */
                        constructor() {
                            _transferOwnership(_msgSender());
                        }
                    
                        /**
                         * @dev Throws if called by any account other than the owner.
                         */
                        modifier onlyOwner() {
                            _checkOwner();
                            _;
                        }
                    
                        /**
                         * @dev Returns the address of the current owner.
                         */
                        function owner() public view virtual returns (address) {
                            return _owner;
                        }
                    
                        /**
                         * @dev Throws if the sender is not the owner.
                         */
                        function _checkOwner() internal view virtual {
                            require(owner() == _msgSender(), "Ownable: caller is not the owner");
                        }
                    
                        /**
                         * @dev Leaves the contract without owner. It will not be possible to call
                         * `onlyOwner` functions anymore. Can only be called by the current owner.
                         *
                         * NOTE: Renouncing ownership will leave the contract without an owner,
                         * thereby removing any functionality that is only available to the owner.
                         */
                        function renounceOwnership() public virtual onlyOwner {
                            _transferOwnership(address(0));
                        }
                    
                        /**
                         * @dev Transfers ownership of the contract to a new account (`newOwner`).
                         * Can only be called by the current owner.
                         */
                        function transferOwnership(address newOwner) public virtual onlyOwner {
                            require(newOwner != address(0), "Ownable: new owner is the zero address");
                            _transferOwnership(newOwner);
                        }
                    
                        /**
                         * @dev Transfers ownership of the contract to a new account (`newOwner`).
                         * Internal function without access restriction.
                         */
                        function _transferOwnership(address newOwner) internal virtual {
                            address oldOwner = _owner;
                            _owner = newOwner;
                            emit OwnershipTransferred(oldOwner, newOwner);
                        }
                    }
                    
                    
                    // File contracts/AggregationRouterV5.sol
                    
                    
                    pragma solidity 0.8.17;
                    
                    
                    
                    
                    
                    
                    
                    
                    
                    /// @notice Main contract incorporates a number of routers to perform swaps and limit orders protocol to fill limit orders
                    contract AggregationRouterV5 is EIP712("1inch Aggregation Router", "5"), Ownable,
                        ClipperRouter, GenericRouter, UnoswapRouter, UnoswapV3Router, OrderMixin, OrderRFQMixin
                    {
                        using UniERC20 for IERC20;
                    
                        error ZeroAddress();
                    
                        /**
                         * @dev Sets the wrapped eth token and clipper exhange interface
                         * Both values are immutable: they can only be set once during
                         * construction.
                         */
                        constructor(IWETH weth)
                            UnoswapV3Router(weth)
                            ClipperRouter(weth)
                            OrderMixin(weth)
                            OrderRFQMixin(weth)
                        {
                            if (address(weth) == address(0)) revert ZeroAddress();
                        }
                    
                        /**
                         * @notice Retrieves funds accidently sent directly to the contract address
                         * @param token ERC20 token to retrieve
                         * @param amount amount to retrieve
                         */
                        function rescueFunds(IERC20 token, uint256 amount) external onlyOwner {
                            token.uniTransfer(payable(msg.sender), amount);
                        }
                    
                        /**
                         * @notice Destroys the contract and sends eth to sender. Use with caution.
                         * The only case when the use of the method is justified is if there is an exploit found.
                         * And the damage from the exploit is greater than from just an urgent contract change.
                         */
                        function destroy() external onlyOwner {
                            selfdestruct(payable(msg.sender));
                        }
                    
                        function _receive() internal override(EthReceiver, OnlyWethReceiver) {
                            EthReceiver._receive();
                        }
                    }