ETH Price: $2,440.84 (-0.02%)

Transaction Decoder

Block:
21231062 at Nov-20-2024 07:33:59 PM +UTC
Transaction Fee:
0.008133457017394546 ETH $19.85
Gas Used:
458,681 Gas / 17.732273666 Gwei

Emitted Events:

146 UnifiedRouterV2.FeePaid( payer=[Sender] 0x5f023a855586ebb99f6261697363375a7a5e13ab, accountant=0x94a365ca808029af8db18257ecd296c16c61ac05, executionPrice=1149695388169 )
147 WETH9.Deposit( dst=[Receiver] UnifiedRouterV2, wad=230000000000000000 )
148 WETH9.Transfer( src=[Receiver] UnifiedRouterV2, dst=PortalV2, wad=230000000000000000 )
149 PortalV2.Locked( token=WETH9, amount=230000000000000000, from=PortalV2, to=[Receiver] UnifiedRouterV2 )
150 GateKeeper.CrossChainCallPaid( sender=[Receiver] UnifiedRouterV2, token=0x00000000...000000000, transactionCost=0 )
151 BridgeV2.RequestSent( requestId=7D15298CCF6C4AB8A2378BDE5A702240D824B62101B1F93065C26C5AA51DEDE6, data=0x0000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000058000000000000000000000000000000000000000000000000000000000000005046B750D637D15298CCF6C4AB8A2378BDE5A702240D824B62101B1F93065C26C5AA51DEDE60000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000001C00000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000A000000000000000000000000000000000000000000000000000000000000000E00000000000000000000000000000000000000000000000000000000000000001570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000024C4D0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001410000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000030000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000080000000000000000000000000C02AAA39B223FE8D0A0E5C4F27EAD9083C756CC200000000000000000000000000000000000000000000000003311FC80A5700000000000000000000000000005F023A855586EBB99F6261697363375A7A5E13AB000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000E0000000000000000000000000C02AAA39B223FE8D0A0E5C4F27EAD9083C756CC200000000000000000000000000000000000000000000000003311FC80A570000000000000000000000000000AC8F44CECA92B2A4B30360E5BD3043850A0FFCBE000000000000000000000000A2A786FF9148F7C88EE93372DB8CBE9E94585C7400000000000000000000000000000000000000000000000000000000000000FA00000000000000000000000000000000000000000000000000000000000000010000000000000000000000005F023A855586EBB99F6261697363375A7A5E13AB00000000000000000000000000000000000000000000000000000000000001000000000000000000000000000C935328A69155DD43AA57F23288D868BAE440FEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000000000000000000000000000000000000000000000000000000000000000000000000000005F023A855586EBB99F6261697363375A7A5E13AB0000000000000000000000003C2FCF53F742345C5C1B3DCB2612A1949BC1F18D000000000000000000000000000000000000000000000000032CF7E7AE05053A00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000064B4CCCA0D6B750D6300000000000000000000000000000000000000000000000000000000000000000000000000000000A2A786FF9148F7C88EE93372DB8CBE9E94585C74000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000, to=[Receiver] UnifiedRouterV2, chainIdTo=250 )
152 UnifiedRouterV2.ComplexOpProcessed( currentChainId=1, currentRequestId=0000000000000000000000000000000000000000000000000000000000000000, nextChainId=250, nextRequestId=7D15298CCF6C4AB8A2378BDE5A702240D824B62101B1F93065C26C5AA51DEDE6, result=1, lastOp=1 )

Account State Difference:

  Address   Before After State Difference Code
0x5f023a85...A7A5E13aB
0.293702459653581514 Eth
Nonce: 93
0.055567852940798799 Eth
Nonce: 94
0.238134606712782715
0x94a365CA...16C61AC05 0.282789226392511075 Eth0.282790376087899244 Eth0.000001149695388169
(beaverbuild)
17.226738254421450023 Eth17.227387843690411 Eth0.000649589268960977
0xA2A786ff...e94585c74
0xAc8f44ce...50a0FFcbE
(Eywa: CLP Portal)
0xC02aaA39...83C756Cc2 2,929,395.918417260841529217 Eth2,929,396.148417260841529217 Eth0.23
0xEce9CF6A...AfEAa5167

Execution Trace

ETH 0.230001149695388169 UnifiedRouterV2.start( operations=[W, LM, A], params=[AAAAAAAAAAAAAAAAwCqqObIj/o0KDlxPJ+rZCDx1bMIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADMR/IClcAAAAAAAAAAAAAAAAAAF8COoVVhuu5n2JhaXNjN1p6XhOrAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=, AAAAAAAAAAAAAAAAwCqqObIj/o0KDlxPJ+rZCDx1bML//////////////////////////////////////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA+gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAXwI6hVWG67mfYmFpc2M3WnpeE6s=, AAAAAAAAAAAAAAAADJNTKKaRVd1DqlfyMojYaLrkQP7//////////////////////////////////////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAXwI6hVWG67mfYmFpc2M3WnpeE6sAAAAAAAAAAAAAAAA8L89T90I0XFwbPcsmEqGUm8HxjQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMs9+euBQU6AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==], receipt=[{name:executionPrice, type:uint256, order:1, indexed:false, value:1149695388169, valueString:1149695388169}, {name:deadline, type:uint256, order:2, indexed:false, value:1732131491, valueString:1732131491}, {name:v, type:uint8, order:3, indexed:false, value:27, valueString:27}, {name:r, type:bytes32, order:4, indexed:false, value:D89EBFB9A706E59F09585FDD5511FB36F69277489B98762F4334C76A762641D3, valueString:D89EBFB9A706E59F09585FDD5511FB36F69277489B98762F4334C76A762641D3}, {name:s, type:bytes32, order:5, indexed:false, value:6EC28487D115A12F1CF1C32DEA8FEF587968D55F5EFF4BAA08415B6E73651D85, valueString:6EC28487D115A12F1CF1C32DEA8FEF587968D55F5EFF4BAA08415B6E73651D85}] )
  • AddressBook.STATICCALL( )
  • OpsRegistrar.ops( 0F230C0C132A01F489898FE02F55A17248BBE924052C3C0E78E54D329739DD77 ) => ( True )
  • Null: 0x000...001.feac8127( )
  • ETH 0.000001149695388169 0x94a365ca808029af8db18257ecd296c16c61ac05.CALL( )
  • AddressBook.portal( 1 ) => ( 0xAc8f44ceCa92b2a4b30360E5bd3043850a0FFcbE )
  • ETH 0.23 WETH9.CALL( )
  • WETH9.transfer( dst=0xAc8f44ceCa92b2a4b30360E5bd3043850a0FFcbE, wad=230000000000000000 ) => ( True )
  • AddressBook.router( 250 ) => ( 0xA2A786ff9148f7C88EE93372Db8CBe9e94585c74 )
  • AddressBook.portal( 1 ) => ( 0xAc8f44ceCa92b2a4b30360E5bd3043850a0FFcbE )
  • PortalV2.lock( token=0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, amount=230000000000000000, from=0xAc8f44ceCa92b2a4b30360E5bd3043850a0FFcbE, to=0xA2A786ff9148f7C88EE93372Db8CBe9e94585c74 )
    • AddressBook.router( 1 ) => ( 0xA2A786ff9148f7C88EE93372Db8CBe9e94585c74 )
    • AddressBook.STATICCALL( )
    • WhitelistV2.tokenMin( token_=0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 ) => ( 1000000000000000 )
    • WhitelistV2.tokenMax( token_=0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 ) => ( 80000000000000000000 )
    • AddressBook.STATICCALL( )
    • WhitelistV2.tokenState( token_=0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 ) => ( 1 )
    • WETH9.balanceOf( 0xAc8f44ceCa92b2a4b30360E5bd3043850a0FFcbE ) => ( 119626381280789458734 )
    • AddressBook.router( 250 ) => ( 0xA2A786ff9148f7C88EE93372Db8CBe9e94585c74 )
    • AddressBook.STATICCALL( )
    • GateKeeper.STATICCALL( )
      • BridgeV2.nonces( 0xA2A786ff9148f7C88EE93372Db8CBe9e94585c74 ) => ( 596 )
      • AddressBook.STATICCALL( )
      • GateKeeper.sendData( data=0x6B750D637D15298CCF6C4AB8A2378BDE5A702240D824B62101B1F93065C26C5AA51DEDE60000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000001C00000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000A000000000000000000000000000000000000000000000000000000000000000E00000000000000000000000000000000000000000000000000000000000000001570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000024C4D0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001410000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000030000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000080000000000000000000000000C02AAA39B223FE8D0A0E5C4F27EAD9083C756CC200000000000000000000000000000000000000000000000003311FC80A5700000000000000000000000000005F023A855586EBB99F6261697363375A7A5E13AB000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000E0000000000000000000000000C02AAA39B223FE8D0A0E5C4F27EAD9083C756CC200000000000000000000000000000000000000000000000003311FC80A570000000000000000000000000000AC8F44CECA92B2A4B30360E5BD3043850A0FFCBE000000000000000000000000A2A786FF9148F7C88EE93372DB8CBE9E94585C7400000000000000000000000000000000000000000000000000000000000000FA00000000000000000000000000000000000000000000000000000000000000010000000000000000000000005F023A855586EBB99F6261697363375A7A5E13AB00000000000000000000000000000000000000000000000000000000000001000000000000000000000000000C935328A69155DD43AA57F23288D868BAE440FEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000000000000000000000000000000000000000000000000000000000000000000000000000005F023A855586EBB99F6261697363375A7A5E13AB0000000000000000000000003C2FCF53F742345C5C1B3DCB2612A1949BC1F18D000000000000000000000000000000000000000000000000032CF7E7AE05053A00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000, to=0xA2A786ff9148f7C88EE93372Db8CBe9e94585c74, chainIdTo=250, payToken=0x0000000000000000000000000000000000000000 )
        • BridgeV2.nonces( 0xA2A786ff9148f7C88EE93372Db8CBe9e94585c74 ) => ( 596 )
        • BridgeV2.sendV2( params=[{name:requestId, type:bytes32, order:1, indexed:false, value:7D15298CCF6C4AB8A2378BDE5A702240D824B62101B1F93065C26C5AA51DEDE6, valueString:7D15298CCF6C4AB8A2378BDE5A702240D824B62101B1F93065C26C5AA51DEDE6}, {name:data, type:bytes, order:2, indexed:false, value:0x0000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000058000000000000000000000000000000000000000000000000000000000000005046B750D637D15298CCF6C4AB8A2378BDE5A702240D824B62101B1F93065C26C5AA51DEDE60000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000001C00000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000A000000000000000000000000000000000000000000000000000000000000000E00000000000000000000000000000000000000000000000000000000000000001570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000024C4D0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001410000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000030000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000080000000000000000000000000C02AAA39B223FE8D0A0E5C4F27EAD9083C756CC200000000000000000000000000000000000000000000000003311FC80A5700000000000000000000000000005F023A855586EBB99F6261697363375A7A5E13AB000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000E0000000000000000000000000C02AAA39B223FE8D0A0E5C4F27EAD9083C756CC200000000000000000000000000000000000000000000000003311FC80A570000000000000000000000000000AC8F44CECA92B2A4B30360E5BD3043850A0FFCBE000000000000000000000000A2A786FF9148F7C88EE93372DB8CBE9E94585C7400000000000000000000000000000000000000000000000000000000000000FA00000000000000000000000000000000000000000000000000000000000000010000000000000000000000005F023A855586EBB99F6261697363375A7A5E13AB00000000000000000000000000000000000000000000000000000000000001000000000000000000000000000C935328A69155DD43AA57F23288D868BAE440FEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000000000000000000000000000000000000000000000000000000000000000000000000000005F023A855586EBB99F6261697363375A7A5E13AB0000000000000000000000003C2FCF53F742345C5C1B3DCB2612A1949BC1F18D000000000000000000000000000000000000000000000000032CF7E7AE05053A00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000064B4CCCA0D6B750D6300000000000000000000000000000000000000000000000000000000000000000000000000000000A2A786FF9148F7C88EE93372DB8CBE9E94585C74000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000, valueString:0x0000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000058000000000000000000000000000000000000000000000000000000000000005046B750D637D15298CCF6C4AB8A2378BDE5A702240D824B62101B1F93065C26C5AA51DEDE60000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000001C00000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000A000000000000000000000000000000000000000000000000000000000000000E00000000000000000000000000000000000000000000000000000000000000001570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000024C4D0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001410000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000030000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000080000000000000000000000000C02AAA39B223FE8D0A0E5C4F27EAD9083C756CC200000000000000000000000000000000000000000000000003311FC80A5700000000000000000000000000005F023A855586EBB99F6261697363375A7A5E13AB000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000E0000000000000000000000000C02AAA39B223FE8D0A0E5C4F27EAD9083C756CC200000000000000000000000000000000000000000000000003311FC80A570000000000000000000000000000AC8F44CECA92B2A4B30360E5BD3043850A0FFCBE000000000000000000000000A2A786FF9148F7C88EE93372DB8CBE9E94585C7400000000000000000000000000000000000000000000000000000000000000FA00000000000000000000000000000000000000000000000000000000000000010000000000000000000000005F023A855586EBB99F6261697363375A7A5E13AB00000000000000000000000000000000000000000000000000000000000001000000000000000000000000000C935328A69155DD43AA57F23288D868BAE440FEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000000000000000000000000000000000000000000000000000000000000000000000000000005F023A855586EBB99F6261697363375A7A5E13AB0000000000000000000000003C2FCF53F742345C5C1B3DCB2612A1949BC1F18D000000000000000000000000000000000000000000000000032CF7E7AE05053A00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000064B4CCCA0D6B750D6300000000000000000000000000000000000000000000000000000000000000000000000000000000A2A786FF9148F7C88EE93372DB8CBE9E94585C74000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000}, {name:to, type:address, order:3, indexed:false, value:0xA2A786ff9148f7C88EE93372Db8CBe9e94585c74, valueString:0xA2A786ff9148f7C88EE93372Db8CBe9e94585c74}, {name:chainIdTo, type:uint256, order:4, indexed:false, value:250, valueString:250}], from=0xA2A786ff9148f7C88EE93372Db8CBe9e94585c74, nonce=596 ) => ( True )
          File 1 of 8: UnifiedRouterV2
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (access/AccessControl.sol)
          pragma solidity ^0.8.0;
          import "./IAccessControl.sol";
          import "../utils/Context.sol";
          import "../utils/Strings.sol";
          import "../utils/introspection/ERC165.sol";
          /**
           * @dev Contract module that allows children to implement role-based access
           * control mechanisms. This is a lightweight version that doesn't allow enumerating role
           * members except through off-chain means by accessing the contract event logs. Some
           * applications may benefit from on-chain enumerability, for those cases see
           * {AccessControlEnumerable}.
           *
           * Roles are referred to by their `bytes32` identifier. These should be exposed
           * in the external API and be unique. The best way to achieve this is by
           * using `public constant` hash digests:
           *
           * ```solidity
           * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
           * ```
           *
           * Roles can be used to represent a set of permissions. To restrict access to a
           * function call, use {hasRole}:
           *
           * ```solidity
           * function foo() public {
           *     require(hasRole(MY_ROLE, msg.sender));
           *     ...
           * }
           * ```
           *
           * Roles can be granted and revoked dynamically via the {grantRole} and
           * {revokeRole} functions. Each role has an associated admin role, and only
           * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
           *
           * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
           * that only accounts with this role will be able to grant or revoke other
           * roles. More complex role relationships can be created by using
           * {_setRoleAdmin}.
           *
           * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
           * grant and revoke this role. Extra precautions should be taken to secure
           * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
           * to enforce additional security measures for this role.
           */
          abstract contract AccessControl is Context, IAccessControl, ERC165 {
              struct RoleData {
                  mapping(address => bool) members;
                  bytes32 adminRole;
              }
              mapping(bytes32 => RoleData) private _roles;
              bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
              /**
               * @dev Modifier that checks that an account has a specific role. Reverts
               * with a standardized message including the required role.
               *
               * The format of the revert reason is given by the following regular expression:
               *
               *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
               *
               * _Available since v4.1._
               */
              modifier onlyRole(bytes32 role) {
                  _checkRole(role);
                  _;
              }
              /**
               * @dev See {IERC165-supportsInterface}.
               */
              function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                  return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
              }
              /**
               * @dev Returns `true` if `account` has been granted `role`.
               */
              function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
                  return _roles[role].members[account];
              }
              /**
               * @dev Revert with a standard message if `_msgSender()` is missing `role`.
               * Overriding this function changes the behavior of the {onlyRole} modifier.
               *
               * Format of the revert message is described in {_checkRole}.
               *
               * _Available since v4.6._
               */
              function _checkRole(bytes32 role) internal view virtual {
                  _checkRole(role, _msgSender());
              }
              /**
               * @dev Revert with a standard message if `account` is missing `role`.
               *
               * The format of the revert reason is given by the following regular expression:
               *
               *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
               */
              function _checkRole(bytes32 role, address account) internal view virtual {
                  if (!hasRole(role, account)) {
                      revert(
                          string(
                              abi.encodePacked(
                                  "AccessControl: account ",
                                  Strings.toHexString(account),
                                  " is missing role ",
                                  Strings.toHexString(uint256(role), 32)
                              )
                          )
                      );
                  }
              }
              /**
               * @dev Returns the admin role that controls `role`. See {grantRole} and
               * {revokeRole}.
               *
               * To change a role's admin, use {_setRoleAdmin}.
               */
              function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
                  return _roles[role].adminRole;
              }
              /**
               * @dev Grants `role` to `account`.
               *
               * If `account` had not been already granted `role`, emits a {RoleGranted}
               * event.
               *
               * Requirements:
               *
               * - the caller must have ``role``'s admin role.
               *
               * May emit a {RoleGranted} event.
               */
              function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
                  _grantRole(role, account);
              }
              /**
               * @dev Revokes `role` from `account`.
               *
               * If `account` had been granted `role`, emits a {RoleRevoked} event.
               *
               * Requirements:
               *
               * - the caller must have ``role``'s admin role.
               *
               * May emit a {RoleRevoked} event.
               */
              function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
                  _revokeRole(role, account);
              }
              /**
               * @dev Revokes `role` from the calling account.
               *
               * Roles are often managed via {grantRole} and {revokeRole}: this function's
               * purpose is to provide a mechanism for accounts to lose their privileges
               * if they are compromised (such as when a trusted device is misplaced).
               *
               * If the calling account had been revoked `role`, emits a {RoleRevoked}
               * event.
               *
               * Requirements:
               *
               * - the caller must be `account`.
               *
               * May emit a {RoleRevoked} event.
               */
              function renounceRole(bytes32 role, address account) public virtual override {
                  require(account == _msgSender(), "AccessControl: can only renounce roles for self");
                  _revokeRole(role, account);
              }
              /**
               * @dev Grants `role` to `account`.
               *
               * If `account` had not been already granted `role`, emits a {RoleGranted}
               * event. Note that unlike {grantRole}, this function doesn't perform any
               * checks on the calling account.
               *
               * May emit a {RoleGranted} event.
               *
               * [WARNING]
               * ====
               * This function should only be called from the constructor when setting
               * up the initial roles for the system.
               *
               * Using this function in any other way is effectively circumventing the admin
               * system imposed by {AccessControl}.
               * ====
               *
               * NOTE: This function is deprecated in favor of {_grantRole}.
               */
              function _setupRole(bytes32 role, address account) internal virtual {
                  _grantRole(role, account);
              }
              /**
               * @dev Sets `adminRole` as ``role``'s admin role.
               *
               * Emits a {RoleAdminChanged} event.
               */
              function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
                  bytes32 previousAdminRole = getRoleAdmin(role);
                  _roles[role].adminRole = adminRole;
                  emit RoleAdminChanged(role, previousAdminRole, adminRole);
              }
              /**
               * @dev Grants `role` to `account`.
               *
               * Internal function without access restriction.
               *
               * May emit a {RoleGranted} event.
               */
              function _grantRole(bytes32 role, address account) internal virtual {
                  if (!hasRole(role, account)) {
                      _roles[role].members[account] = true;
                      emit RoleGranted(role, account, _msgSender());
                  }
              }
              /**
               * @dev Revokes `role` from `account`.
               *
               * Internal function without access restriction.
               *
               * May emit a {RoleRevoked} event.
               */
              function _revokeRole(bytes32 role, address account) internal virtual {
                  if (hasRole(role, account)) {
                      _roles[role].members[account] = false;
                      emit RoleRevoked(role, account, _msgSender());
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol)
          pragma solidity ^0.8.0;
          import "./IAccessControlEnumerable.sol";
          import "./AccessControl.sol";
          import "../utils/structs/EnumerableSet.sol";
          /**
           * @dev Extension of {AccessControl} that allows enumerating the members of each role.
           */
          abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
              using EnumerableSet for EnumerableSet.AddressSet;
              mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;
              /**
               * @dev See {IERC165-supportsInterface}.
               */
              function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                  return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
              }
              /**
               * @dev Returns one of the accounts that have `role`. `index` must be a
               * value between 0 and {getRoleMemberCount}, non-inclusive.
               *
               * Role bearers are not sorted in any particular way, and their ordering may
               * change at any point.
               *
               * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
               * you perform all queries on the same block. See the following
               * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
               * for more information.
               */
              function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) {
                  return _roleMembers[role].at(index);
              }
              /**
               * @dev Returns the number of accounts that have `role`. Can be used
               * together with {getRoleMember} to enumerate all bearers of a role.
               */
              function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) {
                  return _roleMembers[role].length();
              }
              /**
               * @dev Overload {_grantRole} to track enumerable memberships
               */
              function _grantRole(bytes32 role, address account) internal virtual override {
                  super._grantRole(role, account);
                  _roleMembers[role].add(account);
              }
              /**
               * @dev Overload {_revokeRole} to track enumerable memberships
               */
              function _revokeRole(bytes32 role, address account) internal virtual override {
                  super._revokeRole(role, account);
                  _roleMembers[role].remove(account);
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev External interface of AccessControl declared to support ERC165 detection.
           */
          interface IAccessControl {
              /**
               * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
               *
               * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
               * {RoleAdminChanged} not being emitted signaling this.
               *
               * _Available since v3.1._
               */
              event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
              /**
               * @dev Emitted when `account` is granted `role`.
               *
               * `sender` is the account that originated the contract call, an admin role
               * bearer except when using {AccessControl-_setupRole}.
               */
              event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
              /**
               * @dev Emitted when `account` is revoked `role`.
               *
               * `sender` is the account that originated the contract call:
               *   - if using `revokeRole`, it is the admin role bearer
               *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
               */
              event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
              /**
               * @dev Returns `true` if `account` has been granted `role`.
               */
              function hasRole(bytes32 role, address account) external view returns (bool);
              /**
               * @dev Returns the admin role that controls `role`. See {grantRole} and
               * {revokeRole}.
               *
               * To change a role's admin, use {AccessControl-_setRoleAdmin}.
               */
              function getRoleAdmin(bytes32 role) external view returns (bytes32);
              /**
               * @dev Grants `role` to `account`.
               *
               * If `account` had not been already granted `role`, emits a {RoleGranted}
               * event.
               *
               * Requirements:
               *
               * - the caller must have ``role``'s admin role.
               */
              function grantRole(bytes32 role, address account) external;
              /**
               * @dev Revokes `role` from `account`.
               *
               * If `account` had been granted `role`, emits a {RoleRevoked} event.
               *
               * Requirements:
               *
               * - the caller must have ``role``'s admin role.
               */
              function revokeRole(bytes32 role, address account) external;
              /**
               * @dev Revokes `role` from the calling account.
               *
               * Roles are often managed via {grantRole} and {revokeRole}: this function's
               * purpose is to provide a mechanism for accounts to lose their privileges
               * if they are compromised (such as when a trusted device is misplaced).
               *
               * If the calling account had been granted `role`, emits a {RoleRevoked}
               * event.
               *
               * Requirements:
               *
               * - the caller must be `account`.
               */
              function renounceRole(bytes32 role, address account) external;
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)
          pragma solidity ^0.8.0;
          import "./IAccessControl.sol";
          /**
           * @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
           */
          interface IAccessControlEnumerable is IAccessControl {
              /**
               * @dev Returns one of the accounts that have `role`. `index` must be a
               * value between 0 and {getRoleMemberCount}, non-inclusive.
               *
               * Role bearers are not sorted in any particular way, and their ordering may
               * change at any point.
               *
               * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
               * you perform all queries on the same block. See the following
               * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
               * for more information.
               */
              function getRoleMember(bytes32 role, uint256 index) external view returns (address);
              /**
               * @dev Returns the number of accounts that have `role`. Can be used
               * together with {getRoleMember} to enumerate all bearers of a role.
               */
              function getRoleMemberCount(bytes32 role) external view returns (uint256);
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC5267.sol)
          pragma solidity ^0.8.0;
          interface IERC5267 {
              /**
               * @dev MAY be emitted to signal that the domain could have changed.
               */
              event EIP712DomainChanged();
              /**
               * @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
               * signature.
               */
              function eip712Domain()
                  external
                  view
                  returns (
                      bytes1 fields,
                      string memory name,
                      string memory version,
                      uint256 chainId,
                      address verifyingContract,
                      bytes32 salt,
                      uint256[] memory extensions
                  );
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)
          pragma solidity ^0.8.0;
          import "../utils/Context.sol";
          /**
           * @dev Contract module which allows children to implement an emergency stop
           * mechanism that can be triggered by an authorized account.
           *
           * This module is used through inheritance. It will make available the
           * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
           * the functions of your contract. Note that they will not be pausable by
           * simply including this module, only once the modifiers are put in place.
           */
          abstract contract Pausable is Context {
              /**
               * @dev Emitted when the pause is triggered by `account`.
               */
              event Paused(address account);
              /**
               * @dev Emitted when the pause is lifted by `account`.
               */
              event Unpaused(address account);
              bool private _paused;
              /**
               * @dev Initializes the contract in unpaused state.
               */
              constructor() {
                  _paused = false;
              }
              /**
               * @dev Modifier to make a function callable only when the contract is not paused.
               *
               * Requirements:
               *
               * - The contract must not be paused.
               */
              modifier whenNotPaused() {
                  _requireNotPaused();
                  _;
              }
              /**
               * @dev Modifier to make a function callable only when the contract is paused.
               *
               * Requirements:
               *
               * - The contract must be paused.
               */
              modifier whenPaused() {
                  _requirePaused();
                  _;
              }
              /**
               * @dev Returns true if the contract is paused, and false otherwise.
               */
              function paused() public view virtual returns (bool) {
                  return _paused;
              }
              /**
               * @dev Throws if the contract is paused.
               */
              function _requireNotPaused() internal view virtual {
                  require(!paused(), "Pausable: paused");
              }
              /**
               * @dev Throws if the contract is not paused.
               */
              function _requirePaused() internal view virtual {
                  require(paused(), "Pausable: not paused");
              }
              /**
               * @dev Triggers stopped state.
               *
               * Requirements:
               *
               * - The contract must not be paused.
               */
              function _pause() internal virtual whenNotPaused {
                  _paused = true;
                  emit Paused(_msgSender());
              }
              /**
               * @dev Returns to normal state.
               *
               * Requirements:
               *
               * - The contract must be paused.
               */
              function _unpause() internal virtual whenPaused {
                  _paused = false;
                  emit Unpaused(_msgSender());
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev Contract module that helps prevent reentrant calls to a function.
           *
           * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
           * available, which can be applied to functions to make sure there are no nested
           * (reentrant) calls to them.
           *
           * Note that because there is a single `nonReentrant` guard, functions marked as
           * `nonReentrant` may not call one another. This can be worked around by making
           * those functions `private`, and then adding `external` `nonReentrant` entry
           * points to them.
           *
           * TIP: If you would like to learn more about reentrancy and alternative ways
           * to protect against it, check out our blog post
           * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
           */
          abstract contract ReentrancyGuard {
              // Booleans are more expensive than uint256 or any type that takes up a full
              // word because each write operation emits an extra SLOAD to first read the
              // slot's contents, replace the bits taken up by the boolean, and then write
              // back. This is the compiler's defense against contract upgrades and
              // pointer aliasing, and it cannot be disabled.
              // The values being non-zero value makes deployment a bit more expensive,
              // but in exchange the refund on every call to nonReentrant will be lower in
              // amount. Since refunds are capped to a percentage of the total
              // transaction's gas, it is best to keep them low in cases like this one, to
              // increase the likelihood of the full refund coming into effect.
              uint256 private constant _NOT_ENTERED = 1;
              uint256 private constant _ENTERED = 2;
              uint256 private _status;
              constructor() {
                  _status = _NOT_ENTERED;
              }
              /**
               * @dev Prevents a contract from calling itself, directly or indirectly.
               * Calling a `nonReentrant` function from another `nonReentrant`
               * function is not supported. It is possible to prevent this from happening
               * by making the `nonReentrant` function external, and making it call a
               * `private` function that does the actual work.
               */
              modifier nonReentrant() {
                  _nonReentrantBefore();
                  _;
                  _nonReentrantAfter();
              }
              function _nonReentrantBefore() private {
                  // On the first call to nonReentrant, _status will be _NOT_ENTERED
                  require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
                  // Any calls to nonReentrant after this point will fail
                  _status = _ENTERED;
              }
              function _nonReentrantAfter() private {
                  // By storing the original value once again, a refund is triggered (see
                  // https://eips.ethereum.org/EIPS/eip-2200)
                  _status = _NOT_ENTERED;
              }
              /**
               * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
               * `nonReentrant` function in the call stack.
               */
              function _reentrancyGuardEntered() internal view returns (bool) {
                  return _status == _ENTERED;
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/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.
           *
           * ==== Security Considerations
           *
           * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
           * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
           * considered as an intention to spend the allowance in any specific way. The second is that because permits have
           * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
           * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
           * generally recommended is:
           *
           * ```solidity
           * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
           *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
           *     doThing(..., value);
           * }
           *
           * function doThing(..., uint256 value) public {
           *     token.safeTransferFrom(msg.sender, address(this), value);
           *     ...
           * }
           * ```
           *
           * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
           * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
           * {SafeERC20-safeTransferFrom}).
           *
           * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
           * contracts should have entry points that don't rely on permit.
           */
          interface IERC20Permit {
              /**
               * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
               * given ``owner``'s signed approval.
               *
               * IMPORTANT: The same issues {IERC20-approve} has related to transaction
               * ordering also apply here.
               *
               * Emits an {Approval} event.
               *
               * Requirements:
               *
               * - `spender` cannot be the zero address.
               * - `deadline` must be a timestamp in the future.
               * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
               * over the EIP712-formatted function arguments.
               * - the signature must use ``owner``'s current nonce (see {nonces}).
               *
               * For more information on the signature format, see the
               * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
               * section].
               *
               * CAUTION: See Security Considerations above.
               */
              function permit(
                  address owner,
                  address spender,
                  uint256 value,
                  uint256 deadline,
                  uint8 v,
                  bytes32 r,
                  bytes32 s
              ) external;
              /**
               * @dev Returns the current nonce for `owner`. This value must be
               * included whenever a signature is generated for {permit}.
               *
               * Every successful call to {permit} increases ``owner``'s nonce by one. This
               * prevents a signature from being used multiple times.
               */
              function nonces(address owner) external view returns (uint256);
              /**
               * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
               */
              // solhint-disable-next-line func-name-mixedcase
              function DOMAIN_SEPARATOR() external view returns (bytes32);
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.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);
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
          pragma solidity ^0.8.0;
          import "../IERC20.sol";
          import "../extensions/IERC20Permit.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 Address for address;
              /**
               * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
               * non-reverting calls are assumed to be successful.
               */
              function safeTransfer(IERC20 token, address to, uint256 value) internal {
                  _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
              }
              /**
               * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
               * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
               */
              function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
                  _callOptionalReturn(token, abi.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'
                  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));
              }
              /**
               * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
               * non-reverting calls are assumed to be successful.
               */
              function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                  uint256 oldAllowance = token.allowance(address(this), spender);
                  _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
              }
              /**
               * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
               * non-reverting calls are assumed to be successful.
               */
              function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                  unchecked {
                      uint256 oldAllowance = token.allowance(address(this), spender);
                      require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
                      _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
                  }
              }
              /**
               * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
               * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
               * to be set to zero before setting it to a non-zero value, such as USDT.
               */
              function forceApprove(IERC20 token, address spender, uint256 value) internal {
                  bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
                  if (!_callOptionalReturnBool(token, approvalCall)) {
                      _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
                      _callOptionalReturn(token, approvalCall);
                  }
              }
              /**
               * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
               * Revert on invalid signature.
               */
              function safePermit(
                  IERC20Permit token,
                  address owner,
                  address spender,
                  uint256 value,
                  uint256 deadline,
                  uint8 v,
                  bytes32 r,
                  bytes32 s
              ) internal {
                  uint256 nonceBefore = token.nonces(owner);
                  token.permit(owner, spender, value, deadline, v, r, s);
                  uint256 nonceAfter = token.nonces(owner);
                  require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
              }
              /**
               * @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");
                  require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
              }
              /**
               * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
               * on the return value: the return value is optional (but if data is returned, it must not be false).
               * @param token The token targeted by the call.
               * @param data The call data (encoded using abi.encode or one of its variants).
               *
               * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
               */
              function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
                  // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                  // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
                  // and not revert is the subcall reverts.
                  (bool success, bytes memory returndata) = address(token).call(data);
                  return
                      success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.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
               *
               * Furthermore, `isContract` will also return true if the target contract within
               * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
               * which only has an effect at the end of a transaction.
               * ====
               *
               * [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://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
               *
               * IMPORTANT: because control is transferred to `recipient`, care must be
               * taken to not create reentrancy vulnerabilities. Consider using
               * {ReentrancyGuard} or the
               * https://solidity.readthedocs.io/en/v0.8.0/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 functionCallWithValue(target, data, 0, "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");
                  (bool success, bytes memory returndata) = target.call{value: value}(data);
                  return verifyCallResultFromTarget(target, 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) {
                  (bool success, bytes memory returndata) = target.staticcall(data);
                  return verifyCallResultFromTarget(target, 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) {
                  (bool success, bytes memory returndata) = target.delegatecall(data);
                  return verifyCallResultFromTarget(target, success, returndata, errorMessage);
              }
              /**
               * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
               * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
               *
               * _Available since v4.8._
               */
              function verifyCallResultFromTarget(
                  address target,
                  bool success,
                  bytes memory returndata,
                  string memory errorMessage
              ) internal view returns (bytes memory) {
                  if (success) {
                      if (returndata.length == 0) {
                          // only check isContract if the call was successful and the return data is empty
                          // otherwise we already know that it was a contract
                          require(isContract(target), "Address: call to non-contract");
                      }
                      return returndata;
                  } else {
                      _revert(returndata, errorMessage);
                  }
              }
              /**
               * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
               * revert reason or 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 {
                      _revert(returndata, errorMessage);
                  }
              }
              function _revert(bytes memory returndata, string memory errorMessage) private pure {
                  // Look for revert reason and bubble it up if present
                  if (returndata.length > 0) {
                      // The easiest way to bubble the revert reason is using memory via assembly
                      /// @solidity memory-safe-assembly
                      assembly {
                          let returndata_size := mload(returndata)
                          revert(add(32, returndata), returndata_size)
                      }
                  } else {
                      revert(errorMessage);
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.4) (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;
              }
              function _contextSuffixLength() internal view virtual returns (uint256) {
                  return 0;
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
          pragma solidity ^0.8.0;
          /**
           * @title Counters
           * @author Matt Condon (@shrugs)
           * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
           * of elements in a mapping, issuing ERC721 ids, or counting request ids.
           *
           * Include with `using Counters for Counters.Counter;`
           */
          library Counters {
              struct Counter {
                  // This variable should never be directly accessed by users of the library: interactions must be restricted to
                  // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
                  // this feature: see https://github.com/ethereum/solidity/issues/4637
                  uint256 _value; // default: 0
              }
              function current(Counter storage counter) internal view returns (uint256) {
                  return counter._value;
              }
              function increment(Counter storage counter) internal {
                  unchecked {
                      counter._value += 1;
                  }
              }
              function decrement(Counter storage counter) internal {
                  uint256 value = counter._value;
                  require(value > 0, "Counter: decrement overflow");
                  unchecked {
                      counter._value = value - 1;
                  }
              }
              function reset(Counter storage counter) internal {
                  counter._value = 0;
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (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 // Deprecated in v4.8
              }
              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");
                  }
              }
              /**
               * @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) {
                  if (signature.length == 65) {
                      bytes32 r;
                      bytes32 s;
                      uint8 v;
                      // ecrecover takes the signature parameters, and the only way to get them
                      // currently is to use assembly.
                      /// @solidity memory-safe-assembly
                      assembly {
                          r := mload(add(signature, 0x20))
                          s := mload(add(signature, 0x40))
                          v := byte(0, mload(add(signature, 0x60)))
                      }
                      return tryRecover(hash, v, r, s);
                  } else {
                      return (address(0), RecoverError.InvalidSignatureLength);
                  }
              }
              /**
               * @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 = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
                  uint8 v = uint8((uint256(vs) >> 255) + 27);
                  return tryRecover(hash, v, r, s);
              }
              /**
               * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
               *
               * _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 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 message) {
                  // 32 is the length in bytes of hash,
                  // enforced by the type signature above
                  /// @solidity memory-safe-assembly
                  assembly {
                      mstore(0x00, "\\x19Ethereum Signed Message:\
          32")
                      mstore(0x1c, hash)
                      message := keccak256(0x00, 0x3c)
                  }
              }
              /**
               * @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 data) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      let ptr := mload(0x40)
                      mstore(ptr, "\\x19\\x01")
                      mstore(add(ptr, 0x02), domainSeparator)
                      mstore(add(ptr, 0x22), structHash)
                      data := keccak256(ptr, 0x42)
                  }
              }
              /**
               * @dev Returns an Ethereum Signed Data with intended validator, created from a
               * `validator` and `data` according to the version 0 of EIP-191.
               *
               * See {recover}.
               */
              function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
                  return keccak256(abi.encodePacked("\\x19\\x00", validator, data));
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/EIP712.sol)
          pragma solidity ^0.8.8;
          import "./ECDSA.sol";
          import "../ShortStrings.sol";
          import "../../interfaces/IERC5267.sol";
          /**
           * @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].
           *
           * NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
           * separator of the implementation contract. This will cause the `_domainSeparatorV4` function to always rebuild the
           * separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
           *
           * _Available since v3.4._
           *
           * @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
           */
          abstract contract EIP712 is IERC5267 {
              using ShortStrings for *;
              bytes32 private constant _TYPE_HASH =
                  keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
              // 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 _cachedDomainSeparator;
              uint256 private immutable _cachedChainId;
              address private immutable _cachedThis;
              bytes32 private immutable _hashedName;
              bytes32 private immutable _hashedVersion;
              ShortString private immutable _name;
              ShortString private immutable _version;
              string private _nameFallback;
              string private _versionFallback;
              /**
               * @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) {
                  _name = name.toShortStringWithFallback(_nameFallback);
                  _version = version.toShortStringWithFallback(_versionFallback);
                  _hashedName = keccak256(bytes(name));
                  _hashedVersion = keccak256(bytes(version));
                  _cachedChainId = block.chainid;
                  _cachedDomainSeparator = _buildDomainSeparator();
                  _cachedThis = address(this);
              }
              /**
               * @dev Returns the domain separator for the current chain.
               */
              function _domainSeparatorV4() internal view returns (bytes32) {
                  if (address(this) == _cachedThis && block.chainid == _cachedChainId) {
                      return _cachedDomainSeparator;
                  } else {
                      return _buildDomainSeparator();
                  }
              }
              function _buildDomainSeparator() private view returns (bytes32) {
                  return keccak256(abi.encode(_TYPE_HASH, _hashedName, _hashedVersion, 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);
              }
              /**
               * @dev See {EIP-5267}.
               *
               * _Available since v4.9._
               */
              function eip712Domain()
                  public
                  view
                  virtual
                  override
                  returns (
                      bytes1 fields,
                      string memory name,
                      string memory version,
                      uint256 chainId,
                      address verifyingContract,
                      bytes32 salt,
                      uint256[] memory extensions
                  )
              {
                  return (
                      hex"0f", // 01111
                      _name.toStringWithFallback(_nameFallback),
                      _version.toStringWithFallback(_versionFallback),
                      block.chainid,
                      address(this),
                      bytes32(0),
                      new uint256[](0)
                  );
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
          pragma solidity ^0.8.0;
          import "./IERC165.sol";
          /**
           * @dev Implementation of the {IERC165} interface.
           *
           * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
           * for the additional interface id that will be supported. For example:
           *
           * ```solidity
           * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
           *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
           * }
           * ```
           *
           * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
           */
          abstract contract ERC165 is IERC165 {
              /**
               * @dev See {IERC165-supportsInterface}.
               */
              function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                  return interfaceId == type(IERC165).interfaceId;
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev Interface of the ERC165 standard, as defined in the
           * https://eips.ethereum.org/EIPS/eip-165[EIP].
           *
           * Implementers can declare support of contract interfaces, which can then be
           * queried by others ({ERC165Checker}).
           *
           * For an implementation, see {ERC165}.
           */
          interface IERC165 {
              /**
               * @dev Returns true if this contract implements the interface defined by
               * `interfaceId`. See the corresponding
               * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
               * to learn more about how these ids are created.
               *
               * This function call must use less than 30 000 gas.
               */
              function supportsInterface(bytes4 interfaceId) external view returns (bool);
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev Standard math utilities missing in the Solidity language.
           */
          library Math {
              enum Rounding {
                  Down, // Toward negative infinity
                  Up, // Toward infinity
                  Zero // Toward zero
              }
              /**
               * @dev Returns the largest of two numbers.
               */
              function max(uint256 a, uint256 b) internal pure returns (uint256) {
                  return a > b ? a : b;
              }
              /**
               * @dev Returns the smallest of two numbers.
               */
              function min(uint256 a, uint256 b) internal pure returns (uint256) {
                  return a < b ? a : b;
              }
              /**
               * @dev Returns the average of two numbers. The result is rounded towards
               * zero.
               */
              function average(uint256 a, uint256 b) internal pure returns (uint256) {
                  // (a + b) / 2 can overflow.
                  return (a & b) + (a ^ b) / 2;
              }
              /**
               * @dev Returns the ceiling of the division of two numbers.
               *
               * This differs from standard division with `/` in that it rounds up instead
               * of rounding down.
               */
              function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
                  // (a + b - 1) / b can overflow on addition, so we distribute.
                  return a == 0 ? 0 : (a - 1) / b + 1;
              }
              /**
               * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
               * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
               * with further edits by Uniswap Labs also under MIT license.
               */
              function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
                  unchecked {
                      // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
                      // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
                      // variables such that product = prod1 * 2^256 + prod0.
                      uint256 prod0; // Least significant 256 bits of the product
                      uint256 prod1; // Most significant 256 bits of the product
                      assembly {
                          let mm := mulmod(x, y, not(0))
                          prod0 := mul(x, y)
                          prod1 := sub(sub(mm, prod0), lt(mm, prod0))
                      }
                      // Handle non-overflow cases, 256 by 256 division.
                      if (prod1 == 0) {
                          // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                          // The surrounding unchecked block does not change this fact.
                          // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                          return prod0 / denominator;
                      }
                      // Make sure the result is less than 2^256. Also prevents denominator == 0.
                      require(denominator > prod1, "Math: mulDiv overflow");
                      ///////////////////////////////////////////////
                      // 512 by 256 division.
                      ///////////////////////////////////////////////
                      // Make division exact by subtracting the remainder from [prod1 prod0].
                      uint256 remainder;
                      assembly {
                          // Compute remainder using mulmod.
                          remainder := mulmod(x, y, denominator)
                          // Subtract 256 bit number from 512 bit number.
                          prod1 := sub(prod1, gt(remainder, prod0))
                          prod0 := sub(prod0, remainder)
                      }
                      // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
                      // See https://cs.stackexchange.com/q/138556/92363.
                      // Does not overflow because the denominator cannot be zero at this stage in the function.
                      uint256 twos = denominator & (~denominator + 1);
                      assembly {
                          // Divide denominator by twos.
                          denominator := div(denominator, twos)
                          // Divide [prod1 prod0] by twos.
                          prod0 := div(prod0, twos)
                          // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                          twos := add(div(sub(0, twos), twos), 1)
                      }
                      // Shift in bits from prod1 into prod0.
                      prod0 |= prod1 * twos;
                      // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
                      // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
                      // four bits. That is, denominator * inv = 1 mod 2^4.
                      uint256 inverse = (3 * denominator) ^ 2;
                      // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
                      // in modular arithmetic, doubling the correct bits in each step.
                      inverse *= 2 - denominator * inverse; // inverse mod 2^8
                      inverse *= 2 - denominator * inverse; // inverse mod 2^16
                      inverse *= 2 - denominator * inverse; // inverse mod 2^32
                      inverse *= 2 - denominator * inverse; // inverse mod 2^64
                      inverse *= 2 - denominator * inverse; // inverse mod 2^128
                      inverse *= 2 - denominator * inverse; // inverse mod 2^256
                      // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
                      // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
                      // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
                      // is no longer required.
                      result = prod0 * inverse;
                      return result;
                  }
              }
              /**
               * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
               */
              function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
                  uint256 result = mulDiv(x, y, denominator);
                  if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
                      result += 1;
                  }
                  return result;
              }
              /**
               * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
               *
               * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
               */
              function sqrt(uint256 a) internal pure returns (uint256) {
                  if (a == 0) {
                      return 0;
                  }
                  // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
                  //
                  // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
                  // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
                  //
                  // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
                  // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
                  // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
                  //
                  // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
                  uint256 result = 1 << (log2(a) >> 1);
                  // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
                  // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
                  // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
                  // into the expected uint128 result.
                  unchecked {
                      result = (result + a / result) >> 1;
                      result = (result + a / result) >> 1;
                      result = (result + a / result) >> 1;
                      result = (result + a / result) >> 1;
                      result = (result + a / result) >> 1;
                      result = (result + a / result) >> 1;
                      result = (result + a / result) >> 1;
                      return min(result, a / result);
                  }
              }
              /**
               * @notice Calculates sqrt(a), following the selected rounding direction.
               */
              function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
                  unchecked {
                      uint256 result = sqrt(a);
                      return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
                  }
              }
              /**
               * @dev Return the log in base 2, rounded down, of a positive value.
               * Returns 0 if given 0.
               */
              function log2(uint256 value) internal pure returns (uint256) {
                  uint256 result = 0;
                  unchecked {
                      if (value >> 128 > 0) {
                          value >>= 128;
                          result += 128;
                      }
                      if (value >> 64 > 0) {
                          value >>= 64;
                          result += 64;
                      }
                      if (value >> 32 > 0) {
                          value >>= 32;
                          result += 32;
                      }
                      if (value >> 16 > 0) {
                          value >>= 16;
                          result += 16;
                      }
                      if (value >> 8 > 0) {
                          value >>= 8;
                          result += 8;
                      }
                      if (value >> 4 > 0) {
                          value >>= 4;
                          result += 4;
                      }
                      if (value >> 2 > 0) {
                          value >>= 2;
                          result += 2;
                      }
                      if (value >> 1 > 0) {
                          result += 1;
                      }
                  }
                  return result;
              }
              /**
               * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
               * Returns 0 if given 0.
               */
              function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
                  unchecked {
                      uint256 result = log2(value);
                      return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
                  }
              }
              /**
               * @dev Return the log in base 10, rounded down, of a positive value.
               * Returns 0 if given 0.
               */
              function log10(uint256 value) internal pure returns (uint256) {
                  uint256 result = 0;
                  unchecked {
                      if (value >= 10 ** 64) {
                          value /= 10 ** 64;
                          result += 64;
                      }
                      if (value >= 10 ** 32) {
                          value /= 10 ** 32;
                          result += 32;
                      }
                      if (value >= 10 ** 16) {
                          value /= 10 ** 16;
                          result += 16;
                      }
                      if (value >= 10 ** 8) {
                          value /= 10 ** 8;
                          result += 8;
                      }
                      if (value >= 10 ** 4) {
                          value /= 10 ** 4;
                          result += 4;
                      }
                      if (value >= 10 ** 2) {
                          value /= 10 ** 2;
                          result += 2;
                      }
                      if (value >= 10 ** 1) {
                          result += 1;
                      }
                  }
                  return result;
              }
              /**
               * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
               * Returns 0 if given 0.
               */
              function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
                  unchecked {
                      uint256 result = log10(value);
                      return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
                  }
              }
              /**
               * @dev Return the log in base 256, rounded down, of a positive value.
               * Returns 0 if given 0.
               *
               * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
               */
              function log256(uint256 value) internal pure returns (uint256) {
                  uint256 result = 0;
                  unchecked {
                      if (value >> 128 > 0) {
                          value >>= 128;
                          result += 16;
                      }
                      if (value >> 64 > 0) {
                          value >>= 64;
                          result += 8;
                      }
                      if (value >> 32 > 0) {
                          value >>= 32;
                          result += 4;
                      }
                      if (value >> 16 > 0) {
                          value >>= 16;
                          result += 2;
                      }
                      if (value >> 8 > 0) {
                          result += 1;
                      }
                  }
                  return result;
              }
              /**
               * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
               * Returns 0 if given 0.
               */
              function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
                  unchecked {
                      uint256 result = log256(value);
                      return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev Standard signed math utilities missing in the Solidity language.
           */
          library SignedMath {
              /**
               * @dev Returns the largest of two signed numbers.
               */
              function max(int256 a, int256 b) internal pure returns (int256) {
                  return a > b ? a : b;
              }
              /**
               * @dev Returns the smallest of two signed numbers.
               */
              function min(int256 a, int256 b) internal pure returns (int256) {
                  return a < b ? a : b;
              }
              /**
               * @dev Returns the average of two signed numbers without overflow.
               * The result is rounded towards zero.
               */
              function average(int256 a, int256 b) internal pure returns (int256) {
                  // Formula from the book "Hacker's Delight"
                  int256 x = (a & b) + ((a ^ b) >> 1);
                  return x + (int256(uint256(x) >> 255) & (a ^ b));
              }
              /**
               * @dev Returns the absolute unsigned value of a signed value.
               */
              function abs(int256 n) internal pure returns (uint256) {
                  unchecked {
                      // must be unchecked in order to support `n = type(int256).min`
                      return uint256(n >= 0 ? n : -n);
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (utils/ShortStrings.sol)
          pragma solidity ^0.8.8;
          import "./StorageSlot.sol";
          // | string  | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA   |
          // | length  | 0x                                                              BB |
          type ShortString is bytes32;
          /**
           * @dev This library provides functions to convert short memory strings
           * into a `ShortString` type that can be used as an immutable variable.
           *
           * Strings of arbitrary length can be optimized using this library if
           * they are short enough (up to 31 bytes) by packing them with their
           * length (1 byte) in a single EVM word (32 bytes). Additionally, a
           * fallback mechanism can be used for every other case.
           *
           * Usage example:
           *
           * ```solidity
           * contract Named {
           *     using ShortStrings for *;
           *
           *     ShortString private immutable _name;
           *     string private _nameFallback;
           *
           *     constructor(string memory contractName) {
           *         _name = contractName.toShortStringWithFallback(_nameFallback);
           *     }
           *
           *     function name() external view returns (string memory) {
           *         return _name.toStringWithFallback(_nameFallback);
           *     }
           * }
           * ```
           */
          library ShortStrings {
              // Used as an identifier for strings longer than 31 bytes.
              bytes32 private constant _FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF;
              error StringTooLong(string str);
              error InvalidShortString();
              /**
               * @dev Encode a string of at most 31 chars into a `ShortString`.
               *
               * This will trigger a `StringTooLong` error is the input string is too long.
               */
              function toShortString(string memory str) internal pure returns (ShortString) {
                  bytes memory bstr = bytes(str);
                  if (bstr.length > 31) {
                      revert StringTooLong(str);
                  }
                  return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));
              }
              /**
               * @dev Decode a `ShortString` back to a "normal" string.
               */
              function toString(ShortString sstr) internal pure returns (string memory) {
                  uint256 len = byteLength(sstr);
                  // using `new string(len)` would work locally but is not memory safe.
                  string memory str = new string(32);
                  /// @solidity memory-safe-assembly
                  assembly {
                      mstore(str, len)
                      mstore(add(str, 0x20), sstr)
                  }
                  return str;
              }
              /**
               * @dev Return the length of a `ShortString`.
               */
              function byteLength(ShortString sstr) internal pure returns (uint256) {
                  uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF;
                  if (result > 31) {
                      revert InvalidShortString();
                  }
                  return result;
              }
              /**
               * @dev Encode a string into a `ShortString`, or write it to storage if it is too long.
               */
              function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) {
                  if (bytes(value).length < 32) {
                      return toShortString(value);
                  } else {
                      StorageSlot.getStringSlot(store).value = value;
                      return ShortString.wrap(_FALLBACK_SENTINEL);
                  }
              }
              /**
               * @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
               */
              function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {
                  if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) {
                      return toString(value);
                  } else {
                      return store;
                  }
              }
              /**
               * @dev Return the length of a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
               *
               * WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of
               * actual characters as the UTF-8 encoding of a single character can span over multiple bytes.
               */
              function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {
                  if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) {
                      return byteLength(value);
                  } else {
                      return bytes(store).length;
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol)
          // This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
          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:
           * ```solidity
           * 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`, `uint256`._
           * _Available since v4.9 for `string`, `bytes`._
           */
          library StorageSlot {
              struct AddressSlot {
                  address value;
              }
              struct BooleanSlot {
                  bool value;
              }
              struct Bytes32Slot {
                  bytes32 value;
              }
              struct Uint256Slot {
                  uint256 value;
              }
              struct StringSlot {
                  string value;
              }
              struct BytesSlot {
                  bytes value;
              }
              /**
               * @dev Returns an `AddressSlot` with member `value` located at `slot`.
               */
              function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := slot
                  }
              }
              /**
               * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
               */
              function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := slot
                  }
              }
              /**
               * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
               */
              function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := slot
                  }
              }
              /**
               * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
               */
              function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := slot
                  }
              }
              /**
               * @dev Returns an `StringSlot` with member `value` located at `slot`.
               */
              function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := slot
                  }
              }
              /**
               * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
               */
              function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := store.slot
                  }
              }
              /**
               * @dev Returns an `BytesSlot` with member `value` located at `slot`.
               */
              function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := slot
                  }
              }
              /**
               * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
               */
              function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
                  /// @solidity memory-safe-assembly
                  assembly {
                      r.slot := store.slot
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)
          pragma solidity ^0.8.0;
          import "./math/Math.sol";
          import "./math/SignedMath.sol";
          /**
           * @dev String operations.
           */
          library Strings {
              bytes16 private constant _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) {
                  unchecked {
                      uint256 length = Math.log10(value) + 1;
                      string memory buffer = new string(length);
                      uint256 ptr;
                      /// @solidity memory-safe-assembly
                      assembly {
                          ptr := add(buffer, add(32, length))
                      }
                      while (true) {
                          ptr--;
                          /// @solidity memory-safe-assembly
                          assembly {
                              mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
                          }
                          value /= 10;
                          if (value == 0) break;
                      }
                      return buffer;
                  }
              }
              /**
               * @dev Converts a `int256` to its ASCII `string` decimal representation.
               */
              function toString(int256 value) internal pure returns (string memory) {
                  return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
              }
              /**
               * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
               */
              function toHexString(uint256 value) internal pure returns (string memory) {
                  unchecked {
                      return toHexString(value, Math.log256(value) + 1);
                  }
              }
              /**
               * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
               */
              function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
                  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] = _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);
              }
              /**
               * @dev Returns true if the two strings are equal.
               */
              function equal(string memory a, string memory b) internal pure returns (bool) {
                  return keccak256(bytes(a)) == keccak256(bytes(b));
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/EnumerableSet.sol)
          // This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
          pragma solidity ^0.8.0;
          /**
           * @dev Library for managing
           * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
           * types.
           *
           * Sets have the following properties:
           *
           * - Elements are added, removed, and checked for existence in constant time
           * (O(1)).
           * - Elements are enumerated in O(n). No guarantees are made on the ordering.
           *
           * ```solidity
           * contract Example {
           *     // Add the library methods
           *     using EnumerableSet for EnumerableSet.AddressSet;
           *
           *     // Declare a set state variable
           *     EnumerableSet.AddressSet private mySet;
           * }
           * ```
           *
           * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
           * and `uint256` (`UintSet`) are supported.
           *
           * [WARNING]
           * ====
           * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
           * unusable.
           * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
           *
           * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
           * array of EnumerableSet.
           * ====
           */
          library EnumerableSet {
              // To implement this library for multiple types with as little code
              // repetition as possible, we write it in terms of a generic Set type with
              // bytes32 values.
              // The Set implementation uses private functions, and user-facing
              // implementations (such as AddressSet) are just wrappers around the
              // underlying Set.
              // This means that we can only create new EnumerableSets for types that fit
              // in bytes32.
              struct Set {
                  // Storage of set values
                  bytes32[] _values;
                  // Position of the value in the `values` array, plus 1 because index 0
                  // means a value is not in the set.
                  mapping(bytes32 => uint256) _indexes;
              }
              /**
               * @dev Add a value to a set. O(1).
               *
               * Returns true if the value was added to the set, that is if it was not
               * already present.
               */
              function _add(Set storage set, bytes32 value) private returns (bool) {
                  if (!_contains(set, value)) {
                      set._values.push(value);
                      // The value is stored at length-1, but we add 1 to all indexes
                      // and use 0 as a sentinel value
                      set._indexes[value] = set._values.length;
                      return true;
                  } else {
                      return false;
                  }
              }
              /**
               * @dev Removes a value from a set. O(1).
               *
               * Returns true if the value was removed from the set, that is if it was
               * present.
               */
              function _remove(Set storage set, bytes32 value) private returns (bool) {
                  // We read and store the value's index to prevent multiple reads from the same storage slot
                  uint256 valueIndex = set._indexes[value];
                  if (valueIndex != 0) {
                      // Equivalent to contains(set, value)
                      // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
                      // the array, and then remove the last element (sometimes called as 'swap and pop').
                      // This modifies the order of the array, as noted in {at}.
                      uint256 toDeleteIndex = valueIndex - 1;
                      uint256 lastIndex = set._values.length - 1;
                      if (lastIndex != toDeleteIndex) {
                          bytes32 lastValue = set._values[lastIndex];
                          // Move the last value to the index where the value to delete is
                          set._values[toDeleteIndex] = lastValue;
                          // Update the index for the moved value
                          set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
                      }
                      // Delete the slot where the moved value was stored
                      set._values.pop();
                      // Delete the index for the deleted slot
                      delete set._indexes[value];
                      return true;
                  } else {
                      return false;
                  }
              }
              /**
               * @dev Returns true if the value is in the set. O(1).
               */
              function _contains(Set storage set, bytes32 value) private view returns (bool) {
                  return set._indexes[value] != 0;
              }
              /**
               * @dev Returns the number of values on the set. O(1).
               */
              function _length(Set storage set) private view returns (uint256) {
                  return set._values.length;
              }
              /**
               * @dev Returns the value stored at position `index` in the set. O(1).
               *
               * Note that there are no guarantees on the ordering of values inside the
               * array, and it may change when more values are added or removed.
               *
               * Requirements:
               *
               * - `index` must be strictly less than {length}.
               */
              function _at(Set storage set, uint256 index) private view returns (bytes32) {
                  return set._values[index];
              }
              /**
               * @dev Return the entire set in an array
               *
               * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
               * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
               * this function has an unbounded cost, and using it as part of a state-changing function may render the function
               * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
               */
              function _values(Set storage set) private view returns (bytes32[] memory) {
                  return set._values;
              }
              // Bytes32Set
              struct Bytes32Set {
                  Set _inner;
              }
              /**
               * @dev Add a value to a set. O(1).
               *
               * Returns true if the value was added to the set, that is if it was not
               * already present.
               */
              function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
                  return _add(set._inner, value);
              }
              /**
               * @dev Removes a value from a set. O(1).
               *
               * Returns true if the value was removed from the set, that is if it was
               * present.
               */
              function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
                  return _remove(set._inner, value);
              }
              /**
               * @dev Returns true if the value is in the set. O(1).
               */
              function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
                  return _contains(set._inner, value);
              }
              /**
               * @dev Returns the number of values in the set. O(1).
               */
              function length(Bytes32Set storage set) internal view returns (uint256) {
                  return _length(set._inner);
              }
              /**
               * @dev Returns the value stored at position `index` in the set. O(1).
               *
               * Note that there are no guarantees on the ordering of values inside the
               * array, and it may change when more values are added or removed.
               *
               * Requirements:
               *
               * - `index` must be strictly less than {length}.
               */
              function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
                  return _at(set._inner, index);
              }
              /**
               * @dev Return the entire set in an array
               *
               * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
               * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
               * this function has an unbounded cost, and using it as part of a state-changing function may render the function
               * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
               */
              function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
                  bytes32[] memory store = _values(set._inner);
                  bytes32[] memory result;
                  /// @solidity memory-safe-assembly
                  assembly {
                      result := store
                  }
                  return result;
              }
              // AddressSet
              struct AddressSet {
                  Set _inner;
              }
              /**
               * @dev Add a value to a set. O(1).
               *
               * Returns true if the value was added to the set, that is if it was not
               * already present.
               */
              function add(AddressSet storage set, address value) internal returns (bool) {
                  return _add(set._inner, bytes32(uint256(uint160(value))));
              }
              /**
               * @dev Removes a value from a set. O(1).
               *
               * Returns true if the value was removed from the set, that is if it was
               * present.
               */
              function remove(AddressSet storage set, address value) internal returns (bool) {
                  return _remove(set._inner, bytes32(uint256(uint160(value))));
              }
              /**
               * @dev Returns true if the value is in the set. O(1).
               */
              function contains(AddressSet storage set, address value) internal view returns (bool) {
                  return _contains(set._inner, bytes32(uint256(uint160(value))));
              }
              /**
               * @dev Returns the number of values in the set. O(1).
               */
              function length(AddressSet storage set) internal view returns (uint256) {
                  return _length(set._inner);
              }
              /**
               * @dev Returns the value stored at position `index` in the set. O(1).
               *
               * Note that there are no guarantees on the ordering of values inside the
               * array, and it may change when more values are added or removed.
               *
               * Requirements:
               *
               * - `index` must be strictly less than {length}.
               */
              function at(AddressSet storage set, uint256 index) internal view returns (address) {
                  return address(uint160(uint256(_at(set._inner, index))));
              }
              /**
               * @dev Return the entire set in an array
               *
               * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
               * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
               * this function has an unbounded cost, and using it as part of a state-changing function may render the function
               * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
               */
              function values(AddressSet storage set) internal view returns (address[] memory) {
                  bytes32[] memory store = _values(set._inner);
                  address[] memory result;
                  /// @solidity memory-safe-assembly
                  assembly {
                      result := store
                  }
                  return result;
              }
              // UintSet
              struct UintSet {
                  Set _inner;
              }
              /**
               * @dev Add a value to a set. O(1).
               *
               * Returns true if the value was added to the set, that is if it was not
               * already present.
               */
              function add(UintSet storage set, uint256 value) internal returns (bool) {
                  return _add(set._inner, bytes32(value));
              }
              /**
               * @dev Removes a value from a set. O(1).
               *
               * Returns true if the value was removed from the set, that is if it was
               * present.
               */
              function remove(UintSet storage set, uint256 value) internal returns (bool) {
                  return _remove(set._inner, bytes32(value));
              }
              /**
               * @dev Returns true if the value is in the set. O(1).
               */
              function contains(UintSet storage set, uint256 value) internal view returns (bool) {
                  return _contains(set._inner, bytes32(value));
              }
              /**
               * @dev Returns the number of values in the set. O(1).
               */
              function length(UintSet storage set) internal view returns (uint256) {
                  return _length(set._inner);
              }
              /**
               * @dev Returns the value stored at position `index` in the set. O(1).
               *
               * Note that there are no guarantees on the ordering of values inside the
               * array, and it may change when more values are added or removed.
               *
               * Requirements:
               *
               * - `index` must be strictly less than {length}.
               */
              function at(UintSet storage set, uint256 index) internal view returns (uint256) {
                  return uint256(_at(set._inner, index));
              }
              /**
               * @dev Return the entire set in an array
               *
               * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
               * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
               * this function has an unbounded cost, and using it as part of a state-changing function may render the function
               * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
               */
              function values(UintSet storage set) internal view returns (uint256[] memory) {
                  bytes32[] memory store = _values(set._inner);
                  uint256[] memory result;
                  /// @solidity memory-safe-assembly
                  assembly {
                      result := store
                  }
                  return result;
              }
          }
          // SPDX-License-Identifier: UNLICENSED
          // Copyright (c) Eywa.Fi, 2021-2023 - all rights reserved
          pragma solidity 0.8.17;
          import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
          import "@openzeppelin/contracts/utils/Counters.sol";
          import "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
          import "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
          import "@openzeppelin/contracts/security/Pausable.sol";
          import "./EndPoint.sol";
          import "./interfaces/IGateKeeper.sol";
          import "./interfaces/IRouterV2.sol";
          import "./interfaces/IAddressBook.sol";
          import "./interfaces/IOpsRegistrar.sol";
          import "./utils/RequestIdLib.sol";
          abstract contract BaseRouter is Pausable, EIP712, EndPoint, AccessControlEnumerable {
              using Counters for Counters.Counter;
              enum ExecutionResult { Failed, Succeeded, Interrupted }
              struct MaskedParams {
                  uint256 amountOut;
                  address to;
                  address emergencyTo;
              }
              /// @dev accountant role id
              bytes32 public constant ACCOUNTANT_ROLE = keccak256("ACCOUNTANT_ROLE");
              /// @dev operator role id
              bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE");
              /// @dev nonces
              mapping(address => Counters.Counter) private _nonces;
              
              /// @dev started crocss-chain ops, requestId => serialized op params
              mapping(bytes32 => bytes) public startedOps;
              /// @dev used to check is function called from resume\\onlyBridge handler, otherwise not set 
              bytes32 internal currentRequestId;
              /// @dev should be set between receiveValidatedData and resume call
              uint64 internal currentChainIdFrom;
              /// @dev current ops index
              uint256 internal currentOpsIdx;
              /// @dev current ops count
              uint256 internal currentOpsCount;
              /// @dev should be true when start proceeding (only on initial call)
              bool internal isOriginNetwork;
              
              event FeePaid(address indexed payer, address accountant, uint256 executionPrice);
              event ComplexOpProcessed(
                  uint64 currentChainId,
                  bytes32 currentRequestId,
                  uint64 nextChainId,
                  bytes32 nextRequestId,
                  ExecutionResult result,
                  uint8 lastOp
              );
              modifier originNetwork() {
                  isOriginNetwork = true;
                  _;
                  isOriginNetwork = false;
              }
              modifier crosschainHandling(bytes32 requestId) {
                  currentRequestId = requestId;
                  _;
                  currentRequestId = 0;
                  currentChainIdFrom = 0;
              }
              constructor(
                  address addressBook_
              ) EIP712("EYWA", "1") EndPoint(addressBook_) {
                  _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
              }
              function nonces(address whose) public view returns (uint256) {
                  return _nonces[whose].current();
              }
              /**
               * @dev Sets address book.
               *
               * Controlled by DAO and\\or multisig (3 out of 5, Gnosis Safe).
               *
               * @param addressBook_ address book contract address.
               */
              function setAddressBook(address addressBook_) external onlyRole(DEFAULT_ADMIN_ROLE) {
                  _setAddressBook(addressBook_);
              }
              /**
               * @dev Triggers stopped state.
               *
               * Controlled by DAO and\\or multisig (3 out of 5, Gnosis Safe).
               */
              function pause() external onlyRole(DEFAULT_ADMIN_ROLE) {
                  _pause();
              }
              /**
               * @dev Returns to normal state.
               *
               * Controlled by DAO and\\or multisig (3 out of 5, Gnosis Safe).
               */
              function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) {
                  _unpause();
              }
              /**
               * @dev Token synthesize request to another EVM chain via native payment.
               *
               * A: Lock(X) -> B: Mint(sX_A) = sX_A
               *
               * @param operations operation types;
               * @param params operation params;
               * @param receipt clp invoice.
               */
              function _start(
                  string[] calldata operations,
                  bytes[] memory params,
                  IRouterParams.Invoice calldata receipt
              ) internal virtual {
                  require(operations.length < 2**8, "BaseRouter: wrong params count");
                  require(operations.length == params.length, "BaseRouter: wrong params");
                  uint256 balanceBeforeStart = address(this).balance - msg.value;
                  address opsRegistrar = IAddressBook(addressBook).opsRegistrar();
                  {
                      (bytes32 hash, bytes memory data) = _getRawData(operations, params);
                      require(IOpsRegistrar(opsRegistrar).ops(hash) == true, "BaseRouter: complex op not registered");
                      address accountant = _checkSignature(msg.sender, hash, data, receipt);
                      _proceedFees(receipt.executionPrice, accountant);
                  }
                  (
                      bytes32 nextRequestId,
                      uint64 chainIdTo,
                      ExecutionResult result,
                      uint8 lastOp
                  ) = _execute(0, operations, params);
                  uint256 newBalance = address(this).balance;
                  if(newBalance > balanceBeforeStart) {
                      (bool sent, ) = msg.sender.call{value: newBalance - balanceBeforeStart}("");
                      require(sent, "BaseRouter: failed to send ETH");
                  }
                  emit ComplexOpProcessed(uint64(block.chainid), 0, chainIdTo, nextRequestId, result, lastOp);
              }
              function _resume(
                  bytes32 requestId,
                  uint8 cPos,
                  string[] calldata operations,
                  bytes[] memory params
              ) internal virtual {
                  require(operations.length < 2**8, "BaseRouter: wrong params count");
                  require(operations.length == params.length, "BaseRouter: wrong params");
                  require(cPos < params.length, "BaseRouter: wrong params");
                  (
                      bytes32 nextRequestId,
                      uint64 chainIdTo,
                      ExecutionResult result,
                      uint8 lastOp
                  ) = _execute(cPos, operations, params);
                  emit ComplexOpProcessed(uint64(block.chainid), requestId, chainIdTo, nextRequestId, result, lastOp);
              }
              function _execute(uint256 cPos, string[] calldata operations, bytes[] memory params) internal virtual whenNotPaused returns (
                  bytes32 nextRequestId,
                  uint64 chainIdTo,
                  ExecutionResult result,
                  uint8 lastOp
              ) {
                  MaskedParams memory maskedParams;
                  bytes memory updatedParams;
                  currentOpsCount = operations.length;
                  for (uint256 i = cPos; i < operations.length; ++i) {
                      currentOpsIdx = i;
                      (chainIdTo, updatedParams, maskedParams, result) = _executeOp(
                          (currentRequestId != 0 && i == cPos),
                          keccak256(bytes(operations[i])),
                          i < (operations.length - 1) ? keccak256(bytes(operations[i + 1])) : bytes32(0),
                          params[i],
                          maskedParams
                      );
                      require(result != ExecutionResult.Failed, string(abi.encodePacked("Router: op ", operations[i], " is not supported")));
                      lastOp = uint8(i);
                      if (result == ExecutionResult.Interrupted) {
                          break;
                      } else if (chainIdTo != 0) {
                          address router = IAddressBook(addressBook).router(chainIdTo);
                          nextRequestId = _getRequestId(router, chainIdTo);
                          if (updatedParams.length != 0) {
                              params[i] = updatedParams;
                          }
                          bytes memory out = abi.encodeWithSelector(
                              IRouter.resume.selector,
                              nextRequestId,
                              uint8(i),
                              operations,
                              params
                          );
                          address gateKeeper = IAddressBook(addressBook).gateKeeper();
                          IGateKeeper(gateKeeper).sendData(out, router, chainIdTo, address(0));
                          startedOps[nextRequestId] = params[i];
                          break;
                      }
                  }
                  currentOpsIdx = 0;
                  currentOpsCount = 0;
              }
              /**
               * @dev Returns current nonce and increment it.
               *
               * @param whose whose nonce.
               */
              function _getAndUpdateNonce(address whose) internal returns (uint256 nonce) {
                  Counters.Counter storage counter = _nonces[whose];
                  nonce = counter.current();
                  counter.increment();
              }
              function _checkSignature(
                  address from,
                  bytes32 operationHash,
                  bytes memory data,
                  IRouterParams.Invoice calldata receipt
              ) internal returns (address accountant) {
                  uint256 nonce = _getAndUpdateNonce(from);
                  bytes32 accountantHash = keccak256(
                      abi.encodePacked(
                          keccak256(
                              "AccountantPermit(address from,uint256 nonce,bytes32 operationHash,bytes data,uint256 executionPrice,uint256 deadline)"
                          ),
                          from,
                          nonce,
                          operationHash,
                          data,
                          receipt.executionPrice,
                          receipt.deadline
                      )
                  );
                  bytes32 hash = ECDSA.toEthSignedMessageHash(_hashTypedDataV4(accountantHash));
                  accountant = ECDSA.recover(hash, receipt.v, receipt.r, receipt.s);
                  require(block.timestamp <= receipt.deadline, "BaseRouter: deadline");
                  require(hasRole(ACCOUNTANT_ROLE, accountant), "BaseRouter: invalid signature from worker");
              }
              function _getRawData(
                  string[] calldata operations,
                  bytes[] memory params
              ) internal pure returns (bytes32 hash, bytes memory data) {
                  bytes memory op;
                  for (uint256 i = 0; i < operations.length; ++i) {
                      op = bytes.concat(op, bytes(operations[i]));
                      if (data.length == 0) {
                          data = params[i];
                      } else {
                          data = bytes.concat(data, ",", params[i]);
                      }
                  }
                  hash = keccak256(op);
              }
              function _getRequestId(address receiver, uint64 chainIdTo) internal view returns (bytes32 requestId) {
                  address gateKeeper = IAddressBook(addressBook).gateKeeper();
                  uint256 nonce = IGateKeeper(gateKeeper).getNonce();
                  requestId = RequestIdLib.prepareRequestId(
                      castToBytes32(receiver),
                      chainIdTo,
                      castToBytes32(address(this)),
                      block.chainid,
                      nonce
                  );
              }
              function _proceedFees(uint256 executionPrice, address accountant) internal virtual;
              function _executeOp(
                  bool isOpHalfDone,
                  bytes32 op,
                  bytes32 nextOp,
                  bytes memory params,
                  MaskedParams memory prevMaskedParams
              ) internal virtual returns (
                  uint64 chainIdTo,
                  bytes memory updatedParams,
                  MaskedParams memory maskedParams,
                  ExecutionResult result
              );
          }
          // SPDX-License-Identifier: UNLICENSED
          // Copyright (c) Eywa.Fi, 2021-2023 - all rights reserved
          pragma solidity 0.8.17;
          import "./utils/Typecast.sol";
          contract EndPoint is Typecast {
              /// @dev version
              string public version;
              /// @dev clp address book
              address public addressBook;
              constructor (address addressBook_) {
                  version = "2.2.3";
                  _checkAddress(addressBook_);
                  addressBook = addressBook_;
              }
              function _setAddressBook(address addressBook_) internal {
                  _checkAddress(addressBook_);
                  addressBook = addressBook_;
              }
              function _checkAddress(address checkingAddress) private pure {
                  require(checkingAddress != address(0), "EndPoint: zero address");
              }
          }
          // SPDX-License-Identifier: UNLICENSED
          // Copyright (c) Eywa.Fi, 2021-2024 - all rights reserved
          pragma solidity 0.8.17;
          interface IAddressBook {
              /// @dev returns portal by given chainId
              function portal(uint64 chainId) external view returns (address);
              /// @dev returns synthesis by given chainId
              function synthesis(uint64 chainId) external view returns (address);
              /// @dev returns router by given chainId
              function router(uint64 chainId) external view returns (address);
              /// @dev returns whitelist
              function whitelist() external view returns (address);
              /// @dev returns treasury
              function treasury() external view returns (address);
              /// @dev returns gateKeeper
              function gateKeeper() external view returns (address);
              /// @dev returns bridge
              function bridge() external view returns (address);
              /// @dev returns opsRegistrar
              function opsRegistrar() external view returns (address);
              /// @dev returns wrapped native asset (WETH)
              function WETH() external view returns (address);
          }// SPDX-License-Identifier: UNLICENSED
          // Copyright (c) Eywa.Fi, 2021-2023 - all rights reserved
          pragma solidity 0.8.17;
          interface IERC20WithPermit {
              function permit(
                  address owner,
                  address spender,
                  uint256 value,
                  uint256 deadline,
                  uint8 v,
                  bytes32 r,
                  bytes32 s
              ) external;
          }
          // SPDX-License-Identifier: UNLICENSED
          // Copyright (c) Eywa.Fi, 2021-2023 - all rights reserved
          pragma solidity 0.8.17;
          interface IGateKeeper {
              function calculateCost(
                  address payToken,
                  uint256 dataLength,
                  uint64 chainIdTo,
                  address sender
              ) external returns (uint256 amountToPay);
              function sendData(
                  bytes calldata data,
                  address to,
                  uint64 chainIdTo,
                  address payToken
              ) external payable;
              function getNonce() external view returns (uint256);
              function bridge() external view returns (address);
          }// SPDX-License-Identifier: UNLICENSED
          // Copyright (c) Eywa.Fi, 2021-2023 - all rights reserved
          pragma solidity 0.8.17;
          interface IOpsRegistrar {
              struct ComplexOp {
                  string operation;
                  bool registered;
              }
              /// @dev returns is complex op registered
              function ops(bytes32 ops_) external returns (bool);
              /// @dev registers ComplexOp's
              function registerComplexOp(ComplexOp[] memory complexOps_) external;
          }// SPDX-License-Identifier: UNLICENSED
          // Copyright (c) Eywa.Fi, 2021-2023 - all rights reserved
          pragma solidity 0.8.17;
          interface IPortalV2 {
              function lock(
                  address token,
                  uint256 amount,
                  address from,
                  address to
              ) external;
              function unlock(
                  address token,
                  uint256 amount,
                  address from,
                  address to
              ) external returns (uint256);
              function emergencyUnlock(
                  address token,
                  uint256 amount,
                  address from,
                  address to
              ) external returns (uint256);
          }
          // SPDX-License-Identifier: UNLICENSED
          // Copyright (c) Eywa.Fi, 2021-2023 - all rights reserved
          pragma solidity 0.8.17;
          interface IRouterParams {
              struct Invoice {
                  uint256 executionPrice;
                  uint256 deadline;
                  uint8 v;
                  bytes32 r;
                  bytes32 s;
              }
              struct PermitParams {
                  address token;
                  address owner;
                  uint256 amount;
                  uint256 deadline;
                  uint8 v;
                  bytes32 r;
                  bytes32 s;
              }
              /**
               * @dev amount can be set as prev op result by using uint256 max. 
               */
              struct SynthParams {
                  address tokenIn;
                  uint256 amountIn; // amount | 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
                  address from; // from | 0x0000000000000000000000000000000000000000
                  address to;
                  uint64 chainIdTo;
                  uint64 tokenInChainIdFrom;
                  address emergencyTo;
              }
              /**
               * @dev Cancellation applicable only for cross-chain ops (LM, BU, BM).
               */
              struct CancelParams {
                  bytes32 requestId;
                  uint64 chainIdTo;
              }
              /**
               * @dev amountIn can be set as prev op result by using uint256 max. 
               */
              struct AddParams {
                  address tokenIn;
                  uint256 amountIn; // amount | 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
                  address from;  // from | 0x0000000000000000000000000000000000000000
                  address to;
                  address pool;
                  uint256 minAmountOut;
                  uint8 i;
                  address emergencyTo;
              }
              /**
               * @dev amountIn can be set as prev op result by using uint256 max. 
               */
              struct RemoveParams {
                  address tokenIn;
                  uint256 amountIn; // amount | 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
                  address from;  // from | 0x0000000000000000000000000000000000000000
                  address to;
                  address pool;
                  uint256 minAmountOut;
                  uint8 j;
                  address emergencyTo;
              }
              /**
               * @dev amountIn can be set as prev op result by using uint256 max. 
               */
              struct SwapParams {
                  address tokenIn;
                  uint256 amountIn; // amount | 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
                  address from;  // from | 0x0000000000000000000000000000000000000000
                  address to;
                  address pool;
                  uint256 minAmountOut;
                  uint8 i;
                  uint8 j;
                  address emergencyTo;
              }
              /**
               * @dev amount can be set as prev op result by using uint256 max.
               */
              struct WrapParams {
                  address tokenIn;
                  uint256 amountIn; // amount | 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
                  address from;  // from | 0x0000000000000000000000000000000000000000
                  address to; // router if op not last
              }
          }
          interface IRouter is IRouterParams {
              function start(
                  string[] calldata operations,
                  bytes[] calldata params,
                  Invoice calldata receipt
              ) external payable;
              function resume(
                  bytes32 requestId,
                  uint8 cPos,
                  string[] calldata operations,
                  bytes[] calldata params
              ) external;
          }
          interface IUnifiedRouter is IRouter {
          }// SPDX-License-Identifier: UNLICENSED
          // Copyright (c) Eywa.Fi, 2021-2023 - all rights reserved
          pragma solidity 0.8.17;
          import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
          /**
           * @dev Should be implemented by "treasury" contract in cases when third party token used instead of our synth.
           *
           * Mint\\Burn can be implemented as Lock\\Unlock in treasury contract.
           */
          interface ISynthAdapter {
              enum SynthType { Unknown, DefaultSynth, CustomSynth, ThirdPartySynth, ThirdPartyToken }
              function mint(address account, uint256 amount) external;
              function burn(address account, uint256 amount) external;
              function setCap(uint256) external;
              function decimals() external view returns (uint8);
              function originalToken() external view returns (address);
              function synthToken() external view returns (address);
              function chainIdFrom() external view returns (uint64); // TODO what if token native in 2-3-4 chains? // []
              function chainSymbolFrom() external view returns (string memory);
              function synthType() external view returns (uint8);
              function cap() external view returns (uint256);
              event CapSet(uint256 cap);
          }
          interface ISynthERC20 is ISynthAdapter, IERC20 {
          }
          // SPDX-License-Identifier: UNLICENSED
          // Copyright (c) Eywa.Fi, 2021-2023 - all rights reserved
          pragma solidity 0.8.17;
          interface ISynthesisV2 {
              function synthByOriginal(uint64 chainIdFrom, address otoken) external view returns (address stoken);
              function synthBySynth(address stoken) external view returns (address adapter);
              function mint(
                  address token,
                  uint256 amount,
                  address from,
                  address to,
                  uint64 chainIdFrom
              ) external returns (uint256 amountOut);
              function emergencyMint(
                  address token,
                  uint256 amount,
                  address from,
                  address to
              ) external returns (uint256 amountOut);
              function burn(
                  address stoken,
                  uint256 amount,
                  address from,
                  address to,
                  uint64 chainIdTo
              ) external;
          }
          // SPDX-License-Identifier: UNLICENSED
          // Copyright (c) Eywa.Fi, 2021-2023 - all rights reserved
          pragma solidity 0.8.17;
          interface IUnifiedPoolAdapter {
              function addLiquidity(
                  address tokenIn,
                  uint256 amountIn,
                  address to,
                  address pool,
                  uint256 minAmountOut,
                  uint8 i,
                  address emergencyTo
              ) external returns (uint256 amountOut);
              function swap(
                  address tokenIn,
                  uint256 amountIn,
                  address to,
                  address pool,
                  uint256 minAmountOut,
                  uint8 i,
                  uint8 j,
                  address emergencyTo
              ) external returns (uint256 amountOut);
              function removeLiquidity(
                  address tokenIn,
                  uint256 amountIn,
                  address to,
                  address pool,
                  uint256 minAmountOut,
                  uint8 j,
                  address emergencyTo
              ) external returns (uint256 amountOut);
          }
          // SPDX-License-Identifier: UNLICENSED
          // Copyright (c) Eywa.Fi, 2021-2023 - all rights reserved
          pragma solidity 0.8.17;
          interface IWETH9 {
              
              function withdraw(uint wad) external;
              function deposit() external payable;
              
          }// SPDX-License-Identifier: UNLICENSED
          // Copyright (c) Eywa.Fi, 2021-2023 - all rights reserved
          pragma solidity 0.8.17;
          interface IWhitelist {
              enum TokenState { NotSet, InOut }
              enum PoolState { NotSet, AddSwapRemove }
              struct TokenStatus {
                  address token;
                  uint256 min;
                  uint256 max;
                  uint256 bridgeFee;
                  TokenState state;
              }
              struct PoolStatus {
                  address pool;
                  uint256 aggregationFee;
                  PoolState state;
              }
              
              function tokenMin(address token) external view returns (uint256);
              function tokenMax(address token) external view returns (uint256);
              function tokenMinMax(address token) external view returns (uint256, uint256);
              function bridgeFee(address token) external view returns (uint256);
              function tokenState(address token) external view returns (uint8);
              function tokenStatus(address token) external view returns (TokenStatus memory);
              function tokens(uint256 offset, uint256 count) external view returns (TokenStatus[] memory);
              function aggregationFee(address pool) external view returns (uint256);
              function poolState(address pool) external view returns (uint8);
              function poolStatus(address pool) external view returns (PoolStatus memory);
              function pools(uint256 offset, uint256 count) external view returns (PoolStatus[] memory);
          }
          // SPDX-License-Identifier: UNLICENSED
          // Copyright (c) Eywa.Fi, 2021-2023 - all rights reserved
          pragma solidity 0.8.17;
          import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
          import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
          import "./BaseRouter.sol";
          import "./interfaces/IPortalV2.sol";
          import "./interfaces/ISynthesisV2.sol";
          import "./interfaces/IRouterV2.sol";
          import "./interfaces/IAddressBook.sol";
          import "./interfaces/IWETH.sol";
          import "./interfaces/IERC20WithPermit.sol";
          import "./interfaces/ISynth.sol";
          import "./interfaces/IWhitelist.sol";
          contract RouterV2 is BaseRouter, ReentrancyGuard, IRouter {
              enum CrossChainOpState { Unknown, Succeeded, Reverted }
              /// @dev permit operation code
              bytes32 public constant PERMIT_CODE = keccak256(abi.encodePacked("P"));
              /// @dev lock operation code
              bytes32 public constant LOCK_MINT_CODE = keccak256(abi.encodePacked("LM"));
              /// @dev unlock operation code
              bytes32 public constant BURN_UNLOCK_CODE = keccak256(abi.encodePacked("BU"));
              /// @dev mint operation code
              bytes32 public constant BURN_MINT_CODE = keccak256(abi.encodePacked("BM"));
              /// @dev wrap operation code
              bytes32 public constant WRAP_CODE = keccak256(abi.encodePacked("W"));
              /// @dev unwrap operation code
              bytes32 public constant UNWRAP_CODE = keccak256(abi.encodePacked("Uw"));
              /// @dev emergency cancel lock operation code
              bytes32 public constant EMERGENCY_UNLOCK_CODE = keccak256(abi.encodePacked("!M"));
              /// @dev emergency cancel burn operation code
              bytes32 public constant EMERGENCY_MINT_CODE = keccak256(abi.encodePacked("!U"));
              /// @dev processed cross-chain ops (can't be reverted)
              mapping(bytes32 => CrossChainOpState) public processedOps;
              /// @dev WETH address
              address public WETH;
              modifier onlyBridge() {
                  address bridge = IAddressBook(addressBook).bridge();
                  require(bridge == msg.sender, "Router: bridge only");
                  _;
              }
              constructor(address addressBook_) BaseRouter(addressBook_) {
                  WETH = IAddressBook(addressBook).WETH();
                  require(WETH != address(0), "Router: WETH incorrect");
              }
              receive() external payable {
                  require(msg.sender == WETH, "Router: Invalid sender");
              }
              function receiveValidatedData(bytes4 selector, address from, uint64 chainIdFrom) external virtual onlyBridge returns (bool) {
                  address router = IAddressBook(addressBook).router(chainIdFrom);
                  require(from == router, "Router: wrong sender");
                  require(selector == RouterV2.resume.selector, "Router: wrong selector");
                  currentChainIdFrom = chainIdFrom;
                  return true;
              }
              /**
               * @dev Token synthesize request to another EVM chain via native payment.
               *
               * A: Lock(X) -> B: Mint(sX_A) = sX_A
               *
               * @param operations operation types;
               * @param params operation params;
               * @param receipt clp invoice.
               */
              function start(
                  string[] calldata operations,
                  bytes[] memory params,
                  Invoice calldata receipt
              ) external payable nonReentrant originNetwork {
                  _start(operations, params, receipt);
              }
              function resume(
                  bytes32 requestId,
                  uint8 cPos,
                  string[] calldata operations,
                  bytes[] memory params
              ) external nonReentrant onlyBridge crosschainHandling(requestId) {
                  _resume(requestId, cPos, operations, params);
              }
              /**
               * @dev Should be implemented for each router.
               *
               * Each implementation must:
               * Revert execution if op is not supported;
               * Return chainId and destination router if current op is cross-chain; 
               */
              function _executeOp(
                  bool isOpHalfDone,
                  bytes32 op,
                  bytes32 nextOp,
                  bytes memory params,
                  MaskedParams memory prevMaskedParams
              ) internal virtual override returns (uint64 chainIdTo, bytes memory updatedParams, MaskedParams memory maskedParams, ExecutionResult result) {
                  result = ExecutionResult.Succeeded;
                  if (PERMIT_CODE == op) {
                      require(currentOpsIdx == 0, "Router: permit not allowed");
                      PermitParams memory p = abi.decode(params, (PermitParams));
                      try IERC20WithPermit(p.token).permit(
                              p.owner,
                              address(this),
                              p.amount,
                              p.deadline,
                              p.v,
                              p.r,
                              p.s
                      ) {
                      } catch {
                          require(IERC20(p.token).allowance(p.owner, address(this)) >= p.amount, "Router: permit failure");
                      }
                  } else if (LOCK_MINT_CODE == op || BURN_UNLOCK_CODE == op || BURN_MINT_CODE == op) {
                      SynthParams memory p = abi.decode(params, (SynthParams));
                      if (isOpHalfDone == false) {
                          (p.amountIn, p.from, p.emergencyTo) = _checkMaskedParams(p.amountIn, p.from, p.emergencyTo, prevMaskedParams);
                          p.to = _checkTo(p.to, p.emergencyTo, p.chainIdTo, nextOp);
                          address possibleAdapter;
                          if (LOCK_MINT_CODE == op) {
                              _lock(p);
                          } else {
                              address synthesis = IAddressBook(addressBook).synthesis(uint64(block.chainid));
                              possibleAdapter = ISynthesisV2(synthesis).synthBySynth(p.tokenIn);
                              if (possibleAdapter != address(0)) {
                                  if (p.from != synthesis) {
                                      SafeERC20.safeTransferFrom(IERC20(p.tokenIn), p.from, synthesis, p.amountIn);
                                  }
                                  p.from = synthesis;
                              } else {
                                  // check for backward compatibility with deployed SynthesisV2
                                  IAddressBook addressBookImpl = IAddressBook(addressBook);
                                  address whitelist = addressBookImpl.whitelist();
                                  require(IWhitelist(whitelist).tokenState(p.tokenIn) >= 0, "Router: synth must be whitelisted");
                                  possibleAdapter = p.tokenIn;
                              }
                              ISynthesisV2(synthesis).burn(p.tokenIn, p.amountIn, p.from, p.to, p.chainIdTo);
                          }
                          chainIdTo = p.chainIdTo;
                          if (LOCK_MINT_CODE != op) {
                              ISynthAdapter synthImpl = ISynthAdapter(possibleAdapter);
                              p.tokenIn = synthImpl.originalToken();
                              p.tokenInChainIdFrom = synthImpl.chainIdFrom();
                          } else {
                              p.tokenInChainIdFrom = uint64(block.chainid);
                          }
                          updatedParams = abi.encode(p);
                      } else {
                          require(processedOps[currentRequestId] == CrossChainOpState.Unknown, "Router: op processed");
                          processedOps[currentRequestId] = CrossChainOpState.Succeeded;
                          if (p.to == address(0)) {
                              p.to = _checkTo(p.to, p.emergencyTo, p.chainIdTo, nextOp);
                          }
                          maskedParams.amountOut = BURN_UNLOCK_CODE == op ? _unlock(p) : _mint(p);
                          maskedParams.to = p.to;
                          maskedParams.emergencyTo = p.emergencyTo;
                      }
                  } else if (WRAP_CODE == op || UNWRAP_CODE == op) {
                      WrapParams memory p = abi.decode(params, (WrapParams));
                      address tmp;
                      (p.amountIn, p.from, tmp) = _checkMaskedParams(p.amountIn, p.from, address(0), prevMaskedParams);
                      p.to = _checkTo(p.to, p.to, uint64(block.chainid), nextOp);
                      maskedParams.amountOut = WRAP_CODE == op ? _wrap(p) : _unwrap(p);
                      maskedParams.to = p.to;
                      maskedParams.emergencyTo = prevMaskedParams.emergencyTo;
                  } else if (EMERGENCY_UNLOCK_CODE == op || EMERGENCY_MINT_CODE == op) {
                      CancelParams memory p = abi.decode(params, (CancelParams));
                      if (isOpHalfDone == false) {
                          require(processedOps[p.requestId] != CrossChainOpState.Succeeded, "Router: op processed");
                          processedOps[p.requestId] = CrossChainOpState.Reverted;
                          chainIdTo = p.chainIdTo;
                      } else {
                          bytes memory emergencyParams = startedOps[p.requestId];
                          require(emergencyParams.length != 0, "Router: op not started");
                          SynthParams memory eP = abi.decode(emergencyParams, (SynthParams));
                          delete startedOps[p.requestId];
                          if (EMERGENCY_UNLOCK_CODE == op) {
                              maskedParams.amountOut = _emergencyUnlock(eP);
                          } else {
                              maskedParams.amountOut = _emergencyMint(eP);
                          }
                      }
                  } else {
                      maskedParams = prevMaskedParams;
                      result = ExecutionResult.Failed;
                  }
              }
              function _lock(SynthParams memory p) internal {
                  address portal = IAddressBook(addressBook).portal(uint64(block.chainid));
                  if (p.from != portal) {
                      SafeERC20.safeTransferFrom(IERC20(p.tokenIn), p.from, portal, p.amountIn);
                  }
                  IPortalV2(portal).lock(p.tokenIn, p.amountIn, p.from, p.to);
              }
              function _unlock(SynthParams memory p) internal returns (uint256 amountOut) {
                  address portal = IAddressBook(addressBook).portal(uint64(block.chainid));
                  amountOut = IPortalV2(portal).unlock(p.tokenIn, p.amountIn, p.from, p.to);
              }
              function _emergencyUnlock(SynthParams memory p) internal returns (uint256 amountOut) {
                  require(currentChainIdFrom == p.chainIdTo, "Router: wrong emergency init");
                  address portal = IAddressBook(addressBook).portal(uint64(block.chainid));
                  amountOut = IPortalV2(portal).emergencyUnlock(p.tokenIn, p.amountIn, p.from, p.emergencyTo);
              }
              function _mint(SynthParams memory p) internal returns (uint256 amountOut) {
                  address synthesis = IAddressBook(addressBook).synthesis(uint64(block.chainid));
                  amountOut = ISynthesisV2(synthesis).mint(p.tokenIn, p.amountIn, p.from, p.to, p.tokenInChainIdFrom);
              }
              function _emergencyMint(SynthParams memory p) internal returns (uint256 amountOut) {
                  require(currentChainIdFrom == p.chainIdTo, "Router: wrong emergency init");
                  address synthesis = IAddressBook(addressBook).synthesis(uint64(block.chainid));
                  p.tokenIn = ISynthesisV2(synthesis).synthByOriginal(p.tokenInChainIdFrom, p.tokenIn);
                  amountOut = ISynthesisV2(synthesis).emergencyMint(p.tokenIn, p.amountIn, p.from, p.emergencyTo);
              }
              function _wrap(WrapParams memory p) internal returns (uint256 amountOut) {
                  require(currentOpsIdx == 0, "Router: wrap not allowed");
                  require(msg.value >= p.amountIn, "Router: invalid amount");
                  IWETH9(p.tokenIn).deposit{ value: p.amountIn }();
                  SafeERC20.safeTransfer(IERC20(p.tokenIn), p.to, p.amountIn);
                  amountOut = p.amountIn;
              }
              function _unwrap(WrapParams memory p) internal returns (uint256 amountOut) {
                  require(currentOpsIdx == (currentOpsCount - 1), "Router: unwrap not allowed");
                  if (p.from != address(this)) {
                      SafeERC20.safeTransferFrom(IERC20(p.tokenIn), p.from, address(this), p.amountIn);
                  }
                  IWETH9(p.tokenIn).withdraw(p.amountIn);
                  (bool sent, ) = p.to.call{ value: p.amountIn }("");
                  require(sent, "Router: failed to send ETH");
                  amountOut = p.amountIn;
              }
              function _proceedFees(uint256 executionPrice, address accountant) internal virtual override {
                  if (executionPrice != 0) {
                      require(msg.value >= executionPrice, "Router: invalid amount");
                      (bool sent, ) = accountant.call{ value: executionPrice }("");
                      require(sent, "Router: failed to send Ether");
                  }
                  emit FeePaid(msg.sender, accountant, executionPrice);
              }
              /**
               * @dev Should check current params for mask and return correct values.
               *
               * @param currentAmountIn current op amountIn, can be UINT256_MAX;
               * @param currentFrom current op from, always must be equal address(0), except initial op;
               * @param currentEmergencyTo current op emergencyTo, must be msg.sender in initial op or addres(0) in all others;
               * @param prevMaskedParams prev params, which can be used to update current given params.
               */
              function _checkMaskedParams(
                  uint256 currentAmountIn,
                  address currentFrom,
                  address currentEmergencyTo,
                  MaskedParams memory prevMaskedParams
              ) internal view returns (uint256 amountIn, address from, address emergencyTo) {
                  // amountIn check
                  amountIn = currentAmountIn == type(uint256).max ? prevMaskedParams.amountOut : currentAmountIn;
                  // from check
                  if (currentFrom != address(0)) {
                      require(currentFrom == msg.sender, "Router: wrong sender");
                      from = currentFrom;
                  } else {
                      from = prevMaskedParams.to;
                  }
                  // emergencyTo check
                  if (currentRequestId == 0 && currentEmergencyTo != address(0)) {
                      // only in initial chain (currentRequestId always 0)
                      require(currentEmergencyTo == msg.sender, "Router: wrong emergencyTo");
                      emergencyTo = currentEmergencyTo;
                  } else {
                      // on next chain always using first one
                      emergencyTo = prevMaskedParams.emergencyTo;
                  }
              }
              function _checkTo(address to, address emergencyTo, uint64 chainId, bytes32 nextOp) internal view virtual returns (address correctTo) {
                  require(to == address(0) || nextOp == bytes32(0), "Router: wrong to");
                  if (nextOp == bytes32(0)) {
                      correctTo = to;
                      require(correctTo == emergencyTo, "Router: wrong receiver");
                  } else if (nextOp == LOCK_MINT_CODE) {
                      correctTo = IAddressBook(addressBook).portal(chainId);
                  } else if (nextOp == BURN_UNLOCK_CODE || nextOp == BURN_MINT_CODE) {
                      correctTo = IAddressBook(addressBook).synthesis(chainId);
                  } else if (WRAP_CODE == nextOp || UNWRAP_CODE == nextOp) {
                      correctTo = IAddressBook(addressBook).router(chainId);
                  }
              }
          }
          // SPDX-License-Identifier: UNLICENSED
          // Copyright (c) Eywa.Fi, 2021-2023 - all rights reserved
          pragma solidity 0.8.17;
          import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
          import "./RouterV2.sol";
          import "./interfaces/IUnifiedPoolAdapter.sol";
          contract UnifiedRouterV2 is RouterV2, IUnifiedRouter {
              event PoolAdapterSet(address pool, address poolAdapter);
              /// @dev add operation code
              bytes32 public constant ADD_CODE = keccak256(abi.encodePacked("A"));
              /// @dev remove operation code
              bytes32 public constant REMOVE_CODE = keccak256(abi.encodePacked("R"));
              /// @dev swap operation code
              bytes32 public constant SWAP_CODE = keccak256(abi.encodePacked("S"));
              /// @dev pool adapters
              mapping(address => address) public poolAdapter;
              constructor(address addressBook_) RouterV2(addressBook_) {}
              /**
               * @dev Sets pool adapter for given pool.
               *
               * Each supported pool must be set.
               *
               * @param pool_ The Curve pool;
               * @param poolAdapter_ The pool adapter for pool_. 
               */
              function setPoolAdapter(
                  address pool_,
                  address poolAdapter_
              ) external onlyRole(OPERATOR_ROLE) {
                  require(pool_ != address(0), "UnifiedRouterV2: zero address");
                  poolAdapter[pool_] = poolAdapter_;
                  emit PoolAdapterSet(pool_, poolAdapter_);
              }
              /**
               * @dev Should be implemented for each router.
               *
               * Each implementation must:
               * Revert execution if op is not supported;
               * Return chainId, destination router (if current op is cross-chain) and execution result.
               *
               * @param op operation hash;
               * @param params serialized params corresponding to op.
               */
              function _executeOp(
                  bool isOpHalfDone,
                  bytes32 op,
                  bytes32 nextOp,
                  bytes memory params,
                  MaskedParams memory prevMaskedParams
              ) internal virtual override returns (uint64 chainIdTo, bytes memory updatedParams, MaskedParams memory maskedParams, ExecutionResult result) {
                  (chainIdTo, updatedParams, maskedParams, result) = super._executeOp(isOpHalfDone, op, nextOp, params, prevMaskedParams);
                  if (result == ExecutionResult.Failed) {
                      result = ExecutionResult.Succeeded;
                      if (ADD_CODE == op) {
                          AddParams memory p = abi.decode(params, (AddParams));
                          address adapter = _getPoolAdapter(p.pool);
                          (p.amountIn, p.from, p.emergencyTo) = _checkMaskedParams(p.amountIn, p.from, p.emergencyTo, maskedParams);
                          p.to = _checkTo(p.to, p.emergencyTo, uint64(block.chainid), nextOp);
                          _transferToAdapter(p.tokenIn, p.from, adapter, p.amountIn);
                          maskedParams.amountOut = IUnifiedPoolAdapter(adapter).addLiquidity(
                              p.tokenIn,
                              p.amountIn,
                              p.to,
                              p.pool,
                              p.minAmountOut,
                              p.i,
                              p.emergencyTo
                          );
                          maskedParams.to = p.to;
                          maskedParams.emergencyTo = p.emergencyTo;
                          if (maskedParams.amountOut == 0) {
                              if (isOriginNetwork) {
                                  revert("UnifiedRouterV2: slippage");
                              }
                              result = ExecutionResult.Interrupted;
                          }
                      } else if (REMOVE_CODE == op) {
                          RemoveParams memory p = abi.decode(params, (RemoveParams));
                          address adapter = _getPoolAdapter(p.pool);
                          (p.amountIn, p.from, p.emergencyTo) = _checkMaskedParams(p.amountIn, p.from, p.emergencyTo, maskedParams);
                          p.to = _checkTo(p.to, p.emergencyTo, uint64(block.chainid), nextOp);
                          _transferToAdapter(p.tokenIn, p.from, adapter, p.amountIn);
                          maskedParams.amountOut = IUnifiedPoolAdapter(adapter).removeLiquidity(
                              p.tokenIn,
                              p.amountIn,
                              p.to,
                              p.pool,
                              p.minAmountOut,
                              p.j,
                              p.emergencyTo
                          );
                          maskedParams.to = p.to;
                          maskedParams.emergencyTo = p.emergencyTo;
                          if (maskedParams.amountOut == 0) {
                              if (isOriginNetwork) {
                                  revert("UnifiedRouterV2: slippage");
                              }
                              result = ExecutionResult.Interrupted;
                          }
                      } else if (SWAP_CODE == op) {
                          SwapParams memory p = abi.decode(params, (SwapParams));
                          address adapter = _getPoolAdapter(p.pool);
                          (p.amountIn, p.from, p.emergencyTo) = _checkMaskedParams(p.amountIn, p.from, p.emergencyTo, maskedParams);
                          p.to = _checkTo(p.to, p.emergencyTo, uint64(block.chainid), nextOp);
                          _transferToAdapter(p.tokenIn, p.from, adapter, p.amountIn);
                          maskedParams.amountOut = IUnifiedPoolAdapter(adapter).swap(
                              p.tokenIn,
                              p.amountIn,
                              p.to,
                              p.pool,
                              p.minAmountOut,
                              p.i,
                              p.j,
                              p.emergencyTo
                          );
                          maskedParams.to = p.to;
                          maskedParams.emergencyTo = p.emergencyTo;
                          if (maskedParams.amountOut == 0) {
                              if (isOriginNetwork) {
                                  revert("UnifiedRouterV2: slippage");
                              }
                              result = ExecutionResult.Interrupted;
                          }
                      } else {
                          result = ExecutionResult.Failed;
                      }
                  }
              }
              function _checkTo(address to, address emergencyTo, uint64 chainId, bytes32 nextOp) internal view virtual override returns (address correctTo) {
                  correctTo = super._checkTo(to, emergencyTo, chainId, nextOp);
                  if (correctTo == address(0)) {
                      if (nextOp == ADD_CODE || nextOp == REMOVE_CODE || nextOp == SWAP_CODE) {
                          correctTo = IAddressBook(addressBook).router(chainId);
                      }
                  }
              }
              function _getPoolAdapter(address pool) private view returns (address adapter) {
                  adapter = poolAdapter[pool];
                  require(adapter != address(0), "UnifiedRouterV2: pool adapter not set");
              }
              function _transferToAdapter(address tokenIn, address from, address adapter, uint256 amountIn) private {
                  if (from == address(this)) {
                      SafeERC20.safeTransfer(IERC20(tokenIn), adapter, amountIn);
                  } else {
                      SafeERC20.safeTransferFrom(IERC20(tokenIn), from, adapter, amountIn);
                  }
              }
          }
          // SPDX-License-Identifier: UNLICENSED
          // Copyright (c) Eywa.Fi, 2021-2023 - all rights reserved
          pragma solidity 0.8.17;
          library RequestIdLib {
              /**
               * @dev Prepares a request ID with the given arguments.
               *
               * @param to receiver;
               * @param chainIdTo opposite chain id;
               * @param from sender;
               * @param chainIdFrom current chain id;
               * @param nonce current nonce.
               */
              function prepareRequestId(
                  bytes32 to,
                  uint256 chainIdTo,
                  bytes32 from,
                  uint256 chainIdFrom,
                  uint256 nonce
              ) internal pure returns (bytes32) {
                  return keccak256(abi.encodePacked(from, nonce, chainIdTo, chainIdFrom, to));
              }
          }
          // SPDX-License-Identifier: UNLICENSED
          // Copyright (c) Eywa.Fi, 2021-2023 - all rights reserved
          pragma solidity 0.8.17;
          abstract contract Typecast {
              function castToAddress(bytes32 x) public pure returns (address) {
                  return address(uint160(uint256(x)));
              }
              function castToBytes32(address a) public pure returns (bytes32) {
                  return bytes32(uint256(uint160(a)));
              }
          }
          

          File 2 of 8: WETH9
          // Copyright (C) 2015, 2016, 2017 Dapphub
          
          // This program is free software: you can redistribute it and/or modify
          // it under the terms of the GNU General Public License as published by
          // the Free Software Foundation, either version 3 of the License, or
          // (at your option) any later version.
          
          // This program is distributed in the hope that it will be useful,
          // but WITHOUT ANY WARRANTY; without even the implied warranty of
          // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
          // GNU General Public License for more details.
          
          // You should have received a copy of the GNU General Public License
          // along with this program.  If not, see <http://www.gnu.org/licenses/>.
          
          pragma solidity ^0.4.18;
          
          contract WETH9 {
              string public name     = "Wrapped Ether";
              string public symbol   = "WETH";
              uint8  public decimals = 18;
          
              event  Approval(address indexed src, address indexed guy, uint wad);
              event  Transfer(address indexed src, address indexed dst, uint wad);
              event  Deposit(address indexed dst, uint wad);
              event  Withdrawal(address indexed src, uint wad);
          
              mapping (address => uint)                       public  balanceOf;
              mapping (address => mapping (address => uint))  public  allowance;
          
              function() public payable {
                  deposit();
              }
              function deposit() public payable {
                  balanceOf[msg.sender] += msg.value;
                  Deposit(msg.sender, msg.value);
              }
              function withdraw(uint wad) public {
                  require(balanceOf[msg.sender] >= wad);
                  balanceOf[msg.sender] -= wad;
                  msg.sender.transfer(wad);
                  Withdrawal(msg.sender, wad);
              }
          
              function totalSupply() public view returns (uint) {
                  return this.balance;
              }
          
              function approve(address guy, uint wad) public returns (bool) {
                  allowance[msg.sender][guy] = wad;
                  Approval(msg.sender, guy, wad);
                  return true;
              }
          
              function transfer(address dst, uint wad) public returns (bool) {
                  return transferFrom(msg.sender, dst, wad);
              }
          
              function transferFrom(address src, address dst, uint wad)
                  public
                  returns (bool)
              {
                  require(balanceOf[src] >= wad);
          
                  if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) {
                      require(allowance[src][msg.sender] >= wad);
                      allowance[src][msg.sender] -= wad;
                  }
          
                  balanceOf[src] -= wad;
                  balanceOf[dst] += wad;
          
                  Transfer(src, dst, wad);
          
                  return true;
              }
          }
          
          
          /*
                              GNU GENERAL PUBLIC LICENSE
                                 Version 3, 29 June 2007
          
           Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
           Everyone is permitted to copy and distribute verbatim copies
           of this license document, but changing it is not allowed.
          
                                      Preamble
          
            The GNU General Public License is a free, copyleft license for
          software and other kinds of works.
          
            The licenses for most software and other practical works are designed
          to take away your freedom to share and change the works.  By contrast,
          the GNU General Public License is intended to guarantee your freedom to
          share and change all versions of a program--to make sure it remains free
          software for all its users.  We, the Free Software Foundation, use the
          GNU General Public License for most of our software; it applies also to
          any other work released this way by its authors.  You can apply it to
          your programs, too.
          
            When we speak of free software, we are referring to freedom, not
          price.  Our General Public Licenses are designed to make sure that you
          have the freedom to distribute copies of free software (and charge for
          them if you wish), that you receive source code or can get it if you
          want it, that you can change the software or use pieces of it in new
          free programs, and that you know you can do these things.
          
            To protect your rights, we need to prevent others from denying you
          these rights or asking you to surrender the rights.  Therefore, you have
          certain responsibilities if you distribute copies of the software, or if
          you modify it: responsibilities to respect the freedom of others.
          
            For example, if you distribute copies of such a program, whether
          gratis or for a fee, you must pass on to the recipients the same
          freedoms that you received.  You must make sure that they, too, receive
          or can get the source code.  And you must show them these terms so they
          know their rights.
          
            Developers that use the GNU GPL protect your rights with two steps:
          (1) assert copyright on the software, and (2) offer you this License
          giving you legal permission to copy, distribute and/or modify it.
          
            For the developers' and authors' protection, the GPL clearly explains
          that there is no warranty for this free software.  For both users' and
          authors' sake, the GPL requires that modified versions be marked as
          changed, so that their problems will not be attributed erroneously to
          authors of previous versions.
          
            Some devices are designed to deny users access to install or run
          modified versions of the software inside them, although the manufacturer
          can do so.  This is fundamentally incompatible with the aim of
          protecting users' freedom to change the software.  The systematic
          pattern of such abuse occurs in the area of products for individuals to
          use, which is precisely where it is most unacceptable.  Therefore, we
          have designed this version of the GPL to prohibit the practice for those
          products.  If such problems arise substantially in other domains, we
          stand ready to extend this provision to those domains in future versions
          of the GPL, as needed to protect the freedom of users.
          
            Finally, every program is threatened constantly by software patents.
          States should not allow patents to restrict development and use of
          software on general-purpose computers, but in those that do, we wish to
          avoid the special danger that patents applied to a free program could
          make it effectively proprietary.  To prevent this, the GPL assures that
          patents cannot be used to render the program non-free.
          
            The precise terms and conditions for copying, distribution and
          modification follow.
          
                                 TERMS AND CONDITIONS
          
            0. Definitions.
          
            "This License" refers to version 3 of the GNU General Public License.
          
            "Copyright" also means copyright-like laws that apply to other kinds of
          works, such as semiconductor masks.
          
            "The Program" refers to any copyrightable work licensed under this
          License.  Each licensee is addressed as "you".  "Licensees" and
          "recipients" may be individuals or organizations.
          
            To "modify" a work means to copy from or adapt all or part of the work
          in a fashion requiring copyright permission, other than the making of an
          exact copy.  The resulting work is called a "modified version" of the
          earlier work or a work "based on" the earlier work.
          
            A "covered work" means either the unmodified Program or a work based
          on the Program.
          
            To "propagate" a work means to do anything with it that, without
          permission, would make you directly or secondarily liable for
          infringement under applicable copyright law, except executing it on a
          computer or modifying a private copy.  Propagation includes copying,
          distribution (with or without modification), making available to the
          public, and in some countries other activities as well.
          
            To "convey" a work means any kind of propagation that enables other
          parties to make or receive copies.  Mere interaction with a user through
          a computer network, with no transfer of a copy, is not conveying.
          
            An interactive user interface displays "Appropriate Legal Notices"
          to the extent that it includes a convenient and prominently visible
          feature that (1) displays an appropriate copyright notice, and (2)
          tells the user that there is no warranty for the work (except to the
          extent that warranties are provided), that licensees may convey the
          work under this License, and how to view a copy of this License.  If
          the interface presents a list of user commands or options, such as a
          menu, a prominent item in the list meets this criterion.
          
            1. Source Code.
          
            The "source code" for a work means the preferred form of the work
          for making modifications to it.  "Object code" means any non-source
          form of a work.
          
            A "Standard Interface" means an interface that either is an official
          standard defined by a recognized standards body, or, in the case of
          interfaces specified for a particular programming language, one that
          is widely used among developers working in that language.
          
            The "System Libraries" of an executable work include anything, other
          than the work as a whole, that (a) is included in the normal form of
          packaging a Major Component, but which is not part of that Major
          Component, and (b) serves only to enable use of the work with that
          Major Component, or to implement a Standard Interface for which an
          implementation is available to the public in source code form.  A
          "Major Component", in this context, means a major essential component
          (kernel, window system, and so on) of the specific operating system
          (if any) on which the executable work runs, or a compiler used to
          produce the work, or an object code interpreter used to run it.
          
            The "Corresponding Source" for a work in object code form means all
          the source code needed to generate, install, and (for an executable
          work) run the object code and to modify the work, including scripts to
          control those activities.  However, it does not include the work's
          System Libraries, or general-purpose tools or generally available free
          programs which are used unmodified in performing those activities but
          which are not part of the work.  For example, Corresponding Source
          includes interface definition files associated with source files for
          the work, and the source code for shared libraries and dynamically
          linked subprograms that the work is specifically designed to require,
          such as by intimate data communication or control flow between those
          subprograms and other parts of the work.
          
            The Corresponding Source need not include anything that users
          can regenerate automatically from other parts of the Corresponding
          Source.
          
            The Corresponding Source for a work in source code form is that
          same work.
          
            2. Basic Permissions.
          
            All rights granted under this License are granted for the term of
          copyright on the Program, and are irrevocable provided the stated
          conditions are met.  This License explicitly affirms your unlimited
          permission to run the unmodified Program.  The output from running a
          covered work is covered by this License only if the output, given its
          content, constitutes a covered work.  This License acknowledges your
          rights of fair use or other equivalent, as provided by copyright law.
          
            You may make, run and propagate covered works that you do not
          convey, without conditions so long as your license otherwise remains
          in force.  You may convey covered works to others for the sole purpose
          of having them make modifications exclusively for you, or provide you
          with facilities for running those works, provided that you comply with
          the terms of this License in conveying all material for which you do
          not control copyright.  Those thus making or running the covered works
          for you must do so exclusively on your behalf, under your direction
          and control, on terms that prohibit them from making any copies of
          your copyrighted material outside their relationship with you.
          
            Conveying under any other circumstances is permitted solely under
          the conditions stated below.  Sublicensing is not allowed; section 10
          makes it unnecessary.
          
            3. Protecting Users' Legal Rights From Anti-Circumvention Law.
          
            No covered work shall be deemed part of an effective technological
          measure under any applicable law fulfilling obligations under article
          11 of the WIPO copyright treaty adopted on 20 December 1996, or
          similar laws prohibiting or restricting circumvention of such
          measures.
          
            When you convey a covered work, you waive any legal power to forbid
          circumvention of technological measures to the extent such circumvention
          is effected by exercising rights under this License with respect to
          the covered work, and you disclaim any intention to limit operation or
          modification of the work as a means of enforcing, against the work's
          users, your or third parties' legal rights to forbid circumvention of
          technological measures.
          
            4. Conveying Verbatim Copies.
          
            You may convey verbatim copies of the Program's source code as you
          receive it, in any medium, provided that you conspicuously and
          appropriately publish on each copy an appropriate copyright notice;
          keep intact all notices stating that this License and any
          non-permissive terms added in accord with section 7 apply to the code;
          keep intact all notices of the absence of any warranty; and give all
          recipients a copy of this License along with the Program.
          
            You may charge any price or no price for each copy that you convey,
          and you may offer support or warranty protection for a fee.
          
            5. Conveying Modified Source Versions.
          
            You may convey a work based on the Program, or the modifications to
          produce it from the Program, in the form of source code under the
          terms of section 4, provided that you also meet all of these conditions:
          
              a) The work must carry prominent notices stating that you modified
              it, and giving a relevant date.
          
              b) The work must carry prominent notices stating that it is
              released under this License and any conditions added under section
              7.  This requirement modifies the requirement in section 4 to
              "keep intact all notices".
          
              c) You must license the entire work, as a whole, under this
              License to anyone who comes into possession of a copy.  This
              License will therefore apply, along with any applicable section 7
              additional terms, to the whole of the work, and all its parts,
              regardless of how they are packaged.  This License gives no
              permission to license the work in any other way, but it does not
              invalidate such permission if you have separately received it.
          
              d) If the work has interactive user interfaces, each must display
              Appropriate Legal Notices; however, if the Program has interactive
              interfaces that do not display Appropriate Legal Notices, your
              work need not make them do so.
          
            A compilation of a covered work with other separate and independent
          works, which are not by their nature extensions of the covered work,
          and which are not combined with it such as to form a larger program,
          in or on a volume of a storage or distribution medium, is called an
          "aggregate" if the compilation and its resulting copyright are not
          used to limit the access or legal rights of the compilation's users
          beyond what the individual works permit.  Inclusion of a covered work
          in an aggregate does not cause this License to apply to the other
          parts of the aggregate.
          
            6. Conveying Non-Source Forms.
          
            You may convey a covered work in object code form under the terms
          of sections 4 and 5, provided that you also convey the
          machine-readable Corresponding Source under the terms of this License,
          in one of these ways:
          
              a) Convey the object code in, or embodied in, a physical product
              (including a physical distribution medium), accompanied by the
              Corresponding Source fixed on a durable physical medium
              customarily used for software interchange.
          
              b) Convey the object code in, or embodied in, a physical product
              (including a physical distribution medium), accompanied by a
              written offer, valid for at least three years and valid for as
              long as you offer spare parts or customer support for that product
              model, to give anyone who possesses the object code either (1) a
              copy of the Corresponding Source for all the software in the
              product that is covered by this License, on a durable physical
              medium customarily used for software interchange, for a price no
              more than your reasonable cost of physically performing this
              conveying of source, or (2) access to copy the
              Corresponding Source from a network server at no charge.
          
              c) Convey individual copies of the object code with a copy of the
              written offer to provide the Corresponding Source.  This
              alternative is allowed only occasionally and noncommercially, and
              only if you received the object code with such an offer, in accord
              with subsection 6b.
          
              d) Convey the object code by offering access from a designated
              place (gratis or for a charge), and offer equivalent access to the
              Corresponding Source in the same way through the same place at no
              further charge.  You need not require recipients to copy the
              Corresponding Source along with the object code.  If the place to
              copy the object code is a network server, the Corresponding Source
              may be on a different server (operated by you or a third party)
              that supports equivalent copying facilities, provided you maintain
              clear directions next to the object code saying where to find the
              Corresponding Source.  Regardless of what server hosts the
              Corresponding Source, you remain obligated to ensure that it is
              available for as long as needed to satisfy these requirements.
          
              e) Convey the object code using peer-to-peer transmission, provided
              you inform other peers where the object code and Corresponding
              Source of the work are being offered to the general public at no
              charge under subsection 6d.
          
            A separable portion of the object code, whose source code is excluded
          from the Corresponding Source as a System Library, need not be
          included in conveying the object code work.
          
            A "User Product" is either (1) a "consumer product", which means any
          tangible personal property which is normally used for personal, family,
          or household purposes, or (2) anything designed or sold for incorporation
          into a dwelling.  In determining whether a product is a consumer product,
          doubtful cases shall be resolved in favor of coverage.  For a particular
          product received by a particular user, "normally used" refers to a
          typical or common use of that class of product, regardless of the status
          of the particular user or of the way in which the particular user
          actually uses, or expects or is expected to use, the product.  A product
          is a consumer product regardless of whether the product has substantial
          commercial, industrial or non-consumer uses, unless such uses represent
          the only significant mode of use of the product.
          
            "Installation Information" for a User Product means any methods,
          procedures, authorization keys, or other information required to install
          and execute modified versions of a covered work in that User Product from
          a modified version of its Corresponding Source.  The information must
          suffice to ensure that the continued functioning of the modified object
          code is in no case prevented or interfered with solely because
          modification has been made.
          
            If you convey an object code work under this section in, or with, or
          specifically for use in, a User Product, and the conveying occurs as
          part of a transaction in which the right of possession and use of the
          User Product is transferred to the recipient in perpetuity or for a
          fixed term (regardless of how the transaction is characterized), the
          Corresponding Source conveyed under this section must be accompanied
          by the Installation Information.  But this requirement does not apply
          if neither you nor any third party retains the ability to install
          modified object code on the User Product (for example, the work has
          been installed in ROM).
          
            The requirement to provide Installation Information does not include a
          requirement to continue to provide support service, warranty, or updates
          for a work that has been modified or installed by the recipient, or for
          the User Product in which it has been modified or installed.  Access to a
          network may be denied when the modification itself materially and
          adversely affects the operation of the network or violates the rules and
          protocols for communication across the network.
          
            Corresponding Source conveyed, and Installation Information provided,
          in accord with this section must be in a format that is publicly
          documented (and with an implementation available to the public in
          source code form), and must require no special password or key for
          unpacking, reading or copying.
          
            7. Additional Terms.
          
            "Additional permissions" are terms that supplement the terms of this
          License by making exceptions from one or more of its conditions.
          Additional permissions that are applicable to the entire Program shall
          be treated as though they were included in this License, to the extent
          that they are valid under applicable law.  If additional permissions
          apply only to part of the Program, that part may be used separately
          under those permissions, but the entire Program remains governed by
          this License without regard to the additional permissions.
          
            When you convey a copy of a covered work, you may at your option
          remove any additional permissions from that copy, or from any part of
          it.  (Additional permissions may be written to require their own
          removal in certain cases when you modify the work.)  You may place
          additional permissions on material, added by you to a covered work,
          for which you have or can give appropriate copyright permission.
          
            Notwithstanding any other provision of this License, for material you
          add to a covered work, you may (if authorized by the copyright holders of
          that material) supplement the terms of this License with terms:
          
              a) Disclaiming warranty or limiting liability differently from the
              terms of sections 15 and 16 of this License; or
          
              b) Requiring preservation of specified reasonable legal notices or
              author attributions in that material or in the Appropriate Legal
              Notices displayed by works containing it; or
          
              c) Prohibiting misrepresentation of the origin of that material, or
              requiring that modified versions of such material be marked in
              reasonable ways as different from the original version; or
          
              d) Limiting the use for publicity purposes of names of licensors or
              authors of the material; or
          
              e) Declining to grant rights under trademark law for use of some
              trade names, trademarks, or service marks; or
          
              f) Requiring indemnification of licensors and authors of that
              material by anyone who conveys the material (or modified versions of
              it) with contractual assumptions of liability to the recipient, for
              any liability that these contractual assumptions directly impose on
              those licensors and authors.
          
            All other non-permissive additional terms are considered "further
          restrictions" within the meaning of section 10.  If the Program as you
          received it, or any part of it, contains a notice stating that it is
          governed by this License along with a term that is a further
          restriction, you may remove that term.  If a license document contains
          a further restriction but permits relicensing or conveying under this
          License, you may add to a covered work material governed by the terms
          of that license document, provided that the further restriction does
          not survive such relicensing or conveying.
          
            If you add terms to a covered work in accord with this section, you
          must place, in the relevant source files, a statement of the
          additional terms that apply to those files, or a notice indicating
          where to find the applicable terms.
          
            Additional terms, permissive or non-permissive, may be stated in the
          form of a separately written license, or stated as exceptions;
          the above requirements apply either way.
          
            8. Termination.
          
            You may not propagate or modify a covered work except as expressly
          provided under this License.  Any attempt otherwise to propagate or
          modify it is void, and will automatically terminate your rights under
          this License (including any patent licenses granted under the third
          paragraph of section 11).
          
            However, if you cease all violation of this License, then your
          license from a particular copyright holder is reinstated (a)
          provisionally, unless and until the copyright holder explicitly and
          finally terminates your license, and (b) permanently, if the copyright
          holder fails to notify you of the violation by some reasonable means
          prior to 60 days after the cessation.
          
            Moreover, your license from a particular copyright holder is
          reinstated permanently if the copyright holder notifies you of the
          violation by some reasonable means, this is the first time you have
          received notice of violation of this License (for any work) from that
          copyright holder, and you cure the violation prior to 30 days after
          your receipt of the notice.
          
            Termination of your rights under this section does not terminate the
          licenses of parties who have received copies or rights from you under
          this License.  If your rights have been terminated and not permanently
          reinstated, you do not qualify to receive new licenses for the same
          material under section 10.
          
            9. Acceptance Not Required for Having Copies.
          
            You are not required to accept this License in order to receive or
          run a copy of the Program.  Ancillary propagation of a covered work
          occurring solely as a consequence of using peer-to-peer transmission
          to receive a copy likewise does not require acceptance.  However,
          nothing other than this License grants you permission to propagate or
          modify any covered work.  These actions infringe copyright if you do
          not accept this License.  Therefore, by modifying or propagating a
          covered work, you indicate your acceptance of this License to do so.
          
            10. Automatic Licensing of Downstream Recipients.
          
            Each time you convey a covered work, the recipient automatically
          receives a license from the original licensors, to run, modify and
          propagate that work, subject to this License.  You are not responsible
          for enforcing compliance by third parties with this License.
          
            An "entity transaction" is a transaction transferring control of an
          organization, or substantially all assets of one, or subdividing an
          organization, or merging organizations.  If propagation of a covered
          work results from an entity transaction, each party to that
          transaction who receives a copy of the work also receives whatever
          licenses to the work the party's predecessor in interest had or could
          give under the previous paragraph, plus a right to possession of the
          Corresponding Source of the work from the predecessor in interest, if
          the predecessor has it or can get it with reasonable efforts.
          
            You may not impose any further restrictions on the exercise of the
          rights granted or affirmed under this License.  For example, you may
          not impose a license fee, royalty, or other charge for exercise of
          rights granted under this License, and you may not initiate litigation
          (including a cross-claim or counterclaim in a lawsuit) alleging that
          any patent claim is infringed by making, using, selling, offering for
          sale, or importing the Program or any portion of it.
          
            11. Patents.
          
            A "contributor" is a copyright holder who authorizes use under this
          License of the Program or a work on which the Program is based.  The
          work thus licensed is called the contributor's "contributor version".
          
            A contributor's "essential patent claims" are all patent claims
          owned or controlled by the contributor, whether already acquired or
          hereafter acquired, that would be infringed by some manner, permitted
          by this License, of making, using, or selling its contributor version,
          but do not include claims that would be infringed only as a
          consequence of further modification of the contributor version.  For
          purposes of this definition, "control" includes the right to grant
          patent sublicenses in a manner consistent with the requirements of
          this License.
          
            Each contributor grants you a non-exclusive, worldwide, royalty-free
          patent license under the contributor's essential patent claims, to
          make, use, sell, offer for sale, import and otherwise run, modify and
          propagate the contents of its contributor version.
          
            In the following three paragraphs, a "patent license" is any express
          agreement or commitment, however denominated, not to enforce a patent
          (such as an express permission to practice a patent or covenant not to
          sue for patent infringement).  To "grant" such a patent license to a
          party means to make such an agreement or commitment not to enforce a
          patent against the party.
          
            If you convey a covered work, knowingly relying on a patent license,
          and the Corresponding Source of the work is not available for anyone
          to copy, free of charge and under the terms of this License, through a
          publicly available network server or other readily accessible means,
          then you must either (1) cause the Corresponding Source to be so
          available, or (2) arrange to deprive yourself of the benefit of the
          patent license for this particular work, or (3) arrange, in a manner
          consistent with the requirements of this License, to extend the patent
          license to downstream recipients.  "Knowingly relying" means you have
          actual knowledge that, but for the patent license, your conveying the
          covered work in a country, or your recipient's use of the covered work
          in a country, would infringe one or more identifiable patents in that
          country that you have reason to believe are valid.
          
            If, pursuant to or in connection with a single transaction or
          arrangement, you convey, or propagate by procuring conveyance of, a
          covered work, and grant a patent license to some of the parties
          receiving the covered work authorizing them to use, propagate, modify
          or convey a specific copy of the covered work, then the patent license
          you grant is automatically extended to all recipients of the covered
          work and works based on it.
          
            A patent license is "discriminatory" if it does not include within
          the scope of its coverage, prohibits the exercise of, or is
          conditioned on the non-exercise of one or more of the rights that are
          specifically granted under this License.  You may not convey a covered
          work if you are a party to an arrangement with a third party that is
          in the business of distributing software, under which you make payment
          to the third party based on the extent of your activity of conveying
          the work, and under which the third party grants, to any of the
          parties who would receive the covered work from you, a discriminatory
          patent license (a) in connection with copies of the covered work
          conveyed by you (or copies made from those copies), or (b) primarily
          for and in connection with specific products or compilations that
          contain the covered work, unless you entered into that arrangement,
          or that patent license was granted, prior to 28 March 2007.
          
            Nothing in this License shall be construed as excluding or limiting
          any implied license or other defenses to infringement that may
          otherwise be available to you under applicable patent law.
          
            12. No Surrender of Others' Freedom.
          
            If conditions are imposed on you (whether by court order, agreement or
          otherwise) that contradict the conditions of this License, they do not
          excuse you from the conditions of this License.  If you cannot convey a
          covered work so as to satisfy simultaneously your obligations under this
          License and any other pertinent obligations, then as a consequence you may
          not convey it at all.  For example, if you agree to terms that obligate you
          to collect a royalty for further conveying from those to whom you convey
          the Program, the only way you could satisfy both those terms and this
          License would be to refrain entirely from conveying the Program.
          
            13. Use with the GNU Affero General Public License.
          
            Notwithstanding any other provision of this License, you have
          permission to link or combine any covered work with a work licensed
          under version 3 of the GNU Affero General Public License into a single
          combined work, and to convey the resulting work.  The terms of this
          License will continue to apply to the part which is the covered work,
          but the special requirements of the GNU Affero General Public License,
          section 13, concerning interaction through a network will apply to the
          combination as such.
          
            14. Revised Versions of this License.
          
            The Free Software Foundation may publish revised and/or new versions of
          the GNU General Public License from time to time.  Such new versions will
          be similar in spirit to the present version, but may differ in detail to
          address new problems or concerns.
          
            Each version is given a distinguishing version number.  If the
          Program specifies that a certain numbered version of the GNU General
          Public License "or any later version" applies to it, you have the
          option of following the terms and conditions either of that numbered
          version or of any later version published by the Free Software
          Foundation.  If the Program does not specify a version number of the
          GNU General Public License, you may choose any version ever published
          by the Free Software Foundation.
          
            If the Program specifies that a proxy can decide which future
          versions of the GNU General Public License can be used, that proxy's
          public statement of acceptance of a version permanently authorizes you
          to choose that version for the Program.
          
            Later license versions may give you additional or different
          permissions.  However, no additional obligations are imposed on any
          author or copyright holder as a result of your choosing to follow a
          later version.
          
            15. Disclaimer of Warranty.
          
            THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
          APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
          HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
          OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
          THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
          PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
          IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
          ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
          
            16. Limitation of Liability.
          
            IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
          WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
          THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
          GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
          USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
          DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
          PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
          EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
          SUCH DAMAGES.
          
            17. Interpretation of Sections 15 and 16.
          
            If the disclaimer of warranty and limitation of liability provided
          above cannot be given local legal effect according to their terms,
          reviewing courts shall apply local law that most closely approximates
          an absolute waiver of all civil liability in connection with the
          Program, unless a warranty or assumption of liability accompanies a
          copy of the Program in return for a fee.
          
                               END OF TERMS AND CONDITIONS
          
                      How to Apply These Terms to Your New Programs
          
            If you develop a new program, and you want it to be of the greatest
          possible use to the public, the best way to achieve this is to make it
          free software which everyone can redistribute and change under these terms.
          
            To do so, attach the following notices to the program.  It is safest
          to attach them to the start of each source file to most effectively
          state the exclusion of warranty; and each file should have at least
          the "copyright" line and a pointer to where the full notice is found.
          
              <one line to give the program's name and a brief idea of what it does.>
              Copyright (C) <year>  <name of author>
          
              This program is free software: you can redistribute it and/or modify
              it under the terms of the GNU General Public License as published by
              the Free Software Foundation, either version 3 of the License, or
              (at your option) any later version.
          
              This program is distributed in the hope that it will be useful,
              but WITHOUT ANY WARRANTY; without even the implied warranty of
              MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
              GNU General Public License for more details.
          
              You should have received a copy of the GNU General Public License
              along with this program.  If not, see <http://www.gnu.org/licenses/>.
          
          Also add information on how to contact you by electronic and paper mail.
          
            If the program does terminal interaction, make it output a short
          notice like this when it starts in an interactive mode:
          
              <program>  Copyright (C) <year>  <name of author>
              This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
              This is free software, and you are welcome to redistribute it
              under certain conditions; type `show c' for details.
          
          The hypothetical commands `show w' and `show c' should show the appropriate
          parts of the General Public License.  Of course, your program's commands
          might be different; for a GUI interface, you would use an "about box".
          
            You should also get your employer (if you work as a programmer) or school,
          if any, to sign a "copyright disclaimer" for the program, if necessary.
          For more information on this, and how to apply and follow the GNU GPL, see
          <http://www.gnu.org/licenses/>.
          
            The GNU General Public License does not permit incorporating your program
          into proprietary programs.  If your program is a subroutine library, you
          may consider it more useful to permit linking proprietary applications with
          the library.  If this is what you want to do, use the GNU Lesser General
          Public License instead of this License.  But first, please read
          <http://www.gnu.org/philosophy/why-not-lgpl.html>.
          
          */

          File 3 of 8: PortalV2
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (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 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. Can only be called by the current owner.
               *
               * NOTE: Renouncing ownership will leave the contract without an owner,
               * thereby disabling any functionality that is only available to the owner.
               */
              function renounceOwnership() public virtual onlyOwner {
                  _transferOwnership(address(0));
              }
              /**
               * @dev Transfers ownership of the contract to a new account (`newOwner`).
               * Can only be called by the current owner.
               */
              function transferOwnership(address newOwner) public virtual onlyOwner {
                  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 (last updated v4.9.0) (token/ERC20/extensions/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 (last updated v4.9.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);
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
          pragma solidity ^0.8.0;
          import "../IERC20.sol";
          import "../extensions/IERC20Permit.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 Address for address;
              /**
               * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
               * non-reverting calls are assumed to be successful.
               */
              function safeTransfer(IERC20 token, address to, uint256 value) internal {
                  _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
              }
              /**
               * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
               * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
               */
              function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
                  _callOptionalReturn(token, abi.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'
                  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));
              }
              /**
               * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
               * non-reverting calls are assumed to be successful.
               */
              function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                  uint256 oldAllowance = token.allowance(address(this), spender);
                  _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
              }
              /**
               * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
               * non-reverting calls are assumed to be successful.
               */
              function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                  unchecked {
                      uint256 oldAllowance = token.allowance(address(this), spender);
                      require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
                      _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
                  }
              }
              /**
               * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
               * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
               * to be set to zero before setting it to a non-zero value, such as USDT.
               */
              function forceApprove(IERC20 token, address spender, uint256 value) internal {
                  bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
                  if (!_callOptionalReturnBool(token, approvalCall)) {
                      _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
                      _callOptionalReturn(token, approvalCall);
                  }
              }
              /**
               * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
               * Revert on invalid signature.
               */
              function safePermit(
                  IERC20Permit token,
                  address owner,
                  address spender,
                  uint256 value,
                  uint256 deadline,
                  uint8 v,
                  bytes32 r,
                  bytes32 s
              ) internal {
                  uint256 nonceBefore = token.nonces(owner);
                  token.permit(owner, spender, value, deadline, v, r, s);
                  uint256 nonceAfter = token.nonces(owner);
                  require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
              }
              /**
               * @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");
                  require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
              }
              /**
               * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
               * on the return value: the return value is optional (but if data is returned, it must not be false).
               * @param token The token targeted by the call.
               * @param data The call data (encoded using abi.encode or one of its variants).
               *
               * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
               */
              function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
                  // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                  // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
                  // and not revert is the subcall reverts.
                  (bool success, bytes memory returndata) = address(token).call(data);
                  return
                      success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.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
               *
               * Furthermore, `isContract` will also return true if the target contract within
               * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
               * which only has an effect at the end of a transaction.
               * ====
               *
               * [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://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
               *
               * IMPORTANT: because control is transferred to `recipient`, care must be
               * taken to not create reentrancy vulnerabilities. Consider using
               * {ReentrancyGuard} or the
               * https://solidity.readthedocs.io/en/v0.8.0/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 functionCallWithValue(target, data, 0, "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");
                  (bool success, bytes memory returndata) = target.call{value: value}(data);
                  return verifyCallResultFromTarget(target, 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) {
                  (bool success, bytes memory returndata) = target.staticcall(data);
                  return verifyCallResultFromTarget(target, 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) {
                  (bool success, bytes memory returndata) = target.delegatecall(data);
                  return verifyCallResultFromTarget(target, success, returndata, errorMessage);
              }
              /**
               * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
               * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
               *
               * _Available since v4.8._
               */
              function verifyCallResultFromTarget(
                  address target,
                  bool success,
                  bytes memory returndata,
                  string memory errorMessage
              ) internal view returns (bytes memory) {
                  if (success) {
                      if (returndata.length == 0) {
                          // only check isContract if the call was successful and the return data is empty
                          // otherwise we already know that it was a contract
                          require(isContract(target), "Address: call to non-contract");
                      }
                      return returndata;
                  } else {
                      _revert(returndata, errorMessage);
                  }
              }
              /**
               * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
               * revert reason or 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 {
                      _revert(returndata, errorMessage);
                  }
              }
              function _revert(bytes memory returndata, string memory errorMessage) private pure {
                  // Look for revert reason and bubble it up if present
                  if (returndata.length > 0) {
                      // The easiest way to bubble the revert reason is using memory via assembly
                      /// @solidity memory-safe-assembly
                      assembly {
                          let returndata_size := mload(returndata)
                          revert(add(32, returndata), returndata_size)
                      }
                  } else {
                      revert(errorMessage);
                  }
              }
          }
          // 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: UNLICENSED
          // Copyright (c) Eywa.Fi, 2021-2023 - all rights reserved
          pragma solidity 0.8.17;
          import "./utils/Typecast.sol";
          contract EndPoint is Typecast {
              /// @dev version
              string public version;
              /// @dev clp address book
              address public addressBook;
              constructor (address addressBook_) {
                  version = "2.2.3";
                  _checkAddress(addressBook_);
                  addressBook = addressBook_;
              }
              function _setAddressBook(address addressBook_) internal {
                  _checkAddress(addressBook_);
                  addressBook = addressBook_;
              }
              function _checkAddress(address checkingAddress) private pure {
                  require(checkingAddress != address(0), "EndPoint: zero address");
              }
          }
          // SPDX-License-Identifier: UNLICENSED
          // Copyright (c) Eywa.Fi, 2021-2023 - all rights reserved
          pragma solidity 0.8.17;
          interface IAddressBook {
              /// @dev returns portal by given chainId
              function portal(uint64 chainId) external view returns (address);
              /// @dev returns synthesis by given chainId
              function synthesis(uint64 chainId) external view returns (address);
              /// @dev returns router by given chainId
              function router(uint64 chainId) external view returns (address);
              /// @dev returns whitelist
              function whitelist() external view returns (address);
              /// @dev returns treasury
              function treasury() external view returns (address);
              /// @dev returns gateKeeper
              function gateKeeper() external view returns (address);
              /// @dev returns bridge
              function bridge() external view returns (address);
          }// SPDX-License-Identifier: UNLICENSED
          // Copyright (c) Eywa.Fi, 2021-2023 - all rights reserved
          pragma solidity 0.8.17;
          interface IWhitelist {
              enum TokenState { NotSet, InOut }
              enum PoolState { NotSet, AddSwapRemove }
              struct TokenStatus {
                  address token;
                  uint256 min;
                  uint256 max;
                  uint256 bridgeFee;
                  TokenState state;
              }
              struct PoolStatus {
                  address pool;
                  uint256 aggregationFee;
                  PoolState state;
              }
              
              function tokenMin(address token) external view returns (uint256);
              function tokenMax(address token) external view returns (uint256);
              function tokenMinMax(address token) external view returns (uint256, uint256);
              function bridgeFee(address token) external view returns (uint256);
              function tokenState(address token) external view returns (uint8);
              function tokenStatus(address token) external view returns (TokenStatus memory);
              function tokens(uint256 offset, uint256 count) external view returns (TokenStatus[] memory);
              function aggregationFee(address pool) external view returns (uint256);
              function poolState(address pool) external view returns (uint8);
              function poolStatus(address pool) external view returns (PoolStatus memory);
              function pools(uint256 offset, uint256 count) external view returns (PoolStatus[] memory);
          }
          // SPDX-License-Identifier: UNLICENSED
          // Copyright (c) Eywa.Fi, 2021-2023 - all rights reserved
          pragma solidity 0.8.17;
          import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
          import "@openzeppelin/contracts/access/Ownable.sol";
          import "./EndPoint.sol";
          import "./interfaces/IWhitelist.sol";
          import "./interfaces/IAddressBook.sol";
          contract PortalV2 is EndPoint, Ownable {
              /// @dev fee denominator
              uint256 public constant FEE_DENOMINATOR = 10000;
              /// @dev locked balances
              mapping(address => uint256) public balanceOf;
              event Locked(address token, uint256 amount, address from, address to);
              event Unlocked(address token, uint256 amount, address from, address to);
              modifier checkAmount(uint256 amount, address token) {
                  address whitelist = IAddressBook(addressBook).whitelist();
                  require(
                      amount >= IWhitelist(whitelist).tokenMin(token) && amount <= IWhitelist(whitelist).tokenMax(token),
                      "Portal: wrong amount"
                  );
                  _;
              }
              modifier onlyRouter() {
                  address router = IAddressBook(addressBook).router(uint64(block.chainid));
                  require(router == msg.sender, "Portal: router only");
                  _;
              }
              constructor (address addressBook_) EndPoint(addressBook_) {}
              /**
               * @dev Sets address book.
               *
               * Controlled by DAO and\\or multisig (3 out of 5, Gnosis Safe).
               *
               * @param addressBook_ address book contract address.
               */
              function setAddressBook(address addressBook_) external onlyOwner {
                  _setAddressBook(addressBook_);
              }
              /**
               * @dev Lock token.
               *
               * @param token token address to synthesize;
               * @param amount amount to synthesize;
               * @param from sender address;
               * @param to receiver address.
               */
              function lock(
                  address token,
                  uint256 amount,
                  address from,
                  address to
              ) external onlyRouter checkAmount(amount, token) {
                  address whitelist = IAddressBook(addressBook).whitelist();
                  require(IWhitelist(whitelist).tokenState(token) == uint8(IWhitelist.TokenState.InOut), "Portal: token must be whitelisted");
                  _updateBalance(token, amount);
                  emit Locked(token, amount, from, to);
              }
              /**
               * @dev Unlock. Can be called only by router after initiation on a second chain.
               *
               * @param otoken token address to unsynth;
               * @param amount amount to unsynth;
               * @param from sender address;
               * @param to recipient address.
               */
              function unlock(
                  address otoken,
                  uint256 amount,
                  address from,
                  address to
              ) external onlyRouter returns (uint256 amountOut) {
                  IAddressBook addressBookImpl = IAddressBook(addressBook);
                  address whitelist = addressBookImpl.whitelist();
                  address treasury = addressBookImpl.treasury();
                  require(IWhitelist(whitelist).tokenState(otoken) == uint8(IWhitelist.TokenState.InOut), "Portal: token must be whitelisted");
                  uint256 feeAmount = amount * IWhitelist(whitelist).bridgeFee(otoken) / FEE_DENOMINATOR;
                  amountOut = amount - feeAmount;
                  SafeERC20.safeTransfer(IERC20(otoken), to, amountOut);
                  SafeERC20.safeTransfer(IERC20(otoken), treasury, feeAmount);
                  balanceOf[otoken] -= amount;
                  emit Unlocked(otoken, amount, from, to);
              }
              /**
               * @dev Emergency unlock. Can be called only by router after initiation on opposite chain.
               *
               * @param otoken token address to unsynth;
               * @param amount amount to unsynth;
               * @param from sender address;
               * @param to recipient address.
               */
              function emergencyUnlock(
                  address otoken,
                  uint256 amount,
                  address from,
                  address to
              ) external onlyRouter returns (uint256 amountOut) {
                  address whitelist = IAddressBook(addressBook).whitelist();
                  require(IWhitelist(whitelist).tokenState(otoken) == uint8(IWhitelist.TokenState.InOut), "Portal: token must be whitelisted");
                  amountOut = amount;
                  SafeERC20.safeTransfer(IERC20(otoken), to, amountOut);
                  balanceOf[otoken] -= amount;
                  emit Unlocked(otoken, amount, from, to);
              }
              function _updateBalance(address token, uint256 expectedAmount) private {
                  uint256 oldBalance = balanceOf[token];
                  require(
                      (IERC20(token).balanceOf(address(this)) - oldBalance) >= expectedAmount,
                      "Portal: insufficient balance"
                  );
                  balanceOf[token] += expectedAmount;
              }
          }
          // SPDX-License-Identifier: UNLICENSED
          // Copyright (c) Eywa.Fi, 2021-2023 - all rights reserved
          pragma solidity 0.8.17;
          abstract contract Typecast {
              function castToAddress(bytes32 x) public pure returns (address) {
                  return address(uint160(uint256(x)));
              }
              function castToBytes32(address a) public pure returns (bytes32) {
                  return bytes32(uint256(uint160(a)));
              }
          }
          

          File 4 of 8: GateKeeper
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.8.0) (access/AccessControl.sol)
          pragma solidity ^0.8.0;
          import "./IAccessControl.sol";
          import "../utils/Context.sol";
          import "../utils/Strings.sol";
          import "../utils/introspection/ERC165.sol";
          /**
           * @dev Contract module that allows children to implement role-based access
           * control mechanisms. This is a lightweight version that doesn't allow enumerating role
           * members except through off-chain means by accessing the contract event logs. Some
           * applications may benefit from on-chain enumerability, for those cases see
           * {AccessControlEnumerable}.
           *
           * Roles are referred to by their `bytes32` identifier. These should be exposed
           * in the external API and be unique. The best way to achieve this is by
           * using `public constant` hash digests:
           *
           * ```
           * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
           * ```
           *
           * Roles can be used to represent a set of permissions. To restrict access to a
           * function call, use {hasRole}:
           *
           * ```
           * function foo() public {
           *     require(hasRole(MY_ROLE, msg.sender));
           *     ...
           * }
           * ```
           *
           * Roles can be granted and revoked dynamically via the {grantRole} and
           * {revokeRole} functions. Each role has an associated admin role, and only
           * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
           *
           * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
           * that only accounts with this role will be able to grant or revoke other
           * roles. More complex role relationships can be created by using
           * {_setRoleAdmin}.
           *
           * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
           * grant and revoke this role. Extra precautions should be taken to secure
           * accounts that have been granted it.
           */
          abstract contract AccessControl is Context, IAccessControl, ERC165 {
              struct RoleData {
                  mapping(address => bool) members;
                  bytes32 adminRole;
              }
              mapping(bytes32 => RoleData) private _roles;
              bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
              /**
               * @dev Modifier that checks that an account has a specific role. Reverts
               * with a standardized message including the required role.
               *
               * The format of the revert reason is given by the following regular expression:
               *
               *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
               *
               * _Available since v4.1._
               */
              modifier onlyRole(bytes32 role) {
                  _checkRole(role);
                  _;
              }
              /**
               * @dev See {IERC165-supportsInterface}.
               */
              function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                  return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
              }
              /**
               * @dev Returns `true` if `account` has been granted `role`.
               */
              function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
                  return _roles[role].members[account];
              }
              /**
               * @dev Revert with a standard message if `_msgSender()` is missing `role`.
               * Overriding this function changes the behavior of the {onlyRole} modifier.
               *
               * Format of the revert message is described in {_checkRole}.
               *
               * _Available since v4.6._
               */
              function _checkRole(bytes32 role) internal view virtual {
                  _checkRole(role, _msgSender());
              }
              /**
               * @dev Revert with a standard message if `account` is missing `role`.
               *
               * The format of the revert reason is given by the following regular expression:
               *
               *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
               */
              function _checkRole(bytes32 role, address account) internal view virtual {
                  if (!hasRole(role, account)) {
                      revert(
                          string(
                              abi.encodePacked(
                                  "AccessControl: account ",
                                  Strings.toHexString(account),
                                  " is missing role ",
                                  Strings.toHexString(uint256(role), 32)
                              )
                          )
                      );
                  }
              }
              /**
               * @dev Returns the admin role that controls `role`. See {grantRole} and
               * {revokeRole}.
               *
               * To change a role's admin, use {_setRoleAdmin}.
               */
              function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
                  return _roles[role].adminRole;
              }
              /**
               * @dev Grants `role` to `account`.
               *
               * If `account` had not been already granted `role`, emits a {RoleGranted}
               * event.
               *
               * Requirements:
               *
               * - the caller must have ``role``'s admin role.
               *
               * May emit a {RoleGranted} event.
               */
              function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
                  _grantRole(role, account);
              }
              /**
               * @dev Revokes `role` from `account`.
               *
               * If `account` had been granted `role`, emits a {RoleRevoked} event.
               *
               * Requirements:
               *
               * - the caller must have ``role``'s admin role.
               *
               * May emit a {RoleRevoked} event.
               */
              function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
                  _revokeRole(role, account);
              }
              /**
               * @dev Revokes `role` from the calling account.
               *
               * Roles are often managed via {grantRole} and {revokeRole}: this function's
               * purpose is to provide a mechanism for accounts to lose their privileges
               * if they are compromised (such as when a trusted device is misplaced).
               *
               * If the calling account had been revoked `role`, emits a {RoleRevoked}
               * event.
               *
               * Requirements:
               *
               * - the caller must be `account`.
               *
               * May emit a {RoleRevoked} event.
               */
              function renounceRole(bytes32 role, address account) public virtual override {
                  require(account == _msgSender(), "AccessControl: can only renounce roles for self");
                  _revokeRole(role, account);
              }
              /**
               * @dev Grants `role` to `account`.
               *
               * If `account` had not been already granted `role`, emits a {RoleGranted}
               * event. Note that unlike {grantRole}, this function doesn't perform any
               * checks on the calling account.
               *
               * May emit a {RoleGranted} event.
               *
               * [WARNING]
               * ====
               * This function should only be called from the constructor when setting
               * up the initial roles for the system.
               *
               * Using this function in any other way is effectively circumventing the admin
               * system imposed by {AccessControl}.
               * ====
               *
               * NOTE: This function is deprecated in favor of {_grantRole}.
               */
              function _setupRole(bytes32 role, address account) internal virtual {
                  _grantRole(role, account);
              }
              /**
               * @dev Sets `adminRole` as ``role``'s admin role.
               *
               * Emits a {RoleAdminChanged} event.
               */
              function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
                  bytes32 previousAdminRole = getRoleAdmin(role);
                  _roles[role].adminRole = adminRole;
                  emit RoleAdminChanged(role, previousAdminRole, adminRole);
              }
              /**
               * @dev Grants `role` to `account`.
               *
               * Internal function without access restriction.
               *
               * May emit a {RoleGranted} event.
               */
              function _grantRole(bytes32 role, address account) internal virtual {
                  if (!hasRole(role, account)) {
                      _roles[role].members[account] = true;
                      emit RoleGranted(role, account, _msgSender());
                  }
              }
              /**
               * @dev Revokes `role` from `account`.
               *
               * Internal function without access restriction.
               *
               * May emit a {RoleRevoked} event.
               */
              function _revokeRole(bytes32 role, address account) internal virtual {
                  if (hasRole(role, account)) {
                      _roles[role].members[account] = false;
                      emit RoleRevoked(role, account, _msgSender());
                  }
              }
          }// SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol)
          pragma solidity ^0.8.0;
          import "./IAccessControlEnumerable.sol";
          import "./AccessControl.sol";
          import "../utils/structs/EnumerableSet.sol";
          /**
           * @dev Extension of {AccessControl} that allows enumerating the members of each role.
           */
          abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
              using EnumerableSet for EnumerableSet.AddressSet;
              mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;
              /**
               * @dev See {IERC165-supportsInterface}.
               */
              function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                  return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
              }
              /**
               * @dev Returns one of the accounts that have `role`. `index` must be a
               * value between 0 and {getRoleMemberCount}, non-inclusive.
               *
               * Role bearers are not sorted in any particular way, and their ordering may
               * change at any point.
               *
               * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
               * you perform all queries on the same block. See the following
               * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
               * for more information.
               */
              function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) {
                  return _roleMembers[role].at(index);
              }
              /**
               * @dev Returns the number of accounts that have `role`. Can be used
               * together with {getRoleMember} to enumerate all bearers of a role.
               */
              function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) {
                  return _roleMembers[role].length();
              }
              /**
               * @dev Overload {_grantRole} to track enumerable memberships
               */
              function _grantRole(bytes32 role, address account) internal virtual override {
                  super._grantRole(role, account);
                  _roleMembers[role].add(account);
              }
              /**
               * @dev Overload {_revokeRole} to track enumerable memberships
               */
              function _revokeRole(bytes32 role, address account) internal virtual override {
                  super._revokeRole(role, account);
                  _roleMembers[role].remove(account);
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev External interface of AccessControl declared to support ERC165 detection.
           */
          interface IAccessControl {
              /**
               * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
               *
               * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
               * {RoleAdminChanged} not being emitted signaling this.
               *
               * _Available since v3.1._
               */
              event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
              /**
               * @dev Emitted when `account` is granted `role`.
               *
               * `sender` is the account that originated the contract call, an admin role
               * bearer except when using {AccessControl-_setupRole}.
               */
              event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
              /**
               * @dev Emitted when `account` is revoked `role`.
               *
               * `sender` is the account that originated the contract call:
               *   - if using `revokeRole`, it is the admin role bearer
               *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
               */
              event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
              /**
               * @dev Returns `true` if `account` has been granted `role`.
               */
              function hasRole(bytes32 role, address account) external view returns (bool);
              /**
               * @dev Returns the admin role that controls `role`. See {grantRole} and
               * {revokeRole}.
               *
               * To change a role's admin, use {AccessControl-_setRoleAdmin}.
               */
              function getRoleAdmin(bytes32 role) external view returns (bytes32);
              /**
               * @dev Grants `role` to `account`.
               *
               * If `account` had not been already granted `role`, emits a {RoleGranted}
               * event.
               *
               * Requirements:
               *
               * - the caller must have ``role``'s admin role.
               */
              function grantRole(bytes32 role, address account) external;
              /**
               * @dev Revokes `role` from `account`.
               *
               * If `account` had been granted `role`, emits a {RoleRevoked} event.
               *
               * Requirements:
               *
               * - the caller must have ``role``'s admin role.
               */
              function revokeRole(bytes32 role, address account) external;
              /**
               * @dev Revokes `role` from the calling account.
               *
               * Roles are often managed via {grantRole} and {revokeRole}: this function's
               * purpose is to provide a mechanism for accounts to lose their privileges
               * if they are compromised (such as when a trusted device is misplaced).
               *
               * If the calling account had been granted `role`, emits a {RoleRevoked}
               * event.
               *
               * Requirements:
               *
               * - the caller must be `account`.
               */
              function renounceRole(bytes32 role, address account) external;
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)
          pragma solidity ^0.8.0;
          import "./IAccessControl.sol";
          /**
           * @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
           */
          interface IAccessControlEnumerable is IAccessControl {
              /**
               * @dev Returns one of the accounts that have `role`. `index` must be a
               * value between 0 and {getRoleMemberCount}, non-inclusive.
               *
               * Role bearers are not sorted in any particular way, and their ordering may
               * change at any point.
               *
               * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
               * you perform all queries on the same block. See the following
               * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
               * for more information.
               */
              function getRoleMember(bytes32 role, uint256 index) external view returns (address);
              /**
               * @dev Returns the number of accounts that have `role`. Can be used
               * together with {getRoleMember} to enumerate all bearers of a role.
               */
              function getRoleMemberCount(bytes32 role) external view returns (uint256);
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.8.0) (security/ReentrancyGuard.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev Contract module that helps prevent reentrant calls to a function.
           *
           * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
           * available, which can be applied to functions to make sure there are no nested
           * (reentrant) calls to them.
           *
           * Note that because there is a single `nonReentrant` guard, functions marked as
           * `nonReentrant` may not call one another. This can be worked around by making
           * those functions `private`, and then adding `external` `nonReentrant` entry
           * points to them.
           *
           * TIP: If you would like to learn more about reentrancy and alternative ways
           * to protect against it, check out our blog post
           * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
           */
          abstract contract ReentrancyGuard {
              // Booleans are more expensive than uint256 or any type that takes up a full
              // word because each write operation emits an extra SLOAD to first read the
              // slot's contents, replace the bits taken up by the boolean, and then write
              // back. This is the compiler's defense against contract upgrades and
              // pointer aliasing, and it cannot be disabled.
              // The values being non-zero value makes deployment a bit more expensive,
              // but in exchange the refund on every call to nonReentrant will be lower in
              // amount. Since refunds are capped to a percentage of the total
              // transaction's gas, it is best to keep them low in cases like this one, to
              // increase the likelihood of the full refund coming into effect.
              uint256 private constant _NOT_ENTERED = 1;
              uint256 private constant _ENTERED = 2;
              uint256 private _status;
              constructor() {
                  _status = _NOT_ENTERED;
              }
              /**
               * @dev Prevents a contract from calling itself, directly or indirectly.
               * Calling a `nonReentrant` function from another `nonReentrant`
               * function is not supported. It is possible to prevent this from happening
               * by making the `nonReentrant` function external, and making it call a
               * `private` function that does the actual work.
               */
              modifier nonReentrant() {
                  _nonReentrantBefore();
                  _;
                  _nonReentrantAfter();
              }
              function _nonReentrantBefore() private {
                  // On the first call to nonReentrant, _status will be _NOT_ENTERED
                  require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
                  // Any calls to nonReentrant after this point will fail
                  _status = _ENTERED;
              }
              function _nonReentrantAfter() private {
                  // By storing the original value once again, a refund is triggered (see
                  // https://eips.ethereum.org/EIPS/eip-2200)
                  _status = _NOT_ENTERED;
              }
          }// 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 (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);
          }// SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol)
          pragma solidity ^0.8.0;
          import "../IERC20.sol";
          import "../extensions/draft-IERC20Permit.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 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'
                  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) + value;
                  _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
              }
              function safeDecreaseAllowance(
                  IERC20 token,
                  address spender,
                  uint256 value
              ) internal {
                  unchecked {
                      uint256 oldAllowance = token.allowance(address(this), spender);
                      require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
                      uint256 newAllowance = oldAllowance - value;
                      _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                  }
              }
              function safePermit(
                  IERC20Permit token,
                  address owner,
                  address spender,
                  uint256 value,
                  uint256 deadline,
                  uint8 v,
                  bytes32 r,
                  bytes32 s
              ) internal {
                  uint256 nonceBefore = token.nonces(owner);
                  token.permit(owner, spender, value, deadline, v, r, s);
                  uint256 nonceAfter = token.nonces(owner);
                  require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
              }
              /**
               * @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
                      require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
                  }
              }
          }// SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.8.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 functionCallWithValue(target, data, 0, "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");
                  (bool success, bytes memory returndata) = target.call{value: value}(data);
                  return verifyCallResultFromTarget(target, 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) {
                  (bool success, bytes memory returndata) = target.staticcall(data);
                  return verifyCallResultFromTarget(target, 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) {
                  (bool success, bytes memory returndata) = target.delegatecall(data);
                  return verifyCallResultFromTarget(target, success, returndata, errorMessage);
              }
              /**
               * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
               * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
               *
               * _Available since v4.8._
               */
              function verifyCallResultFromTarget(
                  address target,
                  bool success,
                  bytes memory returndata,
                  string memory errorMessage
              ) internal view returns (bytes memory) {
                  if (success) {
                      if (returndata.length == 0) {
                          // only check isContract if the call was successful and the return data is empty
                          // otherwise we already know that it was a contract
                          require(isContract(target), "Address: call to non-contract");
                      }
                      return returndata;
                  } else {
                      _revert(returndata, errorMessage);
                  }
              }
              /**
               * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
               * revert reason or 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 {
                      _revert(returndata, errorMessage);
                  }
              }
              function _revert(bytes memory returndata, string memory errorMessage) private pure {
                  // Look for revert reason and bubble it up if present
                  if (returndata.length > 0) {
                      // The easiest way to bubble the revert reason is using memory via assembly
                      /// @solidity memory-safe-assembly
                      assembly {
                          let returndata_size := mload(returndata)
                          revert(add(32, returndata), returndata_size)
                      }
                  } else {
                      revert(errorMessage);
                  }
              }
          }// 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: MIT
          // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
          pragma solidity ^0.8.0;
          import "./IERC165.sol";
          /**
           * @dev Implementation of the {IERC165} interface.
           *
           * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
           * for the additional interface id that will be supported. For example:
           *
           * ```solidity
           * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
           *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
           * }
           * ```
           *
           * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
           */
          abstract contract ERC165 is IERC165 {
              /**
               * @dev See {IERC165-supportsInterface}.
               */
              function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                  return interfaceId == type(IERC165).interfaceId;
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev Interface of the ERC165 standard, as defined in the
           * https://eips.ethereum.org/EIPS/eip-165[EIP].
           *
           * Implementers can declare support of contract interfaces, which can then be
           * queried by others ({ERC165Checker}).
           *
           * For an implementation, see {ERC165}.
           */
          interface IERC165 {
              /**
               * @dev Returns true if this contract implements the interface defined by
               * `interfaceId`. See the corresponding
               * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
               * to learn more about how these ids are created.
               *
               * This function call must use less than 30 000 gas.
               */
              function supportsInterface(bytes4 interfaceId) external view returns (bool);
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev Standard math utilities missing in the Solidity language.
           */
          library Math {
              enum Rounding {
                  Down, // Toward negative infinity
                  Up, // Toward infinity
                  Zero // Toward zero
              }
              /**
               * @dev Returns the largest of two numbers.
               */
              function max(uint256 a, uint256 b) internal pure returns (uint256) {
                  return a > b ? a : b;
              }
              /**
               * @dev Returns the smallest of two numbers.
               */
              function min(uint256 a, uint256 b) internal pure returns (uint256) {
                  return a < b ? a : b;
              }
              /**
               * @dev Returns the average of two numbers. The result is rounded towards
               * zero.
               */
              function average(uint256 a, uint256 b) internal pure returns (uint256) {
                  // (a + b) / 2 can overflow.
                  return (a & b) + (a ^ b) / 2;
              }
              /**
               * @dev Returns the ceiling of the division of two numbers.
               *
               * This differs from standard division with `/` in that it rounds up instead
               * of rounding down.
               */
              function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
                  // (a + b - 1) / b can overflow on addition, so we distribute.
                  return a == 0 ? 0 : (a - 1) / b + 1;
              }
              /**
               * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
               * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
               * with further edits by Uniswap Labs also under MIT license.
               */
              function mulDiv(
                  uint256 x,
                  uint256 y,
                  uint256 denominator
              ) internal pure returns (uint256 result) {
                  unchecked {
                      // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
                      // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
                      // variables such that product = prod1 * 2^256 + prod0.
                      uint256 prod0; // Least significant 256 bits of the product
                      uint256 prod1; // Most significant 256 bits of the product
                      assembly {
                          let mm := mulmod(x, y, not(0))
                          prod0 := mul(x, y)
                          prod1 := sub(sub(mm, prod0), lt(mm, prod0))
                      }
                      // Handle non-overflow cases, 256 by 256 division.
                      if (prod1 == 0) {
                          return prod0 / denominator;
                      }
                      // Make sure the result is less than 2^256. Also prevents denominator == 0.
                      require(denominator > prod1);
                      ///////////////////////////////////////////////
                      // 512 by 256 division.
                      ///////////////////////////////////////////////
                      // Make division exact by subtracting the remainder from [prod1 prod0].
                      uint256 remainder;
                      assembly {
                          // Compute remainder using mulmod.
                          remainder := mulmod(x, y, denominator)
                          // Subtract 256 bit number from 512 bit number.
                          prod1 := sub(prod1, gt(remainder, prod0))
                          prod0 := sub(prod0, remainder)
                      }
                      // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
                      // See https://cs.stackexchange.com/q/138556/92363.
                      // Does not overflow because the denominator cannot be zero at this stage in the function.
                      uint256 twos = denominator & (~denominator + 1);
                      assembly {
                          // Divide denominator by twos.
                          denominator := div(denominator, twos)
                          // Divide [prod1 prod0] by twos.
                          prod0 := div(prod0, twos)
                          // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                          twos := add(div(sub(0, twos), twos), 1)
                      }
                      // Shift in bits from prod1 into prod0.
                      prod0 |= prod1 * twos;
                      // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
                      // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
                      // four bits. That is, denominator * inv = 1 mod 2^4.
                      uint256 inverse = (3 * denominator) ^ 2;
                      // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
                      // in modular arithmetic, doubling the correct bits in each step.
                      inverse *= 2 - denominator * inverse; // inverse mod 2^8
                      inverse *= 2 - denominator * inverse; // inverse mod 2^16
                      inverse *= 2 - denominator * inverse; // inverse mod 2^32
                      inverse *= 2 - denominator * inverse; // inverse mod 2^64
                      inverse *= 2 - denominator * inverse; // inverse mod 2^128
                      inverse *= 2 - denominator * inverse; // inverse mod 2^256
                      // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
                      // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
                      // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
                      // is no longer required.
                      result = prod0 * inverse;
                      return result;
                  }
              }
              /**
               * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
               */
              function mulDiv(
                  uint256 x,
                  uint256 y,
                  uint256 denominator,
                  Rounding rounding
              ) internal pure returns (uint256) {
                  uint256 result = mulDiv(x, y, denominator);
                  if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
                      result += 1;
                  }
                  return result;
              }
              /**
               * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
               *
               * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
               */
              function sqrt(uint256 a) internal pure returns (uint256) {
                  if (a == 0) {
                      return 0;
                  }
                  // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
                  //
                  // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
                  // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
                  //
                  // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
                  // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
                  // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
                  //
                  // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
                  uint256 result = 1 << (log2(a) >> 1);
                  // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
                  // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
                  // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
                  // into the expected uint128 result.
                  unchecked {
                      result = (result + a / result) >> 1;
                      result = (result + a / result) >> 1;
                      result = (result + a / result) >> 1;
                      result = (result + a / result) >> 1;
                      result = (result + a / result) >> 1;
                      result = (result + a / result) >> 1;
                      result = (result + a / result) >> 1;
                      return min(result, a / result);
                  }
              }
              /**
               * @notice Calculates sqrt(a), following the selected rounding direction.
               */
              function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
                  unchecked {
                      uint256 result = sqrt(a);
                      return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
                  }
              }
              /**
               * @dev Return the log in base 2, rounded down, of a positive value.
               * Returns 0 if given 0.
               */
              function log2(uint256 value) internal pure returns (uint256) {
                  uint256 result = 0;
                  unchecked {
                      if (value >> 128 > 0) {
                          value >>= 128;
                          result += 128;
                      }
                      if (value >> 64 > 0) {
                          value >>= 64;
                          result += 64;
                      }
                      if (value >> 32 > 0) {
                          value >>= 32;
                          result += 32;
                      }
                      if (value >> 16 > 0) {
                          value >>= 16;
                          result += 16;
                      }
                      if (value >> 8 > 0) {
                          value >>= 8;
                          result += 8;
                      }
                      if (value >> 4 > 0) {
                          value >>= 4;
                          result += 4;
                      }
                      if (value >> 2 > 0) {
                          value >>= 2;
                          result += 2;
                      }
                      if (value >> 1 > 0) {
                          result += 1;
                      }
                  }
                  return result;
              }
              /**
               * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
               * Returns 0 if given 0.
               */
              function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
                  unchecked {
                      uint256 result = log2(value);
                      return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
                  }
              }
              /**
               * @dev Return the log in base 10, rounded down, of a positive value.
               * Returns 0 if given 0.
               */
              function log10(uint256 value) internal pure returns (uint256) {
                  uint256 result = 0;
                  unchecked {
                      if (value >= 10**64) {
                          value /= 10**64;
                          result += 64;
                      }
                      if (value >= 10**32) {
                          value /= 10**32;
                          result += 32;
                      }
                      if (value >= 10**16) {
                          value /= 10**16;
                          result += 16;
                      }
                      if (value >= 10**8) {
                          value /= 10**8;
                          result += 8;
                      }
                      if (value >= 10**4) {
                          value /= 10**4;
                          result += 4;
                      }
                      if (value >= 10**2) {
                          value /= 10**2;
                          result += 2;
                      }
                      if (value >= 10**1) {
                          result += 1;
                      }
                  }
                  return result;
              }
              /**
               * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
               * Returns 0 if given 0.
               */
              function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
                  unchecked {
                      uint256 result = log10(value);
                      return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);
                  }
              }
              /**
               * @dev Return the log in base 256, rounded down, of a positive value.
               * Returns 0 if given 0.
               *
               * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
               */
              function log256(uint256 value) internal pure returns (uint256) {
                  uint256 result = 0;
                  unchecked {
                      if (value >> 128 > 0) {
                          value >>= 128;
                          result += 16;
                      }
                      if (value >> 64 > 0) {
                          value >>= 64;
                          result += 8;
                      }
                      if (value >> 32 > 0) {
                          value >>= 32;
                          result += 4;
                      }
                      if (value >> 16 > 0) {
                          value >>= 16;
                          result += 2;
                      }
                      if (value >> 8 > 0) {
                          result += 1;
                      }
                  }
                  return result;
              }
              /**
               * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
               * Returns 0 if given 0.
               */
              function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
                  unchecked {
                      uint256 result = log256(value);
                      return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);
                  }
              }
          }// SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)
          pragma solidity ^0.8.0;
          import "./math/Math.sol";
          /**
           * @dev String operations.
           */
          library Strings {
              bytes16 private constant _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) {
                  unchecked {
                      uint256 length = Math.log10(value) + 1;
                      string memory buffer = new string(length);
                      uint256 ptr;
                      /// @solidity memory-safe-assembly
                      assembly {
                          ptr := add(buffer, add(32, length))
                      }
                      while (true) {
                          ptr--;
                          /// @solidity memory-safe-assembly
                          assembly {
                              mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
                          }
                          value /= 10;
                          if (value == 0) break;
                      }
                      return buffer;
                  }
              }
              /**
               * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
               */
              function toHexString(uint256 value) internal pure returns (string memory) {
                  unchecked {
                      return toHexString(value, Math.log256(value) + 1);
                  }
              }
              /**
               * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
               */
              function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
                  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] = _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);
              }
          }// SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.8.0) (utils/structs/EnumerableSet.sol)
          // This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
          pragma solidity ^0.8.0;
          /**
           * @dev Library for managing
           * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
           * types.
           *
           * Sets have the following properties:
           *
           * - Elements are added, removed, and checked for existence in constant time
           * (O(1)).
           * - Elements are enumerated in O(n). No guarantees are made on the ordering.
           *
           * ```
           * contract Example {
           *     // Add the library methods
           *     using EnumerableSet for EnumerableSet.AddressSet;
           *
           *     // Declare a set state variable
           *     EnumerableSet.AddressSet private mySet;
           * }
           * ```
           *
           * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
           * and `uint256` (`UintSet`) are supported.
           *
           * [WARNING]
           * ====
           * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
           * unusable.
           * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
           *
           * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
           * array of EnumerableSet.
           * ====
           */
          library EnumerableSet {
              // To implement this library for multiple types with as little code
              // repetition as possible, we write it in terms of a generic Set type with
              // bytes32 values.
              // The Set implementation uses private functions, and user-facing
              // implementations (such as AddressSet) are just wrappers around the
              // underlying Set.
              // This means that we can only create new EnumerableSets for types that fit
              // in bytes32.
              struct Set {
                  // Storage of set values
                  bytes32[] _values;
                  // Position of the value in the `values` array, plus 1 because index 0
                  // means a value is not in the set.
                  mapping(bytes32 => uint256) _indexes;
              }
              /**
               * @dev Add a value to a set. O(1).
               *
               * Returns true if the value was added to the set, that is if it was not
               * already present.
               */
              function _add(Set storage set, bytes32 value) private returns (bool) {
                  if (!_contains(set, value)) {
                      set._values.push(value);
                      // The value is stored at length-1, but we add 1 to all indexes
                      // and use 0 as a sentinel value
                      set._indexes[value] = set._values.length;
                      return true;
                  } else {
                      return false;
                  }
              }
              /**
               * @dev Removes a value from a set. O(1).
               *
               * Returns true if the value was removed from the set, that is if it was
               * present.
               */
              function _remove(Set storage set, bytes32 value) private returns (bool) {
                  // We read and store the value's index to prevent multiple reads from the same storage slot
                  uint256 valueIndex = set._indexes[value];
                  if (valueIndex != 0) {
                      // Equivalent to contains(set, value)
                      // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
                      // the array, and then remove the last element (sometimes called as 'swap and pop').
                      // This modifies the order of the array, as noted in {at}.
                      uint256 toDeleteIndex = valueIndex - 1;
                      uint256 lastIndex = set._values.length - 1;
                      if (lastIndex != toDeleteIndex) {
                          bytes32 lastValue = set._values[lastIndex];
                          // Move the last value to the index where the value to delete is
                          set._values[toDeleteIndex] = lastValue;
                          // Update the index for the moved value
                          set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
                      }
                      // Delete the slot where the moved value was stored
                      set._values.pop();
                      // Delete the index for the deleted slot
                      delete set._indexes[value];
                      return true;
                  } else {
                      return false;
                  }
              }
              /**
               * @dev Returns true if the value is in the set. O(1).
               */
              function _contains(Set storage set, bytes32 value) private view returns (bool) {
                  return set._indexes[value] != 0;
              }
              /**
               * @dev Returns the number of values on the set. O(1).
               */
              function _length(Set storage set) private view returns (uint256) {
                  return set._values.length;
              }
              /**
               * @dev Returns the value stored at position `index` in the set. O(1).
               *
               * Note that there are no guarantees on the ordering of values inside the
               * array, and it may change when more values are added or removed.
               *
               * Requirements:
               *
               * - `index` must be strictly less than {length}.
               */
              function _at(Set storage set, uint256 index) private view returns (bytes32) {
                  return set._values[index];
              }
              /**
               * @dev Return the entire set in an array
               *
               * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
               * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
               * this function has an unbounded cost, and using it as part of a state-changing function may render the function
               * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
               */
              function _values(Set storage set) private view returns (bytes32[] memory) {
                  return set._values;
              }
              // Bytes32Set
              struct Bytes32Set {
                  Set _inner;
              }
              /**
               * @dev Add a value to a set. O(1).
               *
               * Returns true if the value was added to the set, that is if it was not
               * already present.
               */
              function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
                  return _add(set._inner, value);
              }
              /**
               * @dev Removes a value from a set. O(1).
               *
               * Returns true if the value was removed from the set, that is if it was
               * present.
               */
              function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
                  return _remove(set._inner, value);
              }
              /**
               * @dev Returns true if the value is in the set. O(1).
               */
              function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
                  return _contains(set._inner, value);
              }
              /**
               * @dev Returns the number of values in the set. O(1).
               */
              function length(Bytes32Set storage set) internal view returns (uint256) {
                  return _length(set._inner);
              }
              /**
               * @dev Returns the value stored at position `index` in the set. O(1).
               *
               * Note that there are no guarantees on the ordering of values inside the
               * array, and it may change when more values are added or removed.
               *
               * Requirements:
               *
               * - `index` must be strictly less than {length}.
               */
              function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
                  return _at(set._inner, index);
              }
              /**
               * @dev Return the entire set in an array
               *
               * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
               * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
               * this function has an unbounded cost, and using it as part of a state-changing function may render the function
               * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
               */
              function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
                  bytes32[] memory store = _values(set._inner);
                  bytes32[] memory result;
                  /// @solidity memory-safe-assembly
                  assembly {
                      result := store
                  }
                  return result;
              }
              // AddressSet
              struct AddressSet {
                  Set _inner;
              }
              /**
               * @dev Add a value to a set. O(1).
               *
               * Returns true if the value was added to the set, that is if it was not
               * already present.
               */
              function add(AddressSet storage set, address value) internal returns (bool) {
                  return _add(set._inner, bytes32(uint256(uint160(value))));
              }
              /**
               * @dev Removes a value from a set. O(1).
               *
               * Returns true if the value was removed from the set, that is if it was
               * present.
               */
              function remove(AddressSet storage set, address value) internal returns (bool) {
                  return _remove(set._inner, bytes32(uint256(uint160(value))));
              }
              /**
               * @dev Returns true if the value is in the set. O(1).
               */
              function contains(AddressSet storage set, address value) internal view returns (bool) {
                  return _contains(set._inner, bytes32(uint256(uint160(value))));
              }
              /**
               * @dev Returns the number of values in the set. O(1).
               */
              function length(AddressSet storage set) internal view returns (uint256) {
                  return _length(set._inner);
              }
              /**
               * @dev Returns the value stored at position `index` in the set. O(1).
               *
               * Note that there are no guarantees on the ordering of values inside the
               * array, and it may change when more values are added or removed.
               *
               * Requirements:
               *
               * - `index` must be strictly less than {length}.
               */
              function at(AddressSet storage set, uint256 index) internal view returns (address) {
                  return address(uint160(uint256(_at(set._inner, index))));
              }
              /**
               * @dev Return the entire set in an array
               *
               * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
               * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
               * this function has an unbounded cost, and using it as part of a state-changing function may render the function
               * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
               */
              function values(AddressSet storage set) internal view returns (address[] memory) {
                  bytes32[] memory store = _values(set._inner);
                  address[] memory result;
                  /// @solidity memory-safe-assembly
                  assembly {
                      result := store
                  }
                  return result;
              }
              // UintSet
              struct UintSet {
                  Set _inner;
              }
              /**
               * @dev Add a value to a set. O(1).
               *
               * Returns true if the value was added to the set, that is if it was not
               * already present.
               */
              function add(UintSet storage set, uint256 value) internal returns (bool) {
                  return _add(set._inner, bytes32(value));
              }
              /**
               * @dev Removes a value from a set. O(1).
               *
               * Returns true if the value was removed from the set, that is if it was
               * present.
               */
              function remove(UintSet storage set, uint256 value) internal returns (bool) {
                  return _remove(set._inner, bytes32(value));
              }
              /**
               * @dev Returns true if the value is in the set. O(1).
               */
              function contains(UintSet storage set, uint256 value) internal view returns (bool) {
                  return _contains(set._inner, bytes32(value));
              }
              /**
               * @dev Returns the number of values in the set. O(1).
               */
              function length(UintSet storage set) internal view returns (uint256) {
                  return _length(set._inner);
              }
              /**
               * @dev Returns the value stored at position `index` in the set. O(1).
               *
               * Note that there are no guarantees on the ordering of values inside the
               * array, and it may change when more values are added or removed.
               *
               * Requirements:
               *
               * - `index` must be strictly less than {length}.
               */
              function at(UintSet storage set, uint256 index) internal view returns (uint256) {
                  return uint256(_at(set._inner, index));
              }
              /**
               * @dev Return the entire set in an array
               *
               * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
               * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
               * this function has an unbounded cost, and using it as part of a state-changing function may render the function
               * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
               */
              function values(UintSet storage set) internal view returns (uint256[] memory) {
                  bytes32[] memory store = _values(set._inner);
                  uint256[] memory result;
                  /// @solidity memory-safe-assembly
                  assembly {
                      result := store
                  }
                  return result;
              }
          }// SPDX-License-Identifier: UNLICENSED
          // Copyright (c) Eywa.Fi, 2021-2023 - all rights reserved
          pragma solidity 0.8.17;
          import "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
          import "@openzeppelin/contracts/utils/Address.sol";
          import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
          import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
          import "../utils/Typecast.sol";
          import "../utils/RequestIdLib.sol";
          import "../interfaces/IBridgeV2.sol";
          import "../interfaces/IValidatedDataReciever.sol";
          contract GateKeeper is AccessControlEnumerable, Typecast, ReentrancyGuard {
              using Address for address;
              struct BaseFee {
                  /// @dev chainId The ID of the chain for which the base fee is being set
                  uint64 chainId;
                  /// @dev payToken The token for which the base fee is being set; use 0x0 to set base fee in a native asset
                  address payToken;
                  /// @dev fee The amount of the base fee being set
                  uint256 fee;
              }
              struct Rate {
                  /// @dev chainId The ID of the chain for which the base fee is being set
                  uint64 chainId;
                  /// @dev payToken The token for which the base fee is being set; use 0x0 to set base fee in a native asset
                  address payToken;
                  /// @dev rate The rate being set
                  uint256 rate;
              }
              /// @dev operator role id
              bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE");
              /// @dev bridge conract, can be changed any time
              address public bridge;
              /// @dev chainId => pay token => base fees
              mapping(uint64 => mapping(address => uint256)) public baseFees;
              /// @dev chainId => pay token => rate (per byte)
              mapping(uint64 => mapping(address => uint256)) public rates;
              /// @dev caller => discounts, [0, 10000]
              mapping(address => uint256) public discounts;
              /// @dev treasury address
              address public treasury;
              event CrossChainCallPaid(address indexed sender, address indexed token, uint256 transactionCost);
              event BridgeSet(address bridge);
              event BaseFeeSet(uint64 chainId, address payToken, uint256 fee);
              event RateSet(uint64 chainId, address payToken, uint256 rate);
              event DiscountSet(address caller, uint256 discount);
              event FeesWithdrawn(address token, uint256 amount, address to);
              event TreasurySet(address treasury);
              /**
               * @dev Constructor function for GateKeeper contract.
               *
               * @param bridge_ The address of the BridgeV2 contract.
               */
              constructor(address bridge_) {
                  _grantRole(DEFAULT_ADMIN_ROLE, _msgSender());
                  require(bridge_ != address(0), "GateKeeper: zero address");
                  bridge = bridge_;
              }
              /**
               * @dev Returns same nonce as bridge (on request from same sender).
               */
              function getNonce() external view returns (uint256 nonce) {
                  nonce = IBridgeV2(bridge).nonces(msg.sender);
              }
              /**
               * @notice Sets the address of the BridgeV2 contract.
               *
               * @dev Only the contract owner is allowed to call this function.
               *
               * @param bridge_ the address of the new BridgeV2 contract to be set.
               */
              function setBridge(address bridge_) external onlyRole(DEFAULT_ADMIN_ROLE) {
                  require(bridge_ != address(0), "GateKeeper: zero address");
                  bridge = bridge_;
                  emit BridgeSet(bridge);
              }
              /**
               * @notice Sets the address of the treasury contract.
               *
               * @dev Only the contract owner is allowed to call this function.
               *
               * @param treasury_ the address of the new BridgeV2 contract to be set.
               */
              function setTreasury(address treasury_) external onlyRole(DEFAULT_ADMIN_ROLE) {
                  require(treasury_ != address(0), "GateKeeper: zero address");
                  treasury = treasury_;
                  emit TreasurySet(bridge);
              }
              /**
               * @notice Sets the base fee for a given chain ID and token address.
               * The base fee represents the minimum amount of pay {TOKEN} required as transaction fee.
               * Use 0x0 as payToken address to set base fee in native asset.
               *
               * @param baseFees_ The array of the BaseFee structs.
               */
              function setBaseFee(BaseFee[] memory baseFees_) external onlyRole(OPERATOR_ROLE) {
                  for (uint256 i = 0; i < baseFees_.length; ++i) {
                      BaseFee memory baseFee = baseFees_[i];
                      baseFees[baseFee.chainId][baseFee.payToken] = baseFee.fee;
                      emit BaseFeeSet(baseFee.chainId, baseFee.payToken, baseFee.fee);
                  }
              }
              /**
               * @notice Sets the rate for a given chain ID and token address.
               * The rate will be applied based on the length of the data being transmitted between the chains.
               *
               * @param rates_ The array of the Rate structs.
               */
              function setRate(Rate[] memory rates_) external onlyRole(OPERATOR_ROLE) {
                  for (uint256 i = 0; i < rates_.length; ++i) {
                      Rate memory rate = rates_[i];
                      rates[rate.chainId][rate.payToken] = rate.rate;
                      emit RateSet(rate.chainId, rate.payToken, rate.rate);
                  }
              }
              /**
               * @notice Sets the discount for a given caller. Have to be in [0, 10000], where 10000 is 100%.
               *
               * @param caller The address of the caller for which the discount is being set;
               * @param discount The discount being set.
               */
              function setDiscount(address caller, uint256 discount) external onlyRole(OPERATOR_ROLE) {
                  require(discount <= 10000, "GateKeeper: wrong discount");
                  discounts[caller] = discount;
                  emit DiscountSet(caller, discount);
              }
              /**
               * @notice Calculates the cost for a cross-chain operation in the specified token.
               *
               * @param payToken The address of the token to be used for fee payment. Use address(0) to pay with Ether;
               * @param dataLength The length of the data being transmitted in the cross-chain operation;
               * @param chainIdTo The ID of the destination chain;
               * @param sender The address of the caller requesting the cross-chain operation;
               * @return amountToPay The fee amount to be paid for the cross-chain operation.
               */
              function calculateCost(
                  address payToken,
                  uint256 dataLength,
                  uint64 chainIdTo,
                  address sender
              ) public view returns (uint256 amountToPay) {
                  uint256 baseFee = baseFees[chainIdTo][payToken];
                  uint256 rate = rates[chainIdTo][payToken];
                  require(baseFee != 0, "GateKeeper: base fee not set");
                  require(rate != 0, "GateKeeper: rate not set");
                  (amountToPay) = _getPercentValues(baseFee + (dataLength * rate), discounts[sender]);
              }
              /**
               * @notice Calculates the final amount to be paid after applying a discount percentage to the original amount.
               *
               * @param amount The original amount to be paid;
               * @param basePercent The percentage of discount to be applied;
               * @return amountToPay The final amount to be paid after the discount has been applied.
               */
              function _getPercentValues(
                  uint256 amount,
                  uint256 basePercent
              ) private pure returns (uint256 amountToPay) {
                  require(amount >= 10, "GateKeeper: amount is too small");
                  uint256 discount = (amount * basePercent) / 10000;
                  amountToPay = amount - discount;
              }
              /**
               * @notice Allows the owner to withdraw collected fees from the contract. Use address(0) to
               * withdraw native asset.
               *
               * @param token The token address from which the fees need to be withdrawn;
               * @param amount The amount of fees to be withdrawn.
               */
              function withdrawFees(address token, uint256 amount) external onlyRole(OPERATOR_ROLE) nonReentrant {
                  require(treasury != address(0), "GateKeeper: treasury not set");
                  if (token == address(0)) {
                      (bool sent,) = treasury.call{value: amount}("");
                      require(sent, "GateKeeper: failed to send Ether");
                  } else {
                      SafeERC20.safeTransfer(IERC20(token), treasury, amount);
                  }
                  emit FeesWithdrawn(token, amount, treasury);
              }
              /**
               * @dev Sends data to a destination contract on a specified chain using the opposite BridgeV2 contract.
               * If payToken is address(0), the payment is made in Ether, otherwise it is made using the ERC20 token 
               * at the specified address.
               * The payment amount is calculated based on the data length and the specified chain ID and discount rate of the sender.
               *
               * Emits a PaymentReceived event after the payment has been processed.
               *
               * @param data The data (encoded with selector) which would be send to the destination contract;
               * @param to The address of the destination contract;
               * @param chainIdTo The ID of the chain where the destination contract resides;
               * @param payToken The address of the ERC20 token used to pay the fee or address(0) if Ether is used.
               */
              function sendData(
                  bytes calldata data,
                  address to,
                  uint64 chainIdTo,
                  address payToken
              ) external payable nonReentrant {
                  uint256 amountToPay = calculateCost(payToken, data.length, chainIdTo, msg.sender);
                  _proceedCrosschainFees(payToken, amountToPay);
                  uint256 nonce = IBridgeV2(bridge).nonces(msg.sender);
                  bytes32 requestId = RequestIdLib.prepareRequestId(
                      castToBytes32(to),
                      chainIdTo,
                      castToBytes32(msg.sender),
                      block.chainid,
                      nonce
                  );
                  bytes memory info = abi.encodeWithSelector(
                      IValidatedDataReciever.receiveValidatedData.selector,
                      bytes4(data[:4]),
                      msg.sender,
                      block.chainid
                  );
                  bytes memory out = abi.encode(data, info);
                  IBridgeV2(bridge).sendV2(
                      IBridgeV2.SendParams({
                          requestId: requestId,
                          data: out,
                          to: to,
                          chainIdTo: chainIdTo
                      }),
                      msg.sender,
                      nonce
                  );
              }
              /**
               * @notice Proceeds with cross-chain fees payment in the specified token.
               *
               * @param payToken The address of the token to be used for fee payment.
               * @param transactionCost The amount of fees to be paid for the cross-chain operation.
               */
              function _proceedCrosschainFees(address payToken, uint256 transactionCost) private {
                  emit CrossChainCallPaid(msg.sender, payToken, transactionCost);
                  if (payToken == address(0)) {
                      require(msg.value >= transactionCost, "GateKeeper: invalid payment amount");
                  } else {
                      SafeERC20.safeTransferFrom(IERC20(payToken), msg.sender, address(this), transactionCost);
                  }
              }
          }
          // SPDX-License-Identifier: UNLICENSED
          // Copyright (c) Eywa.Fi, 2021-2023 - all rights reserved
          pragma solidity ^0.8.17;
          interface IBridgeV2 {
              enum State { 
                  Active, // data send and receive possible
                  Inactive, // data send and receive impossible
                  Limited // only data receive possible
              }
              struct SendParams {
                  /// @param requestId unique request ID
                  bytes32 requestId;
                  /// @param data call data
                  bytes data;
                  /// @param to receiver contract address
                  address to;
                  /// @param chainIdTo destination chain ID
                  uint256 chainIdTo;
              }
              struct ReceiveParams {
                  /// @param blockHeader block header serialization
                  bytes blockHeader;
                  /// @param merkleProof OracleRequest transaction payload and its Merkle audit path
                  bytes merkleProof;
                  /// @param votersPubKey aggregated public key of the old epoch participants, who voted for the block
                  bytes votersPubKey;
                  /// @param votersSignature aggregated signature of the old epoch participants, who voted for the block
                  bytes votersSignature;
                  /// @param votersMask bitmask of epoch participants, who voted, among all participants
                  uint256 votersMask;
              }
              function sendV2(
                  SendParams calldata params,
                  address sender,
                  uint256 nonce
              ) external returns (bool);
              function receiveV2(ReceiveParams[] calldata params) external returns (bool);
              function nonces(address from) external view returns (uint256);
          }
          // SPDX-License-Identifier: UNLICENSED
          // Copyright (c) Eywa.Fi, 2021-2023 - all rights reserved
          pragma solidity 0.8.17;
          interface IValidatedDataReciever {
              /**
               * @notice Function which will be called by desination bridge.
               *
               * @dev Receiver contract must ensure that's from and chainIdFrom correct.
               *
               * @param selector selector which will be called;
               * @param from sender address in source chain;
               * @param chainIdFrom source chain id. TODO change to uint64
               */
              function receiveValidatedData(bytes4 selector, address from, uint64 chainIdFrom) external returns (bool);
          }// SPDX-License-Identifier: UNLICENSED
          // Copyright (c) Eywa.Fi, 2021-2023 - all rights reserved
          pragma solidity 0.8.17;
          library RequestIdLib {
              /**
               * @dev Prepares a request ID with the given arguments.
               * @param oppositeBridge padded opposite bridge address
               * @param chainIdTo opposite chain ID
               * @param chainIdFrom current chain ID
               * @param receiveSide padded receive contract address
               * @param from padded sender's address
               * @param nonce current nonce
               */
              function prepareRqId(
                  bytes32 oppositeBridge,
                  uint256 chainIdTo,
                  uint256 chainIdFrom,
                  bytes32 receiveSide,
                  bytes32 from,
                  uint256 nonce
              ) internal pure returns (bytes32) {
                  return keccak256(abi.encodePacked(from, nonce, chainIdTo, chainIdFrom, receiveSide, oppositeBridge));
              }
              function prepareRequestId(
                  bytes32 to,
                  uint256 chainIdTo,
                  bytes32 from,
                  uint256 chainIdFrom,
                  uint256 nonce
              ) internal pure returns (bytes32) {
                  return keccak256(abi.encodePacked(from, nonce, chainIdTo, chainIdFrom, to));
              }
          }
          // SPDX-License-Identifier: UNLICENSED
          // Copyright (c) Eywa.Fi, 2021-2023 - all rights reserved
          pragma solidity 0.8.17;
          abstract contract Typecast {
              function castToAddress(bytes32 x) public pure returns (address) {
                  return address(uint160(uint256(x)));
              }
              function castToBytes32(address a) public pure returns (bytes32) {
                  return bytes32(uint256(uint160(a)));
              }
          }
          

          File 5 of 8: BridgeV2
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.8.0) (access/AccessControl.sol)
          pragma solidity ^0.8.0;
          import "./IAccessControl.sol";
          import "../utils/Context.sol";
          import "../utils/Strings.sol";
          import "../utils/introspection/ERC165.sol";
          /**
           * @dev Contract module that allows children to implement role-based access
           * control mechanisms. This is a lightweight version that doesn't allow enumerating role
           * members except through off-chain means by accessing the contract event logs. Some
           * applications may benefit from on-chain enumerability, for those cases see
           * {AccessControlEnumerable}.
           *
           * Roles are referred to by their `bytes32` identifier. These should be exposed
           * in the external API and be unique. The best way to achieve this is by
           * using `public constant` hash digests:
           *
           * ```
           * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
           * ```
           *
           * Roles can be used to represent a set of permissions. To restrict access to a
           * function call, use {hasRole}:
           *
           * ```
           * function foo() public {
           *     require(hasRole(MY_ROLE, msg.sender));
           *     ...
           * }
           * ```
           *
           * Roles can be granted and revoked dynamically via the {grantRole} and
           * {revokeRole} functions. Each role has an associated admin role, and only
           * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
           *
           * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
           * that only accounts with this role will be able to grant or revoke other
           * roles. More complex role relationships can be created by using
           * {_setRoleAdmin}.
           *
           * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
           * grant and revoke this role. Extra precautions should be taken to secure
           * accounts that have been granted it.
           */
          abstract contract AccessControl is Context, IAccessControl, ERC165 {
              struct RoleData {
                  mapping(address => bool) members;
                  bytes32 adminRole;
              }
              mapping(bytes32 => RoleData) private _roles;
              bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
              /**
               * @dev Modifier that checks that an account has a specific role. Reverts
               * with a standardized message including the required role.
               *
               * The format of the revert reason is given by the following regular expression:
               *
               *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
               *
               * _Available since v4.1._
               */
              modifier onlyRole(bytes32 role) {
                  _checkRole(role);
                  _;
              }
              /**
               * @dev See {IERC165-supportsInterface}.
               */
              function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                  return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
              }
              /**
               * @dev Returns `true` if `account` has been granted `role`.
               */
              function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
                  return _roles[role].members[account];
              }
              /**
               * @dev Revert with a standard message if `_msgSender()` is missing `role`.
               * Overriding this function changes the behavior of the {onlyRole} modifier.
               *
               * Format of the revert message is described in {_checkRole}.
               *
               * _Available since v4.6._
               */
              function _checkRole(bytes32 role) internal view virtual {
                  _checkRole(role, _msgSender());
              }
              /**
               * @dev Revert with a standard message if `account` is missing `role`.
               *
               * The format of the revert reason is given by the following regular expression:
               *
               *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
               */
              function _checkRole(bytes32 role, address account) internal view virtual {
                  if (!hasRole(role, account)) {
                      revert(
                          string(
                              abi.encodePacked(
                                  "AccessControl: account ",
                                  Strings.toHexString(account),
                                  " is missing role ",
                                  Strings.toHexString(uint256(role), 32)
                              )
                          )
                      );
                  }
              }
              /**
               * @dev Returns the admin role that controls `role`. See {grantRole} and
               * {revokeRole}.
               *
               * To change a role's admin, use {_setRoleAdmin}.
               */
              function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
                  return _roles[role].adminRole;
              }
              /**
               * @dev Grants `role` to `account`.
               *
               * If `account` had not been already granted `role`, emits a {RoleGranted}
               * event.
               *
               * Requirements:
               *
               * - the caller must have ``role``'s admin role.
               *
               * May emit a {RoleGranted} event.
               */
              function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
                  _grantRole(role, account);
              }
              /**
               * @dev Revokes `role` from `account`.
               *
               * If `account` had been granted `role`, emits a {RoleRevoked} event.
               *
               * Requirements:
               *
               * - the caller must have ``role``'s admin role.
               *
               * May emit a {RoleRevoked} event.
               */
              function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
                  _revokeRole(role, account);
              }
              /**
               * @dev Revokes `role` from the calling account.
               *
               * Roles are often managed via {grantRole} and {revokeRole}: this function's
               * purpose is to provide a mechanism for accounts to lose their privileges
               * if they are compromised (such as when a trusted device is misplaced).
               *
               * If the calling account had been revoked `role`, emits a {RoleRevoked}
               * event.
               *
               * Requirements:
               *
               * - the caller must be `account`.
               *
               * May emit a {RoleRevoked} event.
               */
              function renounceRole(bytes32 role, address account) public virtual override {
                  require(account == _msgSender(), "AccessControl: can only renounce roles for self");
                  _revokeRole(role, account);
              }
              /**
               * @dev Grants `role` to `account`.
               *
               * If `account` had not been already granted `role`, emits a {RoleGranted}
               * event. Note that unlike {grantRole}, this function doesn't perform any
               * checks on the calling account.
               *
               * May emit a {RoleGranted} event.
               *
               * [WARNING]
               * ====
               * This function should only be called from the constructor when setting
               * up the initial roles for the system.
               *
               * Using this function in any other way is effectively circumventing the admin
               * system imposed by {AccessControl}.
               * ====
               *
               * NOTE: This function is deprecated in favor of {_grantRole}.
               */
              function _setupRole(bytes32 role, address account) internal virtual {
                  _grantRole(role, account);
              }
              /**
               * @dev Sets `adminRole` as ``role``'s admin role.
               *
               * Emits a {RoleAdminChanged} event.
               */
              function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
                  bytes32 previousAdminRole = getRoleAdmin(role);
                  _roles[role].adminRole = adminRole;
                  emit RoleAdminChanged(role, previousAdminRole, adminRole);
              }
              /**
               * @dev Grants `role` to `account`.
               *
               * Internal function without access restriction.
               *
               * May emit a {RoleGranted} event.
               */
              function _grantRole(bytes32 role, address account) internal virtual {
                  if (!hasRole(role, account)) {
                      _roles[role].members[account] = true;
                      emit RoleGranted(role, account, _msgSender());
                  }
              }
              /**
               * @dev Revokes `role` from `account`.
               *
               * Internal function without access restriction.
               *
               * May emit a {RoleRevoked} event.
               */
              function _revokeRole(bytes32 role, address account) internal virtual {
                  if (hasRole(role, account)) {
                      _roles[role].members[account] = false;
                      emit RoleRevoked(role, account, _msgSender());
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol)
          pragma solidity ^0.8.0;
          import "./IAccessControlEnumerable.sol";
          import "./AccessControl.sol";
          import "../utils/structs/EnumerableSet.sol";
          /**
           * @dev Extension of {AccessControl} that allows enumerating the members of each role.
           */
          abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
              using EnumerableSet for EnumerableSet.AddressSet;
              mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;
              /**
               * @dev See {IERC165-supportsInterface}.
               */
              function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                  return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
              }
              /**
               * @dev Returns one of the accounts that have `role`. `index` must be a
               * value between 0 and {getRoleMemberCount}, non-inclusive.
               *
               * Role bearers are not sorted in any particular way, and their ordering may
               * change at any point.
               *
               * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
               * you perform all queries on the same block. See the following
               * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
               * for more information.
               */
              function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) {
                  return _roleMembers[role].at(index);
              }
              /**
               * @dev Returns the number of accounts that have `role`. Can be used
               * together with {getRoleMember} to enumerate all bearers of a role.
               */
              function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) {
                  return _roleMembers[role].length();
              }
              /**
               * @dev Overload {_grantRole} to track enumerable memberships
               */
              function _grantRole(bytes32 role, address account) internal virtual override {
                  super._grantRole(role, account);
                  _roleMembers[role].add(account);
              }
              /**
               * @dev Overload {_revokeRole} to track enumerable memberships
               */
              function _revokeRole(bytes32 role, address account) internal virtual override {
                  super._revokeRole(role, account);
                  _roleMembers[role].remove(account);
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev External interface of AccessControl declared to support ERC165 detection.
           */
          interface IAccessControl {
              /**
               * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
               *
               * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
               * {RoleAdminChanged} not being emitted signaling this.
               *
               * _Available since v3.1._
               */
              event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
              /**
               * @dev Emitted when `account` is granted `role`.
               *
               * `sender` is the account that originated the contract call, an admin role
               * bearer except when using {AccessControl-_setupRole}.
               */
              event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
              /**
               * @dev Emitted when `account` is revoked `role`.
               *
               * `sender` is the account that originated the contract call:
               *   - if using `revokeRole`, it is the admin role bearer
               *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
               */
              event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
              /**
               * @dev Returns `true` if `account` has been granted `role`.
               */
              function hasRole(bytes32 role, address account) external view returns (bool);
              /**
               * @dev Returns the admin role that controls `role`. See {grantRole} and
               * {revokeRole}.
               *
               * To change a role's admin, use {AccessControl-_setRoleAdmin}.
               */
              function getRoleAdmin(bytes32 role) external view returns (bytes32);
              /**
               * @dev Grants `role` to `account`.
               *
               * If `account` had not been already granted `role`, emits a {RoleGranted}
               * event.
               *
               * Requirements:
               *
               * - the caller must have ``role``'s admin role.
               */
              function grantRole(bytes32 role, address account) external;
              /**
               * @dev Revokes `role` from `account`.
               *
               * If `account` had been granted `role`, emits a {RoleRevoked} event.
               *
               * Requirements:
               *
               * - the caller must have ``role``'s admin role.
               */
              function revokeRole(bytes32 role, address account) external;
              /**
               * @dev Revokes `role` from the calling account.
               *
               * Roles are often managed via {grantRole} and {revokeRole}: this function's
               * purpose is to provide a mechanism for accounts to lose their privileges
               * if they are compromised (such as when a trusted device is misplaced).
               *
               * If the calling account had been granted `role`, emits a {RoleRevoked}
               * event.
               *
               * Requirements:
               *
               * - the caller must be `account`.
               */
              function renounceRole(bytes32 role, address account) external;
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)
          pragma solidity ^0.8.0;
          import "./IAccessControl.sol";
          /**
           * @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
           */
          interface IAccessControlEnumerable is IAccessControl {
              /**
               * @dev Returns one of the accounts that have `role`. `index` must be a
               * value between 0 and {getRoleMemberCount}, non-inclusive.
               *
               * Role bearers are not sorted in any particular way, and their ordering may
               * change at any point.
               *
               * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
               * you perform all queries on the same block. See the following
               * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
               * for more information.
               */
              function getRoleMember(bytes32 role, uint256 index) external view returns (address);
              /**
               * @dev Returns the number of accounts that have `role`. Can be used
               * together with {getRoleMember} to enumerate all bearers of a role.
               */
              function getRoleMemberCount(bytes32 role) external view returns (uint256);
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.8.0) (security/ReentrancyGuard.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev Contract module that helps prevent reentrant calls to a function.
           *
           * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
           * available, which can be applied to functions to make sure there are no nested
           * (reentrant) calls to them.
           *
           * Note that because there is a single `nonReentrant` guard, functions marked as
           * `nonReentrant` may not call one another. This can be worked around by making
           * those functions `private`, and then adding `external` `nonReentrant` entry
           * points to them.
           *
           * TIP: If you would like to learn more about reentrancy and alternative ways
           * to protect against it, check out our blog post
           * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
           */
          abstract contract ReentrancyGuard {
              // Booleans are more expensive than uint256 or any type that takes up a full
              // word because each write operation emits an extra SLOAD to first read the
              // slot's contents, replace the bits taken up by the boolean, and then write
              // back. This is the compiler's defense against contract upgrades and
              // pointer aliasing, and it cannot be disabled.
              // The values being non-zero value makes deployment a bit more expensive,
              // but in exchange the refund on every call to nonReentrant will be lower in
              // amount. Since refunds are capped to a percentage of the total
              // transaction's gas, it is best to keep them low in cases like this one, to
              // increase the likelihood of the full refund coming into effect.
              uint256 private constant _NOT_ENTERED = 1;
              uint256 private constant _ENTERED = 2;
              uint256 private _status;
              constructor() {
                  _status = _NOT_ENTERED;
              }
              /**
               * @dev Prevents a contract from calling itself, directly or indirectly.
               * Calling a `nonReentrant` function from another `nonReentrant`
               * function is not supported. It is possible to prevent this from happening
               * by making the `nonReentrant` function external, and making it call a
               * `private` function that does the actual work.
               */
              modifier nonReentrant() {
                  _nonReentrantBefore();
                  _;
                  _nonReentrantAfter();
              }
              function _nonReentrantBefore() private {
                  // On the first call to nonReentrant, _status will be _NOT_ENTERED
                  require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
                  // Any calls to nonReentrant after this point will fail
                  _status = _ENTERED;
              }
              function _nonReentrantAfter() private {
                  // By storing the original value once again, a refund is triggered (see
                  // https://eips.ethereum.org/EIPS/eip-2200)
                  _status = _NOT_ENTERED;
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.8.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 functionCallWithValue(target, data, 0, "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");
                  (bool success, bytes memory returndata) = target.call{value: value}(data);
                  return verifyCallResultFromTarget(target, 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) {
                  (bool success, bytes memory returndata) = target.staticcall(data);
                  return verifyCallResultFromTarget(target, 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) {
                  (bool success, bytes memory returndata) = target.delegatecall(data);
                  return verifyCallResultFromTarget(target, success, returndata, errorMessage);
              }
              /**
               * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
               * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
               *
               * _Available since v4.8._
               */
              function verifyCallResultFromTarget(
                  address target,
                  bool success,
                  bytes memory returndata,
                  string memory errorMessage
              ) internal view returns (bytes memory) {
                  if (success) {
                      if (returndata.length == 0) {
                          // only check isContract if the call was successful and the return data is empty
                          // otherwise we already know that it was a contract
                          require(isContract(target), "Address: call to non-contract");
                      }
                      return returndata;
                  } else {
                      _revert(returndata, errorMessage);
                  }
              }
              /**
               * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
               * revert reason or 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 {
                      _revert(returndata, errorMessage);
                  }
              }
              function _revert(bytes memory returndata, string memory errorMessage) private pure {
                  // Look for revert reason and bubble it up if present
                  if (returndata.length > 0) {
                      // The easiest way to bubble the revert reason is using memory via assembly
                      /// @solidity memory-safe-assembly
                      assembly {
                          let returndata_size := mload(returndata)
                          revert(add(32, returndata), returndata_size)
                      }
                  } else {
                      revert(errorMessage);
                  }
              }
          }
          // 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: MIT
          // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
          pragma solidity ^0.8.0;
          import "./IERC165.sol";
          /**
           * @dev Implementation of the {IERC165} interface.
           *
           * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
           * for the additional interface id that will be supported. For example:
           *
           * ```solidity
           * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
           *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
           * }
           * ```
           *
           * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
           */
          abstract contract ERC165 is IERC165 {
              /**
               * @dev See {IERC165-supportsInterface}.
               */
              function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                  return interfaceId == type(IERC165).interfaceId;
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev Interface of the ERC165 standard, as defined in the
           * https://eips.ethereum.org/EIPS/eip-165[EIP].
           *
           * Implementers can declare support of contract interfaces, which can then be
           * queried by others ({ERC165Checker}).
           *
           * For an implementation, see {ERC165}.
           */
          interface IERC165 {
              /**
               * @dev Returns true if this contract implements the interface defined by
               * `interfaceId`. See the corresponding
               * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
               * to learn more about how these ids are created.
               *
               * This function call must use less than 30 000 gas.
               */
              function supportsInterface(bytes4 interfaceId) external view returns (bool);
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev Standard math utilities missing in the Solidity language.
           */
          library Math {
              enum Rounding {
                  Down, // Toward negative infinity
                  Up, // Toward infinity
                  Zero // Toward zero
              }
              /**
               * @dev Returns the largest of two numbers.
               */
              function max(uint256 a, uint256 b) internal pure returns (uint256) {
                  return a > b ? a : b;
              }
              /**
               * @dev Returns the smallest of two numbers.
               */
              function min(uint256 a, uint256 b) internal pure returns (uint256) {
                  return a < b ? a : b;
              }
              /**
               * @dev Returns the average of two numbers. The result is rounded towards
               * zero.
               */
              function average(uint256 a, uint256 b) internal pure returns (uint256) {
                  // (a + b) / 2 can overflow.
                  return (a & b) + (a ^ b) / 2;
              }
              /**
               * @dev Returns the ceiling of the division of two numbers.
               *
               * This differs from standard division with `/` in that it rounds up instead
               * of rounding down.
               */
              function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
                  // (a + b - 1) / b can overflow on addition, so we distribute.
                  return a == 0 ? 0 : (a - 1) / b + 1;
              }
              /**
               * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
               * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
               * with further edits by Uniswap Labs also under MIT license.
               */
              function mulDiv(
                  uint256 x,
                  uint256 y,
                  uint256 denominator
              ) internal pure returns (uint256 result) {
                  unchecked {
                      // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
                      // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
                      // variables such that product = prod1 * 2^256 + prod0.
                      uint256 prod0; // Least significant 256 bits of the product
                      uint256 prod1; // Most significant 256 bits of the product
                      assembly {
                          let mm := mulmod(x, y, not(0))
                          prod0 := mul(x, y)
                          prod1 := sub(sub(mm, prod0), lt(mm, prod0))
                      }
                      // Handle non-overflow cases, 256 by 256 division.
                      if (prod1 == 0) {
                          return prod0 / denominator;
                      }
                      // Make sure the result is less than 2^256. Also prevents denominator == 0.
                      require(denominator > prod1);
                      ///////////////////////////////////////////////
                      // 512 by 256 division.
                      ///////////////////////////////////////////////
                      // Make division exact by subtracting the remainder from [prod1 prod0].
                      uint256 remainder;
                      assembly {
                          // Compute remainder using mulmod.
                          remainder := mulmod(x, y, denominator)
                          // Subtract 256 bit number from 512 bit number.
                          prod1 := sub(prod1, gt(remainder, prod0))
                          prod0 := sub(prod0, remainder)
                      }
                      // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
                      // See https://cs.stackexchange.com/q/138556/92363.
                      // Does not overflow because the denominator cannot be zero at this stage in the function.
                      uint256 twos = denominator & (~denominator + 1);
                      assembly {
                          // Divide denominator by twos.
                          denominator := div(denominator, twos)
                          // Divide [prod1 prod0] by twos.
                          prod0 := div(prod0, twos)
                          // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                          twos := add(div(sub(0, twos), twos), 1)
                      }
                      // Shift in bits from prod1 into prod0.
                      prod0 |= prod1 * twos;
                      // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
                      // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
                      // four bits. That is, denominator * inv = 1 mod 2^4.
                      uint256 inverse = (3 * denominator) ^ 2;
                      // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
                      // in modular arithmetic, doubling the correct bits in each step.
                      inverse *= 2 - denominator * inverse; // inverse mod 2^8
                      inverse *= 2 - denominator * inverse; // inverse mod 2^16
                      inverse *= 2 - denominator * inverse; // inverse mod 2^32
                      inverse *= 2 - denominator * inverse; // inverse mod 2^64
                      inverse *= 2 - denominator * inverse; // inverse mod 2^128
                      inverse *= 2 - denominator * inverse; // inverse mod 2^256
                      // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
                      // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
                      // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
                      // is no longer required.
                      result = prod0 * inverse;
                      return result;
                  }
              }
              /**
               * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
               */
              function mulDiv(
                  uint256 x,
                  uint256 y,
                  uint256 denominator,
                  Rounding rounding
              ) internal pure returns (uint256) {
                  uint256 result = mulDiv(x, y, denominator);
                  if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
                      result += 1;
                  }
                  return result;
              }
              /**
               * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
               *
               * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
               */
              function sqrt(uint256 a) internal pure returns (uint256) {
                  if (a == 0) {
                      return 0;
                  }
                  // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
                  //
                  // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
                  // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
                  //
                  // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
                  // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
                  // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
                  //
                  // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
                  uint256 result = 1 << (log2(a) >> 1);
                  // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
                  // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
                  // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
                  // into the expected uint128 result.
                  unchecked {
                      result = (result + a / result) >> 1;
                      result = (result + a / result) >> 1;
                      result = (result + a / result) >> 1;
                      result = (result + a / result) >> 1;
                      result = (result + a / result) >> 1;
                      result = (result + a / result) >> 1;
                      result = (result + a / result) >> 1;
                      return min(result, a / result);
                  }
              }
              /**
               * @notice Calculates sqrt(a), following the selected rounding direction.
               */
              function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
                  unchecked {
                      uint256 result = sqrt(a);
                      return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
                  }
              }
              /**
               * @dev Return the log in base 2, rounded down, of a positive value.
               * Returns 0 if given 0.
               */
              function log2(uint256 value) internal pure returns (uint256) {
                  uint256 result = 0;
                  unchecked {
                      if (value >> 128 > 0) {
                          value >>= 128;
                          result += 128;
                      }
                      if (value >> 64 > 0) {
                          value >>= 64;
                          result += 64;
                      }
                      if (value >> 32 > 0) {
                          value >>= 32;
                          result += 32;
                      }
                      if (value >> 16 > 0) {
                          value >>= 16;
                          result += 16;
                      }
                      if (value >> 8 > 0) {
                          value >>= 8;
                          result += 8;
                      }
                      if (value >> 4 > 0) {
                          value >>= 4;
                          result += 4;
                      }
                      if (value >> 2 > 0) {
                          value >>= 2;
                          result += 2;
                      }
                      if (value >> 1 > 0) {
                          result += 1;
                      }
                  }
                  return result;
              }
              /**
               * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
               * Returns 0 if given 0.
               */
              function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
                  unchecked {
                      uint256 result = log2(value);
                      return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
                  }
              }
              /**
               * @dev Return the log in base 10, rounded down, of a positive value.
               * Returns 0 if given 0.
               */
              function log10(uint256 value) internal pure returns (uint256) {
                  uint256 result = 0;
                  unchecked {
                      if (value >= 10**64) {
                          value /= 10**64;
                          result += 64;
                      }
                      if (value >= 10**32) {
                          value /= 10**32;
                          result += 32;
                      }
                      if (value >= 10**16) {
                          value /= 10**16;
                          result += 16;
                      }
                      if (value >= 10**8) {
                          value /= 10**8;
                          result += 8;
                      }
                      if (value >= 10**4) {
                          value /= 10**4;
                          result += 4;
                      }
                      if (value >= 10**2) {
                          value /= 10**2;
                          result += 2;
                      }
                      if (value >= 10**1) {
                          result += 1;
                      }
                  }
                  return result;
              }
              /**
               * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
               * Returns 0 if given 0.
               */
              function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
                  unchecked {
                      uint256 result = log10(value);
                      return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);
                  }
              }
              /**
               * @dev Return the log in base 256, rounded down, of a positive value.
               * Returns 0 if given 0.
               *
               * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
               */
              function log256(uint256 value) internal pure returns (uint256) {
                  uint256 result = 0;
                  unchecked {
                      if (value >> 128 > 0) {
                          value >>= 128;
                          result += 16;
                      }
                      if (value >> 64 > 0) {
                          value >>= 64;
                          result += 8;
                      }
                      if (value >> 32 > 0) {
                          value >>= 32;
                          result += 4;
                      }
                      if (value >> 16 > 0) {
                          value >>= 16;
                          result += 2;
                      }
                      if (value >> 8 > 0) {
                          result += 1;
                      }
                  }
                  return result;
              }
              /**
               * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
               * Returns 0 if given 0.
               */
              function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
                  unchecked {
                      uint256 result = log256(value);
                      return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);
                  }
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)
          pragma solidity ^0.8.0;
          import "./math/Math.sol";
          /**
           * @dev String operations.
           */
          library Strings {
              bytes16 private constant _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) {
                  unchecked {
                      uint256 length = Math.log10(value) + 1;
                      string memory buffer = new string(length);
                      uint256 ptr;
                      /// @solidity memory-safe-assembly
                      assembly {
                          ptr := add(buffer, add(32, length))
                      }
                      while (true) {
                          ptr--;
                          /// @solidity memory-safe-assembly
                          assembly {
                              mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
                          }
                          value /= 10;
                          if (value == 0) break;
                      }
                      return buffer;
                  }
              }
              /**
               * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
               */
              function toHexString(uint256 value) internal pure returns (string memory) {
                  unchecked {
                      return toHexString(value, Math.log256(value) + 1);
                  }
              }
              /**
               * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
               */
              function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
                  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] = _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);
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.8.0) (utils/structs/EnumerableSet.sol)
          // This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
          pragma solidity ^0.8.0;
          /**
           * @dev Library for managing
           * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
           * types.
           *
           * Sets have the following properties:
           *
           * - Elements are added, removed, and checked for existence in constant time
           * (O(1)).
           * - Elements are enumerated in O(n). No guarantees are made on the ordering.
           *
           * ```
           * contract Example {
           *     // Add the library methods
           *     using EnumerableSet for EnumerableSet.AddressSet;
           *
           *     // Declare a set state variable
           *     EnumerableSet.AddressSet private mySet;
           * }
           * ```
           *
           * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
           * and `uint256` (`UintSet`) are supported.
           *
           * [WARNING]
           * ====
           * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
           * unusable.
           * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
           *
           * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
           * array of EnumerableSet.
           * ====
           */
          library EnumerableSet {
              // To implement this library for multiple types with as little code
              // repetition as possible, we write it in terms of a generic Set type with
              // bytes32 values.
              // The Set implementation uses private functions, and user-facing
              // implementations (such as AddressSet) are just wrappers around the
              // underlying Set.
              // This means that we can only create new EnumerableSets for types that fit
              // in bytes32.
              struct Set {
                  // Storage of set values
                  bytes32[] _values;
                  // Position of the value in the `values` array, plus 1 because index 0
                  // means a value is not in the set.
                  mapping(bytes32 => uint256) _indexes;
              }
              /**
               * @dev Add a value to a set. O(1).
               *
               * Returns true if the value was added to the set, that is if it was not
               * already present.
               */
              function _add(Set storage set, bytes32 value) private returns (bool) {
                  if (!_contains(set, value)) {
                      set._values.push(value);
                      // The value is stored at length-1, but we add 1 to all indexes
                      // and use 0 as a sentinel value
                      set._indexes[value] = set._values.length;
                      return true;
                  } else {
                      return false;
                  }
              }
              /**
               * @dev Removes a value from a set. O(1).
               *
               * Returns true if the value was removed from the set, that is if it was
               * present.
               */
              function _remove(Set storage set, bytes32 value) private returns (bool) {
                  // We read and store the value's index to prevent multiple reads from the same storage slot
                  uint256 valueIndex = set._indexes[value];
                  if (valueIndex != 0) {
                      // Equivalent to contains(set, value)
                      // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
                      // the array, and then remove the last element (sometimes called as 'swap and pop').
                      // This modifies the order of the array, as noted in {at}.
                      uint256 toDeleteIndex = valueIndex - 1;
                      uint256 lastIndex = set._values.length - 1;
                      if (lastIndex != toDeleteIndex) {
                          bytes32 lastValue = set._values[lastIndex];
                          // Move the last value to the index where the value to delete is
                          set._values[toDeleteIndex] = lastValue;
                          // Update the index for the moved value
                          set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
                      }
                      // Delete the slot where the moved value was stored
                      set._values.pop();
                      // Delete the index for the deleted slot
                      delete set._indexes[value];
                      return true;
                  } else {
                      return false;
                  }
              }
              /**
               * @dev Returns true if the value is in the set. O(1).
               */
              function _contains(Set storage set, bytes32 value) private view returns (bool) {
                  return set._indexes[value] != 0;
              }
              /**
               * @dev Returns the number of values on the set. O(1).
               */
              function _length(Set storage set) private view returns (uint256) {
                  return set._values.length;
              }
              /**
               * @dev Returns the value stored at position `index` in the set. O(1).
               *
               * Note that there are no guarantees on the ordering of values inside the
               * array, and it may change when more values are added or removed.
               *
               * Requirements:
               *
               * - `index` must be strictly less than {length}.
               */
              function _at(Set storage set, uint256 index) private view returns (bytes32) {
                  return set._values[index];
              }
              /**
               * @dev Return the entire set in an array
               *
               * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
               * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
               * this function has an unbounded cost, and using it as part of a state-changing function may render the function
               * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
               */
              function _values(Set storage set) private view returns (bytes32[] memory) {
                  return set._values;
              }
              // Bytes32Set
              struct Bytes32Set {
                  Set _inner;
              }
              /**
               * @dev Add a value to a set. O(1).
               *
               * Returns true if the value was added to the set, that is if it was not
               * already present.
               */
              function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
                  return _add(set._inner, value);
              }
              /**
               * @dev Removes a value from a set. O(1).
               *
               * Returns true if the value was removed from the set, that is if it was
               * present.
               */
              function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
                  return _remove(set._inner, value);
              }
              /**
               * @dev Returns true if the value is in the set. O(1).
               */
              function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
                  return _contains(set._inner, value);
              }
              /**
               * @dev Returns the number of values in the set. O(1).
               */
              function length(Bytes32Set storage set) internal view returns (uint256) {
                  return _length(set._inner);
              }
              /**
               * @dev Returns the value stored at position `index` in the set. O(1).
               *
               * Note that there are no guarantees on the ordering of values inside the
               * array, and it may change when more values are added or removed.
               *
               * Requirements:
               *
               * - `index` must be strictly less than {length}.
               */
              function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
                  return _at(set._inner, index);
              }
              /**
               * @dev Return the entire set in an array
               *
               * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
               * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
               * this function has an unbounded cost, and using it as part of a state-changing function may render the function
               * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
               */
              function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
                  bytes32[] memory store = _values(set._inner);
                  bytes32[] memory result;
                  /// @solidity memory-safe-assembly
                  assembly {
                      result := store
                  }
                  return result;
              }
              // AddressSet
              struct AddressSet {
                  Set _inner;
              }
              /**
               * @dev Add a value to a set. O(1).
               *
               * Returns true if the value was added to the set, that is if it was not
               * already present.
               */
              function add(AddressSet storage set, address value) internal returns (bool) {
                  return _add(set._inner, bytes32(uint256(uint160(value))));
              }
              /**
               * @dev Removes a value from a set. O(1).
               *
               * Returns true if the value was removed from the set, that is if it was
               * present.
               */
              function remove(AddressSet storage set, address value) internal returns (bool) {
                  return _remove(set._inner, bytes32(uint256(uint160(value))));
              }
              /**
               * @dev Returns true if the value is in the set. O(1).
               */
              function contains(AddressSet storage set, address value) internal view returns (bool) {
                  return _contains(set._inner, bytes32(uint256(uint160(value))));
              }
              /**
               * @dev Returns the number of values in the set. O(1).
               */
              function length(AddressSet storage set) internal view returns (uint256) {
                  return _length(set._inner);
              }
              /**
               * @dev Returns the value stored at position `index` in the set. O(1).
               *
               * Note that there are no guarantees on the ordering of values inside the
               * array, and it may change when more values are added or removed.
               *
               * Requirements:
               *
               * - `index` must be strictly less than {length}.
               */
              function at(AddressSet storage set, uint256 index) internal view returns (address) {
                  return address(uint160(uint256(_at(set._inner, index))));
              }
              /**
               * @dev Return the entire set in an array
               *
               * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
               * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
               * this function has an unbounded cost, and using it as part of a state-changing function may render the function
               * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
               */
              function values(AddressSet storage set) internal view returns (address[] memory) {
                  bytes32[] memory store = _values(set._inner);
                  address[] memory result;
                  /// @solidity memory-safe-assembly
                  assembly {
                      result := store
                  }
                  return result;
              }
              // UintSet
              struct UintSet {
                  Set _inner;
              }
              /**
               * @dev Add a value to a set. O(1).
               *
               * Returns true if the value was added to the set, that is if it was not
               * already present.
               */
              function add(UintSet storage set, uint256 value) internal returns (bool) {
                  return _add(set._inner, bytes32(value));
              }
              /**
               * @dev Removes a value from a set. O(1).
               *
               * Returns true if the value was removed from the set, that is if it was
               * present.
               */
              function remove(UintSet storage set, uint256 value) internal returns (bool) {
                  return _remove(set._inner, bytes32(value));
              }
              /**
               * @dev Returns true if the value is in the set. O(1).
               */
              function contains(UintSet storage set, uint256 value) internal view returns (bool) {
                  return _contains(set._inner, bytes32(value));
              }
              /**
               * @dev Returns the number of values in the set. O(1).
               */
              function length(UintSet storage set) internal view returns (uint256) {
                  return _length(set._inner);
              }
              /**
               * @dev Returns the value stored at position `index` in the set. O(1).
               *
               * Note that there are no guarantees on the ordering of values inside the
               * array, and it may change when more values are added or removed.
               *
               * Requirements:
               *
               * - `index` must be strictly less than {length}.
               */
              function at(UintSet storage set, uint256 index) internal view returns (uint256) {
                  return uint256(_at(set._inner, index));
              }
              /**
               * @dev Return the entire set in an array
               *
               * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
               * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
               * this function has an unbounded cost, and using it as part of a state-changing function may render the function
               * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
               */
              function values(UintSet storage set) internal view returns (uint256[] memory) {
                  bytes32[] memory store = _values(set._inner);
                  uint256[] memory result;
                  /// @solidity memory-safe-assembly
                  assembly {
                      result := store
                  }
                  return result;
              }
          }
          // SPDX-License-Identifier: UNLICENSED
          // Copyright (c) Eywa.Fi, 2021-2023 - all rights reserved
          pragma solidity ^0.8.17;
          import "@openzeppelin/contracts/utils/Address.sol";
          import "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
          import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
          import "../interfaces/IBridgeV2.sol";
          import "../utils/Block.sol";
          import "../utils/Bls.sol";
          import "../utils/Merkle.sol";
          import "../utils/RequestIdChecker.sol";
          import "../utils/Typecast.sol";
          contract BridgeV2 is IBridgeV2, AccessControlEnumerable, Typecast, ReentrancyGuard {
              
              using Address for address;
              using Bls for Bls.Epoch;
              /// @dev gate keeper role id
              bytes32 public constant GATEKEEPER_ROLE = keccak256("GATEKEEPER_ROLE");
              /// @dev validator role id
              bytes32 public constant VALIDATOR_ROLE = keccak256("VALIDATOR_ROLE");
              /// @dev operator role id
              bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE");
              /// @dev human readable version
              string public version;
              /// @dev current state Active\\Inactive
              State public state;
              /// @dev nonces
              mapping(address => uint256) public nonces;
              /// @dev received request IDs against relay
              RequestIdChecker public currentRequestIdChecker;
              /// @dev received request IDs against relay
              RequestIdChecker public previousRequestIdChecker;
              // current epoch
              Bls.Epoch internal currentEpoch;
              // previous epoch
              Bls.Epoch internal previousEpoch;
              event EpochUpdated(bytes key, uint32 epochNum, uint64 protocolVersion);
              event RequestSent(
                  bytes32 requestId,
                  bytes data,
                  address to,
                  uint64 chainIdTo
              );
              event RequestReceived(bytes32 requestId, string error);
              event StateSet(State state);
              constructor() {
                  _grantRole(DEFAULT_ADMIN_ROLE, _msgSender());
                  version = "2.2.3";
                  currentRequestIdChecker = new RequestIdChecker();
                  previousRequestIdChecker = new RequestIdChecker();
                  state = State.Inactive;
              }
              /**
               * @dev Get current epoch.
               */
              function getCurrentEpoch() public view returns (bytes memory, uint8, uint32) {
                  return (abi.encode(currentEpoch.publicKey), currentEpoch.participantsCount, currentEpoch.epochNum);
              }
              /**
               * @dev Get previous epoch.
               */
              function getPreviousEpoch() public view returns (bytes memory, uint8, uint32) {
                  return (abi.encode(previousEpoch.publicKey), previousEpoch.participantsCount, previousEpoch.epochNum);
              }
              /**
               * @dev Updates current epoch.
               *
               * @param params ReceiveParams struct.
               */
              function updateEpoch(ReceiveParams calldata params) external onlyRole(VALIDATOR_ROLE) {
                  // TODO ensure that new epoch really next one after previous (by hash)
                  bytes memory payload = Merkle.prove(params.merkleProof, Block.txRootHash(params.blockHeader));
                  (uint64 newEpochProtocolVersion, uint32 newEpochNum, bytes memory newKey, uint8 newParticipantsCount) = Block
                      .decodeEpochUpdate(payload);
                  require(currentEpoch.epochNum + 1 == newEpochNum, "Bridge: wrong epoch number");
              
                  // TODO remove if when resetEpoch will be removed
                  if (currentEpoch.isSet()) {
                      verifyEpoch(currentEpoch, params);
                      rotateEpoch();
                  }
                  // TODO ensure that new epoch really next one after previous (prev hash + params.blockHeader)
                  bytes32 newHash = sha256(params.blockHeader);
                  currentEpoch.update(newKey, newParticipantsCount, newEpochNum, newHash);
                  onEpochStart(newEpochProtocolVersion);
              }
              /**
               * @dev Forcefully reset epoch on all chains.
               */
              function resetEpoch() public onlyRole(OPERATOR_ROLE) {
                  // TODO consider to remove any possible manipulations from protocol
                  if (currentEpoch.isSet()) {
                      rotateEpoch();
                      currentEpoch.epochNum = previousEpoch.epochNum + 1;
                  } else {
                      currentEpoch.epochNum = currentEpoch.epochNum + 1;
                  }
                  onEpochStart(0);
              }
              /**
               * @dev Send crosschain request v2.
               *
               * @param params struct with requestId, data, receiver and opposite cahinId
               * @param from sender's address
               * @param nonce sender's nonce
               */
              function sendV2(
                  SendParams calldata params,
                  address from,
                  uint256 nonce
              ) external override onlyRole(GATEKEEPER_ROLE) returns (bool) {
                  require(state == State.Active, "Bridge: state inactive");
                  require(previousEpoch.isSet() || currentEpoch.isSet(), "Bridge: epoch not set");
              
                  verifyAndUpdateNonce(from, nonce);
                  emit RequestSent(
                      params.requestId,
                      params.data,
                      params.to,
                      uint64(params.chainIdTo)
                  );
                  return true;
              }
              /**
               * @dev Receive (batch) crosschain request v2.
               *
               * @param params array with ReceiveParams structs.
               */
              function receiveV2(ReceiveParams[] calldata params) external override onlyRole(VALIDATOR_ROLE) nonReentrant returns (bool) {
                  require(state != State.Inactive, "Bridge: state inactive");
                  for (uint256 i = 0; i < params.length; ++i) {
                      bytes32 epochHash = Block.epochHash(params[i].blockHeader);
                      // verify the block signature
                      if (epochHash == currentEpoch.epochHash) {
                          require(currentEpoch.isSet(), "Bridge: epoch not set");
                          verifyEpoch(currentEpoch, params[i]);
                      } else if (epochHash == previousEpoch.epochHash) {
                          require(previousEpoch.isSet(), "Bridge: epoch not set");
                          verifyEpoch(previousEpoch, params[i]);
                      } else {
                          revert("Bridge: wrong epoch");
                      }
                      // verify that the transaction is really in the block
                      bytes memory payload = Merkle.prove(params[i].merkleProof, Block.txRootHash(params[i].blockHeader));
                      // get call data
                      (bytes32 requestId, bytes memory receivedData, address to, uint64 chainIdTo) = Block.decodeRequest(payload);
                      require(chainIdTo == block.chainid, "Bridge: wrong chain id");
                      require(to.isContract(), "Bridge: receiver is not a contract");
                      bool isRequestIdUniq;
                      if (epochHash == currentEpoch.epochHash) {
                          isRequestIdUniq = currentRequestIdChecker.check(requestId);
                      } else {
                          isRequestIdUniq = previousRequestIdChecker.check(requestId);
                      }
                      string memory err;
                      
                      if (isRequestIdUniq) {
                          (bytes memory data, bytes memory check) = abi.decode(receivedData, (bytes, bytes));
                          bytes memory result = to.functionCall(check);
                          require(abi.decode(result, (bool)), "Bridge: check failed");
                          
                          to.functionCall(data, "Bridge: receive failed");
                      } else {
                          revert("Bridge: request id already seen");
                      }
                      emit RequestReceived(requestId, err);
                  }
                  return true;
              }
              /**
               * @dev Set new state.
               *
               * @param state_ Active\\Inactive state
               */
              function setState(State state_) external onlyRole(OPERATOR_ROLE) {
                  state = state_;
                  emit StateSet(state);
              }
              /**
               * @dev Verifies epoch.
               *
               * @param epoch current or previous epoch;
               * @param params oracle tx params
               */
              function verifyEpoch(Bls.Epoch storage epoch, ReceiveParams calldata params) internal view {
                  Block.verify(
                      epoch,
                      params.blockHeader,
                      params.votersPubKey,
                      params.votersSignature,
                      params.votersMask
                  );
              }
              /**
               * @dev Verifies and updates the sender's nonce.
               *
               * @param from sender's address
               * @param nonce provided nonce
               */
              function verifyAndUpdateNonce(address from, uint256 nonce) internal {
                  require(nonces[from]++ == nonce, "Bridge: nonce mismatch");
              }
              /**
               * @dev Moves current epoch and current request filter to previous.
               */
              function rotateEpoch() internal {
                  previousEpoch = currentEpoch;
                  Bls.Epoch memory epoch;
                  currentEpoch = epoch;
                  previousRequestIdChecker.destroy();
                  previousRequestIdChecker = currentRequestIdChecker;
                  currentRequestIdChecker = new RequestIdChecker();
              }
              /**
               * @dev Hook on start new epoch.
               */
              function onEpochStart(uint64 protocolVersion_) internal virtual {
                  emit EpochUpdated(abi.encode(currentEpoch.publicKey), currentEpoch.epochNum, protocolVersion_);
              }
          }
          // SPDX-License-Identifier: UNLICENSED
          // Copyright (c) Eywa.Fi, 2021-2023 - all rights reserved
          pragma solidity ^0.8.17;
          interface IBridgeV2 {
              enum State { 
                  Active, // data send and receive possible
                  Inactive, // data send and receive impossible
                  Limited // only data receive possible
              }
              struct SendParams {
                  /// @param requestId unique request ID
                  bytes32 requestId;
                  /// @param data call data
                  bytes data;
                  /// @param to receiver contract address
                  address to;
                  /// @param chainIdTo destination chain ID
                  uint256 chainIdTo;
              }
              struct ReceiveParams {
                  /// @param blockHeader block header serialization
                  bytes blockHeader;
                  /// @param merkleProof OracleRequest transaction payload and its Merkle audit path
                  bytes merkleProof;
                  /// @param votersPubKey aggregated public key of the old epoch participants, who voted for the block
                  bytes votersPubKey;
                  /// @param votersSignature aggregated signature of the old epoch participants, who voted for the block
                  bytes votersSignature;
                  /// @param votersMask bitmask of epoch participants, who voted, among all participants
                  uint256 votersMask;
              }
              function sendV2(
                  SendParams calldata params,
                  address sender,
                  uint256 nonce
              ) external returns (bool);
              function receiveV2(ReceiveParams[] calldata params) external returns (bool);
              function nonces(address from) external view returns (uint256);
          }
          // SPDX-License-Identifier: UNLICENSED
          // Copyright (c) Eywa.Fi, 2021-2023 - all rights reserved
          pragma solidity 0.8.17;
          import "../utils/Bls.sol";
          import "../utils/Utils.sol";
          import "../utils/ZeroCopySource.sol";
          library Block {
              function txRootHash(bytes calldata payload) internal pure returns (bytes32 txRootHash_) {
                  txRootHash_ = Utils.bytesToBytes32(payload[72:104]);
              }
              function epochHash(bytes calldata payload) internal pure returns (bytes32 epochHash_) {
                  epochHash_ = Utils.bytesToBytes32(payload[40:72]);
              }
              function decodeRequest(bytes memory payload) internal pure returns (
                  bytes32 requestId,
                  bytes memory data,
                  address to,
                  uint64 chainIdTo
              ) {
                  uint256 off = 0;
                  (requestId, off) = ZeroCopySource.NextHash(payload, off);
                  (chainIdTo, off) = ZeroCopySource.NextUint64(payload, off);
                  (to, off) = ZeroCopySource.NextAddress(payload, off);
                  (data, off) = ZeroCopySource.NextVarBytes(payload, off);
              }
              function decodeEpochUpdate(bytes memory payload) internal pure returns (
                  uint64 newEpochVersion,
                  uint32 newEpochNum,
                  bytes memory newKey,
                  uint8 newEpochParticipantsCount
              ) {
                  uint256 off = 0;
                  (newEpochVersion, off) = ZeroCopySource.NextUint64(payload, off);
                  (newEpochNum, off) = ZeroCopySource.NextUint32(payload, off);
                  (newEpochParticipantsCount, off) = ZeroCopySource.NextUint8(payload, off);
                  (newKey, off) = ZeroCopySource.NextVarBytes(payload, off);
              }
              function verify(
                  Bls.Epoch memory epoch,
                  bytes calldata blockHeader,
                  bytes calldata votersPubKey,
                  bytes calldata votersSignature,
                  uint256 votersMask
              ) internal view {
                  require(popcnt(votersMask) > (uint256(epoch.participantsCount) * 2) / 3, "Block: not enough participants");
                  require(epoch.participantsCount == 255 || votersMask < (1 << epoch.participantsCount), "Block: bitmask too big");
                  require(
                      Bls.verifyMultisig(epoch, votersPubKey, blockHeader, votersSignature, votersMask),
                      "Block: multisig mismatch"
                  );
              }
              function popcnt(uint256 mask) internal pure returns (uint256 cnt) {
                  cnt = 0;
                  while (mask != 0) {
                      mask = mask & (mask - 1);
                      cnt++;
                  }
              }
          }
          // SPDX-License-Identifier: UNLICENSED
          // Copyright (c) ConsenSys
          // Copyright (c) Eywa.Fi, 2021-2023 - all rights reserved
          pragma solidity 0.8.17;
          import "./ModUtils.sol";
          /**
           * @title Verify BLS Threshold Signed values.
           *
           * Much of the code in this file is derived from here:
           * https://github.com/ConsenSys/gpact/blob/main/common/common/src/main/solidity/BlsSignatureVerification.sol
           * https://github.com/ConsenSys/gpact/blob/main/contracts/contracts/src/common/BlsSignatureVerification.sol
           */
          library Bls {
              using ModUtils for uint256;
              struct E1Point {
                  uint256 x;
                  uint256 y;
              }
              /**
               * @dev Note that the ordering of the elements in each array needs to be the reverse of what you would
               * normally have, to match the ordering expected by the precompile.
               */
              struct E2Point {
                  uint256[2] x;
                  uint256[2] y;
              }
              /**
               * @dev P is a prime over which we form a basic field;
               * taken from go-ethereum/crypto/bn256/cloudflare/constants.go.
               */
              uint256 constant P = 21888242871839275222246405745257275088696311157297823662689037894645226208583;
              struct Epoch {
                  /// @param sum of all participant public keys
                  E2Point publicKey;
                  /// @param // sum of H(Pub, i) hashes of all participants indexes
                  E1Point precomputedSum;
                  /// @param // participants count contributed to the epochKey
                  uint8 participantsCount;
                  /// @param epoch number
                  uint32 epochNum;
                  /// @param epoch hash
                  bytes32 epochHash;
              }
              /**
               * @dev Tests that epoch is set or zero.
               */
              function isSet(Epoch memory epoch) internal pure returns (bool) {
                  return epoch.publicKey.x[0] != 0 || epoch.publicKey.x[1] != 0;
              }
              /**
               * @dev Reset the epoch.
               */
              function reset(Epoch storage epoch) internal {
                  epoch.publicKey.x[0] = 0;
                  epoch.publicKey.x[1] = 0;
                  epoch.precomputedSum.x = 0;
                  epoch.epochHash = 0;
                  epoch.participantsCount = 0;
              }
              /**
               * @dev Update epoch and precompute epoch sum as if all participants signed.
               *
               * @param epoch_ current epoch to update;
               * @param epochPublicKey sum of all participant public keys;
               * @param epochParticipantsCount number of participants;
               * @param epochNum number of participants;
               * @param epochHash epoch hash.
               */
              function update(
                  Epoch storage epoch_,
                  bytes memory epochPublicKey,
                  uint8 epochParticipantsCount,
                  uint32 epochNum,
                  bytes32 epochHash
              ) internal {
                  E2Point memory pub = decodeE2Point(epochPublicKey);
                  E1Point memory sum = E1Point(0, 0);
                  uint256 index = 0;
                  bytes memory buf = abi.encodePacked(pub.x, pub.y, index);
                  while (index < epochParticipantsCount) {
                      assembly {
                          mstore(add(buf, 160), index)
                      } // overwrite index field, same as buf[128] = index
                      sum = addCurveE1(sum, hashToCurveE1(buf));
                      index++;
                  }
                  epoch_.publicKey = pub;
                  epoch_.precomputedSum = sum;
                  epoch_.participantsCount = epochParticipantsCount;
                  epoch_.epochNum = epochNum;
                  epoch_.epochHash = epochHash;
              }
              /**
               * @dev Checks if the BLS multisignature is valid in the current epoch.
               *
               * @param epoch_ current epoch;
               * @param partPublicKey Sum of participated public keys;
               * @param message Message that was signed;
               * @param partSignature Signature over the message;
               * @param signersBitmask Bitmask of participants in this signature;
               * @return True if the message was correctly signed by the given participants.
               */
              function verifyMultisig(
                  Epoch memory epoch_,
                  bytes memory partPublicKey,
                  bytes memory message,
                  bytes memory partSignature,
                  uint256 signersBitmask
              ) internal view returns (bool) {
                  E1Point memory sum = epoch_.precomputedSum;
                  uint256 index = 0;
                  uint256 mask = 1;
                  bytes memory buf = abi.encodePacked(epoch_.publicKey.x, epoch_.publicKey.y, index);
                  while (index < epoch_.participantsCount) {
                      if (signersBitmask & mask == 0) {
                          assembly {
                              mstore(add(buf, 160), index)
                          } // overwrite index field, same as buf[128] = index
                          sum = addCurveE1(sum, negate(hashToCurveE1(buf)));
                      }
                      mask <<= 1;
                      index++;
                  }
                  E1Point[] memory e1points = new E1Point[](3);
                  E2Point[] memory e2points = new E2Point[](3);
                  e1points[0] = negate(decodeE1Point(partSignature));
                  e1points[1] = hashToCurveE1(abi.encodePacked(epoch_.publicKey.x, epoch_.publicKey.y, message));
                  e1points[2] = sum;
                  e2points[0] = G2();
                  e2points[1] = decodeE2Point(partPublicKey);
                  e2points[2] = epoch_.publicKey;
                  return pairing(e1points, e2points);
              }
              /**
               * @return The generator of E1.
               */
              function G1() private pure returns (E1Point memory) {
                  return E1Point(1, 2);
              }
              /**
               * @return The generator of E2.
               */
              function G2() private pure returns (E2Point memory) {
                  return E2Point({
                      x: [
                          11559732032986387107991004021392285783925812861821192530917403151452391805634,
                          10857046999023057135944570762232829481370756359578518086990519993285655852781
                      ],
                      y: [
                          4082367875863433681332203403145435568316851327593401208105741076214120093531,
                          8495653923123431417604973247489272438418190587263600148770280649306958101930
                      ]
                  });
              }
              /**
               * Negate a point: Assuming the point isn't at infinity, the negation is same x value with -y.
               *
               * @dev Negates a point in E1;
               * @param _point Point to negate;
               * @return The negated point.
               */
              function negate(E1Point memory _point) private pure returns (E1Point memory) {
                  if (isAtInfinity(_point)) {
                      return E1Point(0, 0);
                  }
                  return E1Point(_point.x, P - (_point.y % P));
              }
              /**
               * Computes the pairing check e(p1[0], p2[0]) *  .... * e(p1[n], p2[n]) == 1
               *
               * @param _e1points List of points in E1;
               * @param _e2points List of points in E2;
               * @return True if pairing check succeeds.
               */
              function pairing(E1Point[] memory _e1points, E2Point[] memory _e2points) private view returns (bool) {
                  require(_e1points.length == _e2points.length, "Bls: point count mismatch");
                  uint256 elements = _e1points.length;
                  uint256 inputSize = elements * 6;
                  uint256[] memory input = new uint256[](inputSize);
                  for (uint256 i = 0; i < elements; i++) {
                      input[i * 6 + 0] = _e1points[i].x;
                      input[i * 6 + 1] = _e1points[i].y;
                      input[i * 6 + 2] = _e2points[i].x[0];
                      input[i * 6 + 3] = _e2points[i].x[1];
                      input[i * 6 + 4] = _e2points[i].y[0];
                      input[i * 6 + 5] = _e2points[i].y[1];
                  }
                  uint256[1] memory out;
                  bool success;
                  assembly {
                      // Start at memory offset 0x20 rather than 0 as input is a variable length array.
                      // Location 0 is the length field.
                      success := staticcall(sub(gas(), 2000), 8, add(input, 0x20), mul(inputSize, 0x20), out, 0x20)
                  }
                  // The pairing operation will fail if the input data isn't the correct size (this won't happen
                  // given the code above), or if one of the points isn't on the curve.
                  require(success, "Bls: pairing operation failed");
                  return out[0] != 0;
              }
              /**
               * @dev Checks if the point is the point at infinity.
               *
               * @param _point a point on E1;
               * @return true if the point is the point at infinity.
               */
              function isAtInfinity(E1Point memory _point) private pure returns (bool) {
                  return (_point.x == 0 && _point.y == 0);
              }
              /**
               * @dev Hash a byte array message, m, and map it deterministically to a point on G1.
               * Note that this approach was chosen for its simplicity /
               * lower gas cost on the EVM, rather than good distribution of points on G1.
               */
              function hashToCurveE1(bytes memory m) internal view returns (E1Point memory) {
                  bytes32 h = sha256(m);
                  uint256 x = uint256(h) % P;
                  uint256 y;
                  while (true) {
                      y = YFromX(x);
                      if (y > 0) {
                          return E1Point(x, y);
                      }
                      x += 1;
                  }
                  revert("hashToCurveE1: unreachable end point");
              }
              /**
               * @dev g1YFromX computes a Y value for a G1 point based on an X value.
               * This computation is simply evaluating the curve equation for Y on a given X,
               * and allows a point on the curve to be represented by just an X value + a sign bit.
               */
              function YFromX(uint256 x) internal view returns (uint256) {
                  return ((x.modExp(3, P) + 3) % P).modSqrt(P);
              }
              /**
               * @dev return the sum of two points of G1.
               */
              function addCurveE1(E1Point memory _p1, E1Point memory _p2) internal view returns (E1Point memory res) {
                  uint256[4] memory input;
                  input[0] = _p1.x;
                  input[1] = _p1.y;
                  input[2] = _p2.x;
                  input[3] = _p2.y;
                  bool success;
                  assembly {
                      success := staticcall(sub(gas(), 2000), 6, input, 0x80, res, 0x40)
                  }
                  require(success, "Bls: add points failed");
              }
              function decodeE1Point(bytes memory _sig) internal pure returns (E1Point memory signature) {
                  uint256 sigx;
                  uint256 sigy;
                  assembly {
                      sigx := mload(add(_sig, 0x20))
                      sigy := mload(add(_sig, 0x40))
                  }
                  signature.x = sigx;
                  signature.y = sigy;
              }
              function decodeE2Point(bytes memory _pubKey) internal pure returns (E2Point memory pubKey) {
                  uint256 x1;
                  uint256 x2;
                  uint256 y1;
                  uint256 y2;
                  assembly {
                      x1 := mload(add(_pubKey, 0x20))
                      x2 := mload(add(_pubKey, 0x40))
                      y1 := mload(add(_pubKey, 0x60))
                      y2 := mload(add(_pubKey, 0x80))
                  }
                  pubKey.x[0] = x1;
                  pubKey.x[1] = x2;
                  pubKey.y[0] = y1;
                  pubKey.y[1] = y2;
              }
          }
          // SPDX-License-Identifier: UNLICENSED
          // Copyright (c) Eywa.Fi, 2021-2023 - all rights reserved
          pragma solidity 0.8.17;
          import "./ZeroCopySource.sol";
          library Merkle {
              /** @notice Do hash leaf as the multi-chain does.
               *
               *  @param data_ Data in bytes format;
               *  @return result Hashed value in bytes32 format.
               */
              function hashLeaf(bytes memory data_) internal pure returns (bytes32 result) {
                  result = sha256(abi.encodePacked(uint8(0x0), data_));
              }
              /** @notice Do hash children as the multi-chain does.
               *
               *  @param l_ Left node;
               *  @param r_ Right node;
               *  @return result Hashed value in bytes32 format.
               */
              function hashChildren(bytes32 l_, bytes32 r_) internal pure returns (bytes32 result) {
                  result = sha256(abi.encodePacked(bytes1(0x01), l_, r_));
              }
              /** @notice Verify merkle proove.
               *
               *  @param auditPath_ Merkle path;
               *  @param root_ Merkle tree root;
               *  @return The verified value included in auditPath_.
               */
              function prove(bytes memory auditPath_, bytes32 root_) internal pure returns (bytes memory) {
                  uint256 off = 0;
                  bytes memory value;
                  (value, off) = ZeroCopySource.NextVarBytes(auditPath_, off);
                  bytes32 hash = hashLeaf(value);
                  uint256 size = (auditPath_.length - off) / 33; // 33 = sizeof(uint256) + 1
                  bytes32 nodeHash;
                  uint8 pos;
                  for (uint256 i = 0; i < size; i++) {
                      (pos, off) = ZeroCopySource.NextUint8(auditPath_, off);
                      (nodeHash, off) = ZeroCopySource.NextHash(auditPath_, off);
                      if (pos == 0x00) {
                          hash = hashChildren(nodeHash, hash);
                      } else if (pos == 0x01) {
                          hash = hashChildren(hash, nodeHash);
                      } else {
                          revert("Merkle: prove eod");
                      }
                  }
                  require(hash == root_, "Merkle: prove root");
                  return value;
              }
          }
          // SPDX-License-Identifier: MIT
          pragma solidity 0.8.17;
          library ModUtils {
              /**
               * @dev Wrap the modular exponent pre-compile introduced in Byzantium.
               * Returns base^exponent mod p.
               */
              function modExp(
                  uint256 base,
                  uint256 exponent,
                  uint256 p
              ) internal view returns (uint256 o) {
                  /* solium-disable-next-line */
                  assembly {
                      // Args for the precompile: [<length_of_BASE> <length_of_EXPONENT>
                      // <length_of_MODULUS> <BASE> <EXPONENT> <MODULUS>]
                      let output := mload(0x40)
                      let args := add(output, 0x20)
                      mstore(args, 0x20)
                      mstore(add(args, 0x20), 0x20)
                      mstore(add(args, 0x40), 0x20)
                      mstore(add(args, 0x60), base)
                      mstore(add(args, 0x80), exponent)
                      mstore(add(args, 0xa0), p)
                      // 0x05 is the modular exponent contract address
                      if iszero(staticcall(not(0), 0x05, args, 0xc0, output, 0x20)) {
                          revert(0, 0)
                      }
                      o := mload(output)
                  }
              }
              /**
               * @dev Calculates and returns the square root of a mod p if such a square
               * root exists. The modulus p must be an odd prime. If a square root does
               * not exist, function returns 0.
               */
              function modSqrt(uint256 a, uint256 p) internal view returns (uint256) {
                  if (legendre(a, p) != 1) {
                      return 0;
                  }
                  if (a == 0) {
                      return 0;
                  }
                  if (p % 4 == 3) {
                      return modExp(a, (p + 1) / 4, p);
                  }
                  uint256 s = p - 1;
                  uint256 e = 0;
                  while (s % 2 == 0) {
                      s = s / 2;
                      e = e + 1;
                  }
                  // Note the smaller int- finding n with Legendre symbol or -1
                  // should be quick
                  uint256 n = 2;
                  while (legendre(n, p) != -1) {
                      n = n + 1;
                  }
                  uint256 x = modExp(a, (s + 1) / 2, p);
                  uint256 b = modExp(a, s, p);
                  uint256 g = modExp(n, s, p);
                  uint256 r = e;
                  uint256 gs = 0;
                  uint256 m = 0;
                  uint256 t = b;
                  while (true) {
                      t = b;
                      m = 0;
                      for (m = 0; m < r; m++) {
                          if (t == 1) {
                              break;
                          }
                          t = modExp(t, 2, p);
                      }
                      if (m == 0) {
                          return x;
                      }
                      gs = modExp(g, uint256(2)**(r - m - 1), p);
                      g = (gs * gs) % p;
                      x = (x * gs) % p;
                      b = (b * g) % p;
                      r = m;
                  }
                  revert("modSqrt: unreachable end point");
              }
              /**
               * @dev Calculates the Legendre symbol of the given a mod p.
               * @return Returns 1 if a is a quadratic residue mod p, -1 if it is
               * a non-quadratic residue, and 0 if a is 0.
               */
              function legendre(uint256 a, uint256 p) internal view returns (int256) {
                  uint256 raised = modExp(a, (p - 1) / uint256(2), p);
                  if (raised == 0 || raised == 1) {
                      return int256(raised);
                  } else if (raised == p - 1) {
                      return -1;
                  }
                  revert("Failed to calculate legendre.");
              }
          }
          // SPDX-License-Identifier: UNLICENSED
          // Copyright (c) Eywa.Fi, 2021-2023 - all rights reserved
          pragma solidity 0.8.17;
          contract RequestIdChecker {
              
              ///
              mapping(bytes32 => bool) public checks;
              /// 
              address public owner;
              modifier onlyOwner() {
                  require(msg.sender == owner, "RequestIdChecker: caller is not the owner");
                  _;
              }
              constructor() {
                  owner = msg.sender;
              }
              function check(bytes32 id) public onlyOwner returns (bool) {
                  if (checks[id] == false) {
                      checks[id] = true;
                      return true;
                  }
                  return false;
              }
              function destroy() public onlyOwner {
                  selfdestruct(payable(owner));
              }
          }
          // SPDX-License-Identifier: UNLICENSED
          // Copyright (c) Eywa.Fi, 2021-2023 - all rights reserved
          pragma solidity 0.8.17;
          abstract contract Typecast {
              function castToAddress(bytes32 x) public pure returns (address) {
                  return address(uint160(uint256(x)));
              }
              function castToBytes32(address a) public pure returns (bytes32) {
                  return bytes32(uint256(uint160(a)));
              }
          }
          // SPDX-License-Identifier: MIT
          pragma solidity 0.8.17;
          import "solidity-bytes-utils/contracts/BytesLib.sol";
          library Utils {
              /* @notice      Convert the bytes array to bytes32 type, the bytes array length must be 32
               *  @param _bs   Source bytes array
               *  @return      bytes32
               */
              function bytesToBytes32(bytes memory _bs) internal pure returns (bytes32 value) {
                  require(_bs.length == 32, "bytes length is not 32.");
                  assembly {
                      // load 32 bytes from memory starting from position _bs + 0x20 since the first 0x20 bytes stores _bs length
                      value := mload(add(_bs, 0x20))
                  }
              }
              /* @notice      Convert bytes to uint256
               *  @param _b    Source bytes should have length of 32
               *  @return      uint256
               */
              function bytesToUint256(bytes memory _bs) internal pure returns (uint256 value) {
                  require(_bs.length == 32, "bytes length is not 32.");
                  assembly {
                      // load 32 bytes from memory starting from position _bs + 32
                      value := mload(add(_bs, 0x20))
                  }
                  require(value <= 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, "Value exceeds the range");
              }
              /* @notice      Convert uint256 to bytes
               *  @param _b    uint256 that needs to be converted
               *  @return      bytes
               */
              function uint256ToBytes(uint256 _value) internal pure returns (bytes memory bs) {
                  require(
                      _value <= 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff,
                      "Value exceeds the range"
                  );
                  assembly {
                      // Get a location of some free memory and store it in result as
                      // Solidity does for memory variables.
                      bs := mload(0x40)
                      // Put 0x20 at the first word, the length of bytes for uint256 value
                      mstore(bs, 0x20)
                      //In the next word, put value in bytes format to the next 32 bytes
                      mstore(add(bs, 0x20), _value)
                      // Update the free-memory pointer by padding our last write location to 32 bytes
                      mstore(0x40, add(bs, 0x40))
                  }
              }
              /* @notice      Convert bytes to address
               *  @param _bs   Source bytes: bytes length must be 20
               *  @return      Converted address from source bytes
               */
              function bytesToAddress(bytes memory _bs) internal pure returns (address addr) {
                  require(_bs.length == 20, "bytes length does not match address");
                  assembly {
                      // for _bs, first word store _bs.length, second word store _bs.value
                      // load 32 bytes from mem[_bs+20], convert it into Uint160, meaning we take last 20 bytes as addr (address).
                      addr := mload(add(_bs, 0x14))
                  }
              }
              /* @notice      Convert address to bytes
               *  @param _addr Address need to be converted
               *  @return      Converted bytes from address
               */
              function addressToBytes(address _addr) internal pure returns (bytes memory bs) {
                  assembly {
                      // Get a location of some free memory and store it in result as
                      // Solidity does for memory variables.
                      bs := mload(0x40)
                      // Put 20 (address byte length) at the first word, the length of bytes for uint256 value
                      mstore(bs, 0x14)
                      // logical shift left _a by 12 bytes, change _a from right-aligned to left-aligned
                      mstore(add(bs, 0x20), shl(96, _addr))
                      // Update the free-memory pointer by padding our last write location to 32 bytes
                      mstore(0x40, add(bs, 0x40))
                  }
              }
              /* @notice              Compare if two bytes are equal, which are in storage and memory, seperately
                                      Refer from https://github.com/summa-tx/bitcoin-spv/blob/master/solidity/contracts/BytesLib.sol#L368
              *  @param _preBytes     The bytes stored in storage
              *  @param _postBytes    The bytes stored in memory
              *  @return              Bool type indicating if they are equal
              */
              function equalStorage(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) {
                  bool success = true;
                  assembly {
                      // we know _preBytes_offset is 0
                      let fslot := sload(_preBytes.slot)
                      // Arrays of 31 bytes or less have an even value in their slot,
                      // while longer arrays have an odd value. The actual length is
                      // the slot divided by two for odd values, and the lowest order
                      // byte divided by two for even values.
                      // If the slot is even, bitwise and the slot with 255 and divide by
                      // two to get the length. If the slot is odd, bitwise and the slot
                      // with -1 and divide by two.
                      let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
                      let mlength := mload(_postBytes)
                      // if lengths don't match the arrays are not equal
                      switch eq(slength, mlength)
                      case 1 {
                          // fslot can contain both the length and contents of the array
                          // if slength < 32 bytes so let's prepare for that
                          // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
                          // slength != 0
                          if iszero(iszero(slength)) {
                              switch lt(slength, 32)
                              case 1 {
                                  // blank the last byte which is the length
                                  fslot := mul(div(fslot, 0x100), 0x100)
                                  if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
                                      // unsuccess:
                                      success := 0
                                  }
                              }
                              default {
                                  // cb is a circuit breaker in the for loop since there's
                                  //  no said feature for inline assembly loops
                                  // cb = 1 - don't breaker
                                  // cb = 0 - break
                                  let cb := 1
                                  // get the keccak hash to get the contents of the array
                                  mstore(0x0, _preBytes.slot)
                                  let sc := keccak256(0x0, 0x20)
                                  let mc := add(_postBytes, 0x20)
                                  let end := add(mc, mlength)
                                  // the next line is the loop condition:
                                  // while(uint(mc < end) + cb == 2)
                                  for {
                                  } eq(add(lt(mc, end), cb), 2) {
                                      sc := add(sc, 1)
                                      mc := add(mc, 0x20)
                                  } {
                                      if iszero(eq(sload(sc), mload(mc))) {
                                          // unsuccess:
                                          success := 0
                                          cb := 0
                                      }
                                  }
                              }
                          }
                      }
                      default {
                          // unsuccess:
                          success := 0
                      }
                  }
                  return success;
              }
              /* @notice              Slice the _bytes from _start index till the result has length of _length
                                      Refer from https://github.com/summa-tx/bitcoin-spv/blob/master/solidity/contracts/BytesLib.sol#L246
              *  @param _bytes        The original bytes needs to be sliced
              *  @param _start        The index of _bytes for the start of sliced bytes
              *  @param _length       The index of _bytes for the end of sliced bytes
              *  @return              The sliced bytes
              */
              function slice(
                  bytes memory _bytes,
                  uint256 _start,
                  uint256 _length
              ) internal pure returns (bytes memory) {
                  require(_bytes.length >= (_start + _length));
                  bytes memory tempBytes;
                  assembly {
                      switch iszero(_length)
                      case 0 {
                          // Get a location of some free memory and store it in tempBytes as
                          // Solidity does for memory variables.
                          tempBytes := mload(0x40)
                          // The first word of the slice result is potentially a partial
                          // word read from the original array. To read it, we calculate
                          // the length of that partial word and start copying that many
                          // bytes into the array. The first word we copy will start with
                          // data we don't care about, but the last `lengthmod` bytes will
                          // land at the beginning of the contents of the new array. When
                          // we're done copying, we overwrite the full first word with
                          // the actual length of the slice.
                          // lengthmod <= _length % 32
                          let lengthmod := and(_length, 31)
                          // The multiplication in the next line is necessary
                          // because when slicing multiples of 32 bytes (lengthmod == 0)
                          // the following copy loop was copying the origin's length
                          // and then ending prematurely not copying everything it should.
                          let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
                          let end := add(mc, _length)
                          for {
                              // The multiplication in the next line has the same exact purpose
                              // as the one above.
                              let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
                          } lt(mc, end) {
                              mc := add(mc, 0x20)
                              cc := add(cc, 0x20)
                          } {
                              mstore(mc, mload(cc))
                          }
                          mstore(tempBytes, _length)
                          //update free-memory pointer
                          //allocating the array padded to 32 bytes like the compiler does now
                          mstore(0x40, and(add(mc, 31), not(31)))
                      }
                      //if we want a zero-length slice let's just return a zero-length array
                      default {
                          tempBytes := mload(0x40)
                          mstore(0x40, add(tempBytes, 0x20))
                      }
                  }
                  return tempBytes;
              }
              /* @notice              Check if the elements number of _signers within _keepers array is no less than _m
               *  @param _keepers      The array consists of serveral address
               *  @param _signers      Some specific addresses to be looked into
               *  @param _m            The number requirement paramter
               *  @return              True means containment, false meansdo do not contain.
               */
              function containMAddresses(
                  address[] memory _keepers,
                  address[] memory _signers,
                  uint256 _m
              ) internal pure returns (bool) {
                  uint256 m = 0;
                  for (uint256 i = 0; i < _signers.length; i++) {
                      for (uint256 j = 0; j < _keepers.length; j++) {
                          if (_signers[i] == _keepers[j]) {
                              m++;
                              delete _keepers[j];
                          }
                      }
                  }
                  return m >= _m;
              }
              /* @notice              TODO
               *  @param key
               *  @return
               */
              function compressMCPubKey(bytes memory key) internal pure returns (bytes memory newkey) {
                  require(key.length >= 67, "key lenggh is too short");
                  newkey = slice(key, 0, 35);
                  if (uint8(key[66]) % 2 == 0) {
                      newkey[2] = 0x02;
                  } else {
                      newkey[2] = 0x03;
                  }
                  return newkey;
              }
              /**
               * @dev Returns true if `account` is a contract.
               *      Refer from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Address.sol#L18
               *
               * This test is non-exhaustive, and there may be false-negatives: during the
               * execution of a contract's constructor, its address will be reported as
               * not containing 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.
               */
              function isContract(address account) internal view returns (bool) {
                  // This method relies in extcodesize, which returns 0 for contracts in
                  // construction, since the code is only stored at the end of the
                  // constructor execution.
                  // According to EIP-1052, 0x0 is the value returned for not-yet created accounts
                  // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
                  // for accounts without code, i.e. `keccak256('')`
                  bytes32 codehash;
                  bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
                  // solhint-disable-next-line no-inline-assembly
                  assembly {
                      codehash := extcodehash(account)
                  }
                  return (codehash != 0x0 && codehash != accountHash);
              }
              /**
               * @dev Extracts error from the returned data of inter-contract call
               */
              function extractErrorMessage(bytes memory data) internal pure returns (string memory) {
                  if (data.length < 68) return "unknown error";
                  bytes memory revertData = BytesLib.slice(data, 4, data.length - 4);
                  return abi.decode(revertData, (string));
              }
          }
          // SPDX-License-Identifier: MIT
          pragma solidity 0.8.17;
          /**
           * @dev Wrappers over decoding and deserialization operation from bytes into bassic types in Solidity for PolyNetwork cross chain utility.
           *
           * Decode into basic types in Solidity from bytes easily. It's designed to be used
           * for PolyNetwork cross chain application, and the decoding rules on Ethereum chain
           * and the encoding rule on other chains should be consistent, and . Here we
           * follow the underlying deserialization rule with implementation found here:
           * https://github.com/polynetwork/poly/blob/master/common/zero_copy_source.go
           *
           * Using this library instead of the unchecked serialization method can help reduce
           * the risk of serious bugs and handfule, so it's recommended to use it.
           *
           * Please note that risk can be minimized, yet not eliminated.
           */
          library ZeroCopySource {
              /* @notice              Read next byte as boolean type starting at offset from buff
               *  @param buff          Source bytes array
               *  @param offset        The position from where we read the boolean value
               *  @return              The the read boolean value and new offset
               */
              function NextBool(bytes memory buff, uint256 offset) internal pure returns (bool, uint256) {
                  require(offset + 1 <= buff.length && offset < offset + 1, "Offset exceeds limit");
                  // byte === bytes1
                  uint8 v;
                  assembly {
                      v := mload(add(add(buff, 0x20), offset))
                  }
                  bool value;
                  if (v == 0x01) {
                      value = true;
                  } else if (v == 0x00) {
                      value = false;
                  } else {
                      revert("NextBool value error");
                  }
                  return (value, offset + 1);
              }
              /* @notice              Read next byte as uint8 starting at offset from buff
               *  @param buff          Source bytes array
               *  @param offset        The position from where we read the byte value
               *  @return              The read uint8 value and new offset
               */
              function NextUint8(bytes memory buff, uint256 offset) internal pure returns (uint8, uint256) {
                  require(offset + 1 <= buff.length && offset < offset + 1, "NextUint8, Offset exceeds maximum");
                  uint8 v;
                  assembly {
                      let tmpbytes := mload(0x40)
                      let bvalue := mload(add(add(buff, 0x20), offset))
                      mstore8(tmpbytes, byte(0, bvalue))
                      mstore(0x40, add(tmpbytes, 0x01))
                      v := mload(sub(tmpbytes, 0x1f))
                  }
                  return (v, offset + 1);
              }
              /* @notice              Read next two bytes as uint16 type starting from offset
               *  @param buff          Source bytes array
               *  @param offset        The position from where we read the uint16 value
               *  @return              The read uint16 value and updated offset
               */
              function NextUint16(bytes memory buff, uint256 offset) internal pure returns (uint16, uint256) {
                  require(offset + 2 <= buff.length && offset < offset + 2, "NextUint16, offset exceeds maximum");
                  uint16 v;
                  assembly {
                      let tmpbytes := mload(0x40)
                      let bvalue := mload(add(add(buff, 0x20), offset))
                      mstore8(tmpbytes, byte(0x01, bvalue))
                      mstore8(add(tmpbytes, 0x01), byte(0, bvalue))
                      mstore(0x40, add(tmpbytes, 0x02))
                      v := mload(sub(tmpbytes, 0x1e))
                  }
                  return (v, offset + 2);
              }
              /* @notice              Read next four bytes as uint32 type starting from offset
               *  @param buff          Source bytes array
               *  @param offset        The position from where we read the uint32 value
               *  @return              The read uint32 value and updated offset
               */
              function NextUint32(bytes memory buff, uint256 offset) internal pure returns (uint32, uint256) {
                  require(offset + 4 <= buff.length && offset < offset + 4, "NextUint32, offset exceeds maximum");
                  uint32 v;
                  assembly {
                      let tmpbytes := mload(0x40)
                      let byteLen := 0x04
                      for {
                          let tindex := 0x00
                          let bindex := sub(byteLen, 0x01)
                          let bvalue := mload(add(add(buff, 0x20), offset))
                      } lt(tindex, byteLen) {
                          tindex := add(tindex, 0x01)
                          bindex := sub(bindex, 0x01)
                      } {
                          mstore8(add(tmpbytes, tindex), byte(bindex, bvalue))
                      }
                      mstore(0x40, add(tmpbytes, byteLen))
                      v := mload(sub(tmpbytes, sub(0x20, byteLen)))
                  }
                  return (v, offset + 4);
              }
              /* @notice              Read next eight bytes as uint64 type starting from offset
               *  @param buff          Source bytes array
               *  @param offset        The position from where we read the uint64 value
               *  @return              The read uint64 value and updated offset
               */
              function NextUint64(bytes memory buff, uint256 offset) internal pure returns (uint64, uint256) {
                  require(offset + 8 <= buff.length && offset < offset + 8, "NextUint64, offset exceeds maximum");
                  uint64 v;
                  assembly {
                      let tmpbytes := mload(0x40)
                      let byteLen := 0x08
                      for {
                          let tindex := 0x00
                          let bindex := sub(byteLen, 0x01)
                          let bvalue := mload(add(add(buff, 0x20), offset))
                      } lt(tindex, byteLen) {
                          tindex := add(tindex, 0x01)
                          bindex := sub(bindex, 0x01)
                      } {
                          mstore8(add(tmpbytes, tindex), byte(bindex, bvalue))
                      }
                      mstore(0x40, add(tmpbytes, byteLen))
                      v := mload(sub(tmpbytes, sub(0x20, byteLen)))
                  }
                  return (v, offset + 8);
              }
              /* @notice              Read next 32 bytes as uint256 type starting from offset,
                                      there are limits considering the numerical limits in multi-chain
              *  @param buff          Source bytes array
              *  @param offset        The position from where we read the uint256 value
              *  @return              The read uint256 value and updated offset
              */
              function NextUint255(bytes memory buff, uint256 offset) internal pure returns (uint256, uint256) {
                  require(offset + 32 <= buff.length && offset < offset + 32, "NextUint255, offset exceeds maximum");
                  uint256 v;
                  assembly {
                      let tmpbytes := mload(0x40)
                      let byteLen := 0x20
                      for {
                          let tindex := 0x00
                          let bindex := sub(byteLen, 0x01)
                          let bvalue := mload(add(add(buff, 0x20), offset))
                      } lt(tindex, byteLen) {
                          tindex := add(tindex, 0x01)
                          bindex := sub(bindex, 0x01)
                      } {
                          mstore8(add(tmpbytes, tindex), byte(bindex, bvalue))
                      }
                      mstore(0x40, add(tmpbytes, byteLen))
                      v := mload(tmpbytes)
                  }
                  require(v <= 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, "Value exceeds the range");
                  return (v, offset + 32);
              }
              /* @notice              Read next variable bytes starting from offset,
                                      the decoding rule coming from multi-chain
              *  @param buff          Source bytes array
              *  @param offset        The position from where we read the bytes value
              *  @return              The read variable bytes array value and updated offset
              */
              function NextVarBytes(bytes memory buff, uint256 offset) internal pure returns (bytes memory, uint256) {
                  uint256 len;
                  (len, offset) = NextVarUint(buff, offset);
                  require(offset + len <= buff.length && offset < offset + len, "NextVarBytes, offset exceeds maximum");
                  bytes memory tempBytes;
                  assembly {
                      switch iszero(len)
                      case 0 {
                          // Get a location of some free memory and store it in tempBytes as
                          // Solidity does for memory variables.
                          tempBytes := mload(0x40)
                          // The first word of the slice result is potentially a partial
                          // word read from the original array. To read it, we calculate
                          // the length of that partial word and start copying that many
                          // bytes into the array. The first word we copy will start with
                          // data we don't care about, but the last `lengthmod` bytes will
                          // land at the beginning of the contents of the new array. When
                          // we're done copying, we overwrite the full first word with
                          // the actual length of the slice.
                          let lengthmod := and(len, 31)
                          // The multiplication in the next line is necessary
                          // because when slicing multiples of 32 bytes (lengthmod == 0)
                          // the following copy loop was copying the origin's length
                          // and then ending prematurely not copying everything it should.
                          let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
                          let end := add(mc, len)
                          for {
                              // The multiplication in the next line has the same exact purpose
                              // as the one above.
                              let cc := add(add(add(buff, lengthmod), mul(0x20, iszero(lengthmod))), offset)
                          } lt(mc, end) {
                              mc := add(mc, 0x20)
                              cc := add(cc, 0x20)
                          } {
                              mstore(mc, mload(cc))
                          }
                          mstore(tempBytes, len)
                          //update free-memory pointer
                          //allocating the array padded to 32 bytes like the compiler does now
                          mstore(0x40, and(add(mc, 31), not(31)))
                      }
                      //if we want a zero-length slice let's just return a zero-length array
                      default {
                          tempBytes := mload(0x40)
                          mstore(0x40, add(tempBytes, 0x20))
                      }
                  }
                  return (tempBytes, offset + len);
              }
              /* @notice              Read next 32 bytes starting from offset,
               *  @param buff          Source bytes array
               *  @param offset        The position from where we read the bytes value
               *  @return              The read bytes32 value and updated offset
               */
              function NextHash(bytes memory buff, uint256 offset) internal pure returns (bytes32, uint256) {
                  require(offset + 32 <= buff.length && offset < offset + 32, "NextHash, offset exceeds maximum");
                  bytes32 v;
                  assembly {
                      v := mload(add(buff, add(offset, 0x20)))
                  }
                  return (v, offset + 32);
              }
              /* @notice              Read next 20 bytes starting from offset,
               *  @param buff          Source bytes array
               *  @param offset        The position from where we read the bytes value
               *  @return              The read bytes20 value and updated offset
               */
              function NextAddress(bytes memory buff, uint256 offset) internal pure returns (address, uint256) {
                  require(offset + 20 <= buff.length && offset < offset + 20, "NextAddress, offset exceeds maximum");
                  bytes20 v;
                  assembly {
                      v := mload(add(buff, add(offset, 0x20)))
                  }
                  return (address(v), offset + 20);
              }
              function NextVarUint(bytes memory buff, uint256 offset) internal pure returns (uint256, uint256) {
                  uint8 v;
                  (v, offset) = NextUint8(buff, offset);
                  uint256 value;
                  if (v == 0xFD) {
                      // return NextUint16(buff, offset);
                      (value, offset) = NextUint16(buff, offset);
                      require(value >= 0xFD && value <= 0xFFFF, "NextUint16, value outside range");
                      return (value, offset);
                  } else if (v == 0xFE) {
                      // return NextUint32(buff, offset);
                      (value, offset) = NextUint32(buff, offset);
                      require(value > 0xFFFF && value <= 0xFFFFFFFF, "NextVarUint, value outside range");
                      return (value, offset);
                  } else if (v == 0xFF) {
                      // return NextUint64(buff, offset);
                      (value, offset) = NextUint64(buff, offset);
                      require(value > 0xFFFFFFFF, "NextVarUint, value outside range");
                      return (value, offset);
                  } else {
                      // return (uint8(v), offset);
                      value = uint8(v);
                      require(value < 0xFD, "NextVarUint, value outside range");
                      return (value, offset);
                  }
              }
          }
          // SPDX-License-Identifier: Unlicense
          /*
           * @title Solidity Bytes Arrays Utils
           * @author Gonçalo Sá <[email protected]>
           *
           * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
           *      The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
           */
          pragma solidity >=0.8.0 <0.9.0;
          library BytesLib {
              function concat(
                  bytes memory _preBytes,
                  bytes memory _postBytes
              )
                  internal
                  pure
                  returns (bytes memory)
              {
                  bytes memory tempBytes;
                  assembly {
                      // Get a location of some free memory and store it in tempBytes as
                      // Solidity does for memory variables.
                      tempBytes := mload(0x40)
                      // Store the length of the first bytes array at the beginning of
                      // the memory for tempBytes.
                      let length := mload(_preBytes)
                      mstore(tempBytes, length)
                      // Maintain a memory counter for the current write location in the
                      // temp bytes array by adding the 32 bytes for the array length to
                      // the starting location.
                      let mc := add(tempBytes, 0x20)
                      // Stop copying when the memory counter reaches the length of the
                      // first bytes array.
                      let end := add(mc, length)
                      for {
                          // Initialize a copy counter to the start of the _preBytes data,
                          // 32 bytes into its memory.
                          let cc := add(_preBytes, 0x20)
                      } lt(mc, end) {
                          // Increase both counters by 32 bytes each iteration.
                          mc := add(mc, 0x20)
                          cc := add(cc, 0x20)
                      } {
                          // Write the _preBytes data into the tempBytes memory 32 bytes
                          // at a time.
                          mstore(mc, mload(cc))
                      }
                      // Add the length of _postBytes to the current length of tempBytes
                      // and store it as the new length in the first 32 bytes of the
                      // tempBytes memory.
                      length := mload(_postBytes)
                      mstore(tempBytes, add(length, mload(tempBytes)))
                      // Move the memory counter back from a multiple of 0x20 to the
                      // actual end of the _preBytes data.
                      mc := end
                      // Stop copying when the memory counter reaches the new combined
                      // length of the arrays.
                      end := add(mc, length)
                      for {
                          let cc := add(_postBytes, 0x20)
                      } lt(mc, end) {
                          mc := add(mc, 0x20)
                          cc := add(cc, 0x20)
                      } {
                          mstore(mc, mload(cc))
                      }
                      // Update the free-memory pointer by padding our last write location
                      // to 32 bytes: add 31 bytes to the end of tempBytes to move to the
                      // next 32 byte block, then round down to the nearest multiple of
                      // 32. If the sum of the length of the two arrays is zero then add
                      // one before rounding down to leave a blank 32 bytes (the length block with 0).
                      mstore(0x40, and(
                        add(add(end, iszero(add(length, mload(_preBytes)))), 31),
                        not(31) // Round down to the nearest 32 bytes.
                      ))
                  }
                  return tempBytes;
              }
              function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal {
                  assembly {
                      // Read the first 32 bytes of _preBytes storage, which is the length
                      // of the array. (We don't need to use the offset into the slot
                      // because arrays use the entire slot.)
                      let fslot := sload(_preBytes.slot)
                      // Arrays of 31 bytes or less have an even value in their slot,
                      // while longer arrays have an odd value. The actual length is
                      // the slot divided by two for odd values, and the lowest order
                      // byte divided by two for even values.
                      // If the slot is even, bitwise and the slot with 255 and divide by
                      // two to get the length. If the slot is odd, bitwise and the slot
                      // with -1 and divide by two.
                      let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
                      let mlength := mload(_postBytes)
                      let newlength := add(slength, mlength)
                      // slength can contain both the length and contents of the array
                      // if length < 32 bytes so let's prepare for that
                      // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
                      switch add(lt(slength, 32), lt(newlength, 32))
                      case 2 {
                          // Since the new array still fits in the slot, we just need to
                          // update the contents of the slot.
                          // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length
                          sstore(
                              _preBytes.slot,
                              // all the modifications to the slot are inside this
                              // next block
                              add(
                                  // we can just add to the slot contents because the
                                  // bytes we want to change are the LSBs
                                  fslot,
                                  add(
                                      mul(
                                          div(
                                              // load the bytes from memory
                                              mload(add(_postBytes, 0x20)),
                                              // zero all bytes to the right
                                              exp(0x100, sub(32, mlength))
                                          ),
                                          // and now shift left the number of bytes to
                                          // leave space for the length in the slot
                                          exp(0x100, sub(32, newlength))
                                      ),
                                      // increase length by the double of the memory
                                      // bytes length
                                      mul(mlength, 2)
                                  )
                              )
                          )
                      }
                      case 1 {
                          // The stored value fits in the slot, but the combined value
                          // will exceed it.
                          // get the keccak hash to get the contents of the array
                          mstore(0x0, _preBytes.slot)
                          let sc := add(keccak256(0x0, 0x20), div(slength, 32))
                          // save new length
                          sstore(_preBytes.slot, add(mul(newlength, 2), 1))
                          // The contents of the _postBytes array start 32 bytes into
                          // the structure. Our first read should obtain the `submod`
                          // bytes that can fit into the unused space in the last word
                          // of the stored array. To get this, we read 32 bytes starting
                          // from `submod`, so the data we read overlaps with the array
                          // contents by `submod` bytes. Masking the lowest-order
                          // `submod` bytes allows us to add that value directly to the
                          // stored value.
                          let submod := sub(32, slength)
                          let mc := add(_postBytes, submod)
                          let end := add(_postBytes, mlength)
                          let mask := sub(exp(0x100, submod), 1)
                          sstore(
                              sc,
                              add(
                                  and(
                                      fslot,
                                      0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
                                  ),
                                  and(mload(mc), mask)
                              )
                          )
                          for {
                              mc := add(mc, 0x20)
                              sc := add(sc, 1)
                          } lt(mc, end) {
                              sc := add(sc, 1)
                              mc := add(mc, 0x20)
                          } {
                              sstore(sc, mload(mc))
                          }
                          mask := exp(0x100, sub(mc, end))
                          sstore(sc, mul(div(mload(mc), mask), mask))
                      }
                      default {
                          // get the keccak hash to get the contents of the array
                          mstore(0x0, _preBytes.slot)
                          // Start copying to the last used word of the stored array.
                          let sc := add(keccak256(0x0, 0x20), div(slength, 32))
                          // save new length
                          sstore(_preBytes.slot, add(mul(newlength, 2), 1))
                          // Copy over the first `submod` bytes of the new data as in
                          // case 1 above.
                          let slengthmod := mod(slength, 32)
                          let mlengthmod := mod(mlength, 32)
                          let submod := sub(32, slengthmod)
                          let mc := add(_postBytes, submod)
                          let end := add(_postBytes, mlength)
                          let mask := sub(exp(0x100, submod), 1)
                          sstore(sc, add(sload(sc), and(mload(mc), mask)))
                          for {
                              sc := add(sc, 1)
                              mc := add(mc, 0x20)
                          } lt(mc, end) {
                              sc := add(sc, 1)
                              mc := add(mc, 0x20)
                          } {
                              sstore(sc, mload(mc))
                          }
                          mask := exp(0x100, sub(mc, end))
                          sstore(sc, mul(div(mload(mc), mask), mask))
                      }
                  }
              }
              function slice(
                  bytes memory _bytes,
                  uint256 _start,
                  uint256 _length
              )
                  internal
                  pure
                  returns (bytes memory)
              {
                  require(_length + 31 >= _length, "slice_overflow");
                  require(_bytes.length >= _start + _length, "slice_outOfBounds");
                  bytes memory tempBytes;
                  assembly {
                      switch iszero(_length)
                      case 0 {
                          // Get a location of some free memory and store it in tempBytes as
                          // Solidity does for memory variables.
                          tempBytes := mload(0x40)
                          // The first word of the slice result is potentially a partial
                          // word read from the original array. To read it, we calculate
                          // the length of that partial word and start copying that many
                          // bytes into the array. The first word we copy will start with
                          // data we don't care about, but the last `lengthmod` bytes will
                          // land at the beginning of the contents of the new array. When
                          // we're done copying, we overwrite the full first word with
                          // the actual length of the slice.
                          let lengthmod := and(_length, 31)
                          // The multiplication in the next line is necessary
                          // because when slicing multiples of 32 bytes (lengthmod == 0)
                          // the following copy loop was copying the origin's length
                          // and then ending prematurely not copying everything it should.
                          let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
                          let end := add(mc, _length)
                          for {
                              // The multiplication in the next line has the same exact purpose
                              // as the one above.
                              let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
                          } lt(mc, end) {
                              mc := add(mc, 0x20)
                              cc := add(cc, 0x20)
                          } {
                              mstore(mc, mload(cc))
                          }
                          mstore(tempBytes, _length)
                          //update free-memory pointer
                          //allocating the array padded to 32 bytes like the compiler does now
                          mstore(0x40, and(add(mc, 31), not(31)))
                      }
                      //if we want a zero-length slice let's just return a zero-length array
                      default {
                          tempBytes := mload(0x40)
                          //zero out the 32 bytes slice we are about to return
                          //we need to do it because Solidity does not garbage collect
                          mstore(tempBytes, 0)
                          mstore(0x40, add(tempBytes, 0x20))
                      }
                  }
                  return tempBytes;
              }
              function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
                  require(_bytes.length >= _start + 20, "toAddress_outOfBounds");
                  address tempAddress;
                  assembly {
                      tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
                  }
                  return tempAddress;
              }
              function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) {
                  require(_bytes.length >= _start + 1 , "toUint8_outOfBounds");
                  uint8 tempUint;
                  assembly {
                      tempUint := mload(add(add(_bytes, 0x1), _start))
                  }
                  return tempUint;
              }
              function toUint16(bytes memory _bytes, uint256 _start) internal pure returns (uint16) {
                  require(_bytes.length >= _start + 2, "toUint16_outOfBounds");
                  uint16 tempUint;
                  assembly {
                      tempUint := mload(add(add(_bytes, 0x2), _start))
                  }
                  return tempUint;
              }
              function toUint32(bytes memory _bytes, uint256 _start) internal pure returns (uint32) {
                  require(_bytes.length >= _start + 4, "toUint32_outOfBounds");
                  uint32 tempUint;
                  assembly {
                      tempUint := mload(add(add(_bytes, 0x4), _start))
                  }
                  return tempUint;
              }
              function toUint64(bytes memory _bytes, uint256 _start) internal pure returns (uint64) {
                  require(_bytes.length >= _start + 8, "toUint64_outOfBounds");
                  uint64 tempUint;
                  assembly {
                      tempUint := mload(add(add(_bytes, 0x8), _start))
                  }
                  return tempUint;
              }
              function toUint96(bytes memory _bytes, uint256 _start) internal pure returns (uint96) {
                  require(_bytes.length >= _start + 12, "toUint96_outOfBounds");
                  uint96 tempUint;
                  assembly {
                      tempUint := mload(add(add(_bytes, 0xc), _start))
                  }
                  return tempUint;
              }
              function toUint128(bytes memory _bytes, uint256 _start) internal pure returns (uint128) {
                  require(_bytes.length >= _start + 16, "toUint128_outOfBounds");
                  uint128 tempUint;
                  assembly {
                      tempUint := mload(add(add(_bytes, 0x10), _start))
                  }
                  return tempUint;
              }
              function toUint256(bytes memory _bytes, uint256 _start) internal pure returns (uint256) {
                  require(_bytes.length >= _start + 32, "toUint256_outOfBounds");
                  uint256 tempUint;
                  assembly {
                      tempUint := mload(add(add(_bytes, 0x20), _start))
                  }
                  return tempUint;
              }
              function toBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32) {
                  require(_bytes.length >= _start + 32, "toBytes32_outOfBounds");
                  bytes32 tempBytes32;
                  assembly {
                      tempBytes32 := mload(add(add(_bytes, 0x20), _start))
                  }
                  return tempBytes32;
              }
              function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) {
                  bool success = true;
                  assembly {
                      let length := mload(_preBytes)
                      // if lengths don't match the arrays are not equal
                      switch eq(length, mload(_postBytes))
                      case 1 {
                          // cb is a circuit breaker in the for loop since there's
                          //  no said feature for inline assembly loops
                          // cb = 1 - don't breaker
                          // cb = 0 - break
                          let cb := 1
                          let mc := add(_preBytes, 0x20)
                          let end := add(mc, length)
                          for {
                              let cc := add(_postBytes, 0x20)
                          // the next line is the loop condition:
                          // while(uint256(mc < end) + cb == 2)
                          } eq(add(lt(mc, end), cb), 2) {
                              mc := add(mc, 0x20)
                              cc := add(cc, 0x20)
                          } {
                              // if any of these checks fails then arrays are not equal
                              if iszero(eq(mload(mc), mload(cc))) {
                                  // unsuccess:
                                  success := 0
                                  cb := 0
                              }
                          }
                      }
                      default {
                          // unsuccess:
                          success := 0
                      }
                  }
                  return success;
              }
              function equalStorage(
                  bytes storage _preBytes,
                  bytes memory _postBytes
              )
                  internal
                  view
                  returns (bool)
              {
                  bool success = true;
                  assembly {
                      // we know _preBytes_offset is 0
                      let fslot := sload(_preBytes.slot)
                      // Decode the length of the stored array like in concatStorage().
                      let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
                      let mlength := mload(_postBytes)
                      // if lengths don't match the arrays are not equal
                      switch eq(slength, mlength)
                      case 1 {
                          // slength can contain both the length and contents of the array
                          // if length < 32 bytes so let's prepare for that
                          // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
                          if iszero(iszero(slength)) {
                              switch lt(slength, 32)
                              case 1 {
                                  // blank the last byte which is the length
                                  fslot := mul(div(fslot, 0x100), 0x100)
                                  if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
                                      // unsuccess:
                                      success := 0
                                  }
                              }
                              default {
                                  // cb is a circuit breaker in the for loop since there's
                                  //  no said feature for inline assembly loops
                                  // cb = 1 - don't breaker
                                  // cb = 0 - break
                                  let cb := 1
                                  // get the keccak hash to get the contents of the array
                                  mstore(0x0, _preBytes.slot)
                                  let sc := keccak256(0x0, 0x20)
                                  let mc := add(_postBytes, 0x20)
                                  let end := add(mc, mlength)
                                  // the next line is the loop condition:
                                  // while(uint256(mc < end) + cb == 2)
                                  for {} eq(add(lt(mc, end), cb), 2) {
                                      sc := add(sc, 1)
                                      mc := add(mc, 0x20)
                                  } {
                                      if iszero(eq(sload(sc), mload(mc))) {
                                          // unsuccess:
                                          success := 0
                                          cb := 0
                                      }
                                  }
                              }
                          }
                      }
                      default {
                          // unsuccess:
                          success := 0
                      }
                  }
                  return success;
              }
          }
          

          File 6 of 8: AddressBook
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (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 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. Can only be called by the current owner.
               *
               * NOTE: Renouncing ownership will leave the contract without an owner,
               * thereby disabling any functionality that is only available to the owner.
               */
              function renounceOwnership() public virtual onlyOwner {
                  _transferOwnership(address(0));
              }
              /**
               * @dev Transfers ownership of the contract to a new account (`newOwner`).
               * Can only be called by the current owner.
               */
              function transferOwnership(address newOwner) public virtual onlyOwner {
                  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 (last updated v4.9.4) (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;
              }
              function _contextSuffixLength() internal view virtual returns (uint256) {
                  return 0;
              }
          }
          // SPDX-License-Identifier: UNLICENSED
          // Copyright (c) Eywa.Fi, 2021-2023 - all rights reserved
          pragma solidity 0.8.17;
          import "@openzeppelin/contracts/access/Ownable.sol";
          import "./interfaces/IAddressBook.sol";
          import "./interfaces/IGateKeeper.sol";
          /**
           * @title Address book with portals, synthesis etc.
           *
           * @notice Controlled by DAO and\\or multisig (3 out of 5, Gnosis Safe).
           */
          contract AddressBook is IAddressBook, Ownable {
              enum RecordTypes { Portal, Synthesis, Router, PoolAdapter }
              struct Record {
                  /// @dev chainId chain id
                  uint64 chainId;
                  /// @dev portal/sinthesis address in chainId chain
                  address clpEndPoint;
              }
              /// @dev chainId -> portal address
              mapping(uint64 => address) public portal;
              /// @dev chainId -> synthesis address
              mapping(uint64 => address) public synthesis;
              /// @dev chainId -> router address
              mapping(uint64 => address) public router;
              /// @dev treasury address
              address public treasury;
              /// @dev whitelist address
              address public whitelist;
              /// @dev gate keeper address
              address public gateKeeper;
              /// @dev ops registrar address
              address public opsRegistrar;    
              /// @dev wrapped native asset
              address public WETH;
              event PortalSet(address portal, uint64 chainId);
              event SynthesisSet(address synthesis, uint64 chainId);
              event RouterSet(address router, uint64 chainId);
              event TreasurySet(address treasury);
              event WhitelistSet(address whitelist);
              event GateKeeperSet(address gateKeeper);
              event OpsRegistrarSet(address opsRegistrar);
              event WETHSet(address opsRegistrar);
              function bridge() public view returns (address bridge_) {
                  if (gateKeeper != address(0)) {
                      bridge_ = IGateKeeper(gateKeeper).bridge();
                  }
              }
              function setPortal(Record[] memory records) external onlyOwner {
                  _setRecords(portal, records, RecordTypes.Portal);
              }
              function setSynthesis(Record[] memory records) external onlyOwner {
                  _setRecords(synthesis, records, RecordTypes.Synthesis);
              }
              function setRouter(Record[] memory records) external onlyOwner {
                  _setRecords(router, records, RecordTypes.Router);
              }
              function setTreasury(address treasury_) external onlyOwner {
                  _checkAddress(treasury_);
                  treasury = treasury_;
                  emit TreasurySet(treasury);
              }
              function setGateKeeper(address gateKeeper_) external onlyOwner {
                  _checkAddress(gateKeeper_);
                  gateKeeper = gateKeeper_;
                  emit GateKeeperSet(gateKeeper);
              }
              function setWhitelist(address whitelist_) external onlyOwner {
                  _checkAddress(whitelist_);
                  whitelist = whitelist_;
                  emit WhitelistSet(whitelist);
              }
              function setOpsRegistrar(address opsRegistrar_) external onlyOwner {
                  _checkAddress(opsRegistrar_);
                  opsRegistrar = opsRegistrar_;
                  emit OpsRegistrarSet(opsRegistrar);
              }
              function setWETH(address WETH_) external onlyOwner {
                  _checkAddress(WETH_);
                  WETH = WETH_;
                  emit WETHSet(WETH);
              }
              function _setRecords(mapping(uint64 => address) storage map_, Record[] memory records, RecordTypes rtype) private {
                  for (uint256 i = 0; i < records.length; ++i) {
                      _checkAddress(records[i].clpEndPoint);
                      map_[records[i].chainId] = records[i].clpEndPoint;
                      _emitEvent(records[i].clpEndPoint, records[i].chainId, rtype);
                  }
              }
              function _emitEvent(address endPoint, uint64 chainId, RecordTypes rtype) private {
                  if (rtype == RecordTypes.Portal) {
                      emit PortalSet(endPoint, chainId);
                  } else if (rtype == RecordTypes.Synthesis) {
                      emit SynthesisSet(endPoint, chainId);
                  } else if (rtype == RecordTypes.Router) {
                      emit RouterSet(endPoint, chainId);
                  }
              }
              function _checkAddress(address checkingAddress) private pure {
                  require(checkingAddress != address(0), "AddressBook: zero address");
              }
          }// SPDX-License-Identifier: UNLICENSED
          // Copyright (c) Eywa.Fi, 2021-2024 - all rights reserved
          pragma solidity 0.8.17;
          interface IAddressBook {
              /// @dev returns portal by given chainId
              function portal(uint64 chainId) external view returns (address);
              /// @dev returns synthesis by given chainId
              function synthesis(uint64 chainId) external view returns (address);
              /// @dev returns router by given chainId
              function router(uint64 chainId) external view returns (address);
              /// @dev returns whitelist
              function whitelist() external view returns (address);
              /// @dev returns treasury
              function treasury() external view returns (address);
              /// @dev returns gateKeeper
              function gateKeeper() external view returns (address);
              /// @dev returns bridge
              function bridge() external view returns (address);
              /// @dev returns opsRegistrar
              function opsRegistrar() external view returns (address);
              /// @dev returns wrapped native asset (WETH)
              function WETH() external view returns (address);
          }// SPDX-License-Identifier: UNLICENSED
          // Copyright (c) Eywa.Fi, 2021-2023 - all rights reserved
          pragma solidity 0.8.17;
          interface IGateKeeper {
              function calculateCost(
                  address payToken,
                  uint256 dataLength,
                  uint64 chainIdTo,
                  address sender
              ) external returns (uint256 amountToPay);
              function sendData(
                  bytes calldata data,
                  address to,
                  uint64 chainIdTo,
                  address payToken
              ) external payable;
              function getNonce() external view returns (uint256);
              function bridge() external view returns (address);
          }

          File 7 of 8: OpsRegistrar
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (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 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. Can only be called by the current owner.
               *
               * NOTE: Renouncing ownership will leave the contract without an owner,
               * thereby disabling any functionality that is only available to the owner.
               */
              function renounceOwnership() public virtual onlyOwner {
                  _transferOwnership(address(0));
              }
              /**
               * @dev Transfers ownership of the contract to a new account (`newOwner`).
               * Can only be called by the current owner.
               */
              function transferOwnership(address newOwner) public virtual onlyOwner {
                  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 (last updated v4.9.0) (access/Ownable2Step.sol)
          pragma solidity ^0.8.0;
          import "./Ownable.sol";
          /**
           * @dev Contract module which provides access control mechanism, where
           * there is an account (an owner) that can be granted exclusive access to
           * specific functions.
           *
           * By default, the owner account will be the one that deploys the contract. This
           * can later be changed with {transferOwnership} and {acceptOwnership}.
           *
           * This module is used through inheritance. It will make available all functions
           * from parent (Ownable).
           */
          abstract contract Ownable2Step is Ownable {
              address private _pendingOwner;
              event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
              /**
               * @dev Returns the address of the pending owner.
               */
              function pendingOwner() public view virtual returns (address) {
                  return _pendingOwner;
              }
              /**
               * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
               * Can only be called by the current owner.
               */
              function transferOwnership(address newOwner) public virtual override onlyOwner {
                  _pendingOwner = newOwner;
                  emit OwnershipTransferStarted(owner(), newOwner);
              }
              /**
               * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
               * Internal function without access restriction.
               */
              function _transferOwnership(address newOwner) internal virtual override {
                  delete _pendingOwner;
                  super._transferOwnership(newOwner);
              }
              /**
               * @dev The new owner accepts the ownership transfer.
               */
              function acceptOwnership() public virtual {
                  address sender = _msgSender();
                  require(pendingOwner() == sender, "Ownable2Step: caller is not the new owner");
                  _transferOwnership(sender);
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.4) (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;
              }
              function _contextSuffixLength() internal view virtual returns (uint256) {
                  return 0;
              }
          }
          // SPDX-License-Identifier: UNLICENSED
          // Copyright (c) Eywa.Fi, 2021-2023 - all rights reserved
          pragma solidity 0.8.17;
          interface IOpsRegistrar {
              struct ComplexOp {
                  string operation;
                  bool registered;
              }
              /// @dev returns is complex op registered
              function ops(bytes32 ops_) external returns (bool);
              /// @dev registers ComplexOp's
              function registerComplexOp(ComplexOp[] memory complexOps_) external;
          }// SPDX-License-Identifier: UNLICENSED
          // Copyright (c) Eywa.Fi, 2021-2024 - all rights reserved
          pragma solidity 0.8.17;
          import "@openzeppelin/contracts/access/Ownable2Step.sol";
          import "./interfaces/IOpsRegistrar.sol";
          /**
           * @title Ops registry.
           *
           * @notice Controlled by operator.
           */
          contract OpsRegistrar is IOpsRegistrar, Ownable {
              /// @dev registered operations
              mapping(bytes32 => bool) public ops;
              event ComplexOpSet(string oop, bytes32 hash, bool registered);
              /**
               * @dev Registers set of complex operation.
               *
               * @param complexOps_ array of complex operations and registered flags.
               */
              function registerComplexOp(ComplexOp[] memory complexOps_) external onlyOwner {
                  uint256 length = complexOps_.length;
                  for (uint256 i; i < length; ++i) {
                      bytes32 oop = keccak256(bytes(complexOps_[i].operation));
                      ops[oop] = complexOps_[i].registered;
                      emit ComplexOpSet(complexOps_[i].operation, oop, complexOps_[i].registered);
                  }
              }
          }

          File 8 of 8: WhitelistV2
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.7.0) (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 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);
              }
          }
          // 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: MIT
          // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev Standard math utilities missing in the Solidity language.
           */
          library Math {
              enum Rounding {
                  Down, // Toward negative infinity
                  Up, // Toward infinity
                  Zero // Toward zero
              }
              /**
               * @dev Returns the largest of two numbers.
               */
              function max(uint256 a, uint256 b) internal pure returns (uint256) {
                  return a > b ? a : b;
              }
              /**
               * @dev Returns the smallest of two numbers.
               */
              function min(uint256 a, uint256 b) internal pure returns (uint256) {
                  return a < b ? a : b;
              }
              /**
               * @dev Returns the average of two numbers. The result is rounded towards
               * zero.
               */
              function average(uint256 a, uint256 b) internal pure returns (uint256) {
                  // (a + b) / 2 can overflow.
                  return (a & b) + (a ^ b) / 2;
              }
              /**
               * @dev Returns the ceiling of the division of two numbers.
               *
               * This differs from standard division with `/` in that it rounds up instead
               * of rounding down.
               */
              function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
                  // (a + b - 1) / b can overflow on addition, so we distribute.
                  return a == 0 ? 0 : (a - 1) / b + 1;
              }
              /**
               * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
               * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
               * with further edits by Uniswap Labs also under MIT license.
               */
              function mulDiv(
                  uint256 x,
                  uint256 y,
                  uint256 denominator
              ) internal pure returns (uint256 result) {
                  unchecked {
                      // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
                      // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
                      // variables such that product = prod1 * 2^256 + prod0.
                      uint256 prod0; // Least significant 256 bits of the product
                      uint256 prod1; // Most significant 256 bits of the product
                      assembly {
                          let mm := mulmod(x, y, not(0))
                          prod0 := mul(x, y)
                          prod1 := sub(sub(mm, prod0), lt(mm, prod0))
                      }
                      // Handle non-overflow cases, 256 by 256 division.
                      if (prod1 == 0) {
                          return prod0 / denominator;
                      }
                      // Make sure the result is less than 2^256. Also prevents denominator == 0.
                      require(denominator > prod1);
                      ///////////////////////////////////////////////
                      // 512 by 256 division.
                      ///////////////////////////////////////////////
                      // Make division exact by subtracting the remainder from [prod1 prod0].
                      uint256 remainder;
                      assembly {
                          // Compute remainder using mulmod.
                          remainder := mulmod(x, y, denominator)
                          // Subtract 256 bit number from 512 bit number.
                          prod1 := sub(prod1, gt(remainder, prod0))
                          prod0 := sub(prod0, remainder)
                      }
                      // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
                      // See https://cs.stackexchange.com/q/138556/92363.
                      // Does not overflow because the denominator cannot be zero at this stage in the function.
                      uint256 twos = denominator & (~denominator + 1);
                      assembly {
                          // Divide denominator by twos.
                          denominator := div(denominator, twos)
                          // Divide [prod1 prod0] by twos.
                          prod0 := div(prod0, twos)
                          // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                          twos := add(div(sub(0, twos), twos), 1)
                      }
                      // Shift in bits from prod1 into prod0.
                      prod0 |= prod1 * twos;
                      // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
                      // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
                      // four bits. That is, denominator * inv = 1 mod 2^4.
                      uint256 inverse = (3 * denominator) ^ 2;
                      // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
                      // in modular arithmetic, doubling the correct bits in each step.
                      inverse *= 2 - denominator * inverse; // inverse mod 2^8
                      inverse *= 2 - denominator * inverse; // inverse mod 2^16
                      inverse *= 2 - denominator * inverse; // inverse mod 2^32
                      inverse *= 2 - denominator * inverse; // inverse mod 2^64
                      inverse *= 2 - denominator * inverse; // inverse mod 2^128
                      inverse *= 2 - denominator * inverse; // inverse mod 2^256
                      // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
                      // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
                      // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
                      // is no longer required.
                      result = prod0 * inverse;
                      return result;
                  }
              }
              /**
               * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
               */
              function mulDiv(
                  uint256 x,
                  uint256 y,
                  uint256 denominator,
                  Rounding rounding
              ) internal pure returns (uint256) {
                  uint256 result = mulDiv(x, y, denominator);
                  if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
                      result += 1;
                  }
                  return result;
              }
              /**
               * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
               *
               * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
               */
              function sqrt(uint256 a) internal pure returns (uint256) {
                  if (a == 0) {
                      return 0;
                  }
                  // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
                  //
                  // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
                  // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
                  //
                  // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
                  // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
                  // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
                  //
                  // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
                  uint256 result = 1 << (log2(a) >> 1);
                  // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
                  // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
                  // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
                  // into the expected uint128 result.
                  unchecked {
                      result = (result + a / result) >> 1;
                      result = (result + a / result) >> 1;
                      result = (result + a / result) >> 1;
                      result = (result + a / result) >> 1;
                      result = (result + a / result) >> 1;
                      result = (result + a / result) >> 1;
                      result = (result + a / result) >> 1;
                      return min(result, a / result);
                  }
              }
              /**
               * @notice Calculates sqrt(a), following the selected rounding direction.
               */
              function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
                  unchecked {
                      uint256 result = sqrt(a);
                      return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
                  }
              }
              /**
               * @dev Return the log in base 2, rounded down, of a positive value.
               * Returns 0 if given 0.
               */
              function log2(uint256 value) internal pure returns (uint256) {
                  uint256 result = 0;
                  unchecked {
                      if (value >> 128 > 0) {
                          value >>= 128;
                          result += 128;
                      }
                      if (value >> 64 > 0) {
                          value >>= 64;
                          result += 64;
                      }
                      if (value >> 32 > 0) {
                          value >>= 32;
                          result += 32;
                      }
                      if (value >> 16 > 0) {
                          value >>= 16;
                          result += 16;
                      }
                      if (value >> 8 > 0) {
                          value >>= 8;
                          result += 8;
                      }
                      if (value >> 4 > 0) {
                          value >>= 4;
                          result += 4;
                      }
                      if (value >> 2 > 0) {
                          value >>= 2;
                          result += 2;
                      }
                      if (value >> 1 > 0) {
                          result += 1;
                      }
                  }
                  return result;
              }
              /**
               * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
               * Returns 0 if given 0.
               */
              function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
                  unchecked {
                      uint256 result = log2(value);
                      return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
                  }
              }
              /**
               * @dev Return the log in base 10, rounded down, of a positive value.
               * Returns 0 if given 0.
               */
              function log10(uint256 value) internal pure returns (uint256) {
                  uint256 result = 0;
                  unchecked {
                      if (value >= 10**64) {
                          value /= 10**64;
                          result += 64;
                      }
                      if (value >= 10**32) {
                          value /= 10**32;
                          result += 32;
                      }
                      if (value >= 10**16) {
                          value /= 10**16;
                          result += 16;
                      }
                      if (value >= 10**8) {
                          value /= 10**8;
                          result += 8;
                      }
                      if (value >= 10**4) {
                          value /= 10**4;
                          result += 4;
                      }
                      if (value >= 10**2) {
                          value /= 10**2;
                          result += 2;
                      }
                      if (value >= 10**1) {
                          result += 1;
                      }
                  }
                  return result;
              }
              /**
               * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
               * Returns 0 if given 0.
               */
              function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
                  unchecked {
                      uint256 result = log10(value);
                      return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);
                  }
              }
              /**
               * @dev Return the log in base 256, rounded down, of a positive value.
               * Returns 0 if given 0.
               *
               * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
               */
              function log256(uint256 value) internal pure returns (uint256) {
                  uint256 result = 0;
                  unchecked {
                      if (value >> 128 > 0) {
                          value >>= 128;
                          result += 16;
                      }
                      if (value >> 64 > 0) {
                          value >>= 64;
                          result += 8;
                      }
                      if (value >> 32 > 0) {
                          value >>= 32;
                          result += 4;
                      }
                      if (value >> 16 > 0) {
                          value >>= 16;
                          result += 2;
                      }
                      if (value >> 8 > 0) {
                          result += 1;
                      }
                  }
                  return result;
              }
              /**
               * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
               * Returns 0 if given 0.
               */
              function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
                  unchecked {
                      uint256 result = log256(value);
                      return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);
                  }
              }
          }
          // SPDX-License-Identifier: UNLICENSED
          // Copyright (c) Eywa.Fi, 2021-2023 - all rights reserved
          pragma solidity 0.8.17;
          interface IWhitelist {
              enum TokenState { NotSet, InOut }
              enum PoolState { NotSet, AddSwapRemove }
              struct TokenStatus {
                  address token;
                  uint256 min;
                  uint256 max;
                  uint256 bridgeFee;
                  TokenState state;
              }
              struct PoolStatus {
                  address pool;
                  uint256 aggregationFee;
                  PoolState state;
              }
              
              function tokenMin(address token) external view returns (uint256);
              function tokenMax(address token) external view returns (uint256);
              function tokenMinMax(address token) external view returns (uint256, uint256);
              function bridgeFee(address token) external view returns (uint256);
              function tokenState(address token) external view returns (uint8);
              function tokenStatus(address token) external view returns (TokenStatus memory);
              function tokens(uint256 offset, uint256 count) external view returns (TokenStatus[] memory);
              function aggregationFee(address pool) external view returns (uint256);
              function poolState(address pool) external view returns (uint8);
              function poolStatus(address pool) external view returns (PoolStatus memory);
              function pools(uint256 offset, uint256 count) external view returns (PoolStatus[] memory);
          }
          // SPDX-License-Identifier: UNLICENSED
          // Copyright (c) Eywa.Fi, 2021-2023 - all rights reserved
          pragma solidity 0.8.17;
          import "@openzeppelin/contracts/access/Ownable.sol";
          import "@openzeppelin/contracts/utils/math/Math.sol";
          import "./interfaces/IWhitelist.sol";
          contract WhitelistV2 is IWhitelist, Ownable {
              /// @dev fee denominator
              uint256 public constant FEE_DENOMINATOR = 10000;
              /// @dev array of token indices
              mapping(address => uint256) private _tokenIds;
              /// @dev tokens
              IWhitelist.TokenStatus[] private _tokens;
              /// @dev array of pool indices
              mapping(address => uint256) private _poolIds;
              /// @dev pools
              IWhitelist.PoolStatus[] private _pools;
              event TokenSet(address token, uint256 max, uint256 min, uint256 fee, IWhitelist.TokenState state);
              event PoolSet(address pool, uint256 fee, IWhitelist.PoolState state);
              function tokenMin(address token_) external view returns (uint256) {
                  return _getToken(token_).min;
              }
              
              function tokenMax(address token_) external view returns (uint256) {
                  return _getToken(token_).max;
              }
              function tokenMinMax(address token_) external view returns (uint256, uint256) {
                  IWhitelist.TokenStatus memory token = _getToken(token_);
                  return (token.min, token.max);
              }
              function bridgeFee(address token_) external view returns (uint256) {
                  return _getToken(token_).bridgeFee;
              }
              function tokenState(address token_) external view returns (uint8) {
                  return uint8(_getToken(token_).state);
              }
              function tokenStatus(address token_) external view returns (IWhitelist.TokenStatus memory) {
                  return _getToken(token_);
              }
              function aggregationFee(address pool_) external view returns (uint256) {
                  return _getPool(pool_).aggregationFee;
              }
              function poolState(address pool_) external view returns (uint8){
                  return uint8(_getPool(pool_).state);
              }
              function poolStatus(address pool_) external view returns (IWhitelist.PoolStatus memory) {
                  return _getPool(pool_);
              }
              function tokens(uint256 offset, uint256 count) external view returns (IWhitelist.TokenStatus[] memory) {
                  require(offset <= _tokens.length, "Whitelist: wrong offset");
                  count = Math.min(_tokens.length, count + offset);
                  IWhitelist.TokenStatus[] memory tokens_ = new IWhitelist.TokenStatus[](count - offset);
                  for (uint256 i = offset; i < count; ++i) {
                      tokens_[i] = _tokens[i];
                  }
                  return tokens_;
              }
              function pools(uint256 offset, uint256 count) external view returns (IWhitelist.PoolStatus[] memory) {
                  require(offset <= _pools.length, "Whitelist: wrong offset");
                  count = Math.min(_pools.length, count + offset);
                  IWhitelist.PoolStatus[] memory pools_ = new IWhitelist.PoolStatus[](count - offset);
                  for (uint256 i = offset; i < count; ++i) {
                      pools_[i] = _pools[i];
                  }
                  return pools_;
              }
              function setTokens(IWhitelist.TokenStatus[] memory tokens_) external onlyOwner {
                  uint256 count = tokens_.length;
                  for (uint256 i; i < count; ++i) {
                      IWhitelist.TokenStatus memory status = tokens_[i];
                      require(status.token != address(0), "Whitelist: zero address");
                      require(status.max >= status.min, "Whitelist: min max wrong");
                      require(status.bridgeFee <= FEE_DENOMINATOR, "Whitelist: fee > 100%");
                      uint256 id = _tokenIds[status.token];
                      if (id == 0) {
                          _tokens.push(status);
                          _tokenIds[status.token] = _tokens.length;
                      } else {
                          --id;
                          _tokens[id] = status;
                      }
                      emit TokenSet(status.token, status.max, status.min, status.bridgeFee, status.state);
                  }
              }
              function setPools(IWhitelist.PoolStatus[] memory pools_) external onlyOwner {
                  uint256 count = pools_.length;
                  for (uint256 i; i < count; ++i) {
                      IWhitelist.PoolStatus memory status = pools_[i];
                      require(status.pool != address(0), "Whitelist: zero address");
                      require(status.aggregationFee <= FEE_DENOMINATOR, "Whitelist: fee > 100%");
                      uint256 id = _poolIds[status.pool];
                      if (id == 0) {
                          _pools.push(status);
                          _poolIds[status.pool] = _pools.length;
                      } else {
                          --id;
                          _pools[id] = status;
                      }
                      emit PoolSet(status.pool, status.aggregationFee, status.state);
                  }
              }
              function _getToken(address token) private view returns (IWhitelist.TokenStatus memory) {
                  uint256 id = _tokenIds[token];
                  require(id != 0, "Whitelist: token not set");
                  --id;
                  return _tokens[id];
              }
              function _getPool(address pool) private view returns (IWhitelist.PoolStatus memory) {
                  uint256 id = _poolIds[pool];
                  require(id != 0, "Whitelist: pool not set");
                  --id;
                  return _pools[id];
              }
          }