ETH Price: $2,080.49 (-3.14%)

Transaction Decoder

Block:
21910123 at Feb-23-2025 04:09:23 PM +UTC
Transaction Fee:
0.0004075678583613 ETH $0.85
Gas Used:
559,260 Gas / 0.728762755 Gwei

Emitted Events:

538 GraphToken.Approval( owner=0x15F849F82058c37D8Cc69c88c1AD7b0a59f2b753, spender=CheckoutPool, value=115792089237316195423570985008687907853269984665640564039457584007913129639935 )
539 GraphToken.Transfer( from=0x15F849F82058c37D8Cc69c88c1AD7b0a59f2b753, to=CheckoutPool, value=389351615024759563597 )
540 GraphToken.Approval( owner=0x15F849F82058c37D8Cc69c88c1AD7b0a59f2b753, spender=CheckoutPool, value=115792089237316195423570985008687907853269984665640564039068232392888370076338 )
541 CheckoutPool.Deposited( depositAddress=0x15F849F82058c37D8Cc69c88c1AD7b0a59f2b753, receivedAsset=GraphToken, receivedAmount=389351615024759563597 )

Account State Difference:

  Address   Before After State Difference Code
0x15F849F8...a59f2b753
0 Eth
Nonce: 0
0 Eth
Nonce: 1
From: 0 To: 236813696290737737313572634660283371925575687912417124694247650231474508528408647032069118674698509842402098423496125167954422161256517637200084771325458750370181342360674538213390984304701907467236872084999651386404495968059965277240466496721131993013929637356400756427639348568387064364743426299124240464276047252267697246302643119645016787912188936741714703912723347885720531996218107395974385815331685791172229538639481506115970120250318014544451302960283131528890158310137307412740023527996869983853642617280022701992354135667830135246411977152469553041449572878383692921624470326423111441330099051941301423429432632743025697567829678929438859204353172360818832847501096902396832865923550445008725379466594385887897571359000514492223287155820338242826044564652336805577281248868285120707028480147803314356663063791758214385890988718000061550819061505401293454070302105041486437722801446252382553593875146894069094406807946447757639221311826554261607543438708509963432932921926187439524978548822434522340423867919497709065276043558437932644012035404134133120752243387508054374112895064177967338337961367642616575969218750777195721522517597518872254285190477227700778529302327986657720995026456917198380627552294997657830229653568141648195019906265813871419144273636584900334400862192879284822300345918667410228044843953890645077199329564314813870906857400090123009242449690637128001231743761611413925488595671358605090609403889916659797018113098439872148125993078963221693835987962571047940707016041043471943721449425679484458230682518276402445021930413056309271150240801160682585954354546816828546150569913845962992641173158501148190349258139872332478686995304279681856261264571168426012120752145198001861251139970294109069134270932519575945822889737476920633712240049621726385535935173673293717422087359795621544790034049229917634512631078087874569186929470102906794683511485315502103350079172554177206753808717931648987979394703716183975317583839262578310061201837317399398712581578991280070410809406184124437547908303931221963952141793201247531150082906847155564644373227174457998211971081187541824071441395146048488655035252759947011845035461243297043157016754724570578870409508804592370856991492112094540614798272554151578454672188040115397717684558522989418412128617900121480993763577523734456280423961477922676694050386990844400270390453289319433705746087928501195351893150716286107149533472518099879208808213304847603547437436048434325557879004146186253010712445650600628199079519218797617644748551982553657481653636484878294397860323927551639861551772380465898593597223065387816638062118651596516096567179802645852399501446666335190262228520784294921786246274997355189850968746202374406363394787719866744620406943873948847441243180936003584572610566710521035352650238355469098684607121590386257861357247024825196647576845990146501759643437278581620936480204882805316395788175864329346069157294266490521984356996139224618126156273889847169665762383683474153445036356111921781452707304098538836384436408914546249794766349860713019908964008619202633094744678947420950859591625398631859654582124677909105971182902763537901013349331395776316612422175413069910217432646557081740090835090446796251302921905148937312355598099723048727822860287323283722261129747234867
0x1881ad6e...3CFb09919
11.891490975899358623 Eth
Nonce: 33887
11.891083408040997323 Eth
Nonce: 33888
0.0004075678583613
0x1929347E...EfcAcd215
0x8629Bcd3...69DADCCA7
(beaverbuild)
16.080133002913365359 Eth16.080133702185784139 Eth0.00000069927241878
0xc944E90C...05Cda44a7

Execution Trace

Create2ForwarderFactory.createAndForward( checkout=[{name:params, type:tuple, order:1, indexed:false, value:[{name:userOpHash, type:bytes32, order:1, indexed:false, value:0000000000000000000000000000000000000000000000000000000000000000, valueString:0000000000000000000000000000000000000000000000000000000000000000}, {name:targetAsset, type:bytes32, order:2, indexed:false, value:0000000000000000000000002791BCA1F2DE4661ED88A30C99A7A9449AA84174, valueString:0000000000000000000000002791BCA1F2DE4661ED88A30C99A7A9449AA84174}, {name:targetChainId, type:uint96, order:3, indexed:false, value:137, valueString:137}, {name:targetAmount, type:uint128, order:4, indexed:false, value:51191100, valueString:51191100}, {name:expiration, type:uint128, order:5, indexed:false, value:1740328900, valueString:1740328900}, {name:recipient, type:bytes32, order:6, indexed:false, value:0000000000000000000000003E6501EE87C24737A90B2D7326229558F7AA94D3, valueString:0000000000000000000000003E6501EE87C24737A90B2D7326229558F7AA94D3}], valueString:[{name:userOpHash, type:bytes32, order:1, indexed:false, value:0000000000000000000000000000000000000000000000000000000000000000, valueString:0000000000000000000000000000000000000000000000000000000000000000}, {name:targetAsset, type:bytes32, order:2, indexed:false, value:0000000000000000000000002791BCA1F2DE4661ED88A30C99A7A9449AA84174, valueString:0000000000000000000000002791BCA1F2DE4661ED88A30C99A7A9449AA84174}, {name:targetChainId, type:uint96, order:3, indexed:false, value:137, valueString:137}, {name:targetAmount, type:uint128, order:4, indexed:false, value:51191100, valueString:51191100}, {name:expiration, type:uint128, order:5, indexed:false, value:1740328900, valueString:1740328900}, {name:recipient, type:bytes32, order:6, indexed:false, value:0000000000000000000000003E6501EE87C24737A90B2D7326229558F7AA94D3, valueString:0000000000000000000000003E6501EE87C24737A90B2D7326229558F7AA94D3}]}, {name:heldAsset, type:address, order:2, indexed:false, value:0xc944E90C64B2c07662A292be6244BDf05Cda44a7, valueString:0xc944E90C64B2c07662A292be6244BDf05Cda44a7}, {name:heldAmount, type:uint256, order:3, indexed:false, value:389351615024759563597, valueString:389351615024759563597}], salt=AE0EC8B2A101BCBD142A7BA65BF49C2C42D30BCEF4EDFB8EA9C7A5E2495BF3A3 ) => ( 0x15F849F82058c37D8Cc69c88c1AD7b0a59f2b753 )
  • 0x15f849f82058c37d8cc69c88c1ad7b0a59f2b753.6101a060( )
  • 0x15f849f82058c37d8cc69c88c1ad7b0a59f2b753.CALL( )
    • Create2ForwarderImpl.DELEGATECALL( )
      • 0x15f849f82058c37d8cc69c88c1ad7b0a59f2b753.STATICCALL( )
      • GraphToken.balanceOf( account=0x15F849F82058c37D8Cc69c88c1AD7b0a59f2b753 ) => ( 389351615024759563597 )
      • GraphToken.approve( spender=0x1929347E025D4F5F8D6B2Bd2261e2f4EfcAcd215, amount=115792089237316195423570985008687907853269984665640564039457584007913129639935 ) => ( True )
      • CheckoutPool.deposit( checkout=[{name:params, type:tuple, order:1, indexed:false, value:[{name:userOpHash, type:bytes32, order:1, indexed:false, value:0000000000000000000000000000000000000000000000000000000000000000, valueString:0000000000000000000000000000000000000000000000000000000000000000}, {name:targetAsset, type:bytes32, order:2, indexed:false, value:0000000000000000000000002791BCA1F2DE4661ED88A30C99A7A9449AA84174, valueString:0000000000000000000000002791BCA1F2DE4661ED88A30C99A7A9449AA84174}, {name:targetChainId, type:uint96, order:3, indexed:false, value:137, valueString:137}, {name:targetAmount, type:uint128, order:4, indexed:false, value:51191100, valueString:51191100}, {name:expiration, type:uint128, order:5, indexed:false, value:1740328900, valueString:1740328900}, {name:recipient, type:bytes32, order:6, indexed:false, value:0000000000000000000000003E6501EE87C24737A90B2D7326229558F7AA94D3, valueString:0000000000000000000000003E6501EE87C24737A90B2D7326229558F7AA94D3}], valueString:[{name:userOpHash, type:bytes32, order:1, indexed:false, value:0000000000000000000000000000000000000000000000000000000000000000, valueString:0000000000000000000000000000000000000000000000000000000000000000}, {name:targetAsset, type:bytes32, order:2, indexed:false, value:0000000000000000000000002791BCA1F2DE4661ED88A30C99A7A9449AA84174, valueString:0000000000000000000000002791BCA1F2DE4661ED88A30C99A7A9449AA84174}, {name:targetChainId, type:uint96, order:3, indexed:false, value:137, valueString:137}, {name:targetAmount, type:uint128, order:4, indexed:false, value:51191100, valueString:51191100}, {name:expiration, type:uint128, order:5, indexed:false, value:1740328900, valueString:1740328900}, {name:recipient, type:bytes32, order:6, indexed:false, value:0000000000000000000000003E6501EE87C24737A90B2D7326229558F7AA94D3, valueString:0000000000000000000000003E6501EE87C24737A90B2D7326229558F7AA94D3}]}, {name:heldAsset, type:address, order:2, indexed:false, value:0xc944E90C64B2c07662A292be6244BDf05Cda44a7, valueString:0xc944E90C64B2c07662A292be6244BDf05Cda44a7}, {name:heldAmount, type:uint256, order:3, indexed:false, value:389351615024759563597, valueString:389351615024759563597}] )
        • GraphToken.transferFrom( sender=0x15F849F82058c37D8Cc69c88c1AD7b0a59f2b753, recipient=0x1929347E025D4F5F8D6B2Bd2261e2f4EfcAcd215, amount=389351615024759563597 ) => ( True )
          File 1 of 4: Create2ForwarderFactory
          // SPDX-License-Identifier: UNLICENSED
          pragma solidity ^0.8.13;
          import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
          import { CheckoutPoolInterface } from "../interfaces/CheckoutPoolInterface.sol";
          import {
              Create2ForwarderInterface
          } from "../interfaces/Create2ForwarderInterface.sol";
          import {
              Create2ForwarderFactoryInterface
          } from "../interfaces/Create2ForwarderFactoryInterface.sol";
          import { CheckoutState } from "../interfaces/CheckoutPoolInterface.sol";
          import { WETH9Interface } from "../interfaces/WETH9Interface.sol";
          import { Create2ForwarderImpl } from "../forwarder/Create2ForwarderImpl.sol";
          import { Create2ForwarderProxy } from "./Create2ForwarderProxy.sol";
          /**
           * @title Create2ForwarderFactory
           * @author Fun.xyz
           *
           * @notice Factory for “counterfactual” forwarder contracts for the Checkout Pools protocol.
           *
           *  A forwarder contract is created for each checkout operation executed by the protocol.
           *  It is the entry point for funds into the protocol.
           *
           *  Before the forwarder contract is deployed, its CREATE2 address (the “deposit address”)
           *  is calculated, so that the contract can be deployed only as needed, after funds have
           *  been deposited.
           *
           *  As a gas optimization, each forwarder contract is deployed as a proxy. All of the proxy
           *  contracts reference the same implementation logic, which is a constant on the factory contract.
           *
           *  As a gas optimization, checkout parameters that are not expected to change (often) are
           *  stored as constants on the factory contract. Parameters that do not need to be stored
           *  on-chain (e.g. the full user operation) are expected to be stored off-chain by the liquidity
           *  provider that is responsible for executing the checkout.
           *
           *  Constants (same for all forwarders created by the factory).
           *    - source chain
           *    - guardian address
           *    - CheckoutPools contract address (corresponds to a liquidity provider)
           *    - wrapped native token address
           *
           *  On-chain configuration (different for each forwarder / checkout operation)
           *    - user op hash
           *    - target chain
           *    - target asset and amount
           *    - source asset and amount
           *    - expiration timestamp
           *    - salt (not stored)
           *
           *  Off-chain configuration
           *    - user op
           */
          contract Create2ForwarderFactory is Create2ForwarderFactoryInterface {
              error ErrorCreatingProxy();
              Create2ForwarderImpl public immutable IMPLEMENTATION;
              constructor(
                  address guardian,
                  WETH9Interface wrappedNativeToken,
                  CheckoutPoolInterface checkoutPool
              ) {
                  IMPLEMENTATION = new Create2ForwarderImpl(
                      guardian,
                      wrappedNativeToken,
                      checkoutPool
                  );
              }
              function create(
                  CheckoutState calldata checkout,
                  bytes32 salt
              ) external returns (Create2ForwarderInterface) {
                  return _create(checkout, salt);
              }
              function createAndForward(
                  CheckoutState calldata checkout,
                  bytes32 salt
              ) external returns (Create2ForwarderInterface) {
                  Create2ForwarderInterface proxy = _create(checkout, salt);
                  proxy.forward();
                  return proxy;
              }
              function getAddress(
                  CheckoutState calldata checkout,
                  bytes32 salt
              ) external view returns (address payable) {
                  return _getAddress(checkout, salt, block.chainid);
              }
              /**
               * @notice Get the deposit address for a target chain ID.
               *
               *  IMPORTANT NOTE: This implementation assumes that the forwarder factory has the same
               *  address on each chain. This has to be ensured before a chain ID is added to the allowed
               *  list of target chain IDs on the CheckoutPools contract.
               */
              function getAddressForChain(
                  CheckoutState calldata checkout,
                  bytes32 salt,
                  uint256 chainId
              ) external view returns (address payable) {
                  return _getAddress(checkout, salt, chainId);
              }
              function getProxyCreationCode() external pure returns (bytes memory) {
                  return type(Create2ForwarderProxy).creationCode;
              }
              function _create(
                  CheckoutState calldata checkout,
                  bytes32 salt
              ) internal returns (Create2ForwarderInterface) {
                  Create2ForwarderProxy deployed = new Create2ForwarderProxy{
                      salt: salt
                  }(IMPLEMENTATION, checkout, block.chainid);
                  Create2ForwarderInterface proxy = Create2ForwarderInterface(
                      address(deployed)
                  );
                  return proxy;
              }
              function _getAddress(
                  CheckoutState calldata checkout,
                  bytes32 salt,
                  uint256 chainId
              ) internal view returns (address payable) {
                  bytes32 digest = keccak256(
                      abi.encodePacked(
                          bytes1(0xff),
                          address(this),
                          salt,
                          keccak256(
                              abi.encodePacked(
                                  type(Create2ForwarderProxy).creationCode,
                                  abi.encode(IMPLEMENTATION, checkout, chainId)
                              )
                          )
                      )
                  );
                  return payable(address(uint160(uint256(digest))));
              }
          }
          // Compare with:
          // function create3(bytes32 _salt, bytes memory _creationCode, uint256 _value) internal returns (address addr) {
          //     // Creation code
          //     bytes memory creationCode = PROXY_CHILD_BYTECODE;
          //     // Get target final address
          //     addr = addressOf(_salt);
          //     if (codeSize(addr) != 0) revert TargetAlreadyExists();
          //     // Create CREATE2 proxy
          //     address proxy; assembly { proxy := create2(0, add(creationCode, 32), mload(creationCode), _salt)}
          //     if (proxy == address(0)) revert ErrorCreatingProxy();
          //     // Call proxy with final init code
          //     (bool success,) = proxy.call{ value: _value }(_creationCode);
          //     if (!success || codeSize(addr) == 0) revert ErrorCreatingContract();
          // }
          // 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: UNLICENSED
          pragma solidity ^0.8.13;
          import {
              UserOperation
          } from "@account-abstraction/contracts/interfaces/UserOperation.sol";
          import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
          /// @dev Immutable parameters of a checkout account.
          struct CheckoutParams {
              bytes32 userOpHash;
              bytes32 targetAsset;
              uint96 targetChainId;
              uint128 targetAmount;
              uint128 expiration;
              bytes32 recipient;
          }
          /// @dev State of a checkout account.
          struct CheckoutState {
              CheckoutParams params;
              IERC20 heldAsset;
              uint256 heldAmount;
          }
          struct SwapParams {
              address target;
              address spender;
              bytes callData;
              address receivedAsset;
              bool isETHSwap;
          }
          struct BridgeParams {
              address target;
              address spender;
              bytes callData;
              IERC20 bridgeReceivedAsset;
              uint256 minBridgeReceivedAmount;
          }
          interface CheckoutPoolInterface {
              function deposit(CheckoutState calldata checkoutState) external;
              function swap(
                  address depositAddress,
                  SwapParams calldata swapParams
              ) external;
              function bridge(
                  address depositAddress,
                  BridgeParams calldata bridgeParams
              ) external;
              function execute(
                  address depositAddress,
                  UserOperation[] calldata ops // length-1 array (gas optimization)
              ) external;
              function checkoutExists(
                  address depositAddress
              ) external view returns (bool);
              function getCheckout(
                  address depositAddress
              ) external view returns (CheckoutState memory);
              function getCheckoutOrZero(
                  address depositAddress
              ) external view returns (CheckoutState memory);
              function forwardFund(address depositAddress) external;
          }
          // SPDX-License-Identifier: UNLICENSED
          pragma solidity ^0.8.13;
          interface Create2ForwarderInterface {
              function forward() external;
          }
          // SPDX-License-Identifier: UNLICENSED
          pragma solidity ^0.8.13;
          import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
          import {
              Create2ForwarderInterface
          } from "../interfaces/Create2ForwarderInterface.sol";
          import { CheckoutState } from "./CheckoutPoolInterface.sol";
          interface Create2ForwarderFactoryInterface {
              function createAndForward(
                  CheckoutState calldata checkout,
                  bytes32 salt
              ) external returns (Create2ForwarderInterface);
          }
          // SPDX-License-Identifier: UNLICENSED
          pragma solidity ^0.8.13;
          import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
          interface WETH9Interface is IERC20 {
              function deposit() external payable;
              function withdraw(uint256) external;
          }
          // SPDX-License-Identifier: UNLICENSED
          pragma solidity ^0.8.13;
          import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
          import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
          import { CheckoutPoolInterface } from "../interfaces/CheckoutPoolInterface.sol";
          import {
              Create2ForwarderInterface
          } from "../interfaces/Create2ForwarderInterface.sol";
          import {
              Create2ForwarderEventsAndErrors
          } from "../interfaces/Create2ForwarderEventsAndErrors.sol";
          import { WETH9Interface } from "../interfaces/WETH9Interface.sol";
          import {
              CheckoutParams,
              CheckoutState
          } from "../interfaces/CheckoutPoolInterface.sol";
          import { GuardianRescuable } from "../utils/GuardianRescuable.sol";
          import { Create2ForwarderProxy } from "./Create2ForwarderProxy.sol";
          /**
           * @title Create2ForwarderImpl
           * @author Fun.xyz
           *
           * @notice A forwarder contract (a.k.a. “deposit address”) for the Checkout Pools protocol.
           *
           *  See Create2ForwarderFactory and Create2ForwarderProxy for more info.
           */
          contract Create2ForwarderImpl is
              GuardianRescuable,
              Create2ForwarderInterface,
              Create2ForwarderEventsAndErrors
          {
              using SafeERC20 for IERC20;
              address public immutable GUARDIAN;
              WETH9Interface public immutable WRAPPED_NATIVE_TOKEN;
              CheckoutPoolInterface public immutable CHECKOUT_POOL;
              address public immutable USDT_TOKEN = address(0xdAC17F958D2ee523a2206206994597C13D831ec7);  
              bool internal _FORWARDED_;
              receive() external payable {}
              /**
               * @notice Implementation constructor.
               *
               *  Sets immutable values that are the same across all deployed proxies.
               */
              constructor(
                  address initialGuardian,
                  WETH9Interface wrappedNativeToken,
                  CheckoutPoolInterface checkoutPool
              ) {
                  GUARDIAN = initialGuardian;
                  WRAPPED_NATIVE_TOKEN = wrappedNativeToken;
                  CHECKOUT_POOL = checkoutPool;
              }
              function guardian() public override view returns (address) {
                  return GUARDIAN;
              }
              /**
               * @notice Forward deposited funds to the CheckoutPool contract.
               */
              function forward() external {
                  // Forward at most once.
                  if (_FORWARDED_) {
                      revert AlreadyForwarded();
                  }
                  _FORWARDED_ = true;
                  // Read checkout state from proxy immutable configuration.
                  CheckoutState memory checkout = Create2ForwarderProxy(payable(this))
                      .getCheckout();
                  IERC20 heldAsset = checkout.heldAsset;
                  uint256 minSourceAmount = checkout.heldAmount;
                  // Get native value.
                  uint256 value = address(this).balance;
                  // Convert any native value to wrapped native token.
                  if (value != 0) {
                      // Note: Intentionally not sanity checking that ERC20 == WRAPPED_NATIVE_TOKEN
                      //       since that's of little help at this point, if the contract is misconfigured.
                      WRAPPED_NATIVE_TOKEN.deposit{ value: value }();
                  }
                  // Get actual held amount.
                  uint256 actualHeldAmount = heldAsset.balanceOf(address(this));
                  // Validate and possibly overwrite the source amount.
                  if (actualHeldAmount < minSourceAmount) {
                      revert Underfunded(actualHeldAmount, minSourceAmount);
                  } else if (actualHeldAmount > minSourceAmount) {
                      checkout.heldAmount = actualHeldAmount;
                  }
                  // Note: Using approve() instead of safeIncreaseAllowance() or forceApprove() under the
                  // assumption that all allowances from this contract will be zero in between transactions.
                  // We have a condition here if it is USDT, where we will perform a safeApprove as USDT does not return any value
                  if (block.chainid == 1 && address(heldAsset) == USDT_TOKEN) {
                      heldAsset.safeApprove(address(CHECKOUT_POOL), type(uint256).max);
                  } else {
                      heldAsset.approve(address(CHECKOUT_POOL), type(uint256).max);
                  }
                  // Make the external call, reverting on failure.
                  try CHECKOUT_POOL.deposit(checkout) {} catch (bytes memory errorData) {
                      revert ForwardError(errorData);
                  }
              }
          }
          // SPDX-License-Identifier: UNLICENSED
          pragma solidity ^0.8.13;
          import { Proxy } from "@openzeppelin/contracts/proxy/Proxy.sol";
          import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
          import {
              SafeERC20
          } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
          import { Create2ForwarderImpl } from "../forwarder/Create2ForwarderImpl.sol";
          import { WETH9Interface } from "../interfaces/WETH9Interface.sol";
          import { GuardianOwnable } from "../utils/GuardianOwnable.sol";
          import {
              CheckoutParams,
              CheckoutState
          } from "../interfaces/CheckoutPoolInterface.sol";
          /**
           * @title Create2ForwarderProxy
           * @author Fun.xyz
           *
           * @notice A forwarder contract proxy (a.k.a. “deposit address”) for the Checkout Pools protocol.
           *
           *  Intended to be deployed as a “counterfactual” contract.
           *
           *  See Create2ForwarderFactory and Create2ForwarderImpl for more info.
           */
          contract Create2ForwarderProxy is Proxy {
              using SafeERC20 for IERC20;
              Create2ForwarderImpl internal immutable IMPLEMENTATION;
              // Expand out the CheckoutState struct so that it can be stored as immutables.
              bytes32 public immutable USER_OP_HASH;
              uint96 public immutable TARGET_CHAIN_ID;
              bytes32 public immutable TARGET_ASSET;
              uint128 public immutable TARGET_AMOUNT;
              uint128 public immutable EXPIRATION;
              bytes32 public immutable RECIPIENT;
              IERC20 public immutable HELD_ASSET; // Here represents the source asset.
              uint256 public immutable HELD_AMOUNT; // Here represents the min source amount.
              receive() external payable override {}
              /**
               * @notice Proxy constructor.
               *
               *  Sets immutable values that are different between deployed proxy instances.
               *
               *  IMPORTANT: Include chain ID in the constructor to ensure that the deposit address is
               *  unique for all checkout operations globally. This reduces confusion and allows us to use
               *  the deposit address as a unique ID in off-chain services. Note that we include the
               *  chain ID as a constructor param instead of hashing it into the salt, for gas efficiency.
               *
               *  The heldAsset and heldAmount are included in the constructor to ensure that it is possible
               *  to prove whether a liquidity provider is censoring checkouts (differenting this from the
               *  case where checkouts are under-funded).
               */
              constructor(
                  Create2ForwarderImpl implementation,
                  CheckoutState memory checkout,
                  uint256 /* chainId */
              ) {
                  IMPLEMENTATION = implementation;
                  USER_OP_HASH = checkout.params.userOpHash;
                  TARGET_ASSET = checkout.params.targetAsset;
                  TARGET_CHAIN_ID = checkout.params.targetChainId;
                  TARGET_AMOUNT = checkout.params.targetAmount;
                  EXPIRATION = checkout.params.expiration;
                  RECIPIENT = checkout.params.recipient;
                  HELD_ASSET = checkout.heldAsset;
                  HELD_AMOUNT = checkout.heldAmount;
              }
              function getCheckout()
                  external
                  view
                  returns (CheckoutState memory checkout)
              {
                  return
                      CheckoutState({
                          params: CheckoutParams({
                              userOpHash: USER_OP_HASH,
                              targetAsset: TARGET_ASSET,
                              targetChainId: TARGET_CHAIN_ID,
                              targetAmount: TARGET_AMOUNT,
                              expiration: EXPIRATION,
                              recipient: RECIPIENT
                          }),
                          heldAsset: HELD_ASSET,
                          heldAmount: HELD_AMOUNT
                      });
              }
              function _implementation() internal view override returns (address) {
                  return address(IMPLEMENTATION);
              }
          }
          // SPDX-License-Identifier: GPL-3.0
          pragma solidity ^0.8.12;
          /* solhint-disable no-inline-assembly */
          import {calldataKeccak} from "../core/Helpers.sol";
          /**
           * User Operation struct
           * @param sender the sender account of this request.
               * @param nonce unique value the sender uses to verify it is not a replay.
               * @param initCode if set, the account contract will be created by this constructor/
               * @param callData the method call to execute on this account.
               * @param callGasLimit the gas limit passed to the callData method call.
               * @param verificationGasLimit gas used for validateUserOp and validatePaymasterUserOp.
               * @param preVerificationGas gas not calculated by the handleOps method, but added to the gas paid. Covers batch overhead.
               * @param maxFeePerGas same as EIP-1559 gas parameter.
               * @param maxPriorityFeePerGas same as EIP-1559 gas parameter.
               * @param paymasterAndData if set, this field holds the paymaster address and paymaster-specific data. the paymaster will pay for the transaction instead of the sender.
               * @param signature sender-verified signature over the entire request, the EntryPoint address and the chain ID.
               */
              struct UserOperation {
                  address sender;
                  uint256 nonce;
                  bytes initCode;
                  bytes callData;
                  uint256 callGasLimit;
                  uint256 verificationGasLimit;
                  uint256 preVerificationGas;
                  uint256 maxFeePerGas;
                  uint256 maxPriorityFeePerGas;
                  bytes paymasterAndData;
                  bytes signature;
              }
          /**
           * Utility functions helpful when working with UserOperation structs.
           */
          library UserOperationLib {
              function getSender(UserOperation calldata userOp) internal pure returns (address) {
                  address data;
                  //read sender from userOp, which is first userOp member (saves 800 gas...)
                  assembly {data := calldataload(userOp)}
                  return address(uint160(data));
              }
              //relayer/block builder might submit the TX with higher priorityFee, but the user should not
              // pay above what he signed for.
              function gasPrice(UserOperation calldata userOp) internal view returns (uint256) {
              unchecked {
                  uint256 maxFeePerGas = userOp.maxFeePerGas;
                  uint256 maxPriorityFeePerGas = userOp.maxPriorityFeePerGas;
                  if (maxFeePerGas == maxPriorityFeePerGas) {
                      //legacy mode (for networks that don't support basefee opcode)
                      return maxFeePerGas;
                  }
                  return min(maxFeePerGas, maxPriorityFeePerGas + block.basefee);
              }
              }
              function pack(UserOperation calldata userOp) internal pure returns (bytes memory ret) {
                  address sender = getSender(userOp);
                  uint256 nonce = userOp.nonce;
                  bytes32 hashInitCode = calldataKeccak(userOp.initCode);
                  bytes32 hashCallData = calldataKeccak(userOp.callData);
                  uint256 callGasLimit = userOp.callGasLimit;
                  uint256 verificationGasLimit = userOp.verificationGasLimit;
                  uint256 preVerificationGas = userOp.preVerificationGas;
                  uint256 maxFeePerGas = userOp.maxFeePerGas;
                  uint256 maxPriorityFeePerGas = userOp.maxPriorityFeePerGas;
                  bytes32 hashPaymasterAndData = calldataKeccak(userOp.paymasterAndData);
                  return abi.encode(
                      sender, nonce,
                      hashInitCode, hashCallData,
                      callGasLimit, verificationGasLimit, preVerificationGas,
                      maxFeePerGas, maxPriorityFeePerGas,
                      hashPaymasterAndData
                  );
              }
              function hash(UserOperation calldata userOp) internal pure returns (bytes32) {
                  return keccak256(pack(userOp));
              }
              function min(uint256 a, uint256 b) internal pure returns (uint256) {
                  return a < b ? a : b;
              }
          }
          // 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: UNLICENSED
          pragma solidity ^0.8.13;
          interface Create2ForwarderEventsAndErrors {
              error AlreadyForwarded();
              error ForwardError(bytes errorData);
              error Underfunded(uint256 actualHeldAmount, uint256 minSourceAmount);
          }
          // SPDX-License-Identifier: UNLICENSED
          pragma solidity ^0.8.13;
          import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
          import {
              SafeERC20
          } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
          /**
           * @title GuardianRescuable
           * @author Fun.xyz
           */
          abstract contract GuardianRescuable {
              using SafeERC20 for IERC20;
              error NotGuardian(address sender);
              modifier onlyGuardian() {
                  if (msg.sender != guardian()) {
                      revert NotGuardian(msg.sender);
                  }
                  _;
              }
              function guardian() public virtual returns (address);
              function withdrawNative(
                  address payable recipient,
                  uint256 amount
              ) external onlyGuardian {
                  recipient.transfer(amount);
              }
              function withdrawErc20(
                  IERC20 token,
                  address recipient,
                  uint256 amount
              ) external onlyGuardian {
                  token.safeTransfer(recipient, amount);
              }
              function withdrawAllNative(
                  address payable recipient
              ) external onlyGuardian {
                  recipient.transfer(address(this).balance);
              }
              function withdrawAllErc20(
                  IERC20 token,
                  address recipient
              ) external onlyGuardian {
                  uint256 balance = token.balanceOf(address(this));
                  token.safeTransfer(recipient, balance);
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
           * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
           * be specified by overriding the virtual {_implementation} function.
           *
           * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
           * different contract through the {_delegate} function.
           *
           * The success and return data of the delegated call will be returned back to the caller of the proxy.
           */
          abstract contract Proxy {
              /**
               * @dev Delegates the current call to `implementation`.
               *
               * This function does not return to its internal call site, it will return directly to the external caller.
               */
              function _delegate(address implementation) internal virtual {
                  assembly {
                      // Copy msg.data. We take full control of memory in this inline assembly
                      // block because it will not return to Solidity code. We overwrite the
                      // Solidity scratch pad at memory position 0.
                      calldatacopy(0, 0, calldatasize())
                      // Call the implementation.
                      // out and outsize are 0 because we don't know the size yet.
                      let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
                      // Copy the returned data.
                      returndatacopy(0, 0, returndatasize())
                      switch result
                      // delegatecall returns 0 on error.
                      case 0 {
                          revert(0, returndatasize())
                      }
                      default {
                          return(0, returndatasize())
                      }
                  }
              }
              /**
               * @dev This is a virtual function that should be overridden so it returns the address to which the fallback function
               * and {_fallback} should delegate.
               */
              function _implementation() internal view virtual returns (address);
              /**
               * @dev Delegates the current call to the address returned by `_implementation()`.
               *
               * This function does not return to its internal call site, it will return directly to the external caller.
               */
              function _fallback() internal virtual {
                  _beforeFallback();
                  _delegate(_implementation());
              }
              /**
               * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
               * function in the contract matches the call data.
               */
              fallback() external payable virtual {
                  _fallback();
              }
              /**
               * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
               * is empty.
               */
              receive() external payable virtual {
                  _fallback();
              }
              /**
               * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
               * call, or as part of the Solidity `fallback` or `receive` functions.
               *
               * If overridden should call `super._beforeFallback()`.
               */
              function _beforeFallback() internal virtual {}
          }
          // SPDX-License-Identifier: UNLICENSED
          pragma solidity ^0.8.13;
          import { Ownable2Step } from "@openzeppelin/contracts/access/Ownable2Step.sol";
          import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
          import { GuardianRescuable } from "./GuardianRescuable.sol";
          /**
           * @title GuardianOwnable
           * @author Fun.xyz
           */
          abstract contract GuardianOwnable is Ownable2Step, GuardianRescuable {
              error RenounceDisabled();
              function guardian() public view override returns (address) {
                  return owner();
              }
              function renounceOwnership() public view override onlyOwner {
                  revert RenounceDisabled();
              }
          }
          // SPDX-License-Identifier: GPL-3.0
          pragma solidity ^0.8.12;
          /* solhint-disable no-inline-assembly */
          /**
           * returned data from validateUserOp.
           * validateUserOp returns a uint256, with is created by `_packedValidationData` and parsed by `_parseValidationData`
           * @param aggregator - address(0) - the account validated the signature by itself.
           *              address(1) - the account failed to validate the signature.
           *              otherwise - this is an address of a signature aggregator that must be used to validate the signature.
           * @param validAfter - this UserOp is valid only after this timestamp.
           * @param validaUntil - this UserOp is valid only up to this timestamp.
           */
              struct ValidationData {
                  address aggregator;
                  uint48 validAfter;
                  uint48 validUntil;
              }
          //extract sigFailed, validAfter, validUntil.
          // also convert zero validUntil to type(uint48).max
              function _parseValidationData(uint validationData) pure returns (ValidationData memory data) {
                  address aggregator = address(uint160(validationData));
                  uint48 validUntil = uint48(validationData >> 160);
                  if (validUntil == 0) {
                      validUntil = type(uint48).max;
                  }
                  uint48 validAfter = uint48(validationData >> (48 + 160));
                  return ValidationData(aggregator, validAfter, validUntil);
              }
          // intersect account and paymaster ranges.
              function _intersectTimeRange(uint256 validationData, uint256 paymasterValidationData) pure returns (ValidationData memory) {
                  ValidationData memory accountValidationData = _parseValidationData(validationData);
                  ValidationData memory pmValidationData = _parseValidationData(paymasterValidationData);
                  address aggregator = accountValidationData.aggregator;
                  if (aggregator == address(0)) {
                      aggregator = pmValidationData.aggregator;
                  }
                  uint48 validAfter = accountValidationData.validAfter;
                  uint48 validUntil = accountValidationData.validUntil;
                  uint48 pmValidAfter = pmValidationData.validAfter;
                  uint48 pmValidUntil = pmValidationData.validUntil;
                  if (validAfter < pmValidAfter) validAfter = pmValidAfter;
                  if (validUntil > pmValidUntil) validUntil = pmValidUntil;
                  return ValidationData(aggregator, validAfter, validUntil);
              }
          /**
           * helper to pack the return value for validateUserOp
           * @param data - the ValidationData to pack
           */
              function _packValidationData(ValidationData memory data) pure returns (uint256) {
                  return uint160(data.aggregator) | (uint256(data.validUntil) << 160) | (uint256(data.validAfter) << (160 + 48));
              }
          /**
           * helper to pack the return value for validateUserOp, when not using an aggregator
           * @param sigFailed - true for signature failure, false for success
           * @param validUntil last timestamp this UserOperation is valid (or zero for infinite)
           * @param validAfter first timestamp this UserOperation is valid
           */
              function _packValidationData(bool sigFailed, uint48 validUntil, uint48 validAfter) pure returns (uint256) {
                  return (sigFailed ? 1 : 0) | (uint256(validUntil) << 160) | (uint256(validAfter) << (160 + 48));
              }
          /**
           * keccak function over calldata.
           * @dev copy calldata into memory, do keccak and drop allocated memory. Strangely, this is more efficient than letting solidity do it.
           */
              function calldataKeccak(bytes calldata data) pure returns (bytes32 ret) {
                  assembly {
                      let mem := mload(0x40)
                      let len := data.length
                      calldatacopy(mem, data.offset, len)
                      ret := keccak256(mem, len)
                  }
              }
          // 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) (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.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.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 v4.4.1 (utils/Context.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev Provides information about the current execution context, including the
           * sender of the transaction and its data. While these are generally available
           * via msg.sender and msg.data, they should not be accessed in such a direct
           * manner, since when dealing with meta-transactions the account sending and
           * paying for execution may not be the actual sender (as far as an application
           * is concerned).
           *
           * This contract is only required for intermediate, library-like contracts.
           */
          abstract contract Context {
              function _msgSender() internal view virtual returns (address) {
                  return msg.sender;
              }
              function _msgData() internal view virtual returns (bytes calldata) {
                  return msg.data;
              }
          }
          

          File 2 of 4: GraphToken
          // Sources flattened with hardhat v2.0.2 https://hardhat.org
          
          // File @openzeppelin/contracts/GSN/Context.sol@v3.3.0-solc-0.7
          
          // SPDX-License-Identifier: MIT
          
          pragma solidity ^0.7.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 GSN 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 payable) {
                  return msg.sender;
              }
          
              function _msgData() internal view virtual returns (bytes memory) {
                  this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
                  return msg.data;
              }
          }
          
          
          // File @openzeppelin/contracts/token/ERC20/IERC20.sol@v3.3.0-solc-0.7
          
          pragma solidity ^0.7.0;
          
          /**
           * @dev Interface of the ERC20 standard as defined in the EIP.
           */
          interface IERC20 {
              /**
               * @dev Returns the amount of tokens in existence.
               */
              function totalSupply() external view returns (uint256);
          
              /**
               * @dev Returns the amount of tokens owned by `account`.
               */
              function balanceOf(address account) external view returns (uint256);
          
              /**
               * @dev Moves `amount` tokens from the caller's account to `recipient`.
               *
               * Returns a boolean value indicating whether the operation succeeded.
               *
               * Emits a {Transfer} event.
               */
              function transfer(address recipient, uint256 amount) external returns (bool);
          
              /**
               * @dev Returns the remaining number of tokens that `spender` will be
               * allowed to spend on behalf of `owner` through {transferFrom}. This is
               * zero by default.
               *
               * This value changes when {approve} or {transferFrom} are called.
               */
              function allowance(address owner, address spender) external view returns (uint256);
          
              /**
               * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
               *
               * Returns a boolean value indicating whether the operation succeeded.
               *
               * IMPORTANT: Beware that changing an allowance with this method brings the risk
               * that someone may use both the old and the new allowance by unfortunate
               * transaction ordering. One possible solution to mitigate this race
               * condition is to first reduce the spender's allowance to 0 and set the
               * desired value afterwards:
               * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
               *
               * Emits an {Approval} event.
               */
              function approve(address spender, uint256 amount) external returns (bool);
          
              /**
               * @dev Moves `amount` tokens from `sender` to `recipient` using the
               * allowance mechanism. `amount` is then deducted from the caller's
               * allowance.
               *
               * Returns a boolean value indicating whether the operation succeeded.
               *
               * Emits a {Transfer} event.
               */
              function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
          
              /**
               * @dev Emitted when `value` tokens are moved from one account (`from`) to
               * another (`to`).
               *
               * Note that `value` may be zero.
               */
              event Transfer(address indexed from, address indexed to, uint256 value);
          
              /**
               * @dev Emitted when the allowance of a `spender` for an `owner` is set by
               * a call to {approve}. `value` is the new allowance.
               */
              event Approval(address indexed owner, address indexed spender, uint256 value);
          }
          
          
          // File @openzeppelin/contracts/math/SafeMath.sol@v3.3.0-solc-0.7
          
          pragma solidity ^0.7.0;
          
          /**
           * @dev Wrappers over Solidity's arithmetic operations with added overflow
           * checks.
           *
           * Arithmetic operations in Solidity wrap on overflow. This can easily result
           * in bugs, because programmers usually assume that an overflow raises an
           * error, which is the standard behavior in high level programming languages.
           * `SafeMath` restores this intuition by reverting the transaction when an
           * operation overflows.
           *
           * Using this library instead of the unchecked operations eliminates an entire
           * class of bugs, so it's recommended to use it always.
           */
          library SafeMath {
              /**
               * @dev Returns the addition of two unsigned integers, reverting on
               * overflow.
               *
               * Counterpart to Solidity's `+` operator.
               *
               * Requirements:
               *
               * - Addition cannot overflow.
               */
              function add(uint256 a, uint256 b) internal pure returns (uint256) {
                  uint256 c = a + b;
                  require(c >= a, "SafeMath: addition overflow");
          
                  return c;
              }
          
              /**
               * @dev Returns the subtraction of two unsigned integers, reverting on
               * overflow (when the result is negative).
               *
               * Counterpart to Solidity's `-` operator.
               *
               * Requirements:
               *
               * - Subtraction cannot overflow.
               */
              function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                  return sub(a, b, "SafeMath: subtraction overflow");
              }
          
              /**
               * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
               * overflow (when the result is negative).
               *
               * Counterpart to Solidity's `-` operator.
               *
               * Requirements:
               *
               * - Subtraction cannot overflow.
               */
              function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                  require(b <= a, errorMessage);
                  uint256 c = a - b;
          
                  return c;
              }
          
              /**
               * @dev Returns the multiplication of two unsigned integers, reverting on
               * overflow.
               *
               * Counterpart to Solidity's `*` operator.
               *
               * Requirements:
               *
               * - Multiplication cannot overflow.
               */
              function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                  // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
                  // benefit is lost if 'b' is also tested.
                  // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
                  if (a == 0) {
                      return 0;
                  }
          
                  uint256 c = a * b;
                  require(c / a == b, "SafeMath: multiplication overflow");
          
                  return c;
              }
          
              /**
               * @dev Returns the integer division of two unsigned integers. Reverts on
               * division by zero. The result is rounded towards zero.
               *
               * Counterpart to Solidity's `/` operator. Note: this function uses a
               * `revert` opcode (which leaves remaining gas untouched) while Solidity
               * uses an invalid opcode to revert (consuming all remaining gas).
               *
               * Requirements:
               *
               * - The divisor cannot be zero.
               */
              function div(uint256 a, uint256 b) internal pure returns (uint256) {
                  return div(a, b, "SafeMath: division by zero");
              }
          
              /**
               * @dev Returns the integer division of two unsigned integers. Reverts with custom message on
               * division by zero. The result is rounded towards zero.
               *
               * Counterpart to Solidity's `/` operator. Note: this function uses a
               * `revert` opcode (which leaves remaining gas untouched) while Solidity
               * uses an invalid opcode to revert (consuming all remaining gas).
               *
               * Requirements:
               *
               * - The divisor cannot be zero.
               */
              function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                  require(b > 0, errorMessage);
                  uint256 c = a / b;
                  // assert(a == b * c + a % b); // There is no case in which this doesn't hold
          
                  return c;
              }
          
              /**
               * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
               * Reverts when dividing by zero.
               *
               * Counterpart to Solidity's `%` operator. This function uses a `revert`
               * opcode (which leaves remaining gas untouched) while Solidity uses an
               * invalid opcode to revert (consuming all remaining gas).
               *
               * Requirements:
               *
               * - The divisor cannot be zero.
               */
              function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                  return mod(a, b, "SafeMath: modulo by zero");
              }
          
              /**
               * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
               * Reverts with custom message when dividing by zero.
               *
               * Counterpart to Solidity's `%` operator. This function uses a `revert`
               * opcode (which leaves remaining gas untouched) while Solidity uses an
               * invalid opcode to revert (consuming all remaining gas).
               *
               * Requirements:
               *
               * - The divisor cannot be zero.
               */
              function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                  require(b != 0, errorMessage);
                  return a % b;
              }
          }
          
          
          // File @openzeppelin/contracts/token/ERC20/ERC20.sol@v3.3.0-solc-0.7
          
          pragma solidity ^0.7.0;
          
          
          
          /**
           * @dev Implementation of the {IERC20} interface.
           *
           * This implementation is agnostic to the way tokens are created. This means
           * that a supply mechanism has to be added in a derived contract using {_mint}.
           * For a generic mechanism see {ERC20PresetMinterPauser}.
           *
           * TIP: For a detailed writeup see our guide
           * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
           * to implement supply mechanisms].
           *
           * We have followed general OpenZeppelin guidelines: functions revert instead
           * of returning `false` on failure. This behavior is nonetheless conventional
           * and does not conflict with the expectations of ERC20 applications.
           *
           * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
           * This allows applications to reconstruct the allowance for all accounts just
           * by listening to said events. Other implementations of the EIP may not emit
           * these events, as it isn't required by the specification.
           *
           * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
           * functions have been added to mitigate the well-known issues around setting
           * allowances. See {IERC20-approve}.
           */
          contract ERC20 is Context, IERC20 {
              using SafeMath for uint256;
          
              mapping (address => uint256) private _balances;
          
              mapping (address => mapping (address => uint256)) private _allowances;
          
              uint256 private _totalSupply;
          
              string private _name;
              string private _symbol;
              uint8 private _decimals;
          
              /**
               * @dev Sets the values for {name} and {symbol}, initializes {decimals} with
               * a default value of 18.
               *
               * To select a different value for {decimals}, use {_setupDecimals}.
               *
               * All three of these values are immutable: they can only be set once during
               * construction.
               */
              constructor (string memory name_, string memory symbol_) {
                  _name = name_;
                  _symbol = symbol_;
                  _decimals = 18;
              }
          
              /**
               * @dev Returns the name of the token.
               */
              function name() public view returns (string memory) {
                  return _name;
              }
          
              /**
               * @dev Returns the symbol of the token, usually a shorter version of the
               * name.
               */
              function symbol() public view returns (string memory) {
                  return _symbol;
              }
          
              /**
               * @dev Returns the number of decimals used to get its user representation.
               * For example, if `decimals` equals `2`, a balance of `505` tokens should
               * be displayed to a user as `5,05` (`505 / 10 ** 2`).
               *
               * Tokens usually opt for a value of 18, imitating the relationship between
               * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
               * called.
               *
               * NOTE: This information is only used for _display_ purposes: it in
               * no way affects any of the arithmetic of the contract, including
               * {IERC20-balanceOf} and {IERC20-transfer}.
               */
              function decimals() public view returns (uint8) {
                  return _decimals;
              }
          
              /**
               * @dev See {IERC20-totalSupply}.
               */
              function totalSupply() public view override returns (uint256) {
                  return _totalSupply;
              }
          
              /**
               * @dev See {IERC20-balanceOf}.
               */
              function balanceOf(address account) public view override returns (uint256) {
                  return _balances[account];
              }
          
              /**
               * @dev See {IERC20-transfer}.
               *
               * Requirements:
               *
               * - `recipient` cannot be the zero address.
               * - the caller must have a balance of at least `amount`.
               */
              function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
                  _transfer(_msgSender(), recipient, amount);
                  return true;
              }
          
              /**
               * @dev See {IERC20-allowance}.
               */
              function allowance(address owner, address spender) public view virtual override returns (uint256) {
                  return _allowances[owner][spender];
              }
          
              /**
               * @dev See {IERC20-approve}.
               *
               * Requirements:
               *
               * - `spender` cannot be the zero address.
               */
              function approve(address spender, uint256 amount) public virtual override returns (bool) {
                  _approve(_msgSender(), spender, amount);
                  return true;
              }
          
              /**
               * @dev See {IERC20-transferFrom}.
               *
               * Emits an {Approval} event indicating the updated allowance. This is not
               * required by the EIP. See the note at the beginning of {ERC20}.
               *
               * Requirements:
               *
               * - `sender` and `recipient` cannot be the zero address.
               * - `sender` must have a balance of at least `amount`.
               * - the caller must have allowance for ``sender``'s tokens of at least
               * `amount`.
               */
              function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
                  _transfer(sender, recipient, amount);
                  _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
                  return true;
              }
          
              /**
               * @dev Atomically increases the allowance granted to `spender` by the caller.
               *
               * This is an alternative to {approve} that can be used as a mitigation for
               * problems described in {IERC20-approve}.
               *
               * Emits an {Approval} event indicating the updated allowance.
               *
               * Requirements:
               *
               * - `spender` cannot be the zero address.
               */
              function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
                  _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
                  return true;
              }
          
              /**
               * @dev Atomically decreases the allowance granted to `spender` by the caller.
               *
               * This is an alternative to {approve} that can be used as a mitigation for
               * problems described in {IERC20-approve}.
               *
               * Emits an {Approval} event indicating the updated allowance.
               *
               * Requirements:
               *
               * - `spender` cannot be the zero address.
               * - `spender` must have allowance for the caller of at least
               * `subtractedValue`.
               */
              function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
                  _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
                  return true;
              }
          
              /**
               * @dev Moves tokens `amount` from `sender` to `recipient`.
               *
               * This is internal function is equivalent to {transfer}, and can be used to
               * e.g. implement automatic token fees, slashing mechanisms, etc.
               *
               * Emits a {Transfer} event.
               *
               * Requirements:
               *
               * - `sender` cannot be the zero address.
               * - `recipient` cannot be the zero address.
               * - `sender` must have a balance of at least `amount`.
               */
              function _transfer(address sender, address recipient, uint256 amount) internal virtual {
                  require(sender != address(0), "ERC20: transfer from the zero address");
                  require(recipient != address(0), "ERC20: transfer to the zero address");
          
                  _beforeTokenTransfer(sender, recipient, amount);
          
                  _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
                  _balances[recipient] = _balances[recipient].add(amount);
                  emit Transfer(sender, recipient, amount);
              }
          
              /** @dev Creates `amount` tokens and assigns them to `account`, increasing
               * the total supply.
               *
               * Emits a {Transfer} event with `from` set to the zero address.
               *
               * Requirements:
               *
               * - `to` cannot be the zero address.
               */
              function _mint(address account, uint256 amount) internal virtual {
                  require(account != address(0), "ERC20: mint to the zero address");
          
                  _beforeTokenTransfer(address(0), account, amount);
          
                  _totalSupply = _totalSupply.add(amount);
                  _balances[account] = _balances[account].add(amount);
                  emit Transfer(address(0), account, amount);
              }
          
              /**
               * @dev Destroys `amount` tokens from `account`, reducing the
               * total supply.
               *
               * Emits a {Transfer} event with `to` set to the zero address.
               *
               * Requirements:
               *
               * - `account` cannot be the zero address.
               * - `account` must have at least `amount` tokens.
               */
              function _burn(address account, uint256 amount) internal virtual {
                  require(account != address(0), "ERC20: burn from the zero address");
          
                  _beforeTokenTransfer(account, address(0), amount);
          
                  _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
                  _totalSupply = _totalSupply.sub(amount);
                  emit Transfer(account, address(0), amount);
              }
          
              /**
               * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
               *
               * This internal function is equivalent to `approve`, and can be used to
               * e.g. set automatic allowances for certain subsystems, etc.
               *
               * Emits an {Approval} event.
               *
               * Requirements:
               *
               * - `owner` cannot be the zero address.
               * - `spender` cannot be the zero address.
               */
              function _approve(address owner, address spender, uint256 amount) internal virtual {
                  require(owner != address(0), "ERC20: approve from the zero address");
                  require(spender != address(0), "ERC20: approve to the zero address");
          
                  _allowances[owner][spender] = amount;
                  emit Approval(owner, spender, amount);
              }
          
              /**
               * @dev Sets {decimals} to a value other than the default one of 18.
               *
               * WARNING: This function should only be called from the constructor. Most
               * applications that interact with token contracts will not expect
               * {decimals} to ever change, and may work incorrectly if it does.
               */
              function _setupDecimals(uint8 decimals_) internal {
                  _decimals = decimals_;
              }
          
              /**
               * @dev Hook that is called before any transfer of tokens. This includes
               * minting and burning.
               *
               * Calling conditions:
               *
               * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
               * will be to transferred to `to`.
               * - when `from` is zero, `amount` tokens will be minted for `to`.
               * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
               * - `from` and `to` are never both zero.
               *
               * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
               */
              function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
          }
          
          
          // File @openzeppelin/contracts/token/ERC20/ERC20Burnable.sol@v3.3.0-solc-0.7
          
          pragma solidity ^0.7.0;
          
          
          /**
           * @dev Extension of {ERC20} that allows token holders to destroy both their own
           * tokens and those that they have an allowance for, in a way that can be
           * recognized off-chain (via event analysis).
           */
          abstract contract ERC20Burnable is Context, ERC20 {
              using SafeMath for uint256;
          
              /**
               * @dev Destroys `amount` tokens from the caller.
               *
               * See {ERC20-_burn}.
               */
              function burn(uint256 amount) public virtual {
                  _burn(_msgSender(), amount);
              }
          
              /**
               * @dev Destroys `amount` tokens from `account`, deducting from the caller's
               * allowance.
               *
               * See {ERC20-_burn} and {ERC20-allowance}.
               *
               * Requirements:
               *
               * - the caller must have allowance for ``accounts``'s tokens of at least
               * `amount`.
               */
              function burnFrom(address account, uint256 amount) public virtual {
                  uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
          
                  _approve(account, _msgSender(), decreasedAllowance);
                  _burn(account, amount);
              }
          }
          
          
          // File @openzeppelin/contracts/cryptography/ECDSA.sol@v3.3.0-solc-0.7
          
          pragma solidity ^0.7.0;
          
          /**
           * @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 {
              /**
               * @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) {
                  // Check the signature length
                  if (signature.length != 65) {
                      revert("ECDSA: invalid signature length");
                  }
          
                  // Divide the signature in r, s and v variables
                  bytes32 r;
                  bytes32 s;
                  uint8 v;
          
                  // ecrecover takes the signature parameters, and the only way to get them
                  // currently is to use assembly.
                  // solhint-disable-next-line no-inline-assembly
                  assembly {
                      r := mload(add(signature, 0x20))
                      s := mload(add(signature, 0x40))
                      v := byte(0, mload(add(signature, 0x60)))
                  }
          
                  // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
                  // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
                  // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
                  // signatures from current libraries generate a unique signature with an s-value in the lower half order.
                  //
                  // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
                  // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
                  // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
                  // these malleable signatures as well.
                  require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
                  require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
          
                  // If the signature is valid (and not malleable), return the signer address
                  address signer = ecrecover(hash, v, r, s);
                  require(signer != address(0), "ECDSA: invalid signature");
          
                  return signer;
              }
          
              /**
               * @dev Returns an Ethereum Signed Message, created from a `hash`. This
               * replicates the behavior of the
               * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
               * JSON-RPC method.
               *
               * See {recover}.
               */
              function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
                  // 32 is the length in bytes of hash,
                  // enforced by the type signature above
                  return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
              }
          }
          
          
          // File contracts/governance/Governed.sol
          
          pragma solidity ^0.7.3;
          
          /**
           * @title Graph Governance contract
           * @dev All contracts that will be owned by a Governor entity should extend this contract.
           */
          contract Governed {
              // -- State --
          
              address public governor;
              address public pendingGovernor;
          
              // -- Events --
          
              event NewPendingOwnership(address indexed from, address indexed to);
              event NewOwnership(address indexed from, address indexed to);
          
              /**
               * @dev Check if the caller is the governor.
               */
              modifier onlyGovernor {
                  require(msg.sender == governor, "Only Governor can call");
                  _;
              }
          
              /**
               * @dev Initialize the governor to the contract caller.
               */
              function _initialize(address _initGovernor) internal {
                  governor = _initGovernor;
              }
          
              /**
               * @dev Admin function to begin change of governor. The `_newGovernor` must call
               * `acceptOwnership` to finalize the transfer.
               * @param _newGovernor Address of new `governor`
               */
              function transferOwnership(address _newGovernor) external onlyGovernor {
                  require(_newGovernor != address(0), "Governor must be set");
          
                  address oldPendingGovernor = pendingGovernor;
                  pendingGovernor = _newGovernor;
          
                  emit NewPendingOwnership(oldPendingGovernor, pendingGovernor);
              }
          
              /**
               * @dev Admin function for pending governor to accept role and update governor.
               * This function must called by the pending governor.
               */
              function acceptOwnership() external {
                  require(
                      pendingGovernor != address(0) && msg.sender == pendingGovernor,
                      "Caller must be pending governor"
                  );
          
                  address oldGovernor = governor;
                  address oldPendingGovernor = pendingGovernor;
          
                  governor = pendingGovernor;
                  pendingGovernor = address(0);
          
                  emit NewOwnership(oldGovernor, governor);
                  emit NewPendingOwnership(oldPendingGovernor, pendingGovernor);
              }
          }
          
          
          // File contracts/token/GraphToken.sol
          
          pragma solidity ^0.7.3;
          
          
          
          
          /**
           * @title GraphToken contract
           * @dev This is the implementation of the ERC20 Graph Token.
           * The implementation exposes a Permit() function to allow for a spender to send a signed message
           * and approve funds to a spender following EIP2612 to make integration with other contracts easier.
           *
           * The token is initially owned by the deployer address that can mint tokens to create the initial
           * distribution. For convenience, an initial supply can be passed in the constructor that will be
           * assigned to the deployer.
           *
           * The governor can add the RewardsManager contract to mint indexing rewards.
           *
           */
          contract GraphToken is Governed, ERC20, ERC20Burnable {
              using SafeMath for uint256;
          
              // -- EIP712 --
              // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md#definition-of-domainseparator
          
              bytes32 private constant DOMAIN_TYPE_HASH = keccak256(
                  "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)"
              );
              bytes32 private constant DOMAIN_NAME_HASH = keccak256("Graph Token");
              bytes32 private constant DOMAIN_VERSION_HASH = keccak256("0");
              bytes32
                  private constant DOMAIN_SALT = 0x51f3d585afe6dfeb2af01bba0889a36c1db03beec88c6a4d0c53817069026afa; // Randomly generated salt
              bytes32 private constant PERMIT_TYPEHASH = keccak256(
                  "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
              );
          
              // -- State --
          
              bytes32 private DOMAIN_SEPARATOR;
              mapping(address => bool) private _minters;
              mapping(address => uint256) public nonces;
          
              // -- Events --
          
              event MinterAdded(address indexed account);
              event MinterRemoved(address indexed account);
          
              modifier onlyMinter() {
                  require(isMinter(msg.sender), "Only minter can call");
                  _;
              }
          
              /**
               * @dev Graph Token Contract Constructor.
               * @param _initialSupply Initial supply of GRT
               */
              constructor(uint256 _initialSupply) ERC20("Graph Token", "GRT") {
                  Governed._initialize(msg.sender);
          
                  // The Governor has the initial supply of tokens
                  _mint(msg.sender, _initialSupply);
          
                  // The Governor is the default minter
                  _addMinter(msg.sender);
          
                  // EIP-712 domain separator
                  DOMAIN_SEPARATOR = keccak256(
                      abi.encode(
                          DOMAIN_TYPE_HASH,
                          DOMAIN_NAME_HASH,
                          DOMAIN_VERSION_HASH,
                          _getChainID(),
                          address(this),
                          DOMAIN_SALT
                      )
                  );
              }
          
              /**
               * @dev Approve token allowance by validating a message signed by the holder.
               * @param _owner Address of the token holder
               * @param _spender Address of the approved spender
               * @param _value Amount of tokens to approve the spender
               * @param _deadline Expiration time of the signed permit
               * @param _v Signature version
               * @param _r Signature r value
               * @param _s Signature s value
               */
              function permit(
                  address _owner,
                  address _spender,
                  uint256 _value,
                  uint256 _deadline,
                  uint8 _v,
                  bytes32 _r,
                  bytes32 _s
              ) external {
                  bytes32 digest = keccak256(
                      abi.encodePacked(
                          "\x19\x01",
                          DOMAIN_SEPARATOR,
                          keccak256(
                              abi.encode(
                                  PERMIT_TYPEHASH,
                                  _owner,
                                  _spender,
                                  _value,
                                  nonces[_owner],
                                  _deadline
                              )
                          )
                      )
                  );
                  nonces[_owner] = nonces[_owner].add(1);
          
                  address recoveredAddress = ECDSA.recover(digest, abi.encodePacked(_r, _s, _v));
                  require(_owner == recoveredAddress, "GRT: invalid permit");
                  require(_deadline == 0 || block.timestamp <= _deadline, "GRT: expired permit");
          
                  _approve(_owner, _spender, _value);
              }
          
              /**
               * @dev Add a new minter.
               * @param _account Address of the minter
               */
              function addMinter(address _account) external onlyGovernor {
                  _addMinter(_account);
              }
          
              /**
               * @dev Remove a minter.
               * @param _account Address of the minter
               */
              function removeMinter(address _account) external onlyGovernor {
                  _removeMinter(_account);
              }
          
              /**
               * @dev Renounce to be a minter.
               */
              function renounceMinter() external {
                  _removeMinter(msg.sender);
              }
          
              /**
               * @dev Mint new tokens.
               * @param _to Address to send the newly minted tokens
               * @param _amount Amount of tokens to mint
               */
              function mint(address _to, uint256 _amount) external onlyMinter {
                  _mint(_to, _amount);
              }
          
              /**
               * @dev Return if the `_account` is a minter or not.
               * @param _account Address to check
               * @return True if the `_account` is minter
               */
              function isMinter(address _account) public view returns (bool) {
                  return _minters[_account];
              }
          
              /**
               * @dev Add a new minter.
               * @param _account Address of the minter
               */
              function _addMinter(address _account) private {
                  _minters[_account] = true;
                  emit MinterAdded(_account);
              }
          
              /**
               * @dev Remove a minter.
               * @param _account Address of the minter
               */
              function _removeMinter(address _account) private {
                  _minters[_account] = false;
                  emit MinterRemoved(_account);
              }
          
              /**
               * @dev Get the running network chain ID.
               * @return The chain ID
               */
              function _getChainID() private pure returns (uint256) {
                  uint256 id;
                  assembly {
                      id := chainid()
                  }
                  return id;
              }
          }

          File 3 of 4: CheckoutPool
          // SPDX-License-Identifier: UNLICENSED
          pragma solidity ^0.8.13;
          import {
              SimpleAccount
          } from "@account-abstraction/contracts/samples/SimpleAccount.sol";
          import {
              IEntryPoint
          } from "@account-abstraction/contracts/interfaces/IEntryPoint.sol";
          import {
              IPaymaster
          } from "@account-abstraction/contracts/interfaces/IPaymaster.sol";
          import {
              UserOperation
          } from "@account-abstraction/contracts/interfaces/UserOperation.sol";
          import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
          import {
              SafeERC20
          } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
          import {
              Create2ForwarderFactory
          } from "./forwarder/Create2ForwarderFactory.sol";
          import {
              BridgeParams,
              CheckoutPoolInterface,
              CheckoutState,
              SwapParams
          } from "./interfaces/CheckoutPoolInterface.sol";
          import {
              CheckoutPoolEventsAndErrors
          } from "./interfaces/CheckoutPoolEventsAndErrors.sol";
          import {
              InspectablePaymasterInterface
          } from "./interfaces/InspectablePaymasterInterface.sol";
          import { CheckoutPaymaster } from "./paymaster/CheckoutPaymaster.sol";
          import { GuardianOwnable } from "./utils/GuardianOwnable.sol";
          import { WETH9Interface } from "./interfaces/WETH9Interface.sol";
          contract CheckoutPool is
              GuardianOwnable,
              CheckoutPoolInterface,
              CheckoutPoolEventsAndErrors
          {
              using SafeERC20 for IERC20;
              uint256 public timelockDuration = 1 days;
              IEntryPoint public immutable ENTRY_POINT;
              WETH9Interface public immutable WRAPPED_NATIVE_TOKEN;
              address public immutable NATIVE_TOKEN =
                  address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
              address public immutable USDT_TOKEN =
                  address(0xdAC17F958D2ee523a2206206994597C13D831ec7);    
              Create2ForwarderFactory public FORWARDER_FACTORY;
              address public operator;
              address public paymaster;
              bool public _ALLOW_ALL_;
              mapping(address target => bool isAllowed) public _ALLOWED_SWAP_TARGETS_;
              mapping(address target => bool isAllowed) public _ALLOWED_BRIDGE_TARGETS_;
              mapping(uint256 chainId => bool isAllowed) public _ALLOWED_CHAIN_IDS_;
              mapping(IERC20 asset => uint256 excessAmount) public _POOL_EXCESS_;
              mapping(bytes32 => uint256) public _TIMELOCK_EXPIRATION_;
              /// @dev Active checkout accounts.
              mapping(address depositAddress => CheckoutState checkout)
                  internal _CHECKOUTS_;
              modifier allowedSwapTarget(address target) {
                  if (!(_ALLOW_ALL_ || _ALLOWED_SWAP_TARGETS_[target])) {
                      revert SwapTargetNotAllowed(target);
                  }
                  _;
              }
              modifier allowedBridgeTarget(address target) {
                  if (!(_ALLOW_ALL_ || _ALLOWED_BRIDGE_TARGETS_[target])) {
                      revert BridgeTargetNotAllowed(target);
                  }
                  _;
              }
              modifier notExpired(uint256 expiration) {
                  if (block.timestamp >= expiration) {
                      revert CheckoutExpired();
                  }
                  _;
              }
              modifier Timelock() {
                  bytes32 hash = getCallHash(msg.sender, msg.data);
                  uint256 expiration = _TIMELOCK_EXPIRATION_[hash];
                  if (expiration == 0) {
                      _TIMELOCK_EXPIRATION_[hash] = block.timestamp + timelockDuration;
                  } else if (block.timestamp < expiration) {
                      revert TimelockNotExpired(hash, expiration);
                  } else {
                      delete _TIMELOCK_EXPIRATION_[hash];
                      _;
                  }
              }
              modifier onlyOperator() {
                  if (msg.sender != operator) {
                      revert OnlyOperatorAllowed(msg.sender, operator);
                  }
                  _;
              }
              modifier onlyPaymaster() {
                  if (msg.sender != paymaster) {
                      revert OnlyPaymasterAllowed(msg.sender, paymaster);
                  }
                  _;
              }
              receive() external payable {}
              constructor(
                  address guardian,
                  IEntryPoint entryPoint,
                  WETH9Interface wrappedNativeToken
              ) {
                  _transferOwnership(guardian);
                  ENTRY_POINT = entryPoint;
                  WRAPPED_NATIVE_TOKEN = wrappedNativeToken;
                  paymaster = address(0);
              }
              function setAllowAll(bool isAllowed) external onlyOwner {
                  _ALLOW_ALL_ = isAllowed;
              }
              function setTimelockDuration(uint256 duration) external onlyOwner {
                  timelockDuration = duration;
              }
              function setForwarderFactory(
                  Create2ForwarderFactory fowarderFactory
              ) external onlyOwner {
                  FORWARDER_FACTORY = fowarderFactory;
              }
              function setPaymaster(address newPaymaster) external onlyOwner {
                  paymaster = newPaymaster;
              }
              function addAllowedSwapTargets(
                  address[] calldata targets
              ) external onlyOwner Timelock {
                  _updateAllowedSwapTargets(targets, true);
              }
              function addAllowedBridgeTargets(
                  address[] calldata targets
              ) external onlyOwner Timelock {
                  _updateAllowedBridgeTargets(targets, true);
              }
              function addAllowedChainIds(
                  uint256[] calldata chainIds
              ) external onlyOwner Timelock {
                  _updateAllowedChainIds(chainIds, true);
              }
              function removeAllowedSwapTargets(
                  address[] calldata targets
              ) external onlyOwner {
                  _updateAllowedSwapTargets(targets, false);
              }
              function removeAllowedBridgeTargets(
                  address[] calldata targets
              ) external onlyOwner {
                  _updateAllowedBridgeTargets(targets, false);
              }
              function removeAllowedChainIds(
                  uint256[] calldata chainIds
              ) external onlyOwner {
                  _updateAllowedChainIds(chainIds, false);
              }
              function setOperator(address newOperator) external onlyOwner {
                  operator = newOperator;
              }
              function addExcessToPool(IERC20 asset, uint256 amount) external {
                  _POOL_EXCESS_[asset] += amount;
                  asset.safeTransferFrom(msg.sender, address(this), amount);
                  emit ExcessAdded(asset, amount);
              }
              function removeExcessFromPool(
                  IERC20 asset,
                  uint256 amount
              ) external onlyOwner {
                  // Will revert if amount is greater than excess balance.
                  _POOL_EXCESS_[asset] -= amount;
                  asset.safeTransfer(msg.sender, amount);
                  emit ExcessRemoved(asset, amount);
              }
              /**
               * @notice Deposit funds to create a checkout account.
               */
              function deposit(
                  CheckoutState calldata checkout
              ) external notExpired(checkout.params.expiration) {
                  address depositAddress = msg.sender;
                  checkout.heldAsset.safeTransferFrom(
                      depositAddress,
                      address(this),
                      checkout.heldAmount
                  );
                  _CHECKOUTS_[depositAddress] = checkout;
                  emit Deposited(depositAddress, checkout.heldAsset, checkout.heldAmount);
              }
              function swap(
                  address depositAddress,
                  SwapParams calldata swapParams
              )
                  external
                  notExpired(_CHECKOUTS_[depositAddress].params.expiration)
                  allowedSwapTarget(swapParams.target)
                  onlyOperator
              {
                  // Read checkout state from storage.
                  CheckoutState storage checkout = _getCheckout(depositAddress);
                  IERC20 heldAsset = checkout.heldAsset;
                  uint256 heldAmount = checkout.heldAmount;
                  // Set the allowance on the swap spender.
                  //
                  // Note: Using approve() instead of safeIncreaseAllowance() or forceApprove() under the
                  // assumption that all allowances from this contract will be zero in between transactions.
                  // We have a condition here if it is USDT, where we will perform a safeApprove as USDT does not return any value
                  if (block.chainid == 1 && address(heldAsset) == USDT_TOKEN) {
                      heldAsset.safeApprove(swapParams.spender, heldAmount);
                  } else {
                      heldAsset.approve(swapParams.spender, heldAmount);
                  }
                  // Get starting balance of the asset to receive from the swap.
                  uint256 balanceBefore;
                  if (address(swapParams.receivedAsset) == NATIVE_TOKEN) {
                      balanceBefore = address(this).balance;
                  } else {
                      balanceBefore = IERC20(swapParams.receivedAsset).balanceOf(
                          address(this)
                      );
                  }
                  bool success;
                  bytes memory returnData;
                  // Execute the swap.
                  if (swapParams.isETHSwap) {
                      require(
                          heldAsset == WRAPPED_NATIVE_TOKEN,
                          "Held asset must be WETH for ETH swaps"
                      );
                      WETH9Interface(WRAPPED_NATIVE_TOKEN).withdraw(heldAmount);
                      (success, returnData) = swapParams.target.call{value: heldAmount}(
                          swapParams.callData
                      );
                  } else {
                      // Set the allowance on the swap spender.
                      //
                      // Note: Using approve() instead of safeIncreaseAllowance() or forceApprove() under the
                      // assumption that all allowances from this contract will be zero in between transactions.
                      heldAsset.approve(swapParams.spender, heldAmount);
                      (success, returnData) = swapParams.target.call(
                          swapParams.callData
                      );
                      // Require that the full allowance was spent.
                      //
                      // IMPORTANT NOTE: We assume the swap contract supports spending an exact amount.
                      //
                      // Note: This check will fail with some ERC-20 implementations in the case
                      // where heldAmount = type(uint256).max. We assume that this is impossible in practice.
                      uint256 remainingAllowance = heldAsset.allowance(
                          address(this),
                          swapParams.spender
                      );
                      if (remainingAllowance != 0) {
                          revert SwapDidNotSpendExactAmount(remainingAllowance);
                      }
                  }
                  if (!success) {
                      revert SwapReverted(returnData);
                  }
                  uint256 receivedAmount;
                  IERC20 receivedAsset;
                  if (address(swapParams.receivedAsset) == NATIVE_TOKEN) {
                      // Note: The tx will revert if the received asset balance decreased.
                      receivedAmount = address(this).balance - balanceBefore;
                      WRAPPED_NATIVE_TOKEN.deposit{value: receivedAmount}();
                      receivedAsset = WRAPPED_NATIVE_TOKEN;
                  } else {
                      uint256 balanceAfter = IERC20(swapParams.receivedAsset).balanceOf(
                          address(this)
                      );
                      // Note: The tx will revert if the received asset balance decreased.
                      receivedAmount = balanceAfter - balanceBefore;
                      receivedAsset = IERC20(swapParams.receivedAsset);
                  }
                  // Write checkout state to storage.
                  checkout.heldAsset = receivedAsset;
                  checkout.heldAmount = receivedAmount;
                  emit Swapped(
                      depositAddress,
                      swapParams.target,
                      receivedAsset,
                      receivedAmount
                  );
              }
              function bridge(
                  address depositAddress,
                  BridgeParams calldata bridgeParams
              )
                  external
                  notExpired(_CHECKOUTS_[depositAddress].params.expiration)
                  allowedBridgeTarget(bridgeParams.target)
                  onlyOperator
              {
                  // Read checkout state from storage.
                  // Note: Read the whole thing into memory since we use it later.
                  CheckoutState memory checkout = _getCheckout(depositAddress);
                  IERC20 heldAsset = checkout.heldAsset;
                  uint256 heldAmount = checkout.heldAmount;
                  uint256 targetChainId = checkout.params.targetChainId;
                  // Sanity check that we are not already on the target chain.
                  if (targetChainId == block.chainid) {
                      revert BridgeAlreadyOnTargetChain();
                  }
                  // Require that the chain ID is allowed/supported.
                  if (!(_ALLOW_ALL_ || _ALLOWED_CHAIN_IDS_[targetChainId])) {
                      revert BridgeChainIdNotAllowed(targetChainId);
                  }
                  // Set the allowance on the swap spender.
                  //
                  // Note: Using approve() instead of safeIncreaseAllowance() or forceApprove() under the
                  // assumption that all allowances from this contract will be zero in between transactions.
                  // We have a condition here if it is USDT, where we will perform a safeApprove as USDT does not return any value
                  if (block.chainid == 1 && address(heldAsset) == USDT_TOKEN) {
                      heldAsset.safeApprove(bridgeParams.spender, heldAmount);
                  } else {
                      heldAsset.approve(bridgeParams.spender, heldAmount);
                  }
                  bytes32 salt = keccak256(abi.encodePacked(blockhash(block.number - 1)));
                  // Get the counterfactual deployment deposit address for the target chain.
                  //
                  // IMPORTANT NOTE: This implementation assumes that the forwarder factory has the same
                  // address on each chain. This has to be ensured before a chain ID is added to the allowed
                  // list of target chain IDs.
                  CheckoutState memory bridgedCheckout = CheckoutState({
                      params: checkout.params,
                      heldAsset: bridgeParams.bridgeReceivedAsset,
                      heldAmount: bridgeParams.minBridgeReceivedAmount
                  });
                  address targetChainDepositAddress = FORWARDER_FACTORY
                      .getAddressForChain(bridgedCheckout, salt, targetChainId);
                  // Execute the bridge call.
                  _bridgeToRecipient(
                      bridgeParams.target,
                      bridgeParams.callData,
                      targetChainDepositAddress
                  );
                  // Require that the full allowance was spent.
                  //
                  // IMPORTANT NOTE: We assume the bridge contract supports spending an exact amount.
                  uint256 remainingAllowance = heldAsset.allowance(
                      address(this),
                      bridgeParams.spender
                  );
                  if (remainingAllowance != 0) {
                      revert BridgeDidNotSpendExactAmount(remainingAllowance);
                  }
                  // Delete the checkout from storage.
                  delete _CHECKOUTS_[depositAddress];
                  emit Bridged(
                      depositAddress,
                      targetChainDepositAddress,
                      bridgeParams.target,
                      bridgeParams.bridgeReceivedAsset,
                      bridgeParams.minBridgeReceivedAmount
                  );
              }
              // apply to non userOp execution cases
              function forwardFund(
                  address depositAddress
              )
                  external
                  notExpired(_CHECKOUTS_[depositAddress].params.expiration)
                  onlyOperator
              {
                  CheckoutState storage checkout = _getCheckout(depositAddress);
                  if (block.chainid != checkout.params.targetChainId) {
                      revert ForwardFundChainNotReady(block.chainid);
                  }
                  if (checkout.params.recipient == bytes32(0)) {
                      revert ForwardFundRecipientNotSet();
                  }
                  if (checkout.params.userOpHash != bytes32(0)) {
                      revert ForwardFundUserOpHashIsSet(checkout.params.userOpHash);
                  }
                  IERC20 heldAsset = checkout.heldAsset;
                  uint256 heldAmount = checkout.heldAmount;
                  uint256 forwardAmount = checkout.params.targetAmount;
                  checkout.params.targetAmount = 0;
                  if (forwardAmount < heldAmount) {
                      _POOL_EXCESS_[heldAsset] += heldAmount - forwardAmount;
                  } else if (forwardAmount > heldAmount) {
                      uint256 oldExcessAmount = _POOL_EXCESS_[heldAsset];
                      uint256 excessSpend = forwardAmount - heldAmount;
                      if (oldExcessAmount < excessSpend) {
                          revert ExecuteInsufficientExcessBalance(
                              oldExcessAmount,
                              forwardAmount,
                              heldAmount
                          );
                      }
                      _POOL_EXCESS_[heldAsset] = oldExcessAmount - excessSpend;
                  }
                  address targetAssetAddr = address(
                      uint160(uint256(checkout.params.targetAsset))
                  );
                  address recipientAddr = address(
                      uint160(uint256(checkout.params.recipient))
                  );
                  if (targetAssetAddr == NATIVE_TOKEN) {
                      if (heldAsset != WRAPPED_NATIVE_TOKEN) {
                          revert ForwardFundAssetNotReady(heldAsset);
                      } else {
                          WRAPPED_NATIVE_TOKEN.withdraw(forwardAmount);
                          (bool success, ) = payable(recipientAddr).call{
                              value: forwardAmount
                          }("");
                          require(success, "failed to forward fund");
                      }
                  } else if (heldAsset != IERC20(targetAssetAddr)) {
                      revert ForwardFundAssetNotReady(heldAsset);
                  } else if (heldAsset == IERC20(targetAssetAddr)) {
                      heldAsset.safeTransfer(recipientAddr, forwardAmount);
                  } else {
                      revert ForwardFundAssetNotReady(heldAsset);
                  }
                  // Delete the checkout from storage.
                  delete _CHECKOUTS_[depositAddress];
                  emit FundForwarded(
                      depositAddress,
                      forwardAmount,
                      checkout.params.recipient
                  );
              }
              function executeWithPaymaster(
                  CheckoutPaymaster _paymaster,
                  address depositAddress,
                  UserOperation[] calldata ops
              ) external onlyOperator {
                  bytes memory callData = abi.encodeWithSelector(
                      this.execute.selector,
                      depositAddress,
                      ops
                  );
                  _paymaster.activateAndCall(address(this), callData);
              }
              function execute(
                  address depositAddress,
                  UserOperation[] calldata ops
              )
                  external
                  notExpired(_CHECKOUTS_[depositAddress].params.expiration)
                  onlyPaymaster
              {
                  // Note: Currently having execute() take an array UserOperation[] in case this is more
                  // gas efficient than creating the array explicitly in order to call handleOps(). (?)
                  if (ops.length != 1) {
                      revert ExecuteInvalidOpsLength();
                  }
                  CheckoutState storage checkout = _getCheckout(depositAddress);
                  IERC20 heldAsset = checkout.heldAsset;
                  uint256 heldAmount = checkout.heldAmount;
                  if (block.chainid != checkout.params.targetChainId) {
                      revert ExecuteChainNotReady(block.chainid);
                  }
                  bytes32 calculatedUserOpHash = ENTRY_POINT.getUserOpHash(ops[0]);
                  if (calculatedUserOpHash != checkout.params.userOpHash) {
                      revert ExecuteInvalidUserOp(calculatedUserOpHash);
                  }
                  // Add or subtract from the excess amount in the pool, depending on whether the
                  // execution amount is greater or less than the held amount.
                  uint256 executionAmount = checkout.params.targetAmount;
                  checkout.params.targetAmount = 0;
                  if (executionAmount < heldAmount) {
                      _POOL_EXCESS_[heldAsset] += heldAmount - executionAmount;
                  } else if (executionAmount > heldAmount) {
                      uint256 oldExcessAmount = _POOL_EXCESS_[heldAsset];
                      uint256 excessSpend = executionAmount - heldAmount;
                      if (oldExcessAmount < excessSpend) {
                          revert ExecuteInsufficientExcessBalance(
                              oldExcessAmount,
                              executionAmount,
                              heldAmount
                          );
                      }
                      _POOL_EXCESS_[heldAsset] = oldExcessAmount - excessSpend;
                  }
                  address targetAssetAddr = address(
                      uint160(uint256(checkout.params.targetAsset))
                  );
                  // Send the execution amount to the userOp sender and execute the userOp.
                  if (targetAssetAddr == NATIVE_TOKEN) {
                      if (heldAsset != WRAPPED_NATIVE_TOKEN) {
                          revert ExecuteAssetNotReady(heldAsset);
                      } else {
                          WRAPPED_NATIVE_TOKEN.withdraw(executionAmount);
                          (bool success, ) = payable(ops[0].sender).call{
                              value: executionAmount
                          }("");
                          require(success, "failed to send fund before execute userOp");
                      }
                  } else if (heldAsset != IERC20(targetAssetAddr)) {
                      revert ExecuteAssetNotReady(heldAsset);
                  } else if (heldAsset == IERC20(targetAssetAddr)) {
                      heldAsset.safeTransfer(ops[0].sender, executionAmount);
                  } else {
                      revert ExecuteAssetNotReady(heldAsset);
                  }
                  ENTRY_POINT.handleOps(ops, payable(guardian()));
                  // Revert if the userOp reverted.
                  {
                      address paymasterAddress = address(
                          bytes20(ops[0].paymasterAndData[:20])
                      );
                      IPaymaster.PostOpMode userOpMode = InspectablePaymasterInterface(
                          paymasterAddress
                      ).getLastOpMode();
                      if (userOpMode != IPaymaster.PostOpMode.opSucceeded) {
                          revert ExecuteUserOpReverted(userOpMode);
                      }
                  }
                  // Delete the checkout from storage.
                  delete _CHECKOUTS_[depositAddress];
                  emit Executed(depositAddress, executionAmount);
              }
              function checkoutExists(
                  address depositAddress
              ) external view returns (bool) {
                  return _CHECKOUTS_[depositAddress].params.targetAsset != bytes32(0);
              }
              function getCheckout(
                  address depositAddress
              ) external view returns (CheckoutState memory) {
                  return _getCheckout(depositAddress);
              }
              function getCheckoutOrZero(
                  address depositAddress
              ) external view returns (CheckoutState memory) {
                  return _CHECKOUTS_[depositAddress];
              }
              function _getCheckout(
                  address depositAddress
              ) internal view returns (CheckoutState storage) {
                  CheckoutState storage checkout = _CHECKOUTS_[depositAddress];
                  if (checkout.params.targetAsset == bytes32(0)) {
                      revert CheckoutDoesNotExist();
                  }
                  return checkout;
              }
              function _updateAllowedSwapTargets(
                  address[] calldata targets,
                  bool isAllowed
              ) internal {
                  uint256 n = targets.length;
                  for (uint256 i; i < n; ++i) {
                      address target = targets[i];
                      _ALLOWED_SWAP_TARGETS_[target] = isAllowed;
                      emit UpdatedAllowedSwapTarget(target, isAllowed);
                  }
              }
              function _updateAllowedBridgeTargets(
                  address[] calldata targets,
                  bool isAllowed
              ) internal {
                  uint256 n = targets.length;
                  for (uint256 i; i < n; ++i) {
                      address target = targets[i];
                      _ALLOWED_BRIDGE_TARGETS_[target] = isAllowed;
                      emit UpdatedAllowedBridgeTarget(target, isAllowed);
                  }
              }
              function _updateAllowedChainIds(
                  uint256[] calldata chainids,
                  bool isAllowed
              ) internal {
                  uint256 n = chainids.length;
                  for (uint256 i; i < n; ++i) {
                      uint256 chainId = chainids[i];
                      _ALLOWED_CHAIN_IDS_[chainId] = isAllowed;
                      emit UpdatedAllowedChainIds(chainId, isAllowed);
                  }
              }
              function _bridgeToRecipient(
                  address target,
                  bytes calldata callData,
                  address targetChainDepositAddress
              ) internal {
                  // as needed.
                  (bool success, bytes memory returnData) = target.call(callData);
                  if (!success) {
                      revert BridgeReverted(returnData);
                  }
              }
              function getCallHash(
                  address sender,
                  bytes calldata callData
              ) internal pure returns (bytes32) {
                  return keccak256(abi.encode(sender, callData));
              }
          }
          // SPDX-License-Identifier: GPL-3.0
          pragma solidity ^0.8.12;
          /* solhint-disable avoid-low-level-calls */
          /* solhint-disable no-inline-assembly */
          /* solhint-disable reason-string */
          import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
          import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
          import "@openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol";
          import "../core/BaseAccount.sol";
          import "./callback/TokenCallbackHandler.sol";
          /**
            * minimal account.
            *  this is sample minimal account.
            *  has execute, eth handling methods
            *  has a single signer that can send requests through the entryPoint.
            */
          contract SimpleAccount is BaseAccount, TokenCallbackHandler, UUPSUpgradeable, Initializable {
              using ECDSA for bytes32;
              address public owner;
              IEntryPoint private immutable _entryPoint;
              event SimpleAccountInitialized(IEntryPoint indexed entryPoint, address indexed owner);
              modifier onlyOwner() {
                  _onlyOwner();
                  _;
              }
              /// @inheritdoc BaseAccount
              function entryPoint() public view virtual override returns (IEntryPoint) {
                  return _entryPoint;
              }
              // solhint-disable-next-line no-empty-blocks
              receive() external payable {}
              constructor(IEntryPoint anEntryPoint) {
                  _entryPoint = anEntryPoint;
                  _disableInitializers();
              }
              function _onlyOwner() internal view {
                  //directly from EOA owner, or through the account itself (which gets redirected through execute())
                  require(msg.sender == owner || msg.sender == address(this), "only owner");
              }
              /**
               * execute a transaction (called directly from owner, or by entryPoint)
               */
              function execute(address dest, uint256 value, bytes calldata func) external {
                  _requireFromEntryPointOrOwner();
                  _call(dest, value, func);
              }
              /**
               * execute a sequence of transactions
               */
              function executeBatch(address[] calldata dest, bytes[] calldata func) external {
                  _requireFromEntryPointOrOwner();
                  require(dest.length == func.length, "wrong array lengths");
                  for (uint256 i = 0; i < dest.length; i++) {
                      _call(dest[i], 0, func[i]);
                  }
              }
              /**
               * @dev The _entryPoint member is immutable, to reduce gas consumption.  To upgrade EntryPoint,
               * a new implementation of SimpleAccount must be deployed with the new EntryPoint address, then upgrading
                * the implementation by calling `upgradeTo()`
               */
              function initialize(address anOwner) public virtual initializer {
                  _initialize(anOwner);
              }
              function _initialize(address anOwner) internal virtual {
                  owner = anOwner;
                  emit SimpleAccountInitialized(_entryPoint, owner);
              }
              // Require the function call went through EntryPoint or owner
              function _requireFromEntryPointOrOwner() internal view {
                  require(msg.sender == address(entryPoint()) || msg.sender == owner, "account: not Owner or EntryPoint");
              }
              /// implement template method of BaseAccount
              function _validateSignature(UserOperation calldata userOp, bytes32 userOpHash)
              internal override virtual returns (uint256 validationData) {
                  bytes32 hash = userOpHash.toEthSignedMessageHash();
                  if (owner != hash.recover(userOp.signature))
                      return SIG_VALIDATION_FAILED;
                  return 0;
              }
              function _call(address target, uint256 value, bytes memory data) internal {
                  (bool success, bytes memory result) = target.call{value : value}(data);
                  if (!success) {
                      assembly {
                          revert(add(result, 32), mload(result))
                      }
                  }
              }
              /**
               * check current account deposit in the entryPoint
               */
              function getDeposit() public view returns (uint256) {
                  return entryPoint().balanceOf(address(this));
              }
              /**
               * deposit more funds for this account in the entryPoint
               */
              function addDeposit() public payable {
                  entryPoint().depositTo{value : msg.value}(address(this));
              }
              /**
               * withdraw value from the account's deposit
               * @param withdrawAddress target to send to
               * @param amount to withdraw
               */
              function withdrawDepositTo(address payable withdrawAddress, uint256 amount) public onlyOwner {
                  entryPoint().withdrawTo(withdrawAddress, amount);
              }
              function _authorizeUpgrade(address newImplementation) internal view override {
                  (newImplementation);
                  _onlyOwner();
              }
          }
          /**
           ** Account-Abstraction (EIP-4337) singleton EntryPoint implementation.
           ** Only one instance required on each chain.
           **/
          // SPDX-License-Identifier: GPL-3.0
          pragma solidity ^0.8.12;
          /* solhint-disable avoid-low-level-calls */
          /* solhint-disable no-inline-assembly */
          /* solhint-disable reason-string */
          import "./UserOperation.sol";
          import "./IStakeManager.sol";
          import "./IAggregator.sol";
          import "./INonceManager.sol";
          interface IEntryPoint is IStakeManager, INonceManager {
              /***
               * An event emitted after each successful request
               * @param userOpHash - unique identifier for the request (hash its entire content, except signature).
               * @param sender - the account that generates this request.
               * @param paymaster - if non-null, the paymaster that pays for this request.
               * @param nonce - the nonce value from the request.
               * @param success - true if the sender transaction succeeded, false if reverted.
               * @param actualGasCost - actual amount paid (by account or paymaster) for this UserOperation.
               * @param actualGasUsed - total gas used by this UserOperation (including preVerification, creation, validation and execution).
               */
              event UserOperationEvent(bytes32 indexed userOpHash, address indexed sender, address indexed paymaster, uint256 nonce, bool success, uint256 actualGasCost, uint256 actualGasUsed);
              /**
               * account "sender" was deployed.
               * @param userOpHash the userOp that deployed this account. UserOperationEvent will follow.
               * @param sender the account that is deployed
               * @param factory the factory used to deploy this account (in the initCode)
               * @param paymaster the paymaster used by this UserOp
               */
              event AccountDeployed(bytes32 indexed userOpHash, address indexed sender, address factory, address paymaster);
              /**
               * An event emitted if the UserOperation "callData" reverted with non-zero length
               * @param userOpHash the request unique identifier.
               * @param sender the sender of this request
               * @param nonce the nonce used in the request
               * @param revertReason - the return bytes from the (reverted) call to "callData".
               */
              event UserOperationRevertReason(bytes32 indexed userOpHash, address indexed sender, uint256 nonce, bytes revertReason);
              /**
               * an event emitted by handleOps(), before starting the execution loop.
               * any event emitted before this event, is part of the validation.
               */
              event BeforeExecution();
              /**
               * signature aggregator used by the following UserOperationEvents within this bundle.
               */
              event SignatureAggregatorChanged(address indexed aggregator);
              /**
               * a custom revert error of handleOps, to identify the offending op.
               *  NOTE: if simulateValidation passes successfully, there should be no reason for handleOps to fail on it.
               *  @param opIndex - index into the array of ops to the failed one (in simulateValidation, this is always zero)
               *  @param reason - revert reason
               *      The string starts with a unique code "AAmn", where "m" is "1" for factory, "2" for account and "3" for paymaster issues,
               *      so a failure can be attributed to the correct entity.
               *   Should be caught in off-chain handleOps simulation and not happen on-chain.
               *   Useful for mitigating DoS attempts against batchers or for troubleshooting of factory/account/paymaster reverts.
               */
              error FailedOp(uint256 opIndex, string reason);
              /**
               * error case when a signature aggregator fails to verify the aggregated signature it had created.
               */
              error SignatureValidationFailed(address aggregator);
              /**
               * Successful result from simulateValidation.
               * @param returnInfo gas and time-range returned values
               * @param senderInfo stake information about the sender
               * @param factoryInfo stake information about the factory (if any)
               * @param paymasterInfo stake information about the paymaster (if any)
               */
              error ValidationResult(ReturnInfo returnInfo,
                  StakeInfo senderInfo, StakeInfo factoryInfo, StakeInfo paymasterInfo);
              /**
               * Successful result from simulateValidation, if the account returns a signature aggregator
               * @param returnInfo gas and time-range returned values
               * @param senderInfo stake information about the sender
               * @param factoryInfo stake information about the factory (if any)
               * @param paymasterInfo stake information about the paymaster (if any)
               * @param aggregatorInfo signature aggregation info (if the account requires signature aggregator)
               *      bundler MUST use it to verify the signature, or reject the UserOperation
               */
              error ValidationResultWithAggregation(ReturnInfo returnInfo,
                  StakeInfo senderInfo, StakeInfo factoryInfo, StakeInfo paymasterInfo,
                  AggregatorStakeInfo aggregatorInfo);
              /**
               * return value of getSenderAddress
               */
              error SenderAddressResult(address sender);
              /**
               * return value of simulateHandleOp
               */
              error ExecutionResult(uint256 preOpGas, uint256 paid, uint48 validAfter, uint48 validUntil, bool targetSuccess, bytes targetResult);
              //UserOps handled, per aggregator
              struct UserOpsPerAggregator {
                  UserOperation[] userOps;
                  // aggregator address
                  IAggregator aggregator;
                  // aggregated signature
                  bytes signature;
              }
              /**
               * Execute a batch of UserOperation.
               * no signature aggregator is used.
               * if any account requires an aggregator (that is, it returned an aggregator when
               * performing simulateValidation), then handleAggregatedOps() must be used instead.
               * @param ops the operations to execute
               * @param beneficiary the address to receive the fees
               */
              function handleOps(UserOperation[] calldata ops, address payable beneficiary) external;
              /**
               * Execute a batch of UserOperation with Aggregators
               * @param opsPerAggregator the operations to execute, grouped by aggregator (or address(0) for no-aggregator accounts)
               * @param beneficiary the address to receive the fees
               */
              function handleAggregatedOps(
                  UserOpsPerAggregator[] calldata opsPerAggregator,
                  address payable beneficiary
              ) external;
              /**
               * generate a request Id - unique identifier for this request.
               * the request ID is a hash over the content of the userOp (except the signature), the entrypoint and the chainid.
               */
              function getUserOpHash(UserOperation calldata userOp) external view returns (bytes32);
              /**
               * Simulate a call to account.validateUserOp and paymaster.validatePaymasterUserOp.
               * @dev this method always revert. Successful result is ValidationResult error. other errors are failures.
               * @dev The node must also verify it doesn't use banned opcodes, and that it doesn't reference storage outside the account's data.
               * @param userOp the user operation to validate.
               */
              function simulateValidation(UserOperation calldata userOp) external;
              /**
               * gas and return values during simulation
               * @param preOpGas the gas used for validation (including preValidationGas)
               * @param prefund the required prefund for this operation
               * @param sigFailed validateUserOp's (or paymaster's) signature check failed
               * @param validAfter - first timestamp this UserOp is valid (merging account and paymaster time-range)
               * @param validUntil - last timestamp this UserOp is valid (merging account and paymaster time-range)
               * @param paymasterContext returned by validatePaymasterUserOp (to be passed into postOp)
               */
              struct ReturnInfo {
                  uint256 preOpGas;
                  uint256 prefund;
                  bool sigFailed;
                  uint48 validAfter;
                  uint48 validUntil;
                  bytes paymasterContext;
              }
              /**
               * returned aggregated signature info.
               * the aggregator returned by the account, and its current stake.
               */
              struct AggregatorStakeInfo {
                  address aggregator;
                  StakeInfo stakeInfo;
              }
              /**
               * Get counterfactual sender address.
               *  Calculate the sender contract address that will be generated by the initCode and salt in the UserOperation.
               * this method always revert, and returns the address in SenderAddressResult error
               * @param initCode the constructor code to be passed into the UserOperation.
               */
              function getSenderAddress(bytes memory initCode) external;
              /**
               * simulate full execution of a UserOperation (including both validation and target execution)
               * this method will always revert with "ExecutionResult".
               * it performs full validation of the UserOperation, but ignores signature error.
               * an optional target address is called after the userop succeeds, and its value is returned
               * (before the entire call is reverted)
               * Note that in order to collect the the success/failure of the target call, it must be executed
               * with trace enabled to track the emitted events.
               * @param op the UserOperation to simulate
               * @param target if nonzero, a target address to call after userop simulation. If called, the targetSuccess and targetResult
               *        are set to the return from that call.
               * @param targetCallData callData to pass to target address
               */
              function simulateHandleOp(UserOperation calldata op, address target, bytes calldata targetCallData) external;
          }
          // SPDX-License-Identifier: GPL-3.0
          pragma solidity ^0.8.12;
          import "./UserOperation.sol";
          /**
           * the interface exposed by a paymaster contract, who agrees to pay the gas for user's operations.
           * a paymaster must hold a stake to cover the required entrypoint stake and also the gas for the transaction.
           */
          interface IPaymaster {
              enum PostOpMode {
                  opSucceeded, // user op succeeded
                  opReverted, // user op reverted. still has to pay for gas.
                  postOpReverted //user op succeeded, but caused postOp to revert. Now it's a 2nd call, after user's op was deliberately reverted.
              }
              /**
               * payment validation: check if paymaster agrees to pay.
               * Must verify sender is the entryPoint.
               * Revert to reject this request.
               * Note that bundlers will reject this method if it changes the state, unless the paymaster is trusted (whitelisted)
               * The paymaster pre-pays using its deposit, and receive back a refund after the postOp method returns.
               * @param userOp the user operation
               * @param userOpHash hash of the user's request data.
               * @param maxCost the maximum cost of this transaction (based on maximum gas and gas price from userOp)
               * @return context value to send to a postOp
               *      zero length to signify postOp is not required.
               * @return validationData signature and time-range of this operation, encoded the same as the return value of validateUserOperation
               *      <20-byte> sigAuthorizer - 0 for valid signature, 1 to mark signature failure,
               *         otherwise, an address of an "authorizer" contract.
               *      <6-byte> validUntil - last timestamp this operation is valid. 0 for "indefinite"
               *      <6-byte> validAfter - first timestamp this operation is valid
               *      Note that the validation code cannot use block.timestamp (or block.number) directly.
               */
              function validatePaymasterUserOp(UserOperation calldata userOp, bytes32 userOpHash, uint256 maxCost)
              external returns (bytes memory context, uint256 validationData);
              /**
               * post-operation handler.
               * Must verify sender is the entryPoint
               * @param mode enum with the following options:
               *      opSucceeded - user operation succeeded.
               *      opReverted  - user op reverted. still has to pay for gas.
               *      postOpReverted - user op succeeded, but caused postOp (in mode=opSucceeded) to revert.
               *                       Now this is the 2nd call, after user's op was deliberately reverted.
               * @param context - the context value returned by validatePaymasterUserOp
               * @param actualGasCost - actual gas used so far (without this postOp call).
               */
              function postOp(PostOpMode mode, bytes calldata context, uint256 actualGasCost) external;
          }
          // SPDX-License-Identifier: GPL-3.0
          pragma solidity ^0.8.12;
          /* solhint-disable no-inline-assembly */
          import {calldataKeccak} from "../core/Helpers.sol";
          /**
           * User Operation struct
           * @param sender the sender account of this request.
               * @param nonce unique value the sender uses to verify it is not a replay.
               * @param initCode if set, the account contract will be created by this constructor/
               * @param callData the method call to execute on this account.
               * @param callGasLimit the gas limit passed to the callData method call.
               * @param verificationGasLimit gas used for validateUserOp and validatePaymasterUserOp.
               * @param preVerificationGas gas not calculated by the handleOps method, but added to the gas paid. Covers batch overhead.
               * @param maxFeePerGas same as EIP-1559 gas parameter.
               * @param maxPriorityFeePerGas same as EIP-1559 gas parameter.
               * @param paymasterAndData if set, this field holds the paymaster address and paymaster-specific data. the paymaster will pay for the transaction instead of the sender.
               * @param signature sender-verified signature over the entire request, the EntryPoint address and the chain ID.
               */
              struct UserOperation {
                  address sender;
                  uint256 nonce;
                  bytes initCode;
                  bytes callData;
                  uint256 callGasLimit;
                  uint256 verificationGasLimit;
                  uint256 preVerificationGas;
                  uint256 maxFeePerGas;
                  uint256 maxPriorityFeePerGas;
                  bytes paymasterAndData;
                  bytes signature;
              }
          /**
           * Utility functions helpful when working with UserOperation structs.
           */
          library UserOperationLib {
              function getSender(UserOperation calldata userOp) internal pure returns (address) {
                  address data;
                  //read sender from userOp, which is first userOp member (saves 800 gas...)
                  assembly {data := calldataload(userOp)}
                  return address(uint160(data));
              }
              //relayer/block builder might submit the TX with higher priorityFee, but the user should not
              // pay above what he signed for.
              function gasPrice(UserOperation calldata userOp) internal view returns (uint256) {
              unchecked {
                  uint256 maxFeePerGas = userOp.maxFeePerGas;
                  uint256 maxPriorityFeePerGas = userOp.maxPriorityFeePerGas;
                  if (maxFeePerGas == maxPriorityFeePerGas) {
                      //legacy mode (for networks that don't support basefee opcode)
                      return maxFeePerGas;
                  }
                  return min(maxFeePerGas, maxPriorityFeePerGas + block.basefee);
              }
              }
              function pack(UserOperation calldata userOp) internal pure returns (bytes memory ret) {
                  address sender = getSender(userOp);
                  uint256 nonce = userOp.nonce;
                  bytes32 hashInitCode = calldataKeccak(userOp.initCode);
                  bytes32 hashCallData = calldataKeccak(userOp.callData);
                  uint256 callGasLimit = userOp.callGasLimit;
                  uint256 verificationGasLimit = userOp.verificationGasLimit;
                  uint256 preVerificationGas = userOp.preVerificationGas;
                  uint256 maxFeePerGas = userOp.maxFeePerGas;
                  uint256 maxPriorityFeePerGas = userOp.maxPriorityFeePerGas;
                  bytes32 hashPaymasterAndData = calldataKeccak(userOp.paymasterAndData);
                  return abi.encode(
                      sender, nonce,
                      hashInitCode, hashCallData,
                      callGasLimit, verificationGasLimit, preVerificationGas,
                      maxFeePerGas, maxPriorityFeePerGas,
                      hashPaymasterAndData
                  );
              }
              function hash(UserOperation calldata userOp) internal pure returns (bytes32) {
                  return keccak256(pack(userOp));
              }
              function min(uint256 a, uint256 b) internal pure returns (uint256) {
                  return a < b ? a : b;
              }
          }
          // 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: UNLICENSED
          pragma solidity ^0.8.13;
          import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
          import { CheckoutPoolInterface } from "../interfaces/CheckoutPoolInterface.sol";
          import {
              Create2ForwarderInterface
          } from "../interfaces/Create2ForwarderInterface.sol";
          import {
              Create2ForwarderFactoryInterface
          } from "../interfaces/Create2ForwarderFactoryInterface.sol";
          import { CheckoutState } from "../interfaces/CheckoutPoolInterface.sol";
          import { WETH9Interface } from "../interfaces/WETH9Interface.sol";
          import { Create2ForwarderImpl } from "../forwarder/Create2ForwarderImpl.sol";
          import { Create2ForwarderProxy } from "./Create2ForwarderProxy.sol";
          /**
           * @title Create2ForwarderFactory
           * @author Fun.xyz
           *
           * @notice Factory for “counterfactual” forwarder contracts for the Checkout Pools protocol.
           *
           *  A forwarder contract is created for each checkout operation executed by the protocol.
           *  It is the entry point for funds into the protocol.
           *
           *  Before the forwarder contract is deployed, its CREATE2 address (the “deposit address”)
           *  is calculated, so that the contract can be deployed only as needed, after funds have
           *  been deposited.
           *
           *  As a gas optimization, each forwarder contract is deployed as a proxy. All of the proxy
           *  contracts reference the same implementation logic, which is a constant on the factory contract.
           *
           *  As a gas optimization, checkout parameters that are not expected to change (often) are
           *  stored as constants on the factory contract. Parameters that do not need to be stored
           *  on-chain (e.g. the full user operation) are expected to be stored off-chain by the liquidity
           *  provider that is responsible for executing the checkout.
           *
           *  Constants (same for all forwarders created by the factory).
           *    - source chain
           *    - guardian address
           *    - CheckoutPools contract address (corresponds to a liquidity provider)
           *    - wrapped native token address
           *
           *  On-chain configuration (different for each forwarder / checkout operation)
           *    - user op hash
           *    - target chain
           *    - target asset and amount
           *    - source asset and amount
           *    - expiration timestamp
           *    - salt (not stored)
           *
           *  Off-chain configuration
           *    - user op
           */
          contract Create2ForwarderFactory is Create2ForwarderFactoryInterface {
              error ErrorCreatingProxy();
              Create2ForwarderImpl public immutable IMPLEMENTATION;
              constructor(
                  address guardian,
                  WETH9Interface wrappedNativeToken,
                  CheckoutPoolInterface checkoutPool
              ) {
                  IMPLEMENTATION = new Create2ForwarderImpl(
                      guardian,
                      wrappedNativeToken,
                      checkoutPool
                  );
              }
              function create(
                  CheckoutState calldata checkout,
                  bytes32 salt
              ) external returns (Create2ForwarderInterface) {
                  return _create(checkout, salt);
              }
              function createAndForward(
                  CheckoutState calldata checkout,
                  bytes32 salt
              ) external returns (Create2ForwarderInterface) {
                  Create2ForwarderInterface proxy = _create(checkout, salt);
                  proxy.forward();
                  return proxy;
              }
              function getAddress(
                  CheckoutState calldata checkout,
                  bytes32 salt
              ) external view returns (address payable) {
                  return _getAddress(checkout, salt, block.chainid);
              }
              /**
               * @notice Get the deposit address for a target chain ID.
               *
               *  IMPORTANT NOTE: This implementation assumes that the forwarder factory has the same
               *  address on each chain. This has to be ensured before a chain ID is added to the allowed
               *  list of target chain IDs on the CheckoutPools contract.
               */
              function getAddressForChain(
                  CheckoutState calldata checkout,
                  bytes32 salt,
                  uint256 chainId
              ) external view returns (address payable) {
                  return _getAddress(checkout, salt, chainId);
              }
              function getProxyCreationCode() external pure returns (bytes memory) {
                  return type(Create2ForwarderProxy).creationCode;
              }
              function _create(
                  CheckoutState calldata checkout,
                  bytes32 salt
              ) internal returns (Create2ForwarderInterface) {
                  Create2ForwarderProxy deployed = new Create2ForwarderProxy{
                      salt: salt
                  }(IMPLEMENTATION, checkout, block.chainid);
                  Create2ForwarderInterface proxy = Create2ForwarderInterface(
                      address(deployed)
                  );
                  return proxy;
              }
              function _getAddress(
                  CheckoutState calldata checkout,
                  bytes32 salt,
                  uint256 chainId
              ) internal view returns (address payable) {
                  bytes32 digest = keccak256(
                      abi.encodePacked(
                          bytes1(0xff),
                          address(this),
                          salt,
                          keccak256(
                              abi.encodePacked(
                                  type(Create2ForwarderProxy).creationCode,
                                  abi.encode(IMPLEMENTATION, checkout, chainId)
                              )
                          )
                      )
                  );
                  return payable(address(uint160(uint256(digest))));
              }
          }
          // Compare with:
          // function create3(bytes32 _salt, bytes memory _creationCode, uint256 _value) internal returns (address addr) {
          //     // Creation code
          //     bytes memory creationCode = PROXY_CHILD_BYTECODE;
          //     // Get target final address
          //     addr = addressOf(_salt);
          //     if (codeSize(addr) != 0) revert TargetAlreadyExists();
          //     // Create CREATE2 proxy
          //     address proxy; assembly { proxy := create2(0, add(creationCode, 32), mload(creationCode), _salt)}
          //     if (proxy == address(0)) revert ErrorCreatingProxy();
          //     // Call proxy with final init code
          //     (bool success,) = proxy.call{ value: _value }(_creationCode);
          //     if (!success || codeSize(addr) == 0) revert ErrorCreatingContract();
          // }
          // SPDX-License-Identifier: UNLICENSED
          pragma solidity ^0.8.13;
          import {
              UserOperation
          } from "@account-abstraction/contracts/interfaces/UserOperation.sol";
          import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
          /// @dev Immutable parameters of a checkout account.
          struct CheckoutParams {
              bytes32 userOpHash;
              bytes32 targetAsset;
              uint96 targetChainId;
              uint128 targetAmount;
              uint128 expiration;
              bytes32 recipient;
          }
          /// @dev State of a checkout account.
          struct CheckoutState {
              CheckoutParams params;
              IERC20 heldAsset;
              uint256 heldAmount;
          }
          struct SwapParams {
              address target;
              address spender;
              bytes callData;
              address receivedAsset;
              bool isETHSwap;
          }
          struct BridgeParams {
              address target;
              address spender;
              bytes callData;
              IERC20 bridgeReceivedAsset;
              uint256 minBridgeReceivedAmount;
          }
          interface CheckoutPoolInterface {
              function deposit(CheckoutState calldata checkoutState) external;
              function swap(
                  address depositAddress,
                  SwapParams calldata swapParams
              ) external;
              function bridge(
                  address depositAddress,
                  BridgeParams calldata bridgeParams
              ) external;
              function execute(
                  address depositAddress,
                  UserOperation[] calldata ops // length-1 array (gas optimization)
              ) external;
              function checkoutExists(
                  address depositAddress
              ) external view returns (bool);
              function getCheckout(
                  address depositAddress
              ) external view returns (CheckoutState memory);
              function getCheckoutOrZero(
                  address depositAddress
              ) external view returns (CheckoutState memory);
              function forwardFund(address depositAddress) external;
          }
          // SPDX-License-Identifier: UNLICENSED
          pragma solidity ^0.8.13;
          import {
              IPaymaster
          } from "@account-abstraction/contracts/interfaces/IPaymaster.sol";
          import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
          interface CheckoutPoolEventsAndErrors {
              error CheckoutDoesNotExist();
              error CheckoutExpired();
              error SwapTargetNotAllowed(address target);
              error SwapDidNotSpendExactAmount(uint256 remainingAllowance);
              error SwapReverted(bytes errorData);
              error BridgeChainIdNotAllowed(uint256 chainId);
              error BridgeTargetNotAllowed(address target);
              error BridgeAlreadyOnTargetChain();
              error BridgeDidNotSpendExactAmount(uint256 remainingAllowance);
              error BridgeReverted(bytes errorData);
              error ExecuteInvalidOpsLength();
              error ExecuteChainNotReady(uint256 chainId);
              error ExecuteAssetNotReady(IERC20 heldAsset);
              error ExecuteInsufficientExcessBalance(
                  uint256 oldExcessAmount,
                  uint256 executionAmount,
                  uint256 heldAmount
              );
              error ExecuteInvalidUserOp(bytes32 calculatedUserOpHash);
              error ExecuteUserOpReverted(IPaymaster.PostOpMode userOpMode);
              error TimelockNotExpired(bytes32 callHash, uint256 expiration);
              error OnlyOperatorAllowed(address caller, address operator);
              error OnlyPaymasterAllowed(address caller, address paymaster);
              error ForwardFundChainNotReady(uint256 chainId);
              error ForwardFundUserOpHashIsSet(bytes32);
              error ForwardFundAssetNotReady(IERC20 asset);
              error ForwardFundInsufficientExcessBalance(
                  uint256 oldExcessAmount,
                  uint256 forwardAmount,
                  uint256 heldAmount
              );
              error ForwardFundRecipientNotSet();
              event UpdatedAllowedSwapTarget(address indexed target, bool isAllowed);
              event UpdatedAllowedBridgeTarget(address indexed target, bool isAllowed);
              event UpdatedAllowedChainIds(uint256 indexed chainId, bool isAllowed);
              event ExcessAdded(IERC20 indexed asset, uint256 amount);
              event ExcessRemoved(IERC20 indexed asset, uint256 amount);
              event Deposited(
                  address indexed depositAddress,
                  IERC20 receivedAsset,
                  uint256 receivedAmount
              );
              event Bridged(
                  address indexed depositAddress,
                  address indexed targetChainDepositAddress,
                  address indexed bridgeTarget,
                  IERC20 receivedAsset,
                  uint256 minReceivedAmount
              );
              event Swapped(
                  address indexed depositAddress,
                  address indexed swapTarget,
                  IERC20 receivedAsset,
                  uint256 receivedAmount
              );
              event Executed(address indexed depositAddress, uint256 executionAmount);
              event FundForwarded(
                  address indexed depositAddress,
                  uint256 forwardAmount,
                  bytes32 indexed recipient
              );
          }
          // SPDX-License-Identifier: UNLICENSED
          pragma solidity ^0.8.13;
          import {
              IPaymaster
          } from "@account-abstraction/contracts/interfaces/IPaymaster.sol";
          interface InspectablePaymasterInterface {
              function getLastOpMode() external view returns (IPaymaster.PostOpMode);
          }
          // SPDX-License-Identifier: UNLICENSED
          pragma solidity ^0.8.13;
          import {
              BasePaymaster
          } from "@account-abstraction/contracts/core/BasePaymaster.sol";
          import {
              IEntryPoint
          } from "@account-abstraction/contracts/interfaces/IEntryPoint.sol";
          import {
              UserOperation
          } from "@account-abstraction/contracts/interfaces/UserOperation.sol";
          import { ECDSA } from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
          import { EIP712 } from "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
          import {
              InspectablePaymasterInterface
          } from "../interfaces/InspectablePaymasterInterface.sol";
          import {
              CheckoutPaymasterEventsAndErrors
          } from "./CheckoutPaymasterEventsAndErrors.sol";
          enum ActiveState {
              UNSPECIFIED, // 0
              INACTIVE, // 1
              ACTIVE // 2
          }
          /**
           * @title CheckoutPaymaster
           * @author Fun.xyz
           */
          contract CheckoutPaymaster is
              BasePaymaster,
              InspectablePaymasterInterface,
              EIP712,
              CheckoutPaymasterEventsAndErrors
          {
              string public constant EIP712_NAME = "CheckoutPaymaster";
              string public constant VERSION = "2"; // Note: Was a uint256 in version 1.
              bytes32 private constant SPONSOR_USER_OP_TYPEHASH =
                  keccak256(
                      "SponsorUserOp("
                      "bytes32 userOpHash,"
                      "uint64 deadline"
                      ")"
                  );
              bytes1 private constant CONTEXT_ACTIVE = bytes1(uint8(0));
              bytes1 private constant CONTEXT_INACTIVE = bytes1(uint8(1));
              ActiveState internal _ACTIVE_STATE_;
              PostOpMode internal _LAST_OP_MODE_;
              mapping(address => bool) internal _OPERATORS_;
              mapping(address => bool) internal _SIGNERS_;
              mapping(bytes32 => bool) internal _SPONSORED_USER_OP_HASHES_;
              modifier onlyOperator() {
                  if (!_OPERATORS_[msg.sender]) {
                      revert OperatorNotAllowed(msg.sender);
                  }
                  _;
              }
              modifier activate() {
                  _ACTIVE_STATE_ = ActiveState.ACTIVE;
                  _;
                  _ACTIVE_STATE_ = ActiveState.INACTIVE;
              }
              constructor(
                  IEntryPoint entryPoint
              ) BasePaymaster(entryPoint) EIP712(EIP712_NAME, VERSION) {
                  _ACTIVE_STATE_ = ActiveState.INACTIVE;
              }
              function setOperators(
                  address[] calldata operators,
                  bool isAllowed
              ) external onlyOwner {
                  uint256 n = operators.length;
                  for (uint256 i; i < n; ++i) {
                      address operator = operators[i];
                      _OPERATORS_[operator] = isAllowed;
                      emit OperatorSet(operator, isAllowed);
                  }
              }
              function setSigners(
                  address[] calldata signers,
                  bool isAllowed
              ) external onlyOwner {
                  uint256 n = signers.length;
                  for (uint256 i; i < n; ++i) {
                      address signer = signers[i];
                      _SIGNERS_[signer] = isAllowed;
                      emit SignerSet(signer, isAllowed);
                  }
              }
              function activateAndCall(
                  address target,
                  bytes calldata callData
              ) external payable onlyOperator activate returns (bytes memory) {
                  (bool success, bytes memory returnData) = payable(target).call{
                      value: msg.value
                  }(callData);
                  if (!success) {
                      assembly {
                          revert(add(returnData, 32), mload(returnData))
                      }
                  }
                  return returnData;
              }
              function getLastOpMode() external view returns (PostOpMode) {
                  return _LAST_OP_MODE_;
              }
              function isOperatorAllowed(address operator) external view returns (bool) {
                  return _OPERATORS_[operator];
              }
              function isSignerAllowed(address signer) external view returns (bool) {
                  return _SIGNERS_[signer];
              }
              function DOMAIN_SEPARATOR() external view virtual returns (bytes32) {
                  return _domainSeparatorV4();
              }
              /**
               * @notice Validate a user operation that is using this paymaster.
               *
               * @param userOp ERC-4337 UserOperation.
               *
               * @return context The context containing the sponsor, spender, gasPriceUserOp, and opHash.
               * @return validationData The validation result.
               */
              function _validatePaymasterUserOp(
                  UserOperation calldata userOp,
                  bytes32 /* opHash */,
                  uint256 /* maxCost */
              ) internal override returns (bytes memory context, uint256 validationData) {
                  // Assume paymasterAndData.length >= 20 based on reasonable EntryPoint behavior.
                  uint256 len = userOp.paymasterAndData.length;
                  if (len > 20) {
                      // Format of paymasterAndData:
                      //   -  [0:20]  address paymaster
                      //   - [20:40]  address signer
                      //   - [40:48]  uint64  deadline
                      //   - [48:113] bytes   signature
                      if (len != 113) {
                          revert InvalidPaymasterAndDataLength(len);
                      }
                      address expectedSigner = address(
                          bytes20(userOp.paymasterAndData[20:40])
                      );
                      uint64 deadline = uint64(bytes8(userOp.paymasterAndData[40:48]));
                      bytes memory signature = userOp.paymasterAndData[48:];
                      _validateSponsoredUserOp(
                          signature,
                          expectedSigner,
                          deadline,
                          userOp
                      );
                      context = abi.encodePacked(CONTEXT_ACTIVE);
                  } else {
                      context = abi.encodePacked(CONTEXT_INACTIVE);
                  }
                  validationData = 0;
              }
              /**
               * @notice Post-operation handler.
               * @dev Records the result of the user operation (e.g. success or revert).
               *
               *      Also, reverts if the paymaster was not active, ensuring that only allowed
               *      operators can make use of this paymaster.
               *
               * @param mode The mode enum representing the operation result.
               */
              function _postOp(
                  PostOpMode mode,
                  bytes calldata context,
                  uint256 /* actualGasCost */
              ) internal override {
                  if (
                      context[0] == CONTEXT_INACTIVE &&
                      _ACTIVE_STATE_ != ActiveState.ACTIVE
                  ) {
                      revert Inactive();
                  }
                  _LAST_OP_MODE_ = mode;
              }
              function _validateSponsoredUserOp(
                  bytes memory signature,
                  address expectedSigner,
                  uint64 deadline,
                  UserOperation calldata userOp
              ) internal {
                  if (block.timestamp > deadline) {
                      revert SignatureExpired(deadline);
                  }
                  if (!_SIGNERS_[expectedSigner]) {
                      revert SignerNotAllowed(expectedSigner);
                  }
                  // Zero-out paymasterAndData before hashing the userOp.
                  UserOperation memory userOpClone = userOp;
                  userOpClone.paymasterAndData = bytes("");
                  userOpClone.signature = bytes("");
                  bytes32 userOpHash = entryPoint.getUserOpHash(userOpClone);
                  bytes32 structHash = keccak256(
                      abi.encode(SPONSOR_USER_OP_TYPEHASH, userOpHash, deadline)
                  );
                  bytes32 digest = _hashTypedDataV4(structHash);
                  address recoveredSigner = ECDSA.recover(digest, signature);
                  if (recoveredSigner != expectedSigner) {
                      revert SignatureInvalid(recoveredSigner, expectedSigner);
                  }
                  if (_SPONSORED_USER_OP_HASHES_[userOpHash]) {
                      revert SponsoredUserOpRepeated(userOpHash);
                  }
                  _SPONSORED_USER_OP_HASHES_[userOpHash] = true;
                  emit UserOpSponsored(userOpHash);
              }
          }
          // SPDX-License-Identifier: UNLICENSED
          pragma solidity ^0.8.13;
          import { Ownable2Step } from "@openzeppelin/contracts/access/Ownable2Step.sol";
          import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
          import { GuardianRescuable } from "./GuardianRescuable.sol";
          /**
           * @title GuardianOwnable
           * @author Fun.xyz
           */
          abstract contract GuardianOwnable is Ownable2Step, GuardianRescuable {
              error RenounceDisabled();
              function guardian() public view override returns (address) {
                  return owner();
              }
              function renounceOwnership() public view override onlyOwner {
                  revert RenounceDisabled();
              }
          }
          // SPDX-License-Identifier: UNLICENSED
          pragma solidity ^0.8.13;
          import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
          interface WETH9Interface is IERC20 {
              function deposit() external payable;
              function withdraw(uint256) external;
          }
          // 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) (proxy/utils/Initializable.sol)
          pragma solidity ^0.8.2;
          import "../../utils/Address.sol";
          /**
           * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
           * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
           * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
           * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
           *
           * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
           * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
           * case an upgrade adds a module that needs to be initialized.
           *
           * For example:
           *
           * [.hljs-theme-light.nopadding]
           * ```solidity
           * contract MyToken is ERC20Upgradeable {
           *     function initialize() initializer public {
           *         __ERC20_init("MyToken", "MTK");
           *     }
           * }
           *
           * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
           *     function initializeV2() reinitializer(2) public {
           *         __ERC20Permit_init("MyToken");
           *     }
           * }
           * ```
           *
           * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
           * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
           *
           * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
           * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
           *
           * [CAUTION]
           * ====
           * Avoid leaving a contract uninitialized.
           *
           * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
           * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
           * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
           *
           * [.hljs-theme-light.nopadding]
           * ```
           * /// @custom:oz-upgrades-unsafe-allow constructor
           * constructor() {
           *     _disableInitializers();
           * }
           * ```
           * ====
           */
          abstract contract Initializable {
              /**
               * @dev Indicates that the contract has been initialized.
               * @custom:oz-retyped-from bool
               */
              uint8 private _initialized;
              /**
               * @dev Indicates that the contract is in the process of being initialized.
               */
              bool private _initializing;
              /**
               * @dev Triggered when the contract has been initialized or reinitialized.
               */
              event Initialized(uint8 version);
              /**
               * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
               * `onlyInitializing` functions can be used to initialize parent contracts.
               *
               * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
               * constructor.
               *
               * Emits an {Initialized} event.
               */
              modifier initializer() {
                  bool isTopLevelCall = !_initializing;
                  require(
                      (isTopLevelCall && _initialized < 1) || (!Address.isContract(address(this)) && _initialized == 1),
                      "Initializable: contract is already initialized"
                  );
                  _initialized = 1;
                  if (isTopLevelCall) {
                      _initializing = true;
                  }
                  _;
                  if (isTopLevelCall) {
                      _initializing = false;
                      emit Initialized(1);
                  }
              }
              /**
               * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
               * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
               * used to initialize parent contracts.
               *
               * A reinitializer may be used after the original initialization step. This is essential to configure modules that
               * are added through upgrades and that require initialization.
               *
               * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
               * cannot be nested. If one is invoked in the context of another, execution will revert.
               *
               * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
               * a contract, executing them in the right order is up to the developer or operator.
               *
               * WARNING: setting the version to 255 will prevent any future reinitialization.
               *
               * Emits an {Initialized} event.
               */
              modifier reinitializer(uint8 version) {
                  require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
                  _initialized = version;
                  _initializing = true;
                  _;
                  _initializing = false;
                  emit Initialized(version);
              }
              /**
               * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
               * {initializer} and {reinitializer} modifiers, directly or indirectly.
               */
              modifier onlyInitializing() {
                  require(_initializing, "Initializable: contract is not initializing");
                  _;
              }
              /**
               * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
               * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
               * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
               * through proxies.
               *
               * Emits an {Initialized} event the first time it is successfully executed.
               */
              function _disableInitializers() internal virtual {
                  require(!_initializing, "Initializable: contract is initializing");
                  if (_initialized != type(uint8).max) {
                      _initialized = type(uint8).max;
                      emit Initialized(type(uint8).max);
                  }
              }
              /**
               * @dev Returns the highest version that has been initialized. See {reinitializer}.
               */
              function _getInitializedVersion() internal view returns (uint8) {
                  return _initialized;
              }
              /**
               * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
               */
              function _isInitializing() internal view returns (bool) {
                  return _initializing;
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/UUPSUpgradeable.sol)
          pragma solidity ^0.8.0;
          import "../../interfaces/draft-IERC1822.sol";
          import "../ERC1967/ERC1967Upgrade.sol";
          /**
           * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
           * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
           *
           * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
           * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
           * `UUPSUpgradeable` with a custom implementation of upgrades.
           *
           * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
           *
           * _Available since v4.1._
           */
          abstract contract UUPSUpgradeable is IERC1822Proxiable, ERC1967Upgrade {
              /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
              address private immutable __self = address(this);
              /**
               * @dev Check that the execution is being performed through a delegatecall call and that the execution context is
               * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
               * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
               * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
               * fail.
               */
              modifier onlyProxy() {
                  require(address(this) != __self, "Function must be called through delegatecall");
                  require(_getImplementation() == __self, "Function must be called through active proxy");
                  _;
              }
              /**
               * @dev Check that the execution is not being performed through a delegate call. This allows a function to be
               * callable on the implementing contract but not through proxies.
               */
              modifier notDelegated() {
                  require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall");
                  _;
              }
              /**
               * @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the
               * implementation. It is used to validate the implementation's compatibility when performing an upgrade.
               *
               * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
               * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
               * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
               */
              function proxiableUUID() external view virtual override notDelegated returns (bytes32) {
                  return _IMPLEMENTATION_SLOT;
              }
              /**
               * @dev Upgrade the implementation of the proxy to `newImplementation`.
               *
               * Calls {_authorizeUpgrade}.
               *
               * Emits an {Upgraded} event.
               *
               * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
               */
              function upgradeTo(address newImplementation) public virtual onlyProxy {
                  _authorizeUpgrade(newImplementation);
                  _upgradeToAndCallUUPS(newImplementation, new bytes(0), false);
              }
              /**
               * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
               * encoded in `data`.
               *
               * Calls {_authorizeUpgrade}.
               *
               * Emits an {Upgraded} event.
               *
               * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
               */
              function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
                  _authorizeUpgrade(newImplementation);
                  _upgradeToAndCallUUPS(newImplementation, data, true);
              }
              /**
               * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
               * {upgradeTo} and {upgradeToAndCall}.
               *
               * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
               *
               * ```solidity
               * function _authorizeUpgrade(address) internal override onlyOwner {}
               * ```
               */
              function _authorizeUpgrade(address newImplementation) internal virtual;
          }
          // SPDX-License-Identifier: GPL-3.0
          pragma solidity ^0.8.12;
          /* solhint-disable avoid-low-level-calls */
          /* solhint-disable no-empty-blocks */
          import "../interfaces/IAccount.sol";
          import "../interfaces/IEntryPoint.sol";
          import "./Helpers.sol";
          /**
           * Basic account implementation.
           * this contract provides the basic logic for implementing the IAccount interface  - validateUserOp
           * specific account implementation should inherit it and provide the account-specific logic
           */
          abstract contract BaseAccount is IAccount {
              using UserOperationLib for UserOperation;
              //return value in case of signature failure, with no time-range.
              // equivalent to _packValidationData(true,0,0);
              uint256 constant internal SIG_VALIDATION_FAILED = 1;
              /**
               * Return the account nonce.
               * This method returns the next sequential nonce.
               * For a nonce of a specific key, use `entrypoint.getNonce(account, key)`
               */
              function getNonce() public view virtual returns (uint256) {
                  return entryPoint().getNonce(address(this), 0);
              }
              /**
               * return the entryPoint used by this account.
               * subclass should return the current entryPoint used by this account.
               */
              function entryPoint() public view virtual returns (IEntryPoint);
              /**
               * Validate user's signature and nonce.
               * subclass doesn't need to override this method. Instead, it should override the specific internal validation methods.
               */
              function validateUserOp(UserOperation calldata userOp, bytes32 userOpHash, uint256 missingAccountFunds)
              external override virtual returns (uint256 validationData) {
                  _requireFromEntryPoint();
                  validationData = _validateSignature(userOp, userOpHash);
                  _validateNonce(userOp.nonce);
                  _payPrefund(missingAccountFunds);
              }
              /**
               * ensure the request comes from the known entrypoint.
               */
              function _requireFromEntryPoint() internal virtual view {
                  require(msg.sender == address(entryPoint()), "account: not from EntryPoint");
              }
              /**
               * validate the signature is valid for this message.
               * @param userOp validate the userOp.signature field
               * @param userOpHash convenient field: the hash of the request, to check the signature against
               *          (also hashes the entrypoint and chain id)
               * @return validationData signature and time-range of this operation
               *      <20-byte> sigAuthorizer - 0 for valid signature, 1 to mark signature failure,
               *         otherwise, an address of an "authorizer" contract.
               *      <6-byte> validUntil - last timestamp this operation is valid. 0 for "indefinite"
               *      <6-byte> validAfter - first timestamp this operation is valid
               *      If the account doesn't use time-range, it is enough to return SIG_VALIDATION_FAILED value (1) for signature failure.
               *      Note that the validation code cannot use block.timestamp (or block.number) directly.
               */
              function _validateSignature(UserOperation calldata userOp, bytes32 userOpHash)
              internal virtual returns (uint256 validationData);
              /**
               * Validate the nonce of the UserOperation.
               * This method may validate the nonce requirement of this account.
               * e.g.
               * To limit the nonce to use sequenced UserOps only (no "out of order" UserOps):
               *      `require(nonce < type(uint64).max)`
               * For a hypothetical account that *requires* the nonce to be out-of-order:
               *      `require(nonce & type(uint64).max == 0)`
               *
               * The actual nonce uniqueness is managed by the EntryPoint, and thus no other
               * action is needed by the account itself.
               *
               * @param nonce to validate
               *
               * solhint-disable-next-line no-empty-blocks
               */
              function _validateNonce(uint256 nonce) internal view virtual {
              }
              /**
               * sends to the entrypoint (msg.sender) the missing funds for this transaction.
               * subclass MAY override this method for better funds management
               * (e.g. send to the entryPoint more than the minimum required, so that in future transactions
               * it will not be required to send again)
               * @param missingAccountFunds the minimum value this method should send the entrypoint.
               *  this value MAY be zero, in case there is enough deposit, or the userOp has a paymaster.
               */
              function _payPrefund(uint256 missingAccountFunds) internal virtual {
                  if (missingAccountFunds != 0) {
                      (bool success,) = payable(msg.sender).call{value : missingAccountFunds, gas : type(uint256).max}("");
                      (success);
                      //ignore failure (its EntryPoint's job to verify, not account.)
                  }
              }
          }
          // SPDX-License-Identifier: GPL-3.0
          pragma solidity ^0.8.12;
          /* solhint-disable no-empty-blocks */
          import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
          import "@openzeppelin/contracts/token/ERC777/IERC777Recipient.sol";
          import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
          import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
          /**
           * Token callback handler.
           *   Handles supported tokens' callbacks, allowing account receiving these tokens.
           */
          contract TokenCallbackHandler is IERC777Recipient, IERC721Receiver, IERC1155Receiver {
              function tokensReceived(
                  address,
                  address,
                  address,
                  uint256,
                  bytes calldata,
                  bytes calldata
              ) external pure override {
              }
              function onERC721Received(
                  address,
                  address,
                  uint256,
                  bytes calldata
              ) external pure override returns (bytes4) {
                  return IERC721Receiver.onERC721Received.selector;
              }
              function onERC1155Received(
                  address,
                  address,
                  uint256,
                  uint256,
                  bytes calldata
              ) external pure override returns (bytes4) {
                  return IERC1155Receiver.onERC1155Received.selector;
              }
              function onERC1155BatchReceived(
                  address,
                  address,
                  uint256[] calldata,
                  uint256[] calldata,
                  bytes calldata
              ) external pure override returns (bytes4) {
                  return IERC1155Receiver.onERC1155BatchReceived.selector;
              }
              function supportsInterface(bytes4 interfaceId) external view virtual override returns (bool) {
                  return
                      interfaceId == type(IERC721Receiver).interfaceId ||
                      interfaceId == type(IERC1155Receiver).interfaceId ||
                      interfaceId == type(IERC165).interfaceId;
              }
          }
          // SPDX-License-Identifier: GPL-3.0-only
          pragma solidity ^0.8.12;
          /**
           * manage deposits and stakes.
           * deposit is just a balance used to pay for UserOperations (either by a paymaster or an account)
           * stake is value locked for at least "unstakeDelay" by the staked entity.
           */
          interface IStakeManager {
              event Deposited(
                  address indexed account,
                  uint256 totalDeposit
              );
              event Withdrawn(
                  address indexed account,
                  address withdrawAddress,
                  uint256 amount
              );
              /// Emitted when stake or unstake delay are modified
              event StakeLocked(
                  address indexed account,
                  uint256 totalStaked,
                  uint256 unstakeDelaySec
              );
              /// Emitted once a stake is scheduled for withdrawal
              event StakeUnlocked(
                  address indexed account,
                  uint256 withdrawTime
              );
              event StakeWithdrawn(
                  address indexed account,
                  address withdrawAddress,
                  uint256 amount
              );
              /**
               * @param deposit the entity's deposit
               * @param staked true if this entity is staked.
               * @param stake actual amount of ether staked for this entity.
               * @param unstakeDelaySec minimum delay to withdraw the stake.
               * @param withdrawTime - first block timestamp where 'withdrawStake' will be callable, or zero if already locked
               * @dev sizes were chosen so that (deposit,staked, stake) fit into one cell (used during handleOps)
               *    and the rest fit into a 2nd cell.
               *    112 bit allows for 10^15 eth
               *    48 bit for full timestamp
               *    32 bit allows 150 years for unstake delay
               */
              struct DepositInfo {
                  uint112 deposit;
                  bool staked;
                  uint112 stake;
                  uint32 unstakeDelaySec;
                  uint48 withdrawTime;
              }
              //API struct used by getStakeInfo and simulateValidation
              struct StakeInfo {
                  uint256 stake;
                  uint256 unstakeDelaySec;
              }
              /// @return info - full deposit information of given account
              function getDepositInfo(address account) external view returns (DepositInfo memory info);
              /// @return the deposit (for gas payment) of the account
              function balanceOf(address account) external view returns (uint256);
              /**
               * add to the deposit of the given account
               */
              function depositTo(address account) external payable;
              /**
               * add to the account's stake - amount and delay
               * any pending unstake is first cancelled.
               * @param _unstakeDelaySec the new lock duration before the deposit can be withdrawn.
               */
              function addStake(uint32 _unstakeDelaySec) external payable;
              /**
               * attempt to unlock the stake.
               * the value can be withdrawn (using withdrawStake) after the unstake delay.
               */
              function unlockStake() external;
              /**
               * withdraw from the (unlocked) stake.
               * must first call unlockStake and wait for the unstakeDelay to pass
               * @param withdrawAddress the address to send withdrawn value.
               */
              function withdrawStake(address payable withdrawAddress) external;
              /**
               * withdraw from the deposit.
               * @param withdrawAddress the address to send withdrawn value.
               * @param withdrawAmount the amount to withdraw.
               */
              function withdrawTo(address payable withdrawAddress, uint256 withdrawAmount) external;
          }
          // SPDX-License-Identifier: GPL-3.0
          pragma solidity ^0.8.12;
          import "./UserOperation.sol";
          /**
           * Aggregated Signatures validator.
           */
          interface IAggregator {
              /**
               * validate aggregated signature.
               * revert if the aggregated signature does not match the given list of operations.
               */
              function validateSignatures(UserOperation[] calldata userOps, bytes calldata signature) external view;
              /**
               * validate signature of a single userOp
               * This method is should be called by bundler after EntryPoint.simulateValidation() returns (reverts) with ValidationResultWithAggregation
               * First it validates the signature over the userOp. Then it returns data to be used when creating the handleOps.
               * @param userOp the userOperation received from the user.
               * @return sigForUserOp the value to put into the signature field of the userOp when calling handleOps.
               *    (usually empty, unless account and aggregator support some kind of "multisig"
               */
              function validateUserOpSignature(UserOperation calldata userOp)
              external view returns (bytes memory sigForUserOp);
              /**
               * aggregate multiple signatures into a single value.
               * This method is called off-chain to calculate the signature to pass with handleOps()
               * bundler MAY use optimized custom code perform this aggregation
               * @param userOps array of UserOperations to collect the signatures from.
               * @return aggregatedSignature the aggregated signature
               */
              function aggregateSignatures(UserOperation[] calldata userOps) external view returns (bytes memory aggregatedSignature);
          }
          // SPDX-License-Identifier: GPL-3.0
          pragma solidity ^0.8.12;
          interface INonceManager {
              /**
               * Return the next nonce for this sender.
               * Within a given key, the nonce values are sequenced (starting with zero, and incremented by one on each userop)
               * But UserOp with different keys can come with arbitrary order.
               *
               * @param sender the account address
               * @param key the high 192 bit of the nonce
               * @return nonce a full nonce to pass for next UserOp with this sender.
               */
              function getNonce(address sender, uint192 key)
              external view returns (uint256 nonce);
              /**
               * Manually increment the nonce of the sender.
               * This method is exposed just for completeness..
               * Account does NOT need to call it, neither during validation, nor elsewhere,
               * as the EntryPoint will update the nonce regardless.
               * Possible use-case is call it with various keys to "initialize" their nonces to one, so that future
               * UserOperations will not pay extra for the first transaction with a given key.
               */
              function incrementNonce(uint192 key) external;
          }
          // SPDX-License-Identifier: GPL-3.0
          pragma solidity ^0.8.12;
          /* solhint-disable no-inline-assembly */
          /**
           * returned data from validateUserOp.
           * validateUserOp returns a uint256, with is created by `_packedValidationData` and parsed by `_parseValidationData`
           * @param aggregator - address(0) - the account validated the signature by itself.
           *              address(1) - the account failed to validate the signature.
           *              otherwise - this is an address of a signature aggregator that must be used to validate the signature.
           * @param validAfter - this UserOp is valid only after this timestamp.
           * @param validaUntil - this UserOp is valid only up to this timestamp.
           */
              struct ValidationData {
                  address aggregator;
                  uint48 validAfter;
                  uint48 validUntil;
              }
          //extract sigFailed, validAfter, validUntil.
          // also convert zero validUntil to type(uint48).max
              function _parseValidationData(uint validationData) pure returns (ValidationData memory data) {
                  address aggregator = address(uint160(validationData));
                  uint48 validUntil = uint48(validationData >> 160);
                  if (validUntil == 0) {
                      validUntil = type(uint48).max;
                  }
                  uint48 validAfter = uint48(validationData >> (48 + 160));
                  return ValidationData(aggregator, validAfter, validUntil);
              }
          // intersect account and paymaster ranges.
              function _intersectTimeRange(uint256 validationData, uint256 paymasterValidationData) pure returns (ValidationData memory) {
                  ValidationData memory accountValidationData = _parseValidationData(validationData);
                  ValidationData memory pmValidationData = _parseValidationData(paymasterValidationData);
                  address aggregator = accountValidationData.aggregator;
                  if (aggregator == address(0)) {
                      aggregator = pmValidationData.aggregator;
                  }
                  uint48 validAfter = accountValidationData.validAfter;
                  uint48 validUntil = accountValidationData.validUntil;
                  uint48 pmValidAfter = pmValidationData.validAfter;
                  uint48 pmValidUntil = pmValidationData.validUntil;
                  if (validAfter < pmValidAfter) validAfter = pmValidAfter;
                  if (validUntil > pmValidUntil) validUntil = pmValidUntil;
                  return ValidationData(aggregator, validAfter, validUntil);
              }
          /**
           * helper to pack the return value for validateUserOp
           * @param data - the ValidationData to pack
           */
              function _packValidationData(ValidationData memory data) pure returns (uint256) {
                  return uint160(data.aggregator) | (uint256(data.validUntil) << 160) | (uint256(data.validAfter) << (160 + 48));
              }
          /**
           * helper to pack the return value for validateUserOp, when not using an aggregator
           * @param sigFailed - true for signature failure, false for success
           * @param validUntil last timestamp this UserOperation is valid (or zero for infinite)
           * @param validAfter first timestamp this UserOperation is valid
           */
              function _packValidationData(bool sigFailed, uint48 validUntil, uint48 validAfter) pure returns (uint256) {
                  return (sigFailed ? 1 : 0) | (uint256(validUntil) << 160) | (uint256(validAfter) << (160 + 48));
              }
          /**
           * keccak function over calldata.
           * @dev copy calldata into memory, do keccak and drop allocated memory. Strangely, this is more efficient than letting solidity do it.
           */
              function calldataKeccak(bytes calldata data) pure returns (bytes32 ret) {
                  assembly {
                      let mem := mload(0x40)
                      let len := data.length
                      calldatacopy(mem, data.offset, len)
                      ret := keccak256(mem, len)
                  }
              }
          // 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) (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: UNLICENSED
          pragma solidity ^0.8.13;
          interface Create2ForwarderInterface {
              function forward() external;
          }
          // SPDX-License-Identifier: UNLICENSED
          pragma solidity ^0.8.13;
          import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
          import {
              Create2ForwarderInterface
          } from "../interfaces/Create2ForwarderInterface.sol";
          import { CheckoutState } from "./CheckoutPoolInterface.sol";
          interface Create2ForwarderFactoryInterface {
              function createAndForward(
                  CheckoutState calldata checkout,
                  bytes32 salt
              ) external returns (Create2ForwarderInterface);
          }
          // SPDX-License-Identifier: UNLICENSED
          pragma solidity ^0.8.13;
          import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
          import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
          import { CheckoutPoolInterface } from "../interfaces/CheckoutPoolInterface.sol";
          import {
              Create2ForwarderInterface
          } from "../interfaces/Create2ForwarderInterface.sol";
          import {
              Create2ForwarderEventsAndErrors
          } from "../interfaces/Create2ForwarderEventsAndErrors.sol";
          import { WETH9Interface } from "../interfaces/WETH9Interface.sol";
          import {
              CheckoutParams,
              CheckoutState
          } from "../interfaces/CheckoutPoolInterface.sol";
          import { GuardianRescuable } from "../utils/GuardianRescuable.sol";
          import { Create2ForwarderProxy } from "./Create2ForwarderProxy.sol";
          /**
           * @title Create2ForwarderImpl
           * @author Fun.xyz
           *
           * @notice A forwarder contract (a.k.a. “deposit address”) for the Checkout Pools protocol.
           *
           *  See Create2ForwarderFactory and Create2ForwarderProxy for more info.
           */
          contract Create2ForwarderImpl is
              GuardianRescuable,
              Create2ForwarderInterface,
              Create2ForwarderEventsAndErrors
          {
              using SafeERC20 for IERC20;
              address public immutable GUARDIAN;
              WETH9Interface public immutable WRAPPED_NATIVE_TOKEN;
              CheckoutPoolInterface public immutable CHECKOUT_POOL;
              address public immutable USDT_TOKEN = address(0xdAC17F958D2ee523a2206206994597C13D831ec7);  
              bool internal _FORWARDED_;
              receive() external payable {}
              /**
               * @notice Implementation constructor.
               *
               *  Sets immutable values that are the same across all deployed proxies.
               */
              constructor(
                  address initialGuardian,
                  WETH9Interface wrappedNativeToken,
                  CheckoutPoolInterface checkoutPool
              ) {
                  GUARDIAN = initialGuardian;
                  WRAPPED_NATIVE_TOKEN = wrappedNativeToken;
                  CHECKOUT_POOL = checkoutPool;
              }
              function guardian() public override view returns (address) {
                  return GUARDIAN;
              }
              /**
               * @notice Forward deposited funds to the CheckoutPool contract.
               */
              function forward() external {
                  // Forward at most once.
                  if (_FORWARDED_) {
                      revert AlreadyForwarded();
                  }
                  _FORWARDED_ = true;
                  // Read checkout state from proxy immutable configuration.
                  CheckoutState memory checkout = Create2ForwarderProxy(payable(this))
                      .getCheckout();
                  IERC20 heldAsset = checkout.heldAsset;
                  uint256 minSourceAmount = checkout.heldAmount;
                  // Get native value.
                  uint256 value = address(this).balance;
                  // Convert any native value to wrapped native token.
                  if (value != 0) {
                      // Note: Intentionally not sanity checking that ERC20 == WRAPPED_NATIVE_TOKEN
                      //       since that's of little help at this point, if the contract is misconfigured.
                      WRAPPED_NATIVE_TOKEN.deposit{ value: value }();
                  }
                  // Get actual held amount.
                  uint256 actualHeldAmount = heldAsset.balanceOf(address(this));
                  // Validate and possibly overwrite the source amount.
                  if (actualHeldAmount < minSourceAmount) {
                      revert Underfunded(actualHeldAmount, minSourceAmount);
                  } else if (actualHeldAmount > minSourceAmount) {
                      checkout.heldAmount = actualHeldAmount;
                  }
                  // Note: Using approve() instead of safeIncreaseAllowance() or forceApprove() under the
                  // assumption that all allowances from this contract will be zero in between transactions.
                  // We have a condition here if it is USDT, where we will perform a safeApprove as USDT does not return any value
                  if (block.chainid == 1 && address(heldAsset) == USDT_TOKEN) {
                      heldAsset.safeApprove(address(CHECKOUT_POOL), type(uint256).max);
                  } else {
                      heldAsset.approve(address(CHECKOUT_POOL), type(uint256).max);
                  }
                  // Make the external call, reverting on failure.
                  try CHECKOUT_POOL.deposit(checkout) {} catch (bytes memory errorData) {
                      revert ForwardError(errorData);
                  }
              }
          }
          // SPDX-License-Identifier: UNLICENSED
          pragma solidity ^0.8.13;
          import { Proxy } from "@openzeppelin/contracts/proxy/Proxy.sol";
          import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
          import {
              SafeERC20
          } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
          import { Create2ForwarderImpl } from "../forwarder/Create2ForwarderImpl.sol";
          import { WETH9Interface } from "../interfaces/WETH9Interface.sol";
          import { GuardianOwnable } from "../utils/GuardianOwnable.sol";
          import {
              CheckoutParams,
              CheckoutState
          } from "../interfaces/CheckoutPoolInterface.sol";
          /**
           * @title Create2ForwarderProxy
           * @author Fun.xyz
           *
           * @notice A forwarder contract proxy (a.k.a. “deposit address”) for the Checkout Pools protocol.
           *
           *  Intended to be deployed as a “counterfactual” contract.
           *
           *  See Create2ForwarderFactory and Create2ForwarderImpl for more info.
           */
          contract Create2ForwarderProxy is Proxy {
              using SafeERC20 for IERC20;
              Create2ForwarderImpl internal immutable IMPLEMENTATION;
              // Expand out the CheckoutState struct so that it can be stored as immutables.
              bytes32 public immutable USER_OP_HASH;
              uint96 public immutable TARGET_CHAIN_ID;
              bytes32 public immutable TARGET_ASSET;
              uint128 public immutable TARGET_AMOUNT;
              uint128 public immutable EXPIRATION;
              bytes32 public immutable RECIPIENT;
              IERC20 public immutable HELD_ASSET; // Here represents the source asset.
              uint256 public immutable HELD_AMOUNT; // Here represents the min source amount.
              receive() external payable override {}
              /**
               * @notice Proxy constructor.
               *
               *  Sets immutable values that are different between deployed proxy instances.
               *
               *  IMPORTANT: Include chain ID in the constructor to ensure that the deposit address is
               *  unique for all checkout operations globally. This reduces confusion and allows us to use
               *  the deposit address as a unique ID in off-chain services. Note that we include the
               *  chain ID as a constructor param instead of hashing it into the salt, for gas efficiency.
               *
               *  The heldAsset and heldAmount are included in the constructor to ensure that it is possible
               *  to prove whether a liquidity provider is censoring checkouts (differenting this from the
               *  case where checkouts are under-funded).
               */
              constructor(
                  Create2ForwarderImpl implementation,
                  CheckoutState memory checkout,
                  uint256 /* chainId */
              ) {
                  IMPLEMENTATION = implementation;
                  USER_OP_HASH = checkout.params.userOpHash;
                  TARGET_ASSET = checkout.params.targetAsset;
                  TARGET_CHAIN_ID = checkout.params.targetChainId;
                  TARGET_AMOUNT = checkout.params.targetAmount;
                  EXPIRATION = checkout.params.expiration;
                  RECIPIENT = checkout.params.recipient;
                  HELD_ASSET = checkout.heldAsset;
                  HELD_AMOUNT = checkout.heldAmount;
              }
              function getCheckout()
                  external
                  view
                  returns (CheckoutState memory checkout)
              {
                  return
                      CheckoutState({
                          params: CheckoutParams({
                              userOpHash: USER_OP_HASH,
                              targetAsset: TARGET_ASSET,
                              targetChainId: TARGET_CHAIN_ID,
                              targetAmount: TARGET_AMOUNT,
                              expiration: EXPIRATION,
                              recipient: RECIPIENT
                          }),
                          heldAsset: HELD_ASSET,
                          heldAmount: HELD_AMOUNT
                      });
              }
              function _implementation() internal view override returns (address) {
                  return address(IMPLEMENTATION);
              }
          }
          // SPDX-License-Identifier: GPL-3.0
          pragma solidity ^0.8.12;
          /* solhint-disable reason-string */
          import "@openzeppelin/contracts/access/Ownable.sol";
          import "../interfaces/IPaymaster.sol";
          import "../interfaces/IEntryPoint.sol";
          import "./Helpers.sol";
          /**
           * Helper class for creating a paymaster.
           * provides helper methods for staking.
           * validates that the postOp is called only by the entryPoint
           */
          abstract contract BasePaymaster is IPaymaster, Ownable {
              IEntryPoint immutable public entryPoint;
              constructor(IEntryPoint _entryPoint) {
                  entryPoint = _entryPoint;
              }
              /// @inheritdoc IPaymaster
              function validatePaymasterUserOp(UserOperation calldata userOp, bytes32 userOpHash, uint256 maxCost)
              external override returns (bytes memory context, uint256 validationData) {
                   _requireFromEntryPoint();
                  return _validatePaymasterUserOp(userOp, userOpHash, maxCost);
              }
              function _validatePaymasterUserOp(UserOperation calldata userOp, bytes32 userOpHash, uint256 maxCost)
              internal virtual returns (bytes memory context, uint256 validationData);
              /// @inheritdoc IPaymaster
              function postOp(PostOpMode mode, bytes calldata context, uint256 actualGasCost) external override {
                  _requireFromEntryPoint();
                  _postOp(mode, context, actualGasCost);
              }
              /**
               * post-operation handler.
               * (verified to be called only through the entryPoint)
               * @dev if subclass returns a non-empty context from validatePaymasterUserOp, it must also implement this method.
               * @param mode enum with the following options:
               *      opSucceeded - user operation succeeded.
               *      opReverted  - user op reverted. still has to pay for gas.
               *      postOpReverted - user op succeeded, but caused postOp (in mode=opSucceeded) to revert.
               *                       Now this is the 2nd call, after user's op was deliberately reverted.
               * @param context - the context value returned by validatePaymasterUserOp
               * @param actualGasCost - actual gas used so far (without this postOp call).
               */
              function _postOp(PostOpMode mode, bytes calldata context, uint256 actualGasCost) internal virtual {
                  (mode,context,actualGasCost); // unused params
                  // subclass must override this method if validatePaymasterUserOp returns a context
                  revert("must override");
              }
              /**
               * add a deposit for this paymaster, used for paying for transaction fees
               */
              function deposit() public payable {
                  entryPoint.depositTo{value : msg.value}(address(this));
              }
              /**
               * withdraw value from the deposit
               * @param withdrawAddress target to send to
               * @param amount to withdraw
               */
              function withdrawTo(address payable withdrawAddress, uint256 amount) public onlyOwner {
                  entryPoint.withdrawTo(withdrawAddress, amount);
              }
              /**
               * add stake for this paymaster.
               * This method can also carry eth value to add to the current stake.
               * @param unstakeDelaySec - the unstake delay for this paymaster. Can only be increased.
               */
              function addStake(uint32 unstakeDelaySec) external payable onlyOwner {
                  entryPoint.addStake{value : msg.value}(unstakeDelaySec);
              }
              /**
               * return current paymaster's deposit on the entryPoint.
               */
              function getDeposit() public view returns (uint256) {
                  return entryPoint.balanceOf(address(this));
              }
              /**
               * unlock the stake, in order to withdraw it.
               * The paymaster can't serve requests once unlocked, until it calls addStake again
               */
              function unlockStake() external onlyOwner {
                  entryPoint.unlockStake();
              }
              /**
               * withdraw the entire paymaster's stake.
               * stake must be unlocked first (and then wait for the unstakeDelay to be over)
               * @param withdrawAddress the address to send withdrawn value.
               */
              function withdrawStake(address payable withdrawAddress) external onlyOwner {
                  entryPoint.withdrawStake(withdrawAddress);
              }
              /// validate the call is made from a valid entrypoint
              function _requireFromEntryPoint() internal virtual {
                  require(msg.sender == address(entryPoint), "Sender not EntryPoint");
              }
          }
          // 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: UNLICENSED
          pragma solidity ^0.8.13;
          interface CheckoutPaymasterEventsAndErrors {
              error Inactive();
              error InvalidPaymasterAndDataLength(uint256 length);
              error OperatorNotAllowed(address operator);
              error SignerNotAllowed(address signer);
              error SignatureExpired(uint256 deadline);
              error SignatureInvalid(address recoveredSigner, address expectedSigner);
              error SponsoredUserOpRepeated(bytes32 userOpHash);
              event OperatorSet(address indexed operator, bool isAllowed);
              event SignerSet(address indexed signer, bool isAllowed);
              /// @dev Intentionally not indexed to save gas since most clients won't need this.
              event UserOpSponsored(bytes32 userOpHash);
          }
          // 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.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: UNLICENSED
          pragma solidity ^0.8.13;
          import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
          import {
              SafeERC20
          } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
          /**
           * @title GuardianRescuable
           * @author Fun.xyz
           */
          abstract contract GuardianRescuable {
              using SafeERC20 for IERC20;
              error NotGuardian(address sender);
              modifier onlyGuardian() {
                  if (msg.sender != guardian()) {
                      revert NotGuardian(msg.sender);
                  }
                  _;
              }
              function guardian() public virtual returns (address);
              function withdrawNative(
                  address payable recipient,
                  uint256 amount
              ) external onlyGuardian {
                  recipient.transfer(amount);
              }
              function withdrawErc20(
                  IERC20 token,
                  address recipient,
                  uint256 amount
              ) external onlyGuardian {
                  token.safeTransfer(recipient, amount);
              }
              function withdrawAllNative(
                  address payable recipient
              ) external onlyGuardian {
                  recipient.transfer(address(this).balance);
              }
              function withdrawAllErc20(
                  IERC20 token,
                  address recipient
              ) external onlyGuardian {
                  uint256 balance = token.balanceOf(address(this));
                  token.safeTransfer(recipient, balance);
              }
          }
          // 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.5.0) (interfaces/draft-IERC1822.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
           * proxy whose upgrades are fully controlled by the current implementation.
           */
          interface IERC1822Proxiable {
              /**
               * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
               * address.
               *
               * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
               * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
               * function revert if invoked through a proxy.
               */
              function proxiableUUID() external view returns (bytes32);
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (proxy/ERC1967/ERC1967Upgrade.sol)
          pragma solidity ^0.8.2;
          import "../beacon/IBeacon.sol";
          import "../../interfaces/IERC1967.sol";
          import "../../interfaces/draft-IERC1822.sol";
          import "../../utils/Address.sol";
          import "../../utils/StorageSlot.sol";
          /**
           * @dev This abstract contract provides getters and event emitting update functions for
           * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
           *
           * _Available since v4.1._
           */
          abstract contract ERC1967Upgrade is IERC1967 {
              // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
              bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
              /**
               * @dev Storage slot with the address of the current implementation.
               * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
               * validated in the constructor.
               */
              bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
              /**
               * @dev Returns the current implementation address.
               */
              function _getImplementation() internal view returns (address) {
                  return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
              }
              /**
               * @dev Stores a new address in the EIP1967 implementation slot.
               */
              function _setImplementation(address newImplementation) private {
                  require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
                  StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
              }
              /**
               * @dev Perform implementation upgrade
               *
               * Emits an {Upgraded} event.
               */
              function _upgradeTo(address newImplementation) internal {
                  _setImplementation(newImplementation);
                  emit Upgraded(newImplementation);
              }
              /**
               * @dev Perform implementation upgrade with additional setup call.
               *
               * Emits an {Upgraded} event.
               */
              function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal {
                  _upgradeTo(newImplementation);
                  if (data.length > 0 || forceCall) {
                      Address.functionDelegateCall(newImplementation, data);
                  }
              }
              /**
               * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
               *
               * Emits an {Upgraded} event.
               */
              function _upgradeToAndCallUUPS(address newImplementation, bytes memory data, bool forceCall) internal {
                  // Upgrades from old implementations will perform a rollback test. This test requires the new
                  // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
                  // this special case will break upgrade paths from old UUPS implementation to new ones.
                  if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {
                      _setImplementation(newImplementation);
                  } else {
                      try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
                          require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID");
                      } catch {
                          revert("ERC1967Upgrade: new implementation is not UUPS");
                      }
                      _upgradeToAndCall(newImplementation, data, forceCall);
                  }
              }
              /**
               * @dev Storage slot with the admin of the contract.
               * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
               * validated in the constructor.
               */
              bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
              /**
               * @dev Returns the current admin.
               */
              function _getAdmin() internal view returns (address) {
                  return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
              }
              /**
               * @dev Stores a new address in the EIP1967 admin slot.
               */
              function _setAdmin(address newAdmin) private {
                  require(newAdmin != address(0), "ERC1967: new admin is the zero address");
                  StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
              }
              /**
               * @dev Changes the admin of the proxy.
               *
               * Emits an {AdminChanged} event.
               */
              function _changeAdmin(address newAdmin) internal {
                  emit AdminChanged(_getAdmin(), newAdmin);
                  _setAdmin(newAdmin);
              }
              /**
               * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
               * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
               */
              bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
              /**
               * @dev Returns the current beacon.
               */
              function _getBeacon() internal view returns (address) {
                  return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
              }
              /**
               * @dev Stores a new beacon in the EIP1967 beacon slot.
               */
              function _setBeacon(address newBeacon) private {
                  require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract");
                  require(
                      Address.isContract(IBeacon(newBeacon).implementation()),
                      "ERC1967: beacon implementation is not a contract"
                  );
                  StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
              }
              /**
               * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
               * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
               *
               * Emits a {BeaconUpgraded} event.
               */
              function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal {
                  _setBeacon(newBeacon);
                  emit BeaconUpgraded(newBeacon);
                  if (data.length > 0 || forceCall) {
                      Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
                  }
              }
          }
          // SPDX-License-Identifier: GPL-3.0
          pragma solidity ^0.8.12;
          import "./UserOperation.sol";
          interface IAccount {
              /**
               * Validate user's signature and nonce
               * the entryPoint will make the call to the recipient only if this validation call returns successfully.
               * signature failure should be reported by returning SIG_VALIDATION_FAILED (1).
               * This allows making a "simulation call" without a valid signature
               * Other failures (e.g. nonce mismatch, or invalid signature format) should still revert to signal failure.
               *
               * @dev Must validate caller is the entryPoint.
               *      Must validate the signature and nonce
               * @param userOp the operation that is about to be executed.
               * @param userOpHash hash of the user's request data. can be used as the basis for signature.
               * @param missingAccountFunds missing funds on the account's deposit in the entrypoint.
               *      This is the minimum amount to transfer to the sender(entryPoint) to be able to make the call.
               *      The excess is left as a deposit in the entrypoint, for future calls.
               *      can be withdrawn anytime using "entryPoint.withdrawTo()"
               *      In case there is a paymaster in the request (or the current deposit is high enough), this value will be zero.
               * @return validationData packaged ValidationData structure. use `_packValidationData` and `_unpackValidationData` to encode and decode
               *      <20-byte> sigAuthorizer - 0 for valid signature, 1 to mark signature failure,
               *         otherwise, an address of an "authorizer" contract.
               *      <6-byte> validUntil - last timestamp this operation is valid. 0 for "indefinite"
               *      <6-byte> validAfter - first timestamp this operation is valid
               *      If an account doesn't use time-range, it is enough to return SIG_VALIDATION_FAILED value (1) for signature failure.
               *      Note that the validation code cannot use block.timestamp (or block.number) directly.
               */
              function validateUserOp(UserOperation calldata userOp, bytes32 userOpHash, uint256 missingAccountFunds)
              external returns (uint256 validationData);
          }
          // 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 v4.4.1 (token/ERC777/IERC777Recipient.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev Interface of the ERC777TokensRecipient standard as defined in the EIP.
           *
           * Accounts can be notified of {IERC777} tokens being sent to them by having a
           * contract implement this interface (contract holders can be their own
           * implementer) and registering it on the
           * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
           *
           * See {IERC1820Registry} and {ERC1820Implementer}.
           */
          interface IERC777Recipient {
              /**
               * @dev Called by an {IERC777} token contract whenever tokens are being
               * moved or created into a registered account (`to`). The type of operation
               * is conveyed by `from` being the zero address or not.
               *
               * This call occurs _after_ the token contract's state is updated, so
               * {IERC777-balanceOf}, etc., can be used to query the post-operation state.
               *
               * This function may revert to prevent the operation from being executed.
               */
              function tokensReceived(
                  address operator,
                  address from,
                  address to,
                  uint256 amount,
                  bytes calldata userData,
                  bytes calldata operatorData
              ) external;
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)
          pragma solidity ^0.8.0;
          /**
           * @title ERC721 token receiver interface
           * @dev Interface for any contract that wants to support safeTransfers
           * from ERC721 asset contracts.
           */
          interface IERC721Receiver {
              /**
               * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
               * by `operator` from `from`, this function is called.
               *
               * It must return its Solidity selector to confirm the token transfer.
               * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
               *
               * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
               */
              function onERC721Received(
                  address operator,
                  address from,
                  uint256 tokenId,
                  bytes calldata data
              ) external returns (bytes4);
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)
          pragma solidity ^0.8.0;
          import "../../utils/introspection/IERC165.sol";
          /**
           * @dev _Available since v3.1._
           */
          interface IERC1155Receiver is IERC165 {
              /**
               * @dev Handles the receipt of a single ERC1155 token type. This function is
               * called at the end of a `safeTransferFrom` after the balance has been updated.
               *
               * NOTE: To accept the transfer, this must return
               * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
               * (i.e. 0xf23a6e61, or its own function selector).
               *
               * @param operator The address which initiated the transfer (i.e. msg.sender)
               * @param from The address which previously owned the token
               * @param id The ID of the token being transferred
               * @param value The amount of tokens being transferred
               * @param data Additional data with no specified format
               * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
               */
              function onERC1155Received(
                  address operator,
                  address from,
                  uint256 id,
                  uint256 value,
                  bytes calldata data
              ) external returns (bytes4);
              /**
               * @dev Handles the receipt of a multiple ERC1155 token types. This function
               * is called at the end of a `safeBatchTransferFrom` after the balances have
               * been updated.
               *
               * NOTE: To accept the transfer(s), this must return
               * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
               * (i.e. 0xbc197c81, or its own function selector).
               *
               * @param operator The address which initiated the batch transfer (i.e. msg.sender)
               * @param from The address which previously owned the token
               * @param ids An array containing ids of each token being transferred (order and length must match values array)
               * @param values An array containing amounts of each token being transferred (order and length must match ids array)
               * @param data Additional data with no specified format
               * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
               */
              function onERC1155BatchReceived(
                  address operator,
                  address from,
                  uint256[] calldata ids,
                  uint256[] calldata values,
                  bytes calldata data
              ) external returns (bytes4);
          }
          // SPDX-License-Identifier: UNLICENSED
          pragma solidity ^0.8.13;
          interface Create2ForwarderEventsAndErrors {
              error AlreadyForwarded();
              error ForwardError(bytes errorData);
              error Underfunded(uint256 actualHeldAmount, uint256 minSourceAmount);
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
           * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
           * be specified by overriding the virtual {_implementation} function.
           *
           * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
           * different contract through the {_delegate} function.
           *
           * The success and return data of the delegated call will be returned back to the caller of the proxy.
           */
          abstract contract Proxy {
              /**
               * @dev Delegates the current call to `implementation`.
               *
               * This function does not return to its internal call site, it will return directly to the external caller.
               */
              function _delegate(address implementation) internal virtual {
                  assembly {
                      // Copy msg.data. We take full control of memory in this inline assembly
                      // block because it will not return to Solidity code. We overwrite the
                      // Solidity scratch pad at memory position 0.
                      calldatacopy(0, 0, calldatasize())
                      // Call the implementation.
                      // out and outsize are 0 because we don't know the size yet.
                      let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
                      // Copy the returned data.
                      returndatacopy(0, 0, returndatasize())
                      switch result
                      // delegatecall returns 0 on error.
                      case 0 {
                          revert(0, returndatasize())
                      }
                      default {
                          return(0, returndatasize())
                      }
                  }
              }
              /**
               * @dev This is a virtual function that should be overridden so it returns the address to which the fallback function
               * and {_fallback} should delegate.
               */
              function _implementation() internal view virtual returns (address);
              /**
               * @dev Delegates the current call to the address returned by `_implementation()`.
               *
               * This function does not return to its internal call site, it will return directly to the external caller.
               */
              function _fallback() internal virtual {
                  _beforeFallback();
                  _delegate(_implementation());
              }
              /**
               * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
               * function in the contract matches the call data.
               */
              fallback() external payable virtual {
                  _fallback();
              }
              /**
               * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
               * is empty.
               */
              receive() external payable virtual {
                  _fallback();
              }
              /**
               * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
               * call, or as part of the Solidity `fallback` or `receive` functions.
               *
               * If overridden should call `super._beforeFallback()`.
               */
              function _beforeFallback() internal virtual {}
          }
          // 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) (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 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.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 v4.4.1 (proxy/beacon/IBeacon.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev This is the interface that {BeaconProxy} expects of its beacon.
           */
          interface IBeacon {
              /**
               * @dev Must return an address that can be used as a delegate call target.
               *
               * {BeaconProxy} will check that this address is a contract.
               */
              function implementation() external view returns (address);
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC1967.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
           *
           * _Available since v4.8.3._
           */
          interface IERC1967 {
              /**
               * @dev Emitted when the implementation is upgraded.
               */
              event Upgraded(address indexed implementation);
              /**
               * @dev Emitted when the admin account has changed.
               */
              event AdminChanged(address previousAdmin, address newAdmin);
              /**
               * @dev Emitted when the beacon is changed.
               */
              event BeaconUpgraded(address indexed beacon);
          }
          // 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
                  }
              }
          }
          

          File 4 of 4: Create2ForwarderImpl
          // SPDX-License-Identifier: UNLICENSED
          pragma solidity ^0.8.13;
          import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
          import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
          import { CheckoutPoolInterface } from "../interfaces/CheckoutPoolInterface.sol";
          import {
              Create2ForwarderInterface
          } from "../interfaces/Create2ForwarderInterface.sol";
          import {
              Create2ForwarderEventsAndErrors
          } from "../interfaces/Create2ForwarderEventsAndErrors.sol";
          import { WETH9Interface } from "../interfaces/WETH9Interface.sol";
          import {
              CheckoutParams,
              CheckoutState
          } from "../interfaces/CheckoutPoolInterface.sol";
          import { GuardianRescuable } from "../utils/GuardianRescuable.sol";
          import { Create2ForwarderProxy } from "./Create2ForwarderProxy.sol";
          /**
           * @title Create2ForwarderImpl
           * @author Fun.xyz
           *
           * @notice A forwarder contract (a.k.a. “deposit address”) for the Checkout Pools protocol.
           *
           *  See Create2ForwarderFactory and Create2ForwarderProxy for more info.
           */
          contract Create2ForwarderImpl is
              GuardianRescuable,
              Create2ForwarderInterface,
              Create2ForwarderEventsAndErrors
          {
              using SafeERC20 for IERC20;
              address public immutable GUARDIAN;
              WETH9Interface public immutable WRAPPED_NATIVE_TOKEN;
              CheckoutPoolInterface public immutable CHECKOUT_POOL;
              address public immutable USDT_TOKEN = address(0xdAC17F958D2ee523a2206206994597C13D831ec7);  
              bool internal _FORWARDED_;
              receive() external payable {}
              /**
               * @notice Implementation constructor.
               *
               *  Sets immutable values that are the same across all deployed proxies.
               */
              constructor(
                  address initialGuardian,
                  WETH9Interface wrappedNativeToken,
                  CheckoutPoolInterface checkoutPool
              ) {
                  GUARDIAN = initialGuardian;
                  WRAPPED_NATIVE_TOKEN = wrappedNativeToken;
                  CHECKOUT_POOL = checkoutPool;
              }
              function guardian() public override view returns (address) {
                  return GUARDIAN;
              }
              /**
               * @notice Forward deposited funds to the CheckoutPool contract.
               */
              function forward() external {
                  // Forward at most once.
                  if (_FORWARDED_) {
                      revert AlreadyForwarded();
                  }
                  _FORWARDED_ = true;
                  // Read checkout state from proxy immutable configuration.
                  CheckoutState memory checkout = Create2ForwarderProxy(payable(this))
                      .getCheckout();
                  IERC20 heldAsset = checkout.heldAsset;
                  uint256 minSourceAmount = checkout.heldAmount;
                  // Get native value.
                  uint256 value = address(this).balance;
                  // Convert any native value to wrapped native token.
                  if (value != 0) {
                      // Note: Intentionally not sanity checking that ERC20 == WRAPPED_NATIVE_TOKEN
                      //       since that's of little help at this point, if the contract is misconfigured.
                      WRAPPED_NATIVE_TOKEN.deposit{ value: value }();
                  }
                  // Get actual held amount.
                  uint256 actualHeldAmount = heldAsset.balanceOf(address(this));
                  // Validate and possibly overwrite the source amount.
                  if (actualHeldAmount < minSourceAmount) {
                      revert Underfunded(actualHeldAmount, minSourceAmount);
                  } else if (actualHeldAmount > minSourceAmount) {
                      checkout.heldAmount = actualHeldAmount;
                  }
                  // Note: Using approve() instead of safeIncreaseAllowance() or forceApprove() under the
                  // assumption that all allowances from this contract will be zero in between transactions.
                  // We have a condition here if it is USDT, where we will perform a safeApprove as USDT does not return any value
                  if (block.chainid == 1 && address(heldAsset) == USDT_TOKEN) {
                      heldAsset.safeApprove(address(CHECKOUT_POOL), type(uint256).max);
                  } else {
                      heldAsset.approve(address(CHECKOUT_POOL), type(uint256).max);
                  }
                  // Make the external call, reverting on failure.
                  try CHECKOUT_POOL.deposit(checkout) {} catch (bytes memory errorData) {
                      revert ForwardError(errorData);
                  }
              }
          }
          // 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: UNLICENSED
          pragma solidity ^0.8.13;
          import {
              UserOperation
          } from "@account-abstraction/contracts/interfaces/UserOperation.sol";
          import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
          /// @dev Immutable parameters of a checkout account.
          struct CheckoutParams {
              bytes32 userOpHash;
              bytes32 targetAsset;
              uint96 targetChainId;
              uint128 targetAmount;
              uint128 expiration;
              bytes32 recipient;
          }
          /// @dev State of a checkout account.
          struct CheckoutState {
              CheckoutParams params;
              IERC20 heldAsset;
              uint256 heldAmount;
          }
          struct SwapParams {
              address target;
              address spender;
              bytes callData;
              address receivedAsset;
              bool isETHSwap;
          }
          struct BridgeParams {
              address target;
              address spender;
              bytes callData;
              IERC20 bridgeReceivedAsset;
              uint256 minBridgeReceivedAmount;
          }
          interface CheckoutPoolInterface {
              function deposit(CheckoutState calldata checkoutState) external;
              function swap(
                  address depositAddress,
                  SwapParams calldata swapParams
              ) external;
              function bridge(
                  address depositAddress,
                  BridgeParams calldata bridgeParams
              ) external;
              function execute(
                  address depositAddress,
                  UserOperation[] calldata ops // length-1 array (gas optimization)
              ) external;
              function checkoutExists(
                  address depositAddress
              ) external view returns (bool);
              function getCheckout(
                  address depositAddress
              ) external view returns (CheckoutState memory);
              function getCheckoutOrZero(
                  address depositAddress
              ) external view returns (CheckoutState memory);
              function forwardFund(address depositAddress) external;
          }
          // SPDX-License-Identifier: UNLICENSED
          pragma solidity ^0.8.13;
          interface Create2ForwarderInterface {
              function forward() external;
          }
          // SPDX-License-Identifier: UNLICENSED
          pragma solidity ^0.8.13;
          interface Create2ForwarderEventsAndErrors {
              error AlreadyForwarded();
              error ForwardError(bytes errorData);
              error Underfunded(uint256 actualHeldAmount, uint256 minSourceAmount);
          }
          // SPDX-License-Identifier: UNLICENSED
          pragma solidity ^0.8.13;
          import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
          interface WETH9Interface is IERC20 {
              function deposit() external payable;
              function withdraw(uint256) external;
          }
          // SPDX-License-Identifier: UNLICENSED
          pragma solidity ^0.8.13;
          import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
          import {
              SafeERC20
          } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
          /**
           * @title GuardianRescuable
           * @author Fun.xyz
           */
          abstract contract GuardianRescuable {
              using SafeERC20 for IERC20;
              error NotGuardian(address sender);
              modifier onlyGuardian() {
                  if (msg.sender != guardian()) {
                      revert NotGuardian(msg.sender);
                  }
                  _;
              }
              function guardian() public virtual returns (address);
              function withdrawNative(
                  address payable recipient,
                  uint256 amount
              ) external onlyGuardian {
                  recipient.transfer(amount);
              }
              function withdrawErc20(
                  IERC20 token,
                  address recipient,
                  uint256 amount
              ) external onlyGuardian {
                  token.safeTransfer(recipient, amount);
              }
              function withdrawAllNative(
                  address payable recipient
              ) external onlyGuardian {
                  recipient.transfer(address(this).balance);
              }
              function withdrawAllErc20(
                  IERC20 token,
                  address recipient
              ) external onlyGuardian {
                  uint256 balance = token.balanceOf(address(this));
                  token.safeTransfer(recipient, balance);
              }
          }
          // SPDX-License-Identifier: UNLICENSED
          pragma solidity ^0.8.13;
          import { Proxy } from "@openzeppelin/contracts/proxy/Proxy.sol";
          import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
          import {
              SafeERC20
          } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
          import { Create2ForwarderImpl } from "../forwarder/Create2ForwarderImpl.sol";
          import { WETH9Interface } from "../interfaces/WETH9Interface.sol";
          import { GuardianOwnable } from "../utils/GuardianOwnable.sol";
          import {
              CheckoutParams,
              CheckoutState
          } from "../interfaces/CheckoutPoolInterface.sol";
          /**
           * @title Create2ForwarderProxy
           * @author Fun.xyz
           *
           * @notice A forwarder contract proxy (a.k.a. “deposit address”) for the Checkout Pools protocol.
           *
           *  Intended to be deployed as a “counterfactual” contract.
           *
           *  See Create2ForwarderFactory and Create2ForwarderImpl for more info.
           */
          contract Create2ForwarderProxy is Proxy {
              using SafeERC20 for IERC20;
              Create2ForwarderImpl internal immutable IMPLEMENTATION;
              // Expand out the CheckoutState struct so that it can be stored as immutables.
              bytes32 public immutable USER_OP_HASH;
              uint96 public immutable TARGET_CHAIN_ID;
              bytes32 public immutable TARGET_ASSET;
              uint128 public immutable TARGET_AMOUNT;
              uint128 public immutable EXPIRATION;
              bytes32 public immutable RECIPIENT;
              IERC20 public immutable HELD_ASSET; // Here represents the source asset.
              uint256 public immutable HELD_AMOUNT; // Here represents the min source amount.
              receive() external payable override {}
              /**
               * @notice Proxy constructor.
               *
               *  Sets immutable values that are different between deployed proxy instances.
               *
               *  IMPORTANT: Include chain ID in the constructor to ensure that the deposit address is
               *  unique for all checkout operations globally. This reduces confusion and allows us to use
               *  the deposit address as a unique ID in off-chain services. Note that we include the
               *  chain ID as a constructor param instead of hashing it into the salt, for gas efficiency.
               *
               *  The heldAsset and heldAmount are included in the constructor to ensure that it is possible
               *  to prove whether a liquidity provider is censoring checkouts (differenting this from the
               *  case where checkouts are under-funded).
               */
              constructor(
                  Create2ForwarderImpl implementation,
                  CheckoutState memory checkout,
                  uint256 /* chainId */
              ) {
                  IMPLEMENTATION = implementation;
                  USER_OP_HASH = checkout.params.userOpHash;
                  TARGET_ASSET = checkout.params.targetAsset;
                  TARGET_CHAIN_ID = checkout.params.targetChainId;
                  TARGET_AMOUNT = checkout.params.targetAmount;
                  EXPIRATION = checkout.params.expiration;
                  RECIPIENT = checkout.params.recipient;
                  HELD_ASSET = checkout.heldAsset;
                  HELD_AMOUNT = checkout.heldAmount;
              }
              function getCheckout()
                  external
                  view
                  returns (CheckoutState memory checkout)
              {
                  return
                      CheckoutState({
                          params: CheckoutParams({
                              userOpHash: USER_OP_HASH,
                              targetAsset: TARGET_ASSET,
                              targetChainId: TARGET_CHAIN_ID,
                              targetAmount: TARGET_AMOUNT,
                              expiration: EXPIRATION,
                              recipient: RECIPIENT
                          }),
                          heldAsset: HELD_ASSET,
                          heldAmount: HELD_AMOUNT
                      });
              }
              function _implementation() internal view override returns (address) {
                  return address(IMPLEMENTATION);
              }
          }
          // 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) (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: GPL-3.0
          pragma solidity ^0.8.12;
          /* solhint-disable no-inline-assembly */
          import {calldataKeccak} from "../core/Helpers.sol";
          /**
           * User Operation struct
           * @param sender the sender account of this request.
               * @param nonce unique value the sender uses to verify it is not a replay.
               * @param initCode if set, the account contract will be created by this constructor/
               * @param callData the method call to execute on this account.
               * @param callGasLimit the gas limit passed to the callData method call.
               * @param verificationGasLimit gas used for validateUserOp and validatePaymasterUserOp.
               * @param preVerificationGas gas not calculated by the handleOps method, but added to the gas paid. Covers batch overhead.
               * @param maxFeePerGas same as EIP-1559 gas parameter.
               * @param maxPriorityFeePerGas same as EIP-1559 gas parameter.
               * @param paymasterAndData if set, this field holds the paymaster address and paymaster-specific data. the paymaster will pay for the transaction instead of the sender.
               * @param signature sender-verified signature over the entire request, the EntryPoint address and the chain ID.
               */
              struct UserOperation {
                  address sender;
                  uint256 nonce;
                  bytes initCode;
                  bytes callData;
                  uint256 callGasLimit;
                  uint256 verificationGasLimit;
                  uint256 preVerificationGas;
                  uint256 maxFeePerGas;
                  uint256 maxPriorityFeePerGas;
                  bytes paymasterAndData;
                  bytes signature;
              }
          /**
           * Utility functions helpful when working with UserOperation structs.
           */
          library UserOperationLib {
              function getSender(UserOperation calldata userOp) internal pure returns (address) {
                  address data;
                  //read sender from userOp, which is first userOp member (saves 800 gas...)
                  assembly {data := calldataload(userOp)}
                  return address(uint160(data));
              }
              //relayer/block builder might submit the TX with higher priorityFee, but the user should not
              // pay above what he signed for.
              function gasPrice(UserOperation calldata userOp) internal view returns (uint256) {
              unchecked {
                  uint256 maxFeePerGas = userOp.maxFeePerGas;
                  uint256 maxPriorityFeePerGas = userOp.maxPriorityFeePerGas;
                  if (maxFeePerGas == maxPriorityFeePerGas) {
                      //legacy mode (for networks that don't support basefee opcode)
                      return maxFeePerGas;
                  }
                  return min(maxFeePerGas, maxPriorityFeePerGas + block.basefee);
              }
              }
              function pack(UserOperation calldata userOp) internal pure returns (bytes memory ret) {
                  address sender = getSender(userOp);
                  uint256 nonce = userOp.nonce;
                  bytes32 hashInitCode = calldataKeccak(userOp.initCode);
                  bytes32 hashCallData = calldataKeccak(userOp.callData);
                  uint256 callGasLimit = userOp.callGasLimit;
                  uint256 verificationGasLimit = userOp.verificationGasLimit;
                  uint256 preVerificationGas = userOp.preVerificationGas;
                  uint256 maxFeePerGas = userOp.maxFeePerGas;
                  uint256 maxPriorityFeePerGas = userOp.maxPriorityFeePerGas;
                  bytes32 hashPaymasterAndData = calldataKeccak(userOp.paymasterAndData);
                  return abi.encode(
                      sender, nonce,
                      hashInitCode, hashCallData,
                      callGasLimit, verificationGasLimit, preVerificationGas,
                      maxFeePerGas, maxPriorityFeePerGas,
                      hashPaymasterAndData
                  );
              }
              function hash(UserOperation calldata userOp) internal pure returns (bytes32) {
                  return keccak256(pack(userOp));
              }
              function min(uint256 a, uint256 b) internal pure returns (uint256) {
                  return a < b ? a : b;
              }
          }
          // SPDX-License-Identifier: MIT
          // OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol)
          pragma solidity ^0.8.0;
          /**
           * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
           * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
           * be specified by overriding the virtual {_implementation} function.
           *
           * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
           * different contract through the {_delegate} function.
           *
           * The success and return data of the delegated call will be returned back to the caller of the proxy.
           */
          abstract contract Proxy {
              /**
               * @dev Delegates the current call to `implementation`.
               *
               * This function does not return to its internal call site, it will return directly to the external caller.
               */
              function _delegate(address implementation) internal virtual {
                  assembly {
                      // Copy msg.data. We take full control of memory in this inline assembly
                      // block because it will not return to Solidity code. We overwrite the
                      // Solidity scratch pad at memory position 0.
                      calldatacopy(0, 0, calldatasize())
                      // Call the implementation.
                      // out and outsize are 0 because we don't know the size yet.
                      let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
                      // Copy the returned data.
                      returndatacopy(0, 0, returndatasize())
                      switch result
                      // delegatecall returns 0 on error.
                      case 0 {
                          revert(0, returndatasize())
                      }
                      default {
                          return(0, returndatasize())
                      }
                  }
              }
              /**
               * @dev This is a virtual function that should be overridden so it returns the address to which the fallback function
               * and {_fallback} should delegate.
               */
              function _implementation() internal view virtual returns (address);
              /**
               * @dev Delegates the current call to the address returned by `_implementation()`.
               *
               * This function does not return to its internal call site, it will return directly to the external caller.
               */
              function _fallback() internal virtual {
                  _beforeFallback();
                  _delegate(_implementation());
              }
              /**
               * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
               * function in the contract matches the call data.
               */
              fallback() external payable virtual {
                  _fallback();
              }
              /**
               * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
               * is empty.
               */
              receive() external payable virtual {
                  _fallback();
              }
              /**
               * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
               * call, or as part of the Solidity `fallback` or `receive` functions.
               *
               * If overridden should call `super._beforeFallback()`.
               */
              function _beforeFallback() internal virtual {}
          }
          // SPDX-License-Identifier: UNLICENSED
          pragma solidity ^0.8.13;
          import { Ownable2Step } from "@openzeppelin/contracts/access/Ownable2Step.sol";
          import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
          import { GuardianRescuable } from "./GuardianRescuable.sol";
          /**
           * @title GuardianOwnable
           * @author Fun.xyz
           */
          abstract contract GuardianOwnable is Ownable2Step, GuardianRescuable {
              error RenounceDisabled();
              function guardian() public view override returns (address) {
                  return owner();
              }
              function renounceOwnership() public view override onlyOwner {
                  revert RenounceDisabled();
              }
          }
          // SPDX-License-Identifier: GPL-3.0
          pragma solidity ^0.8.12;
          /* solhint-disable no-inline-assembly */
          /**
           * returned data from validateUserOp.
           * validateUserOp returns a uint256, with is created by `_packedValidationData` and parsed by `_parseValidationData`
           * @param aggregator - address(0) - the account validated the signature by itself.
           *              address(1) - the account failed to validate the signature.
           *              otherwise - this is an address of a signature aggregator that must be used to validate the signature.
           * @param validAfter - this UserOp is valid only after this timestamp.
           * @param validaUntil - this UserOp is valid only up to this timestamp.
           */
              struct ValidationData {
                  address aggregator;
                  uint48 validAfter;
                  uint48 validUntil;
              }
          //extract sigFailed, validAfter, validUntil.
          // also convert zero validUntil to type(uint48).max
              function _parseValidationData(uint validationData) pure returns (ValidationData memory data) {
                  address aggregator = address(uint160(validationData));
                  uint48 validUntil = uint48(validationData >> 160);
                  if (validUntil == 0) {
                      validUntil = type(uint48).max;
                  }
                  uint48 validAfter = uint48(validationData >> (48 + 160));
                  return ValidationData(aggregator, validAfter, validUntil);
              }
          // intersect account and paymaster ranges.
              function _intersectTimeRange(uint256 validationData, uint256 paymasterValidationData) pure returns (ValidationData memory) {
                  ValidationData memory accountValidationData = _parseValidationData(validationData);
                  ValidationData memory pmValidationData = _parseValidationData(paymasterValidationData);
                  address aggregator = accountValidationData.aggregator;
                  if (aggregator == address(0)) {
                      aggregator = pmValidationData.aggregator;
                  }
                  uint48 validAfter = accountValidationData.validAfter;
                  uint48 validUntil = accountValidationData.validUntil;
                  uint48 pmValidAfter = pmValidationData.validAfter;
                  uint48 pmValidUntil = pmValidationData.validUntil;
                  if (validAfter < pmValidAfter) validAfter = pmValidAfter;
                  if (validUntil > pmValidUntil) validUntil = pmValidUntil;
                  return ValidationData(aggregator, validAfter, validUntil);
              }
          /**
           * helper to pack the return value for validateUserOp
           * @param data - the ValidationData to pack
           */
              function _packValidationData(ValidationData memory data) pure returns (uint256) {
                  return uint160(data.aggregator) | (uint256(data.validUntil) << 160) | (uint256(data.validAfter) << (160 + 48));
              }
          /**
           * helper to pack the return value for validateUserOp, when not using an aggregator
           * @param sigFailed - true for signature failure, false for success
           * @param validUntil last timestamp this UserOperation is valid (or zero for infinite)
           * @param validAfter first timestamp this UserOperation is valid
           */
              function _packValidationData(bool sigFailed, uint48 validUntil, uint48 validAfter) pure returns (uint256) {
                  return (sigFailed ? 1 : 0) | (uint256(validUntil) << 160) | (uint256(validAfter) << (160 + 48));
              }
          /**
           * keccak function over calldata.
           * @dev copy calldata into memory, do keccak and drop allocated memory. Strangely, this is more efficient than letting solidity do it.
           */
              function calldataKeccak(bytes calldata data) pure returns (bytes32 ret) {
                  assembly {
                      let mem := mload(0x40)
                      let len := data.length
                      calldatacopy(mem, data.offset, len)
                      ret := keccak256(mem, len)
                  }
              }
          // 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.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 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;
              }
          }