ETH Price: $1,999.06 (+3.21%)

Transaction Decoder

Block:
21759261 at Feb-02-2025 01:55:47 PM +UTC
Transaction Fee:
0.000297998859560791 ETH $0.60
Gas Used:
99,061 Gas / 3.008235931 Gwei

Emitted Events:

465 WETH9.Deposit( dst=EnsoShortcuts, wad=300000000000000000 )
466 WETH9.Transfer( src=EnsoShortcuts, dst=[Sender] 0xb47c0381a112c27eef5bc1b45fc4727149c07ccf, wad=300000000000000000 )

Account State Difference:

  Address   Before After State Difference Code
(beaverbuild)
18.214599807470277536 Eth18.214600223526477536 Eth0.0000004160562
0xb47c0381...149C07CcF
0.3103 Eth
Nonce: 0
0.010002001140439209 Eth
Nonce: 1
0.300297998859560791
0xC02aaA39...83C756Cc2 2,959,444.667973697562597337 Eth2,959,444.967973697562597337 Eth0.3

Execution Trace

ETH 0.3 EnsoShortcutRouter.routeSingle( ) => ( returnData=[AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABCnQaRieAAA=, AAAAAAAAAAAAAAAAtHwDgaESwn7vW8G0X8RycUnAfM8=, AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAE=] )
  • ETH 0.3 EnsoShortcuts.executeShortcut( ) => ( [AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABCnQaRieAAA=, AAAAAAAAAAAAAAAAtHwDgaESwn7vW8G0X8RycUnAfM8=, AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAE=] )
    • ETH 0.3 WETH9.CALL( )
    • WETH9.transfer( dst=0xb47c0381a112c27EEF5bc1B45fC4727149C07CcF, wad=300000000000000000 ) => ( True )
    • EnsoShortcutsHelpers.isEqualOrGreaterThan( a=300000000000000000, b=299250000000000000 ) => ( True )
    • EnsoShortcutsHelpers.check( condition=True )
      File 1 of 4: EnsoShortcutRouter
      // SPDX-License-Identifier: GPL-3.0-only
      pragma solidity ^0.8.0;
      import { EnsoShortcuts } from "./EnsoShortcuts.sol";
      import { SafeERC20, IERC20 } from "openzeppelin/token/ERC20/utils/SafeERC20.sol";
      struct Token {
          IERC20 token;
          uint256 amount;
      }
      contract EnsoShortcutRouter {
          using SafeERC20 for IERC20;
          IERC20 private constant _ETH = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
          EnsoShortcuts public immutable enso;
          error WrongValue(uint256 value, uint256 amount);
          error AmountTooLow(address token);
          error Duplicate(address token);
          constructor(address owner_) {
              enso = new EnsoShortcuts(owner_, address(this));
          }
          // @notice Route a single token via an Enso Shortcut
          // @param tokenIn The address of the token to send
          // @param amountIn The amount of the token to send
          // @param commands An array of bytes32 values that encode calls
          // @param state An array of bytes that are used to generate call data for each command
          function routeSingle(
              IERC20 tokenIn,
              uint256 amountIn,
              bytes32[] calldata commands,
              bytes[] calldata state
          ) public payable returns (bytes[] memory returnData) {
              if (tokenIn == _ETH) {
                  if (msg.value != amountIn) revert WrongValue(msg.value, amountIn);
              } else {
                  if (msg.value != 0) revert WrongValue(msg.value, 0);
                  tokenIn.safeTransferFrom(msg.sender, address(enso), amountIn);
              }
              returnData = enso.executeShortcut{value: msg.value}(commands, state);
          }
          // @notice Route multiple tokens via an Enso Shortcut
          // @param tokensIn The addresses and amounts of the tokens to send
          // @param commands An array of bytes32 values that encode calls
          // @param state An array of bytes that are used to generate call data for each command
          function routeMulti(
              Token[] calldata tokensIn,
              bytes32[] calldata commands,
              bytes[] calldata state
          ) public payable returns (bytes[] memory returnData) {
              bool ethFlag;
              IERC20 tokenIn;
              uint256 amountIn;
              for (uint256 i; i < tokensIn.length; ++i) {
                  tokenIn = tokensIn[i].token;
                  amountIn = tokensIn[i].amount;
                  if (tokenIn == _ETH) {
                      if (ethFlag) revert Duplicate(address(_ETH));
                      ethFlag = true;
                      if (msg.value != amountIn) revert WrongValue(msg.value, amountIn);
                  } else {
                      tokenIn.safeTransferFrom(msg.sender, address(enso), amountIn);
                  }
              }
              if (!ethFlag && msg.value != 0) revert WrongValue(msg.value, 0);
              
              returnData = enso.executeShortcut{value: msg.value}(commands, state);
          }
          // @notice Route a single token via an Enso Shortcut and revert if there is insufficient token received
          // @param tokenIn The address of the token to send
          // @param tokenOut The address of the token to receive
          // @param amountIn The amount of the token to send
          // @param minAmountOut The minimum amount of the token to receive
          // @param receiver The address of the wallet that will receive the tokens
          // @param commands An array of bytes32 values that encode calls
          // @param state An array of bytes that are used to generate call data for each command
          function safeRouteSingle(
              IERC20 tokenIn,
              IERC20 tokenOut,
              uint256 amountIn,
              uint256 minAmountOut,
              address receiver,
              bytes32[] calldata commands,
              bytes[] calldata state
          ) external payable returns (bytes[] memory returnData) {
              uint256 balance = tokenOut == _ETH ? receiver.balance : tokenOut.balanceOf(receiver);
              returnData = routeSingle(tokenIn, amountIn, commands, state);
              uint256 amountOut;
              if (tokenOut == _ETH) {
                  amountOut = receiver.balance - balance;
              } else {
                  amountOut = tokenOut.balanceOf(receiver) - balance;
              }
              if (amountOut < minAmountOut) revert AmountTooLow(address(tokenOut));
          }
          // @notice Route multiple tokens via an Enso Shortcut and revert if there is insufficient tokens received
          // @param tokensIn The addresses and amounts of the tokens to send
          // @param tokensOut The addresses and minimum amounts of the tokens to receive
          // @param receiver The address of the wallet that will receive the tokens
          // @param commands An array of bytes32 values that encode calls
          // @param state An array of bytes that are used to generate call data for each command
          function safeRouteMulti(
              Token[] calldata tokensIn,
              Token[] calldata tokensOut,
              address receiver,
              bytes32[] calldata commands,
              bytes[] calldata state
          ) external payable returns (bytes[] memory returnData) {
              uint256 length = tokensOut.length;
              uint256[] memory balances = new uint256[](length);
              IERC20 tokenOut;
              for (uint256 i; i < length; ++i) {
                  tokenOut = tokensOut[i].token;
                  balances[i] = tokenOut == _ETH ? receiver.balance : tokenOut.balanceOf(receiver);
              }
              returnData = routeMulti(tokensIn, commands, state);
              uint256 amountOut;
              for (uint256 i; i < length; ++i) {
                  tokenOut = tokensOut[i].token;
                  if (tokenOut == _ETH) {
                      amountOut = receiver.balance - balances[i];
                  } else {
                      amountOut = tokenOut.balanceOf(receiver) - balances[i];
                  }
                  if (amountOut < tokensOut[i].amount) revert AmountTooLow(address(tokenOut));
              }
          }
      }
      // SPDX-License-Identifier: GPL-3.0-only
      pragma solidity ^0.8.0;
      import { VM } from "enso-weiroll/VM.sol";
      import { MinimalWallet } from "shortcuts-contracts/wallet/MinimalWallet.sol";
      import { AccessController } from "shortcuts-contracts/access/AccessController.sol";
      contract EnsoShortcuts is VM, MinimalWallet, AccessController {
          address public executor;
          constructor(address owner_, address executor_) {
              _setPermission(OWNER_ROLE, owner_, true);
              executor = executor_;
          }
          // @notice Execute a shortcut
          // @param commands An array of bytes32 values that encode calls
          // @param state An array of bytes that are used to generate call data for each command
          function executeShortcut(
              bytes32[] calldata commands,
              bytes[] calldata state
          ) external payable returns (bytes[] memory) {
              // we could use the AccessController here to check if the msg.sender is the executor address
              // but as it's a hot path we do a less gas intensive check
              if (msg.sender != executor) revert NotPermitted();
              return _execute(commands, state);
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.9.0) (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. Compatible with tokens that require the approval to be set to
           * 0 before setting it to a non-zero value.
           */
          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: GPL-3.0-only
      pragma solidity ^0.8.16;
      import "./CommandBuilder.sol";
      abstract contract VM {
          using CommandBuilder for bytes[];
          uint256 constant FLAG_CT_DELEGATECALL = 0x00; // Delegate call not currently supported
          uint256 constant FLAG_CT_CALL = 0x01;
          uint256 constant FLAG_CT_STATICCALL = 0x02;
          uint256 constant FLAG_CT_VALUECALL = 0x03;
          uint256 constant FLAG_CT_MASK = 0x03;
          uint256 constant FLAG_DATA = 0x20;
          uint256 constant FLAG_EXTENDED_COMMAND = 0x40;
          uint256 constant FLAG_TUPLE_RETURN = 0x80;
          uint256 constant SHORT_COMMAND_FILL =
              0x000000000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
          error ExecutionFailed(
              uint256 command_index,
              address target,
              string message
          );
          function _execute(bytes32[] calldata commands, bytes[] memory state)
              internal
              returns (bytes[] memory)
          {
              bytes32 command;
              uint256 flags;
              bytes32 indices;
              bool success;
              bytes memory outData;
              uint256 commandsLength = commands.length;
              uint256 indicesLength;
              for (uint256 i; i < commandsLength; i = _uncheckedIncrement(i)) {
                  command = commands[i];
                  flags = uint256(uint8(bytes1(command << 32)));
                  if (flags & FLAG_EXTENDED_COMMAND != 0) {
                      i = _uncheckedIncrement(i);
                      indices = commands[i];
                      indicesLength = 32;
                  } else {
                      indices = bytes32(uint256(command << 40) | SHORT_COMMAND_FILL);
                      indicesLength = 6;
                  }
                  if (flags & FLAG_CT_MASK == FLAG_CT_CALL) {
                      (success, outData) = address(uint160(uint256(command))).call( // target
                          // inputs
                          flags & FLAG_DATA == 0
                              ? state.buildInputs(
                                  bytes4(command), // selector
                                  indices,
                                  indicesLength
                              )
                              : state[
                                  uint8(bytes1(indices)) &
                                  CommandBuilder.IDX_VALUE_MASK
                              ]
                      );
                  } else if (flags & FLAG_CT_MASK == FLAG_CT_STATICCALL) {
                      (success, outData) = address(uint160(uint256(command))) // target
                          .staticcall(
                              // inputs
                              flags & FLAG_DATA == 0
                                  ? state.buildInputs(
                                      bytes4(command), // selector
                                      indices,
                                      indicesLength
                                  )
                                  : state[
                                      uint8(bytes1(indices)) &
                                      CommandBuilder.IDX_VALUE_MASK
                                  ]
                          );
                  } else if (flags & FLAG_CT_MASK == FLAG_CT_VALUECALL) {
                      bytes memory v = state[
                          uint8(bytes1(indices)) &
                          CommandBuilder.IDX_VALUE_MASK
                      ];
                      require(v.length == 32, "Value must be 32 bytes");
                      uint256 callEth = uint256(bytes32(v));
                      (success, outData) = address(uint160(uint256(command))).call{ // target
                          value: callEth
                      }(
                          // inputs
                          flags & FLAG_DATA == 0
                              ? state.buildInputs(
                                  bytes4(command), // selector
                                  indices << 8, // skip value input
                                  indicesLength - 1 // max indices length reduced by value input
                              )
                              : state[
                                  uint8(bytes1(indices << 8)) & // first byte after value input
                                  CommandBuilder.IDX_VALUE_MASK
                              ]
                      );
                  } else {
                      revert("Invalid calltype");
                  }
                  if (!success) {
                      string memory message = "Unknown";
                      if (outData.length > 68) {
                          // This might be an error message, parse the outData
                          // Estimate the bytes length of the possible error message
                          uint256 estimatedLength = _estimateBytesLength(outData, 68);
                          // Remove selector. First 32 bytes should be a pointer that indicates the start of data in memory
                          assembly {
                              outData := add(outData, 4)
                          }
                          uint256 pointer = uint256(bytes32(outData));
                          if (pointer == 32) {
                              // Remove pointer. If it is a string, the next 32 bytes will hold the size
                              assembly {
                                  outData := add(outData, 32)
                              }
                              uint256 size = uint256(bytes32(outData));
                              // If the size variable is the same as the estimated bytes length, we can be fairly certain
                              // this is a dynamic string, so convert the bytes to a string and emit the message. While an
                              // error function with 3 static parameters is capable of producing a similar output, there is
                              // low risk of a contract unintentionally emitting a message.
                              if (size == estimatedLength) {
                                  // Remove size. The remaining data should be the string content
                                  assembly {
                                      outData := add(outData, 32)
                                  }
                                  message = string(outData);
                              }
                          }
                      }
                      revert ExecutionFailed({
                          command_index: flags & FLAG_EXTENDED_COMMAND == 0
                              ? i
                              : i - 1,
                          target: address(uint160(uint256(command))),
                          message: message
                      });
                  }
                  if (flags & FLAG_TUPLE_RETURN != 0) {
                      state.writeTuple(bytes1(command << 88), outData);
                  } else {
                      state = state.writeOutputs(bytes1(command << 88), outData);
                  }
              }
              return state;
          }
          function _estimateBytesLength(bytes memory data, uint256 pos) internal pure returns (uint256 estimate) {
              uint256 length = data.length;
              estimate = length - pos; // Assume length equals alloted space
              for (uint256 i = pos; i < length; ) {
                  if (data[i] == 0) {
                      // Zero bytes found, adjust estimated length
                      estimate = i - pos;
                      break;
                  }
                  unchecked {
                      ++i;
                  }
              }
          }
          function _uncheckedIncrement(uint256 i) private pure returns (uint256) {
              unchecked {
                  ++i;
              }
              return i;
          }
      }
      // SPDX-License-Identifier: GPL-3.0-only
      pragma solidity ^0.8.16;
      import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
      import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
      import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
      import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol";
      import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";
      import "../access/ACL.sol";
      import "../access/Roles.sol";
      contract MinimalWallet is ACL, Roles, ERC721Holder, ERC1155Holder {
          using SafeERC20 for IERC20;
          enum Protocol {
              ETH,
              ERC20,
              ERC721,
              ERC1155
          }
          struct TransferNote {
              Protocol protocol;
              address token;
              uint256[] ids;
              uint256[] amounts;
          }
          struct ApprovalNote {
              Protocol protocol;
              address token;
              address[] operators;
          }
          error WithdrawFailed();
          error InvalidArrayLength();
          ////////////////////////////////////////////////////
          // External functions //////////////////////////////
          ////////////////////////////////////////////////////
          // @notice Withdraw an array of assets
          // @dev Works for ETH, ERC20s, ERC721s, and ERC1155s
          // @param notes A tuple that contains the protocol id, token address, array of ids and amounts
          function withdraw(TransferNote[] calldata notes) external isPermitted(OWNER_ROLE) {
              TransferNote memory note;
              Protocol protocol;
              uint256[] memory ids;
              uint256[] memory amounts;
              uint256 length = notes.length;
              for (uint256 i; i < length; ) {
                  note = notes[i];
                  protocol = note.protocol;
                  if (protocol == Protocol.ETH) {
                      amounts = note.amounts;
                      if (amounts.length != 1) revert InvalidArrayLength();
                      _withdrawETH(amounts[0]);
                  } else if (protocol == Protocol.ERC20) {
                      amounts = note.amounts;
                      if (amounts.length != 1) revert InvalidArrayLength();
                      _withdrawERC20(IERC20(note.token), amounts[0]);
                  } else if (protocol == Protocol.ERC721) {
                      ids = note.ids;
                      _withdrawERC721s(IERC721(note.token), ids);
                  } else if (protocol == Protocol.ERC1155) {
                      ids = note.ids;
                      amounts = note.amounts;
                      _withdrawERC1155s(IERC1155(note.token), ids, amounts);
                  }
                  unchecked {
                      ++i;
                  }
              }
          }
          // @notice Withdraw ETH from this contract to the msg.sender
          // @param amount The amount of ETH to be withdrawn
          function withdrawETH(uint256 amount) external isPermitted(OWNER_ROLE) {
              _withdrawETH(amount);
          }
          // @notice Withdraw ERC20s
          // @param erc20s An array of erc20 addresses
          // @param amounts An array of amounts for each erc20
          function withdrawERC20s(
              IERC20[] calldata erc20s,
              uint256[] calldata amounts
          ) external isPermitted(OWNER_ROLE) {
              uint256 length = erc20s.length;
              if (amounts.length != length) revert InvalidArrayLength();
              for (uint256 i; i < length; ) {
                  _withdrawERC20(erc20s[i], amounts[i]);
                  unchecked {
                      ++i;
                  }
              }
          }
          // @notice Withdraw multiple ERC721 ids for a single ERC721 contract
          // @param erc721 The address of the ERC721 contract
          // @param ids An array of ids that are to be withdrawn
          function withdrawERC721s(
              IERC721 erc721,
              uint256[] calldata ids
          ) external isPermitted(OWNER_ROLE) {
              _withdrawERC721s(erc721, ids);
          }
          // @notice Withdraw multiple ERC1155 ids for a single ERC1155 contract
          // @param erc1155 The address of the ERC155 contract
          // @param ids An array of ids that are to be withdrawn
          // @param amounts An array of amounts per id
          function withdrawERC1155s(
              IERC1155 erc1155,
              uint256[] calldata ids,
              uint256[] calldata amounts
          ) external isPermitted(OWNER_ROLE) {
              _withdrawERC1155s(erc1155, ids, amounts);
          }
          // @notice Revoke approval on an array of assets and operators
          // @dev Works for ERC20s, ERC721s, and ERC1155s
          // @param notes A tuple that contains the protocol id, token address, and array of operators
          function revokeApprovals(ApprovalNote[] calldata notes) external isPermitted(OWNER_ROLE) {
              ApprovalNote memory note;
              Protocol protocol;
              uint256 length = notes.length;
              for (uint256 i; i < length; ) {
                  note = notes[i];
                  protocol = note.protocol;
                  if (protocol == Protocol.ERC20) {
                      _revokeERC20Approvals(IERC20(note.token), note.operators);
                  } else if (protocol == Protocol.ERC721) {
                      _revokeERC721Approvals(IERC721(note.token), note.operators);
                  } else if (protocol == Protocol.ERC1155) {
                      _revokeERC1155Approvals(IERC1155(note.token), note.operators);
                  }
                  unchecked {
                      ++i;
                  }
              }
          }
          // @notice Revoke approval of an ERC20 for an array of operators
          // @param erc20 The address of the ERC20 token
          // @param operators The array of operators to have approval revoked
          function revokeERC20Approvals(
              IERC20 erc20,
              address[] calldata operators
          ) external isPermitted(OWNER_ROLE) {
              _revokeERC20Approvals(erc20, operators);
          }
          // @notice Revoke approval of an ERC721 for an array of operators
          // @param erc721 The address of the ERC721 token
          // @param operators The array of operators to have approval revoked
          function revokeERC721Approvals(
              IERC721 erc721,
              address[] calldata operators
          ) external isPermitted(OWNER_ROLE) {
              _revokeERC721Approvals(erc721, operators);
          }
          // @notice Revoke approval of an ERC1155 for an array of operators
          // @param erc1155 The address of the ERC1155 token
          // @param operators The array of operators to have approval revoked
          function revokeERC1155Approvals(
              IERC1155 erc1155,
              address[] calldata operators
          ) external isPermitted(OWNER_ROLE) {
              _revokeERC1155Approvals(erc1155, operators);
          }
          ////////////////////////////////////////////////////
          // Internal functions //////////////////////////////
          ////////////////////////////////////////////////////
          function _withdrawETH(uint256 amount) internal {
              (bool success, ) = msg.sender.call{value: amount}("");
              if (!success) revert WithdrawFailed();
          }
          function _withdrawERC20(IERC20 erc20, uint256 amount) internal {
              erc20.safeTransfer(msg.sender, amount);
          }
          function _withdrawERC721s(IERC721 erc721, uint256[] memory ids) internal {
              uint256 length = ids.length;
              for (uint256 i; i < length; ) {
                  erc721.safeTransferFrom(address(this), msg.sender, ids[i]);
                  unchecked {
                      ++i;
                  }
              }
          }
          function _withdrawERC1155s(IERC1155 erc1155, uint256[] memory ids, uint256[] memory amounts) internal {
              // safeBatchTransferFrom will validate the array lengths
              erc1155.safeBatchTransferFrom(address(this), msg.sender, ids, amounts, "");
          }
          function _revokeERC20Approvals(IERC20 erc20, address[] memory operators) internal {
              uint256 length = operators.length;
              for (uint256 i; i < length; ) {
                  erc20.safeApprove(operators[i], 0);
                  unchecked {
                      ++i;
                  }
              }
          }
          function _revokeERC721Approvals(IERC721 erc721, address[] memory operators) internal {
              uint256 length = operators.length;
              for (uint256 i; i < length; ) {
                  erc721.setApprovalForAll(operators[i], false);
                  unchecked {
                      ++i;
                  }
              }
          }
          function _revokeERC1155Approvals(IERC1155 erc1155, address[] memory operators) internal {
              uint256 length = operators.length;
              for (uint256 i; i < length; ) {
                  erc1155.setApprovalForAll(operators[i], false);
                  unchecked {
                      ++i;
                  }
              }
          }
          ////////////////////////////////////////////////////
          // Fallback functions //////////////////////////////
          ////////////////////////////////////////////////////
          receive() external payable {}
      }
      // SPDX-License-Identifier: GPL-3.0-only
      pragma solidity ^0.8.16;
      import "./ACL.sol";
      import "./Roles.sol";
      // @notice The OWNER_ROLE must be set in the importing contract's constructor or initialize function
      abstract contract AccessController is ACL, Roles {
          using StorageAPI for bytes32;
          event PermissionSet(bytes32 role, address account, bool permission);
          error UnsafeSetting();
          error InvalidAccount();
          // @notice Sets user permission over a role
          // @param role The bytes32 value of the role
          // @param account The address of the account
          // @param permission The permission status
          function setPermission(
              bytes32 role,
              address account,
              bool permission
          ) external isPermitted(OWNER_ROLE) {
              if (account == address(0)) revert InvalidAccount();
              if (role == OWNER_ROLE && account == msg.sender && permission == false)
                  revert UnsafeSetting();
              _setPermission(role, account, permission);
          }
          // @notice Internal function to set user permission over a role
          // @param role The bytes32 value of the role
          // @param account The address of the account
          // @param permission The permission status
          function _setPermission(bytes32 role, address account, bool permission) internal {
              bytes32 key = _getKey(role, account);
              key.setBool(permission);
              emit PermissionSet(role, account, permission);
          }
      }
      // 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.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-only
      pragma solidity ^0.8.16;
      library CommandBuilder {
          uint256 constant IDX_VARIABLE_LENGTH = 0x80;
          uint256 constant IDX_VALUE_MASK = 0x7f;
          uint256 constant IDX_END_OF_ARGS = 0xff;
          uint256 constant IDX_USE_STATE = 0xfe;
          uint256 constant IDX_ARRAY_START = 0xfd;
          uint256 constant IDX_TUPLE_START = 0xfc;
          uint256 constant IDX_DYNAMIC_END = 0xfb;
          function buildInputs(
              bytes[] memory state,
              bytes4 selector,
              bytes32 indices,
              uint256 indicesLength
          ) internal view returns (bytes memory ret) {
              uint256 idx; // The current command index
              uint256 offsetIdx; // The index of the current free offset
              uint256 count; // Number of bytes in whole ABI encoded message
              uint256 free; // Pointer to first free byte in tail part of message
              uint256[] memory dynamicLengths = new uint256[](10); // Optionally store the length of all dynamic types (a command cannot fit more than 10 dynamic types)
              bytes memory stateData; // Optionally encode the current state if the call requires it
              // Determine the length of the encoded data
              for (uint256 i; i < indicesLength; ) {
                  idx = uint8(indices[i]);
                  if (idx == IDX_END_OF_ARGS) {
                      indicesLength = i;
                      break;
                  }
                  if (idx & IDX_VARIABLE_LENGTH != 0) {
                      if (idx == IDX_USE_STATE) {
                          if (stateData.length == 0) {
                              stateData = abi.encode(state);
                          }
                          unchecked {
                              count += stateData.length;
                          }
                      } else {
                          (dynamicLengths, offsetIdx, count, i) = setupDynamicType(
                              state,
                              indices,
                              dynamicLengths,
                              idx,
                              offsetIdx,
                              count,
                              i
                          );
                      }
                  } else {
                      count = setupStaticVariable(state, count, idx);
                  }
                  unchecked {
                      free += 32;
                      ++i;
                  }
              }
              // Encode it
              ret = new bytes(count + 4);
              assembly {
                  mstore(add(ret, 32), selector)
              }
              offsetIdx = 0;
              // Use count to track current memory slot
              assembly {
                  count := add(ret, 36)
              }
              for (uint256 i; i < indicesLength; ) {
                  idx = uint8(indices[i]);
                  if (idx & IDX_VARIABLE_LENGTH != 0) {
                      if (idx == IDX_USE_STATE) {
                          assembly {
                              mstore(count, free)
                          }
                          memcpy(stateData, 32, ret, free + 4, stateData.length - 32);
                          unchecked {
                              free += stateData.length - 32;
                          }
                      } else if (idx == IDX_ARRAY_START) {
                          // Start of dynamic type, put pointer in current slot
                          assembly {
                              mstore(count, free)
                          }
                          (offsetIdx, free, i, ) = encodeDynamicArray(
                              ret,
                              state,
                              indices,
                              dynamicLengths,
                              offsetIdx,
                              free,
                              i
                          );
                      } else if (idx == IDX_TUPLE_START) {
                          // Start of dynamic type, put pointer in current slot
                          assembly {
                              mstore(count, free)
                          }
                          (offsetIdx, free, i, ) = encodeDynamicTuple(
                              ret,
                              state,
                              indices,
                              dynamicLengths,
                              offsetIdx,
                              free,
                              i
                          );
                      } else {
                          // Variable length data
                          uint256 argLen = state[idx & IDX_VALUE_MASK].length;
                          // Put a pointer in the current slot and write the data to first free slot
                          assembly {
                              mstore(count, free)
                          }
                          memcpy(
                              state[idx & IDX_VALUE_MASK],
                              0,
                              ret,
                              free + 4,
                              argLen
                          );
                          unchecked {
                              free += argLen;
                          }
                      }
                  } else {
                      // Fixed length data (length previously checked to be 32 bytes)
                      bytes memory stateVar = state[idx & IDX_VALUE_MASK];
                      // Write the data to current slot
                      assembly {
                          mstore(count, mload(add(stateVar, 32)))
                      }
                  }
                  unchecked {
                      count += 32;
                      ++i;
                  }
              }
          }
          function setupStaticVariable(
              bytes[] memory state,
              uint256 count,
              uint256 idx
          ) internal pure returns (uint256 newCount) {
              require(
                  state[idx & IDX_VALUE_MASK].length == 32,
                  "Static state variables must be 32 bytes"
              );
              unchecked {
                  newCount = count + 32;
              }
          }
          function setupDynamicVariable(
              bytes[] memory state,
              uint256 count,
              uint256 idx
          ) internal pure returns (uint256 newCount) {
              bytes memory arg = state[idx & IDX_VALUE_MASK];
              // Validate the length of the data in state is a multiple of 32
              uint256 argLen = arg.length;
              require(
                  argLen != 0 && argLen % 32 == 0,
                  "Dynamic state variables must be a multiple of 32 bytes"
              );
              // Add the length of the value, rounded up to the next word boundary, plus space for pointer
              unchecked {
                  newCount = count + argLen + 32;
              }
          }
          function setupDynamicType(
              bytes[] memory state,
              bytes32 indices,
              uint256[] memory dynamicLengths,
              uint256 idx,
              uint256 offsetIdx,
              uint256 count,
              uint256 index
          ) internal view returns (
              uint256[] memory newDynamicLengths,
              uint256 newOffsetIdx,
              uint256 newCount,
              uint256 newIndex
          ) {
              if (idx == IDX_ARRAY_START) {
                  (newDynamicLengths, newOffsetIdx, newCount, newIndex) = setupDynamicArray(
                      state,
                      indices,
                      dynamicLengths,
                      offsetIdx,
                      count,
                      index
                  );
              } else if (idx == IDX_TUPLE_START) {
                  (newDynamicLengths, newOffsetIdx, newCount, newIndex) = setupDynamicTuple(
                      state,
                      indices,
                      dynamicLengths,
                      offsetIdx,
                      count,
                      index
                  );
              } else {
                  newDynamicLengths = dynamicLengths;
                  newOffsetIdx = offsetIdx;
                  newIndex = index;
                  newCount = setupDynamicVariable(state, count, idx);
              }
          }
          function setupDynamicArray(
              bytes[] memory state,
              bytes32 indices,
              uint256[] memory dynamicLengths,
              uint256 offsetIdx,
              uint256 count,
              uint256 index
          ) internal view returns (
              uint256[] memory newDynamicLengths,
              uint256 newOffsetIdx,
              uint256 newCount,
              uint256 newIndex
          ) {
              // Current idx is IDX_ARRAY_START, next idx will contain the array length
              unchecked {
                  newIndex = index + 1;
                  newCount = count + 32;
              }
              uint256 idx = uint8(indices[newIndex]);
              require(
                  state[idx & IDX_VALUE_MASK].length == 32,
                  "Array length must be 32 bytes"
              );
              (newDynamicLengths, newOffsetIdx, newCount, newIndex) = setupDynamicTuple(
                  state,
                  indices,
                  dynamicLengths,
                  offsetIdx,
                  newCount,
                  newIndex
              );
          }
          function setupDynamicTuple(
              bytes[] memory state,
              bytes32 indices,
              uint256[] memory dynamicLengths,
              uint256 offsetIdx,
              uint256 count,
              uint256 index
          ) internal view returns (
              uint256[] memory newDynamicLengths,
              uint256 newOffsetIdx,
              uint256 newCount,
              uint256 newIndex
          ) {
              uint256 idx;
              uint256 offset;
              newDynamicLengths = dynamicLengths;
              // Progress to first index of the data and progress the next offset idx
              unchecked {
                  newIndex = index + 1;
                  newOffsetIdx = offsetIdx + 1;
                  newCount = count + 32;
              }
              while (newIndex < 32) {
                  idx = uint8(indices[newIndex]);
                  if (idx & IDX_VARIABLE_LENGTH != 0) {
                      if (idx == IDX_DYNAMIC_END) {
                          newDynamicLengths[offsetIdx] = offset;
                          // explicit return saves gas ¯\\_(ツ)_/¯
                          return (newDynamicLengths, newOffsetIdx, newCount, newIndex);
                      } else {
                          require(idx != IDX_USE_STATE, "Cannot use state from inside dynamic type");
                          (newDynamicLengths, newOffsetIdx, newCount, newIndex) = setupDynamicType(
                              state,
                              indices,
                              newDynamicLengths,
                              idx,
                              newOffsetIdx,
                              newCount,
                              newIndex
                          );
                      }
                  } else {
                      newCount = setupStaticVariable(state, newCount, idx);
                  }
                  unchecked {
                      offset += 32;
                      ++newIndex;
                  }
              }
              revert("Dynamic type was not properly closed");
          }
          function encodeDynamicArray(
              bytes memory ret,
              bytes[] memory state,
              bytes32 indices,
              uint256[] memory dynamicLengths,
              uint256 offsetIdx,
              uint256 currentSlot,
              uint256 index
          ) internal view returns (
              uint256 newOffsetIdx,
              uint256 newSlot,
              uint256 newIndex,
              uint256 length
          ) {
              // Progress to array length metadata
              unchecked {
                  newIndex = index + 1;
                  newSlot = currentSlot + 32;
              }
              // Encode array length
              uint256 idx = uint8(indices[newIndex]);
              // Array length value previously checked to be 32 bytes
              bytes memory stateVar = state[idx & IDX_VALUE_MASK];
              assembly {
                  mstore(add(add(ret, 36), currentSlot), mload(add(stateVar, 32)))
              }
              (newOffsetIdx, newSlot, newIndex, length) = encodeDynamicTuple(
                  ret,
                  state,
                  indices,
                  dynamicLengths,
                  offsetIdx,
                  newSlot,
                  newIndex
              );
              unchecked {
                  length += 32; // Increase length to account for array length metadata
              }
          }
          function encodeDynamicTuple(
              bytes memory ret,
              bytes[] memory state,
              bytes32 indices,
              uint256[] memory dynamicLengths,
              uint256 offsetIdx,
              uint256 currentSlot,
              uint256 index
          ) internal view returns (
              uint256 newOffsetIdx,
              uint256 newSlot,
              uint256 newIndex,
              uint256 length
          ) {
              uint256 idx;
              uint256 argLen;
              uint256 freePointer = dynamicLengths[offsetIdx]; // The pointer to the next free slot
              unchecked {
                  newSlot = currentSlot + freePointer; // Update the next slot
                  newOffsetIdx = offsetIdx + 1; // Progress to next offsetIdx
                  newIndex = index + 1; // Progress to first index of the data
              }
              // Shift currentSlot to correct location in memory
              assembly {
                  currentSlot := add(add(ret, 36), currentSlot)
              }
              while (newIndex < 32) {
                  idx = uint8(indices[newIndex]);
                  if (idx & IDX_VARIABLE_LENGTH != 0) {
                      if (idx == IDX_DYNAMIC_END) {
                          break;
                      } else if (idx == IDX_ARRAY_START) {
                          // Start of dynamic type, put pointer in current slot
                          assembly {
                              mstore(currentSlot, freePointer)
                          }
                          (newOffsetIdx, newSlot, newIndex, argLen) = encodeDynamicArray(
                              ret,
                              state,
                              indices,
                              dynamicLengths,
                              newOffsetIdx,
                              newSlot,
                              newIndex
                          );
                          unchecked {
                              freePointer += argLen;
                              length += (argLen + 32); // data + pointer
                          }
                      } else if (idx == IDX_TUPLE_START) {
                          // Start of dynamic type, put pointer in current slot
                          assembly {
                              mstore(currentSlot, freePointer)
                          }
                          (newOffsetIdx, newSlot, newIndex, argLen) = encodeDynamicTuple(
                              ret,
                              state,
                              indices,
                              dynamicLengths,
                              newOffsetIdx,
                              newSlot,
                              newIndex
                          );
                          unchecked {
                              freePointer += argLen;
                              length += (argLen + 32); // data + pointer
                          }
                      } else  {
                          // Variable length data
                          argLen = state[idx & IDX_VALUE_MASK].length;
                          // Start of dynamic type, put pointer in current slot
                          assembly {
                              mstore(currentSlot, freePointer)
                          }
                          memcpy(
                              state[idx & IDX_VALUE_MASK],
                              0,
                              ret,
                              newSlot + 4,
                              argLen
                          );
                          unchecked {
                              newSlot += argLen;
                              freePointer += argLen;
                              length += (argLen + 32); // data + pointer
                          }
                      }
                  } else {
                      // Fixed length data (length previously checked to be 32 bytes)
                      bytes memory stateVar = state[idx & IDX_VALUE_MASK];
                      // Write to first free slot
                      assembly {
                          mstore(currentSlot, mload(add(stateVar, 32)))
                      }
                      unchecked {
                          length += 32;
                      }
                  }
                  unchecked {
                      currentSlot += 32;
                      ++newIndex;
                  }
              }
          }
          function writeOutputs(
              bytes[] memory state,
              bytes1 index,
              bytes memory output
          ) internal pure returns (bytes[] memory) {
              uint256 idx = uint8(index);
              if (idx == IDX_END_OF_ARGS) return state;
              if (idx & IDX_VARIABLE_LENGTH != 0) {
                  if (idx == IDX_USE_STATE) {
                      state = abi.decode(output, (bytes[]));
                  } else {
                      require(idx & IDX_VALUE_MASK < state.length, "Index out-of-bounds");
                      // Check the first field is 0x20 (because we have only a single return value)
                      uint256 argPtr;
                      assembly {
                          argPtr := mload(add(output, 32))
                      }
                      require(
                          argPtr == 32,
                          "Only one return value permitted (variable)"
                      );
                      assembly {
                          // Overwrite the first word of the return data with the length - 32
                          mstore(add(output, 32), sub(mload(output), 32))
                          // Insert a pointer to the return data, starting at the second word, into state
                          mstore(
                              add(add(state, 32), mul(and(idx, IDX_VALUE_MASK), 32)),
                              add(output, 32)
                          )
                      }
                  }
              } else {
                  require(idx & IDX_VALUE_MASK < state.length, "Index out-of-bounds");
                  // Single word
                  require(
                      output.length == 32,
                      "Only one return value permitted (static)"
                  );
                  state[idx & IDX_VALUE_MASK] = output;
              }
              return state;
          }
          function writeTuple(
              bytes[] memory state,
              bytes1 index,
              bytes memory output
          ) internal view {
              uint256 idx = uint8(index);
              if (idx == IDX_END_OF_ARGS) return;
              bytes memory entry = state[idx & IDX_VALUE_MASK] = new bytes(output.length + 32);
              memcpy(output, 0, entry, 32, output.length);
              assembly {
                  let l := mload(output)
                  mstore(add(entry, 32), l)
              }
          }
          function memcpy(
              bytes memory src,
              uint256 srcIdx,
              bytes memory dest,
              uint256 destIdx,
              uint256 len
          ) internal view {
              assembly {
                  pop(
                      staticcall(
                          gas(),
                          4,
                          add(add(src, 32), srcIdx),
                          len,
                          add(add(dest, 32), destIdx),
                          len
                      )
                  )
              }
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol)
      pragma solidity ^0.8.0;
      import "../IERC20.sol";
      import "../extensions/draft-IERC20Permit.sol";
      import "../../../utils/Address.sol";
      /**
       * @title SafeERC20
       * @dev Wrappers around ERC20 operations that throw on failure (when the token
       * contract returns false). Tokens that return no value (and instead revert or
       * throw on failure) are also supported, non-reverting calls are assumed to be
       * successful.
       * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
       * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
       */
      library SafeERC20 {
          using Address for address;
          function safeTransfer(
              IERC20 token,
              address to,
              uint256 value
          ) internal {
              _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
          }
          function safeTransferFrom(
              IERC20 token,
              address from,
              address to,
              uint256 value
          ) internal {
              _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
          }
          /**
           * @dev Deprecated. This function has issues similar to the ones found in
           * {IERC20-approve}, and its usage is discouraged.
           *
           * Whenever possible, use {safeIncreaseAllowance} and
           * {safeDecreaseAllowance} instead.
           */
          function safeApprove(
              IERC20 token,
              address spender,
              uint256 value
          ) internal {
              // safeApprove should only be called when setting an initial allowance,
              // or when resetting it to zero. To increase and decrease it, use
              // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
              require(
                  (value == 0) || (token.allowance(address(this), spender) == 0),
                  "SafeERC20: approve from non-zero to non-zero allowance"
              );
              _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
          }
          function safeIncreaseAllowance(
              IERC20 token,
              address spender,
              uint256 value
          ) internal {
              uint256 newAllowance = token.allowance(address(this), spender) + value;
              _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
          }
          function safeDecreaseAllowance(
              IERC20 token,
              address spender,
              uint256 value
          ) internal {
              unchecked {
                  uint256 oldAllowance = token.allowance(address(this), spender);
                  require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
                  uint256 newAllowance = oldAllowance - value;
                  _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
              }
          }
          function safePermit(
              IERC20Permit token,
              address owner,
              address spender,
              uint256 value,
              uint256 deadline,
              uint8 v,
              bytes32 r,
              bytes32 s
          ) internal {
              uint256 nonceBefore = token.nonces(owner);
              token.permit(owner, spender, value, deadline, v, r, s);
              uint256 nonceAfter = token.nonces(owner);
              require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
          }
          /**
           * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
           * on the return value: the return value is optional (but if data is returned, it must not be false).
           * @param token The token targeted by the call.
           * @param data The call data (encoded using abi.encode or one of its variants).
           */
          function _callOptionalReturn(IERC20 token, bytes memory data) private {
              // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
              // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
              // the target address contains contract code and also asserts for success in the low-level call.
              bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
              if (returndata.length > 0) {
                  // Return data is optional
                  require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
              }
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/IERC721.sol)
      pragma solidity ^0.8.0;
      import "../../utils/introspection/IERC165.sol";
      /**
       * @dev Required interface of an ERC721 compliant contract.
       */
      interface IERC721 is IERC165 {
          /**
           * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
           */
          event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
          /**
           * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
           */
          event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
          /**
           * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
           */
          event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
          /**
           * @dev Returns the number of tokens in ``owner``'s account.
           */
          function balanceOf(address owner) external view returns (uint256 balance);
          /**
           * @dev Returns the owner of the `tokenId` token.
           *
           * Requirements:
           *
           * - `tokenId` must exist.
           */
          function ownerOf(uint256 tokenId) external view returns (address owner);
          /**
           * @dev Safely transfers `tokenId` token from `from` to `to`.
           *
           * Requirements:
           *
           * - `from` cannot be the zero address.
           * - `to` cannot be the zero address.
           * - `tokenId` token must exist and be owned by `from`.
           * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
           * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
           *
           * Emits a {Transfer} event.
           */
          function safeTransferFrom(
              address from,
              address to,
              uint256 tokenId,
              bytes calldata data
          ) external;
          /**
           * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
           * are aware of the ERC721 protocol to prevent tokens from being forever locked.
           *
           * Requirements:
           *
           * - `from` cannot be the zero address.
           * - `to` cannot be the zero address.
           * - `tokenId` token must exist and be owned by `from`.
           * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
           * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
           *
           * Emits a {Transfer} event.
           */
          function safeTransferFrom(
              address from,
              address to,
              uint256 tokenId
          ) external;
          /**
           * @dev Transfers `tokenId` token from `from` to `to`.
           *
           * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
           * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
           * understand this adds an external call which potentially creates a reentrancy vulnerability.
           *
           * Requirements:
           *
           * - `from` cannot be the zero address.
           * - `to` cannot be the zero address.
           * - `tokenId` token must be owned by `from`.
           * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
           *
           * Emits a {Transfer} event.
           */
          function transferFrom(
              address from,
              address to,
              uint256 tokenId
          ) external;
          /**
           * @dev Gives permission to `to` to transfer `tokenId` token to another account.
           * The approval is cleared when the token is transferred.
           *
           * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
           *
           * Requirements:
           *
           * - The caller must own the token or be an approved operator.
           * - `tokenId` must exist.
           *
           * Emits an {Approval} event.
           */
          function approve(address to, uint256 tokenId) external;
          /**
           * @dev Approve or remove `operator` as an operator for the caller.
           * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
           *
           * Requirements:
           *
           * - The `operator` cannot be the caller.
           *
           * Emits an {ApprovalForAll} event.
           */
          function setApprovalForAll(address operator, bool _approved) external;
          /**
           * @dev Returns the account approved for `tokenId` token.
           *
           * Requirements:
           *
           * - `tokenId` must exist.
           */
          function getApproved(uint256 tokenId) external view returns (address operator);
          /**
           * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
           *
           * See {setApprovalForAll}
           */
          function isApprovedForAll(address owner, address operator) external view returns (bool);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.7.0) (token/ERC1155/IERC1155.sol)
      pragma solidity ^0.8.0;
      import "../../utils/introspection/IERC165.sol";
      /**
       * @dev Required interface of an ERC1155 compliant contract, as defined in the
       * https://eips.ethereum.org/EIPS/eip-1155[EIP].
       *
       * _Available since v3.1._
       */
      interface IERC1155 is IERC165 {
          /**
           * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
           */
          event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
          /**
           * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
           * transfers.
           */
          event TransferBatch(
              address indexed operator,
              address indexed from,
              address indexed to,
              uint256[] ids,
              uint256[] values
          );
          /**
           * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
           * `approved`.
           */
          event ApprovalForAll(address indexed account, address indexed operator, bool approved);
          /**
           * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
           *
           * If an {URI} event was emitted for `id`, the standard
           * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
           * returned by {IERC1155MetadataURI-uri}.
           */
          event URI(string value, uint256 indexed id);
          /**
           * @dev Returns the amount of tokens of token type `id` owned by `account`.
           *
           * Requirements:
           *
           * - `account` cannot be the zero address.
           */
          function balanceOf(address account, uint256 id) external view returns (uint256);
          /**
           * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
           *
           * Requirements:
           *
           * - `accounts` and `ids` must have the same length.
           */
          function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
              external
              view
              returns (uint256[] memory);
          /**
           * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
           *
           * Emits an {ApprovalForAll} event.
           *
           * Requirements:
           *
           * - `operator` cannot be the caller.
           */
          function setApprovalForAll(address operator, bool approved) external;
          /**
           * @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
           *
           * See {setApprovalForAll}.
           */
          function isApprovedForAll(address account, address operator) external view returns (bool);
          /**
           * @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
           *
           * Emits a {TransferSingle} event.
           *
           * Requirements:
           *
           * - `to` cannot be the zero address.
           * - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.
           * - `from` must have a balance of tokens of type `id` of at least `amount`.
           * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
           * acceptance magic value.
           */
          function safeTransferFrom(
              address from,
              address to,
              uint256 id,
              uint256 amount,
              bytes calldata data
          ) external;
          /**
           * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
           *
           * Emits a {TransferBatch} event.
           *
           * Requirements:
           *
           * - `ids` and `amounts` must have the same length.
           * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
           * acceptance magic value.
           */
          function safeBatchTransferFrom(
              address from,
              address to,
              uint256[] calldata ids,
              uint256[] calldata amounts,
              bytes calldata data
          ) external;
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts v4.4.1 (token/ERC721/utils/ERC721Holder.sol)
      pragma solidity ^0.8.0;
      import "../IERC721Receiver.sol";
      /**
       * @dev Implementation of the {IERC721Receiver} interface.
       *
       * Accepts all token transfers.
       * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}.
       */
      contract ERC721Holder is IERC721Receiver {
          /**
           * @dev See {IERC721Receiver-onERC721Received}.
           *
           * Always returns `IERC721Receiver.onERC721Received.selector`.
           */
          function onERC721Received(
              address,
              address,
              uint256,
              bytes memory
          ) public virtual override returns (bytes4) {
              return this.onERC721Received.selector;
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/utils/ERC1155Holder.sol)
      pragma solidity ^0.8.0;
      import "./ERC1155Receiver.sol";
      /**
       * Simple implementation of `ERC1155Receiver` that will allow a contract to hold ERC1155 tokens.
       *
       * IMPORTANT: When inheriting this contract, you must include a way to use the received tokens, otherwise they will be
       * stuck.
       *
       * @dev _Available since v3.1._
       */
      contract ERC1155Holder is ERC1155Receiver {
          function onERC1155Received(
              address,
              address,
              uint256,
              uint256,
              bytes memory
          ) public virtual override returns (bytes4) {
              return this.onERC1155Received.selector;
          }
          function onERC1155BatchReceived(
              address,
              address,
              uint256[] memory,
              uint256[] memory,
              bytes memory
          ) public virtual override returns (bytes4) {
              return this.onERC1155BatchReceived.selector;
          }
      }
      // SPDX-License-Identifier: GPL-3.0-only
      pragma solidity ^0.8.16;
      import "../libraries/StorageAPI.sol";
      abstract contract ACL {
          using StorageAPI for bytes32;
          error NotPermitted();
          modifier isPermitted(bytes32 role) {
              bool permitted = _getPermission(role, msg.sender); // TODO: support GSN/Account abstraction
              if (!permitted) revert NotPermitted();
              _;
          }
          // @notice Gets user permission for a role
          // @param role The bytes32 value of the role
          // @param account The address of the account
          // @return The permission status
          function getPermission(bytes32 role, address account) external view returns (bool) {
              return _getPermission(role, account);
          }
          // @notice Internal function to get user permission for a role
          // @param role The bytes32 value of the role
          // @param account The address of the account
          // @return The permission status
          function _getPermission(bytes32 role, address account) internal view returns (bool) {
              bytes32 key = _getKey(role, account);
              return key.getBool();
          }
          // @notice Internal function to get the key for the storage slot
          // @param role The bytes32 value of the role
          // @param account The address of the account
          // @return The bytes32 storage slot
          function _getKey(bytes32 role, address account) internal pure returns (bytes32) {
              return keccak256(abi.encode(role, account));
          }
      }
      // SPDX-License-Identifier: GPL-3.0-only
      pragma solidity ^0.8.16;
      abstract contract Roles {
          // Using same slot generation technique as eip-1967 -- https://eips.ethereum.org/EIPS/eip-1967
          bytes32 public constant OWNER_ROLE = bytes32(uint256(keccak256("enso.access.roles.owner")) - 1);
          bytes32 public constant EXECUTOR_ROLE = bytes32(uint256(keccak256("enso.access.roles.executor")) - 1);
          bytes32 public constant MODULE_ROLE = bytes32(uint256(keccak256("enso.access.roles.module")) - 1);
      }// SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
      pragma solidity ^0.8.0;
      /**
       * @dev Interface of the ERC20 standard as defined in the EIP.
       */
      interface IERC20 {
          /**
           * @dev Emitted when `value` tokens are moved from one account (`from`) to
           * another (`to`).
           *
           * Note that `value` may be zero.
           */
          event Transfer(address indexed from, address indexed to, uint256 value);
          /**
           * @dev Emitted when the allowance of a `spender` for an `owner` is set by
           * a call to {approve}. `value` is the new allowance.
           */
          event Approval(address indexed owner, address indexed spender, uint256 value);
          /**
           * @dev Returns the amount of tokens in existence.
           */
          function totalSupply() external view returns (uint256);
          /**
           * @dev Returns the amount of tokens owned by `account`.
           */
          function balanceOf(address account) external view returns (uint256);
          /**
           * @dev Moves `amount` tokens from the caller's account to `to`.
           *
           * Returns a boolean value indicating whether the operation succeeded.
           *
           * Emits a {Transfer} event.
           */
          function transfer(address to, uint256 amount) external returns (bool);
          /**
           * @dev Returns the remaining number of tokens that `spender` will be
           * allowed to spend on behalf of `owner` through {transferFrom}. This is
           * zero by default.
           *
           * This value changes when {approve} or {transferFrom} are called.
           */
          function allowance(address owner, address spender) external view returns (uint256);
          /**
           * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
           *
           * Returns a boolean value indicating whether the operation succeeded.
           *
           * IMPORTANT: Beware that changing an allowance with this method brings the risk
           * that someone may use both the old and the new allowance by unfortunate
           * transaction ordering. One possible solution to mitigate this race
           * condition is to first reduce the spender's allowance to 0 and set the
           * desired value afterwards:
           * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
           *
           * Emits an {Approval} event.
           */
          function approve(address spender, uint256 amount) external returns (bool);
          /**
           * @dev Moves `amount` tokens from `from` to `to` using the
           * allowance mechanism. `amount` is then deducted from the caller's
           * allowance.
           *
           * Returns a boolean value indicating whether the operation succeeded.
           *
           * Emits a {Transfer} event.
           */
          function transferFrom(
              address from,
              address to,
              uint256 amount
          ) external returns (bool);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
      pragma solidity ^0.8.0;
      /**
       * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
       * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
       *
       * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
       * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
       * need to send a transaction, and thus is not required to hold Ether at all.
       */
      interface IERC20Permit {
          /**
           * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
           * given ``owner``'s signed approval.
           *
           * IMPORTANT: The same issues {IERC20-approve} has related to transaction
           * ordering also apply here.
           *
           * Emits an {Approval} event.
           *
           * Requirements:
           *
           * - `spender` cannot be the zero address.
           * - `deadline` must be a timestamp in the future.
           * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
           * over the EIP712-formatted function arguments.
           * - the signature must use ``owner``'s current nonce (see {nonces}).
           *
           * For more information on the signature format, see the
           * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
           * section].
           */
          function permit(
              address owner,
              address spender,
              uint256 value,
              uint256 deadline,
              uint8 v,
              bytes32 r,
              bytes32 s
          ) external;
          /**
           * @dev Returns the current nonce for `owner`. This value must be
           * included whenever a signature is generated for {permit}.
           *
           * Every successful call to {permit} increases ``owner``'s nonce by one. This
           * prevents a signature from being used multiple times.
           */
          function nonces(address owner) external view returns (uint256);
          /**
           * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
           */
          // solhint-disable-next-line func-name-mixedcase
          function DOMAIN_SEPARATOR() external view returns (bytes32);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)
      pragma solidity ^0.8.1;
      /**
       * @dev Collection of functions related to the address type
       */
      library Address {
          /**
           * @dev Returns true if `account` is a contract.
           *
           * [IMPORTANT]
           * ====
           * It is unsafe to assume that an address for which this function returns
           * false is an externally-owned account (EOA) and not a contract.
           *
           * Among others, `isContract` will return false for the following
           * types of addresses:
           *
           *  - an externally-owned account
           *  - a contract in construction
           *  - an address where a contract will be created
           *  - an address where a contract lived, but was destroyed
           * ====
           *
           * [IMPORTANT]
           * ====
           * You shouldn't rely on `isContract` to protect against flash loan attacks!
           *
           * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
           * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
           * constructor.
           * ====
           */
          function isContract(address account) internal view returns (bool) {
              // This method relies on extcodesize/address.code.length, which returns 0
              // for contracts in construction, since the code is only stored at the end
              // of the constructor execution.
              return account.code.length > 0;
          }
          /**
           * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
           * `recipient`, forwarding all available gas and reverting on errors.
           *
           * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
           * of certain opcodes, possibly making contracts go over the 2300 gas limit
           * imposed by `transfer`, making them unable to receive funds via
           * `transfer`. {sendValue} removes this limitation.
           *
           * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
           *
           * IMPORTANT: because control is transferred to `recipient`, care must be
           * taken to not create reentrancy vulnerabilities. Consider using
           * {ReentrancyGuard} or the
           * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
           */
          function sendValue(address payable recipient, uint256 amount) internal {
              require(address(this).balance >= amount, "Address: insufficient balance");
              (bool success, ) = recipient.call{value: amount}("");
              require(success, "Address: unable to send value, recipient may have reverted");
          }
          /**
           * @dev Performs a Solidity function call using a low level `call`. A
           * plain `call` is an unsafe replacement for a function call: use this
           * function instead.
           *
           * If `target` reverts with a revert reason, it is bubbled up by this
           * function (like regular Solidity function calls).
           *
           * Returns the raw returned data. To convert to the expected return value,
           * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
           *
           * Requirements:
           *
           * - `target` must be a contract.
           * - calling `target` with `data` must not revert.
           *
           * _Available since v3.1._
           */
          function functionCall(address target, bytes memory data) internal returns (bytes memory) {
              return functionCallWithValue(target, data, 0, "Address: low-level call failed");
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
           * `errorMessage` as a fallback revert reason when `target` reverts.
           *
           * _Available since v3.1._
           */
          function functionCall(
              address target,
              bytes memory data,
              string memory errorMessage
          ) internal returns (bytes memory) {
              return functionCallWithValue(target, data, 0, errorMessage);
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
           * but also transferring `value` wei to `target`.
           *
           * Requirements:
           *
           * - the calling contract must have an ETH balance of at least `value`.
           * - the called Solidity function must be `payable`.
           *
           * _Available since v3.1._
           */
          function functionCallWithValue(
              address target,
              bytes memory data,
              uint256 value
          ) internal returns (bytes memory) {
              return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
          }
          /**
           * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
           * with `errorMessage` as a fallback revert reason when `target` reverts.
           *
           * _Available since v3.1._
           */
          function functionCallWithValue(
              address target,
              bytes memory data,
              uint256 value,
              string memory errorMessage
          ) internal returns (bytes memory) {
              require(address(this).balance >= value, "Address: insufficient balance for call");
              (bool success, bytes memory returndata) = target.call{value: value}(data);
              return verifyCallResultFromTarget(target, success, returndata, errorMessage);
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
           * but performing a static call.
           *
           * _Available since v3.3._
           */
          function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
              return functionStaticCall(target, data, "Address: low-level static call failed");
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
           * but performing a static call.
           *
           * _Available since v3.3._
           */
          function functionStaticCall(
              address target,
              bytes memory data,
              string memory errorMessage
          ) internal view returns (bytes memory) {
              (bool success, bytes memory returndata) = target.staticcall(data);
              return verifyCallResultFromTarget(target, success, returndata, errorMessage);
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
           * but performing a delegate call.
           *
           * _Available since v3.4._
           */
          function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
              return functionDelegateCall(target, data, "Address: low-level delegate call failed");
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
           * but performing a delegate call.
           *
           * _Available since v3.4._
           */
          function functionDelegateCall(
              address target,
              bytes memory data,
              string memory errorMessage
          ) internal returns (bytes memory) {
              (bool success, bytes memory returndata) = target.delegatecall(data);
              return verifyCallResultFromTarget(target, success, returndata, errorMessage);
          }
          /**
           * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
           * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
           *
           * _Available since v4.8._
           */
          function verifyCallResultFromTarget(
              address target,
              bool success,
              bytes memory returndata,
              string memory errorMessage
          ) internal view returns (bytes memory) {
              if (success) {
                  if (returndata.length == 0) {
                      // only check isContract if the call was successful and the return data is empty
                      // otherwise we already know that it was a contract
                      require(isContract(target), "Address: call to non-contract");
                  }
                  return returndata;
              } else {
                  _revert(returndata, errorMessage);
              }
          }
          /**
           * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
           * revert reason or using the provided one.
           *
           * _Available since v4.3._
           */
          function verifyCallResult(
              bool success,
              bytes memory returndata,
              string memory errorMessage
          ) internal pure returns (bytes memory) {
              if (success) {
                  return returndata;
              } else {
                  _revert(returndata, errorMessage);
              }
          }
          function _revert(bytes memory returndata, string memory errorMessage) private pure {
              // Look for revert reason and bubble it up if present
              if (returndata.length > 0) {
                  // The easiest way to bubble the revert reason is using memory via assembly
                  /// @solidity memory-safe-assembly
                  assembly {
                      let returndata_size := mload(returndata)
                      revert(add(32, returndata), returndata_size)
                  }
              } else {
                  revert(errorMessage);
              }
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
      pragma solidity ^0.8.0;
      /**
       * @dev Interface of the ERC165 standard, as defined in the
       * https://eips.ethereum.org/EIPS/eip-165[EIP].
       *
       * Implementers can declare support of contract interfaces, which can then be
       * queried by others ({ERC165Checker}).
       *
       * For an implementation, see {ERC165}.
       */
      interface IERC165 {
          /**
           * @dev Returns true if this contract implements the interface defined by
           * `interfaceId`. See the corresponding
           * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
           * to learn more about how these ids are created.
           *
           * This function call must use less than 30 000 gas.
           */
          function supportsInterface(bytes4 interfaceId) external view returns (bool);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.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 v4.4.1 (token/ERC1155/utils/ERC1155Receiver.sol)
      pragma solidity ^0.8.0;
      import "../IERC1155Receiver.sol";
      import "../../../utils/introspection/ERC165.sol";
      /**
       * @dev _Available since v3.1._
       */
      abstract contract ERC1155Receiver is ERC165, IERC1155Receiver {
          /**
           * @dev See {IERC165-supportsInterface}.
           */
          function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
              return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);
          }
      }
      // SPDX-License-Identifier: GPL-3.0-only
      pragma solidity ^0.8.16;
      library StorageAPI {
          function setBytes(bytes32 key, bytes memory data) internal {
              bytes32 slot = keccak256(abi.encodePacked(key));
              assembly {
                  let length := mload(data)
                  switch gt(length, 0x1F)
                  case 0x00 {
                      sstore(key, or(mload(add(data, 0x20)), mul(length, 2)))
                  }
                  case 0x01 {
                      sstore(key, add(mul(length, 2), 1))
                      for {
                          let i := 0
                      } lt(mul(i, 0x20), length) {
                          i := add(i, 0x01)
                      } {
                          sstore(add(slot, i), mload(add(data, mul(add(i, 1), 0x20))))
                      }
                  }
              }
          }
          function setBytes32(bytes32 key, bytes32 val) internal {
              assembly {
                  sstore(key, val)
              }
          }
          function setAddress(bytes32 key, address a) internal {
              assembly {
                  sstore(key, a)
              }
          }
          function setUint256(bytes32 key, uint256 val) internal {
              assembly {
                  sstore(key, val)
              }
          }
          function setInt256(bytes32 key, int256 val) internal {
              assembly {
                  sstore(key, val)
              }
          }
          function setBool(bytes32 key, bool val) internal {
              assembly {
                  sstore(key, val)
              }
          }
          function getBytes(bytes32 key) internal view returns (bytes memory data) {
              bytes32 slot = keccak256(abi.encodePacked(key));
              assembly {
                  let length := sload(key)
                  switch and(length, 0x01)
                  case 0x00 {
                      let decodedLength := div(and(length, 0xFF), 2)
                      mstore(data, decodedLength)
                      mstore(add(data, 0x20), and(length, not(0xFF)))
                      mstore(0x40, add(data, 0x40))
                  }
                  case 0x01 {
                      let decodedLength := div(length, 2)
                      let i := 0
                      mstore(data, decodedLength)
                      for {
                      } lt(mul(i, 0x20), decodedLength) {
                          i := add(i, 0x01)
                      } {
                          mstore(add(add(data, 0x20), mul(i, 0x20)), sload(add(slot, i)))
                      }
                      mstore(0x40, add(data, add(0x20, mul(i, 0x20))))
                  }
              }
          }
          function getBytes32(bytes32 key) internal view returns (bytes32 val) {
              assembly {
                  val := sload(key)
              }
          }
          function getAddress(bytes32 key) internal view returns (address a) {
              assembly {
                  a := sload(key)
              }
          }
          function getUint256(bytes32 key) internal view returns (uint256 val) {
              assembly {
                  val := sload(key)
              }
          }
          function getInt256(bytes32 key) internal view returns (int256 val) {
              assembly {
                  val := sload(key)
              }
          }
          function getBool(bytes32 key) internal view returns (bool val) {
              assembly {
                  val := sload(key)
              }
          }
      }
      // 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: MIT
      // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
      pragma solidity ^0.8.0;
      import "./IERC165.sol";
      /**
       * @dev Implementation of the {IERC165} interface.
       *
       * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
       * for the additional interface id that will be supported. For example:
       *
       * ```solidity
       * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
       *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
       * }
       * ```
       *
       * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
       */
      abstract contract ERC165 is IERC165 {
          /**
           * @dev See {IERC165-supportsInterface}.
           */
          function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
              return interfaceId == type(IERC165).interfaceId;
          }
      }
      

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

      File 3 of 4: EnsoShortcuts
      // SPDX-License-Identifier: GPL-3.0-only
      pragma solidity ^0.8.0;
      import { VM } from "enso-weiroll/VM.sol";
      import { MinimalWallet } from "shortcuts-contracts/wallet/MinimalWallet.sol";
      import { AccessController } from "shortcuts-contracts/access/AccessController.sol";
      contract EnsoShortcuts is VM, MinimalWallet, AccessController {
          address public executor;
          constructor(address owner_, address executor_) {
              _setPermission(OWNER_ROLE, owner_, true);
              executor = executor_;
          }
          // @notice Execute a shortcut
          // @param commands An array of bytes32 values that encode calls
          // @param state An array of bytes that are used to generate call data for each command
          function executeShortcut(
              bytes32[] calldata commands,
              bytes[] calldata state
          ) external payable returns (bytes[] memory) {
              // we could use the AccessController here to check if the msg.sender is the executor address
              // but as it's a hot path we do a less gas intensive check
              if (msg.sender != executor) revert NotPermitted();
              return _execute(commands, state);
          }
      }
      // SPDX-License-Identifier: GPL-3.0-only
      pragma solidity ^0.8.16;
      import "./CommandBuilder.sol";
      abstract contract VM {
          using CommandBuilder for bytes[];
          uint256 constant FLAG_CT_DELEGATECALL = 0x00; // Delegate call not currently supported
          uint256 constant FLAG_CT_CALL = 0x01;
          uint256 constant FLAG_CT_STATICCALL = 0x02;
          uint256 constant FLAG_CT_VALUECALL = 0x03;
          uint256 constant FLAG_CT_MASK = 0x03;
          uint256 constant FLAG_DATA = 0x20;
          uint256 constant FLAG_EXTENDED_COMMAND = 0x40;
          uint256 constant FLAG_TUPLE_RETURN = 0x80;
          uint256 constant SHORT_COMMAND_FILL =
              0x000000000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
          error ExecutionFailed(
              uint256 command_index,
              address target,
              string message
          );
          function _execute(bytes32[] calldata commands, bytes[] memory state)
              internal
              returns (bytes[] memory)
          {
              bytes32 command;
              uint256 flags;
              bytes32 indices;
              bool success;
              bytes memory outData;
              uint256 commandsLength = commands.length;
              uint256 indicesLength;
              for (uint256 i; i < commandsLength; i = _uncheckedIncrement(i)) {
                  command = commands[i];
                  flags = uint256(uint8(bytes1(command << 32)));
                  if (flags & FLAG_EXTENDED_COMMAND != 0) {
                      i = _uncheckedIncrement(i);
                      indices = commands[i];
                      indicesLength = 32;
                  } else {
                      indices = bytes32(uint256(command << 40) | SHORT_COMMAND_FILL);
                      indicesLength = 6;
                  }
                  if (flags & FLAG_CT_MASK == FLAG_CT_CALL) {
                      (success, outData) = address(uint160(uint256(command))).call( // target
                          // inputs
                          flags & FLAG_DATA == 0
                              ? state.buildInputs(
                                  bytes4(command), // selector
                                  indices,
                                  indicesLength
                              )
                              : state[
                                  uint8(bytes1(indices)) &
                                  CommandBuilder.IDX_VALUE_MASK
                              ]
                      );
                  } else if (flags & FLAG_CT_MASK == FLAG_CT_STATICCALL) {
                      (success, outData) = address(uint160(uint256(command))) // target
                          .staticcall(
                              // inputs
                              flags & FLAG_DATA == 0
                                  ? state.buildInputs(
                                      bytes4(command), // selector
                                      indices,
                                      indicesLength
                                  )
                                  : state[
                                      uint8(bytes1(indices)) &
                                      CommandBuilder.IDX_VALUE_MASK
                                  ]
                          );
                  } else if (flags & FLAG_CT_MASK == FLAG_CT_VALUECALL) {
                      bytes memory v = state[
                          uint8(bytes1(indices)) &
                          CommandBuilder.IDX_VALUE_MASK
                      ];
                      require(v.length == 32, "Value must be 32 bytes");
                      uint256 callEth = uint256(bytes32(v));
                      (success, outData) = address(uint160(uint256(command))).call{ // target
                          value: callEth
                      }(
                          // inputs
                          flags & FLAG_DATA == 0
                              ? state.buildInputs(
                                  bytes4(command), // selector
                                  indices << 8, // skip value input
                                  indicesLength - 1 // max indices length reduced by value input
                              )
                              : state[
                                  uint8(bytes1(indices << 8)) & // first byte after value input
                                  CommandBuilder.IDX_VALUE_MASK
                              ]
                      );
                  } else {
                      revert("Invalid calltype");
                  }
                  if (!success) {
                      string memory message = "Unknown";
                      if (outData.length > 68) {
                          // This might be an error message, parse the outData
                          // Estimate the bytes length of the possible error message
                          uint256 estimatedLength = _estimateBytesLength(outData, 68);
                          // Remove selector. First 32 bytes should be a pointer that indicates the start of data in memory
                          assembly {
                              outData := add(outData, 4)
                          }
                          uint256 pointer = uint256(bytes32(outData));
                          if (pointer == 32) {
                              // Remove pointer. If it is a string, the next 32 bytes will hold the size
                              assembly {
                                  outData := add(outData, 32)
                              }
                              uint256 size = uint256(bytes32(outData));
                              // If the size variable is the same as the estimated bytes length, we can be fairly certain
                              // this is a dynamic string, so convert the bytes to a string and emit the message. While an
                              // error function with 3 static parameters is capable of producing a similar output, there is
                              // low risk of a contract unintentionally emitting a message.
                              if (size == estimatedLength) {
                                  // Remove size. The remaining data should be the string content
                                  assembly {
                                      outData := add(outData, 32)
                                  }
                                  message = string(outData);
                              }
                          }
                      }
                      revert ExecutionFailed({
                          command_index: flags & FLAG_EXTENDED_COMMAND == 0
                              ? i
                              : i - 1,
                          target: address(uint160(uint256(command))),
                          message: message
                      });
                  }
                  if (flags & FLAG_TUPLE_RETURN != 0) {
                      state.writeTuple(bytes1(command << 88), outData);
                  } else {
                      state = state.writeOutputs(bytes1(command << 88), outData);
                  }
              }
              return state;
          }
          function _estimateBytesLength(bytes memory data, uint256 pos) internal pure returns (uint256 estimate) {
              uint256 length = data.length;
              estimate = length - pos; // Assume length equals alloted space
              for (uint256 i = pos; i < length; ) {
                  if (data[i] == 0) {
                      // Zero bytes found, adjust estimated length
                      estimate = i - pos;
                      break;
                  }
                  unchecked {
                      ++i;
                  }
              }
          }
          function _uncheckedIncrement(uint256 i) private pure returns (uint256) {
              unchecked {
                  ++i;
              }
              return i;
          }
      }
      // SPDX-License-Identifier: GPL-3.0-only
      pragma solidity ^0.8.16;
      import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
      import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
      import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
      import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol";
      import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";
      import "../access/ACL.sol";
      import "../access/Roles.sol";
      contract MinimalWallet is ACL, Roles, ERC721Holder, ERC1155Holder {
          using SafeERC20 for IERC20;
          enum Protocol {
              ETH,
              ERC20,
              ERC721,
              ERC1155
          }
          struct TransferNote {
              Protocol protocol;
              address token;
              uint256[] ids;
              uint256[] amounts;
          }
          struct ApprovalNote {
              Protocol protocol;
              address token;
              address[] operators;
          }
          error WithdrawFailed();
          error InvalidArrayLength();
          ////////////////////////////////////////////////////
          // External functions //////////////////////////////
          ////////////////////////////////////////////////////
          // @notice Withdraw an array of assets
          // @dev Works for ETH, ERC20s, ERC721s, and ERC1155s
          // @param notes A tuple that contains the protocol id, token address, array of ids and amounts
          function withdraw(TransferNote[] calldata notes) external isPermitted(OWNER_ROLE) {
              TransferNote memory note;
              Protocol protocol;
              uint256[] memory ids;
              uint256[] memory amounts;
              uint256 length = notes.length;
              for (uint256 i; i < length; ) {
                  note = notes[i];
                  protocol = note.protocol;
                  if (protocol == Protocol.ETH) {
                      amounts = note.amounts;
                      if (amounts.length != 1) revert InvalidArrayLength();
                      _withdrawETH(amounts[0]);
                  } else if (protocol == Protocol.ERC20) {
                      amounts = note.amounts;
                      if (amounts.length != 1) revert InvalidArrayLength();
                      _withdrawERC20(IERC20(note.token), amounts[0]);
                  } else if (protocol == Protocol.ERC721) {
                      ids = note.ids;
                      _withdrawERC721s(IERC721(note.token), ids);
                  } else if (protocol == Protocol.ERC1155) {
                      ids = note.ids;
                      amounts = note.amounts;
                      _withdrawERC1155s(IERC1155(note.token), ids, amounts);
                  }
                  unchecked {
                      ++i;
                  }
              }
          }
          // @notice Withdraw ETH from this contract to the msg.sender
          // @param amount The amount of ETH to be withdrawn
          function withdrawETH(uint256 amount) external isPermitted(OWNER_ROLE) {
              _withdrawETH(amount);
          }
          // @notice Withdraw ERC20s
          // @param erc20s An array of erc20 addresses
          // @param amounts An array of amounts for each erc20
          function withdrawERC20s(
              IERC20[] calldata erc20s,
              uint256[] calldata amounts
          ) external isPermitted(OWNER_ROLE) {
              uint256 length = erc20s.length;
              if (amounts.length != length) revert InvalidArrayLength();
              for (uint256 i; i < length; ) {
                  _withdrawERC20(erc20s[i], amounts[i]);
                  unchecked {
                      ++i;
                  }
              }
          }
          // @notice Withdraw multiple ERC721 ids for a single ERC721 contract
          // @param erc721 The address of the ERC721 contract
          // @param ids An array of ids that are to be withdrawn
          function withdrawERC721s(
              IERC721 erc721,
              uint256[] calldata ids
          ) external isPermitted(OWNER_ROLE) {
              _withdrawERC721s(erc721, ids);
          }
          // @notice Withdraw multiple ERC1155 ids for a single ERC1155 contract
          // @param erc1155 The address of the ERC155 contract
          // @param ids An array of ids that are to be withdrawn
          // @param amounts An array of amounts per id
          function withdrawERC1155s(
              IERC1155 erc1155,
              uint256[] calldata ids,
              uint256[] calldata amounts
          ) external isPermitted(OWNER_ROLE) {
              _withdrawERC1155s(erc1155, ids, amounts);
          }
          // @notice Revoke approval on an array of assets and operators
          // @dev Works for ERC20s, ERC721s, and ERC1155s
          // @param notes A tuple that contains the protocol id, token address, and array of operators
          function revokeApprovals(ApprovalNote[] calldata notes) external isPermitted(OWNER_ROLE) {
              ApprovalNote memory note;
              Protocol protocol;
              uint256 length = notes.length;
              for (uint256 i; i < length; ) {
                  note = notes[i];
                  protocol = note.protocol;
                  if (protocol == Protocol.ERC20) {
                      _revokeERC20Approvals(IERC20(note.token), note.operators);
                  } else if (protocol == Protocol.ERC721) {
                      _revokeERC721Approvals(IERC721(note.token), note.operators);
                  } else if (protocol == Protocol.ERC1155) {
                      _revokeERC1155Approvals(IERC1155(note.token), note.operators);
                  }
                  unchecked {
                      ++i;
                  }
              }
          }
          // @notice Revoke approval of an ERC20 for an array of operators
          // @param erc20 The address of the ERC20 token
          // @param operators The array of operators to have approval revoked
          function revokeERC20Approvals(
              IERC20 erc20,
              address[] calldata operators
          ) external isPermitted(OWNER_ROLE) {
              _revokeERC20Approvals(erc20, operators);
          }
          // @notice Revoke approval of an ERC721 for an array of operators
          // @param erc721 The address of the ERC721 token
          // @param operators The array of operators to have approval revoked
          function revokeERC721Approvals(
              IERC721 erc721,
              address[] calldata operators
          ) external isPermitted(OWNER_ROLE) {
              _revokeERC721Approvals(erc721, operators);
          }
          // @notice Revoke approval of an ERC1155 for an array of operators
          // @param erc1155 The address of the ERC1155 token
          // @param operators The array of operators to have approval revoked
          function revokeERC1155Approvals(
              IERC1155 erc1155,
              address[] calldata operators
          ) external isPermitted(OWNER_ROLE) {
              _revokeERC1155Approvals(erc1155, operators);
          }
          ////////////////////////////////////////////////////
          // Internal functions //////////////////////////////
          ////////////////////////////////////////////////////
          function _withdrawETH(uint256 amount) internal {
              (bool success, ) = msg.sender.call{value: amount}("");
              if (!success) revert WithdrawFailed();
          }
          function _withdrawERC20(IERC20 erc20, uint256 amount) internal {
              erc20.safeTransfer(msg.sender, amount);
          }
          function _withdrawERC721s(IERC721 erc721, uint256[] memory ids) internal {
              uint256 length = ids.length;
              for (uint256 i; i < length; ) {
                  erc721.safeTransferFrom(address(this), msg.sender, ids[i]);
                  unchecked {
                      ++i;
                  }
              }
          }
          function _withdrawERC1155s(IERC1155 erc1155, uint256[] memory ids, uint256[] memory amounts) internal {
              // safeBatchTransferFrom will validate the array lengths
              erc1155.safeBatchTransferFrom(address(this), msg.sender, ids, amounts, "");
          }
          function _revokeERC20Approvals(IERC20 erc20, address[] memory operators) internal {
              uint256 length = operators.length;
              for (uint256 i; i < length; ) {
                  erc20.safeApprove(operators[i], 0);
                  unchecked {
                      ++i;
                  }
              }
          }
          function _revokeERC721Approvals(IERC721 erc721, address[] memory operators) internal {
              uint256 length = operators.length;
              for (uint256 i; i < length; ) {
                  erc721.setApprovalForAll(operators[i], false);
                  unchecked {
                      ++i;
                  }
              }
          }
          function _revokeERC1155Approvals(IERC1155 erc1155, address[] memory operators) internal {
              uint256 length = operators.length;
              for (uint256 i; i < length; ) {
                  erc1155.setApprovalForAll(operators[i], false);
                  unchecked {
                      ++i;
                  }
              }
          }
          ////////////////////////////////////////////////////
          // Fallback functions //////////////////////////////
          ////////////////////////////////////////////////////
          receive() external payable {}
      }
      // SPDX-License-Identifier: GPL-3.0-only
      pragma solidity ^0.8.16;
      import "./ACL.sol";
      import "./Roles.sol";
      // @notice The OWNER_ROLE must be set in the importing contract's constructor or initialize function
      abstract contract AccessController is ACL, Roles {
          using StorageAPI for bytes32;
          event PermissionSet(bytes32 role, address account, bool permission);
          error UnsafeSetting();
          error InvalidAccount();
          // @notice Sets user permission over a role
          // @param role The bytes32 value of the role
          // @param account The address of the account
          // @param permission The permission status
          function setPermission(
              bytes32 role,
              address account,
              bool permission
          ) external isPermitted(OWNER_ROLE) {
              if (account == address(0)) revert InvalidAccount();
              if (role == OWNER_ROLE && account == msg.sender && permission == false)
                  revert UnsafeSetting();
              _setPermission(role, account, permission);
          }
          // @notice Internal function to set user permission over a role
          // @param role The bytes32 value of the role
          // @param account The address of the account
          // @param permission The permission status
          function _setPermission(bytes32 role, address account, bool permission) internal {
              bytes32 key = _getKey(role, account);
              key.setBool(permission);
              emit PermissionSet(role, account, permission);
          }
      }
      // SPDX-License-Identifier: GPL-3.0-only
      pragma solidity ^0.8.16;
      library CommandBuilder {
          uint256 constant IDX_VARIABLE_LENGTH = 0x80;
          uint256 constant IDX_VALUE_MASK = 0x7f;
          uint256 constant IDX_END_OF_ARGS = 0xff;
          uint256 constant IDX_USE_STATE = 0xfe;
          uint256 constant IDX_ARRAY_START = 0xfd;
          uint256 constant IDX_TUPLE_START = 0xfc;
          uint256 constant IDX_DYNAMIC_END = 0xfb;
          function buildInputs(
              bytes[] memory state,
              bytes4 selector,
              bytes32 indices,
              uint256 indicesLength
          ) internal view returns (bytes memory ret) {
              uint256 idx; // The current command index
              uint256 offsetIdx; // The index of the current free offset
              uint256 count; // Number of bytes in whole ABI encoded message
              uint256 free; // Pointer to first free byte in tail part of message
              uint256[] memory dynamicLengths = new uint256[](10); // Optionally store the length of all dynamic types (a command cannot fit more than 10 dynamic types)
              bytes memory stateData; // Optionally encode the current state if the call requires it
              // Determine the length of the encoded data
              for (uint256 i; i < indicesLength; ) {
                  idx = uint8(indices[i]);
                  if (idx == IDX_END_OF_ARGS) {
                      indicesLength = i;
                      break;
                  }
                  if (idx & IDX_VARIABLE_LENGTH != 0) {
                      if (idx == IDX_USE_STATE) {
                          if (stateData.length == 0) {
                              stateData = abi.encode(state);
                          }
                          unchecked {
                              count += stateData.length;
                          }
                      } else {
                          (dynamicLengths, offsetIdx, count, i) = setupDynamicType(
                              state,
                              indices,
                              dynamicLengths,
                              idx,
                              offsetIdx,
                              count,
                              i
                          );
                      }
                  } else {
                      count = setupStaticVariable(state, count, idx);
                  }
                  unchecked {
                      free += 32;
                      ++i;
                  }
              }
              // Encode it
              ret = new bytes(count + 4);
              assembly {
                  mstore(add(ret, 32), selector)
              }
              offsetIdx = 0;
              // Use count to track current memory slot
              assembly {
                  count := add(ret, 36)
              }
              for (uint256 i; i < indicesLength; ) {
                  idx = uint8(indices[i]);
                  if (idx & IDX_VARIABLE_LENGTH != 0) {
                      if (idx == IDX_USE_STATE) {
                          assembly {
                              mstore(count, free)
                          }
                          memcpy(stateData, 32, ret, free + 4, stateData.length - 32);
                          unchecked {
                              free += stateData.length - 32;
                          }
                      } else if (idx == IDX_ARRAY_START) {
                          // Start of dynamic type, put pointer in current slot
                          assembly {
                              mstore(count, free)
                          }
                          (offsetIdx, free, i, ) = encodeDynamicArray(
                              ret,
                              state,
                              indices,
                              dynamicLengths,
                              offsetIdx,
                              free,
                              i
                          );
                      } else if (idx == IDX_TUPLE_START) {
                          // Start of dynamic type, put pointer in current slot
                          assembly {
                              mstore(count, free)
                          }
                          (offsetIdx, free, i, ) = encodeDynamicTuple(
                              ret,
                              state,
                              indices,
                              dynamicLengths,
                              offsetIdx,
                              free,
                              i
                          );
                      } else {
                          // Variable length data
                          uint256 argLen = state[idx & IDX_VALUE_MASK].length;
                          // Put a pointer in the current slot and write the data to first free slot
                          assembly {
                              mstore(count, free)
                          }
                          memcpy(
                              state[idx & IDX_VALUE_MASK],
                              0,
                              ret,
                              free + 4,
                              argLen
                          );
                          unchecked {
                              free += argLen;
                          }
                      }
                  } else {
                      // Fixed length data (length previously checked to be 32 bytes)
                      bytes memory stateVar = state[idx & IDX_VALUE_MASK];
                      // Write the data to current slot
                      assembly {
                          mstore(count, mload(add(stateVar, 32)))
                      }
                  }
                  unchecked {
                      count += 32;
                      ++i;
                  }
              }
          }
          function setupStaticVariable(
              bytes[] memory state,
              uint256 count,
              uint256 idx
          ) internal pure returns (uint256 newCount) {
              require(
                  state[idx & IDX_VALUE_MASK].length == 32,
                  "Static state variables must be 32 bytes"
              );
              unchecked {
                  newCount = count + 32;
              }
          }
          function setupDynamicVariable(
              bytes[] memory state,
              uint256 count,
              uint256 idx
          ) internal pure returns (uint256 newCount) {
              bytes memory arg = state[idx & IDX_VALUE_MASK];
              // Validate the length of the data in state is a multiple of 32
              uint256 argLen = arg.length;
              require(
                  argLen != 0 && argLen % 32 == 0,
                  "Dynamic state variables must be a multiple of 32 bytes"
              );
              // Add the length of the value, rounded up to the next word boundary, plus space for pointer
              unchecked {
                  newCount = count + argLen + 32;
              }
          }
          function setupDynamicType(
              bytes[] memory state,
              bytes32 indices,
              uint256[] memory dynamicLengths,
              uint256 idx,
              uint256 offsetIdx,
              uint256 count,
              uint256 index
          ) internal view returns (
              uint256[] memory newDynamicLengths,
              uint256 newOffsetIdx,
              uint256 newCount,
              uint256 newIndex
          ) {
              if (idx == IDX_ARRAY_START) {
                  (newDynamicLengths, newOffsetIdx, newCount, newIndex) = setupDynamicArray(
                      state,
                      indices,
                      dynamicLengths,
                      offsetIdx,
                      count,
                      index
                  );
              } else if (idx == IDX_TUPLE_START) {
                  (newDynamicLengths, newOffsetIdx, newCount, newIndex) = setupDynamicTuple(
                      state,
                      indices,
                      dynamicLengths,
                      offsetIdx,
                      count,
                      index
                  );
              } else {
                  newDynamicLengths = dynamicLengths;
                  newOffsetIdx = offsetIdx;
                  newIndex = index;
                  newCount = setupDynamicVariable(state, count, idx);
              }
          }
          function setupDynamicArray(
              bytes[] memory state,
              bytes32 indices,
              uint256[] memory dynamicLengths,
              uint256 offsetIdx,
              uint256 count,
              uint256 index
          ) internal view returns (
              uint256[] memory newDynamicLengths,
              uint256 newOffsetIdx,
              uint256 newCount,
              uint256 newIndex
          ) {
              // Current idx is IDX_ARRAY_START, next idx will contain the array length
              unchecked {
                  newIndex = index + 1;
                  newCount = count + 32;
              }
              uint256 idx = uint8(indices[newIndex]);
              require(
                  state[idx & IDX_VALUE_MASK].length == 32,
                  "Array length must be 32 bytes"
              );
              (newDynamicLengths, newOffsetIdx, newCount, newIndex) = setupDynamicTuple(
                  state,
                  indices,
                  dynamicLengths,
                  offsetIdx,
                  newCount,
                  newIndex
              );
          }
          function setupDynamicTuple(
              bytes[] memory state,
              bytes32 indices,
              uint256[] memory dynamicLengths,
              uint256 offsetIdx,
              uint256 count,
              uint256 index
          ) internal view returns (
              uint256[] memory newDynamicLengths,
              uint256 newOffsetIdx,
              uint256 newCount,
              uint256 newIndex
          ) {
              uint256 idx;
              uint256 offset;
              newDynamicLengths = dynamicLengths;
              // Progress to first index of the data and progress the next offset idx
              unchecked {
                  newIndex = index + 1;
                  newOffsetIdx = offsetIdx + 1;
                  newCount = count + 32;
              }
              while (newIndex < 32) {
                  idx = uint8(indices[newIndex]);
                  if (idx & IDX_VARIABLE_LENGTH != 0) {
                      if (idx == IDX_DYNAMIC_END) {
                          newDynamicLengths[offsetIdx] = offset;
                          // explicit return saves gas ¯\\_(ツ)_/¯
                          return (newDynamicLengths, newOffsetIdx, newCount, newIndex);
                      } else {
                          require(idx != IDX_USE_STATE, "Cannot use state from inside dynamic type");
                          (newDynamicLengths, newOffsetIdx, newCount, newIndex) = setupDynamicType(
                              state,
                              indices,
                              newDynamicLengths,
                              idx,
                              newOffsetIdx,
                              newCount,
                              newIndex
                          );
                      }
                  } else {
                      newCount = setupStaticVariable(state, newCount, idx);
                  }
                  unchecked {
                      offset += 32;
                      ++newIndex;
                  }
              }
              revert("Dynamic type was not properly closed");
          }
          function encodeDynamicArray(
              bytes memory ret,
              bytes[] memory state,
              bytes32 indices,
              uint256[] memory dynamicLengths,
              uint256 offsetIdx,
              uint256 currentSlot,
              uint256 index
          ) internal view returns (
              uint256 newOffsetIdx,
              uint256 newSlot,
              uint256 newIndex,
              uint256 length
          ) {
              // Progress to array length metadata
              unchecked {
                  newIndex = index + 1;
                  newSlot = currentSlot + 32;
              }
              // Encode array length
              uint256 idx = uint8(indices[newIndex]);
              // Array length value previously checked to be 32 bytes
              bytes memory stateVar = state[idx & IDX_VALUE_MASK];
              assembly {
                  mstore(add(add(ret, 36), currentSlot), mload(add(stateVar, 32)))
              }
              (newOffsetIdx, newSlot, newIndex, length) = encodeDynamicTuple(
                  ret,
                  state,
                  indices,
                  dynamicLengths,
                  offsetIdx,
                  newSlot,
                  newIndex
              );
              unchecked {
                  length += 32; // Increase length to account for array length metadata
              }
          }
          function encodeDynamicTuple(
              bytes memory ret,
              bytes[] memory state,
              bytes32 indices,
              uint256[] memory dynamicLengths,
              uint256 offsetIdx,
              uint256 currentSlot,
              uint256 index
          ) internal view returns (
              uint256 newOffsetIdx,
              uint256 newSlot,
              uint256 newIndex,
              uint256 length
          ) {
              uint256 idx;
              uint256 argLen;
              uint256 freePointer = dynamicLengths[offsetIdx]; // The pointer to the next free slot
              unchecked {
                  newSlot = currentSlot + freePointer; // Update the next slot
                  newOffsetIdx = offsetIdx + 1; // Progress to next offsetIdx
                  newIndex = index + 1; // Progress to first index of the data
              }
              // Shift currentSlot to correct location in memory
              assembly {
                  currentSlot := add(add(ret, 36), currentSlot)
              }
              while (newIndex < 32) {
                  idx = uint8(indices[newIndex]);
                  if (idx & IDX_VARIABLE_LENGTH != 0) {
                      if (idx == IDX_DYNAMIC_END) {
                          break;
                      } else if (idx == IDX_ARRAY_START) {
                          // Start of dynamic type, put pointer in current slot
                          assembly {
                              mstore(currentSlot, freePointer)
                          }
                          (newOffsetIdx, newSlot, newIndex, argLen) = encodeDynamicArray(
                              ret,
                              state,
                              indices,
                              dynamicLengths,
                              newOffsetIdx,
                              newSlot,
                              newIndex
                          );
                          unchecked {
                              freePointer += argLen;
                              length += (argLen + 32); // data + pointer
                          }
                      } else if (idx == IDX_TUPLE_START) {
                          // Start of dynamic type, put pointer in current slot
                          assembly {
                              mstore(currentSlot, freePointer)
                          }
                          (newOffsetIdx, newSlot, newIndex, argLen) = encodeDynamicTuple(
                              ret,
                              state,
                              indices,
                              dynamicLengths,
                              newOffsetIdx,
                              newSlot,
                              newIndex
                          );
                          unchecked {
                              freePointer += argLen;
                              length += (argLen + 32); // data + pointer
                          }
                      } else  {
                          // Variable length data
                          argLen = state[idx & IDX_VALUE_MASK].length;
                          // Start of dynamic type, put pointer in current slot
                          assembly {
                              mstore(currentSlot, freePointer)
                          }
                          memcpy(
                              state[idx & IDX_VALUE_MASK],
                              0,
                              ret,
                              newSlot + 4,
                              argLen
                          );
                          unchecked {
                              newSlot += argLen;
                              freePointer += argLen;
                              length += (argLen + 32); // data + pointer
                          }
                      }
                  } else {
                      // Fixed length data (length previously checked to be 32 bytes)
                      bytes memory stateVar = state[idx & IDX_VALUE_MASK];
                      // Write to first free slot
                      assembly {
                          mstore(currentSlot, mload(add(stateVar, 32)))
                      }
                      unchecked {
                          length += 32;
                      }
                  }
                  unchecked {
                      currentSlot += 32;
                      ++newIndex;
                  }
              }
          }
          function writeOutputs(
              bytes[] memory state,
              bytes1 index,
              bytes memory output
          ) internal pure returns (bytes[] memory) {
              uint256 idx = uint8(index);
              if (idx == IDX_END_OF_ARGS) return state;
              if (idx & IDX_VARIABLE_LENGTH != 0) {
                  if (idx == IDX_USE_STATE) {
                      state = abi.decode(output, (bytes[]));
                  } else {
                      require(idx & IDX_VALUE_MASK < state.length, "Index out-of-bounds");
                      // Check the first field is 0x20 (because we have only a single return value)
                      uint256 argPtr;
                      assembly {
                          argPtr := mload(add(output, 32))
                      }
                      require(
                          argPtr == 32,
                          "Only one return value permitted (variable)"
                      );
                      assembly {
                          // Overwrite the first word of the return data with the length - 32
                          mstore(add(output, 32), sub(mload(output), 32))
                          // Insert a pointer to the return data, starting at the second word, into state
                          mstore(
                              add(add(state, 32), mul(and(idx, IDX_VALUE_MASK), 32)),
                              add(output, 32)
                          )
                      }
                  }
              } else {
                  require(idx & IDX_VALUE_MASK < state.length, "Index out-of-bounds");
                  // Single word
                  require(
                      output.length == 32,
                      "Only one return value permitted (static)"
                  );
                  state[idx & IDX_VALUE_MASK] = output;
              }
              return state;
          }
          function writeTuple(
              bytes[] memory state,
              bytes1 index,
              bytes memory output
          ) internal view {
              uint256 idx = uint8(index);
              if (idx == IDX_END_OF_ARGS) return;
              bytes memory entry = state[idx & IDX_VALUE_MASK] = new bytes(output.length + 32);
              memcpy(output, 0, entry, 32, output.length);
              assembly {
                  let l := mload(output)
                  mstore(add(entry, 32), l)
              }
          }
          function memcpy(
              bytes memory src,
              uint256 srcIdx,
              bytes memory dest,
              uint256 destIdx,
              uint256 len
          ) internal view {
              assembly {
                  pop(
                      staticcall(
                          gas(),
                          4,
                          add(add(src, 32), srcIdx),
                          len,
                          add(add(dest, 32), destIdx),
                          len
                      )
                  )
              }
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol)
      pragma solidity ^0.8.0;
      import "../IERC20.sol";
      import "../extensions/draft-IERC20Permit.sol";
      import "../../../utils/Address.sol";
      /**
       * @title SafeERC20
       * @dev Wrappers around ERC20 operations that throw on failure (when the token
       * contract returns false). Tokens that return no value (and instead revert or
       * throw on failure) are also supported, non-reverting calls are assumed to be
       * successful.
       * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
       * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
       */
      library SafeERC20 {
          using Address for address;
          function safeTransfer(
              IERC20 token,
              address to,
              uint256 value
          ) internal {
              _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
          }
          function safeTransferFrom(
              IERC20 token,
              address from,
              address to,
              uint256 value
          ) internal {
              _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
          }
          /**
           * @dev Deprecated. This function has issues similar to the ones found in
           * {IERC20-approve}, and its usage is discouraged.
           *
           * Whenever possible, use {safeIncreaseAllowance} and
           * {safeDecreaseAllowance} instead.
           */
          function safeApprove(
              IERC20 token,
              address spender,
              uint256 value
          ) internal {
              // safeApprove should only be called when setting an initial allowance,
              // or when resetting it to zero. To increase and decrease it, use
              // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
              require(
                  (value == 0) || (token.allowance(address(this), spender) == 0),
                  "SafeERC20: approve from non-zero to non-zero allowance"
              );
              _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
          }
          function safeIncreaseAllowance(
              IERC20 token,
              address spender,
              uint256 value
          ) internal {
              uint256 newAllowance = token.allowance(address(this), spender) + value;
              _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
          }
          function safeDecreaseAllowance(
              IERC20 token,
              address spender,
              uint256 value
          ) internal {
              unchecked {
                  uint256 oldAllowance = token.allowance(address(this), spender);
                  require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
                  uint256 newAllowance = oldAllowance - value;
                  _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
              }
          }
          function safePermit(
              IERC20Permit token,
              address owner,
              address spender,
              uint256 value,
              uint256 deadline,
              uint8 v,
              bytes32 r,
              bytes32 s
          ) internal {
              uint256 nonceBefore = token.nonces(owner);
              token.permit(owner, spender, value, deadline, v, r, s);
              uint256 nonceAfter = token.nonces(owner);
              require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
          }
          /**
           * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
           * on the return value: the return value is optional (but if data is returned, it must not be false).
           * @param token The token targeted by the call.
           * @param data The call data (encoded using abi.encode or one of its variants).
           */
          function _callOptionalReturn(IERC20 token, bytes memory data) private {
              // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
              // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
              // the target address contains contract code and also asserts for success in the low-level call.
              bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
              if (returndata.length > 0) {
                  // Return data is optional
                  require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
              }
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/IERC721.sol)
      pragma solidity ^0.8.0;
      import "../../utils/introspection/IERC165.sol";
      /**
       * @dev Required interface of an ERC721 compliant contract.
       */
      interface IERC721 is IERC165 {
          /**
           * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
           */
          event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
          /**
           * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
           */
          event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
          /**
           * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
           */
          event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
          /**
           * @dev Returns the number of tokens in ``owner``'s account.
           */
          function balanceOf(address owner) external view returns (uint256 balance);
          /**
           * @dev Returns the owner of the `tokenId` token.
           *
           * Requirements:
           *
           * - `tokenId` must exist.
           */
          function ownerOf(uint256 tokenId) external view returns (address owner);
          /**
           * @dev Safely transfers `tokenId` token from `from` to `to`.
           *
           * Requirements:
           *
           * - `from` cannot be the zero address.
           * - `to` cannot be the zero address.
           * - `tokenId` token must exist and be owned by `from`.
           * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
           * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
           *
           * Emits a {Transfer} event.
           */
          function safeTransferFrom(
              address from,
              address to,
              uint256 tokenId,
              bytes calldata data
          ) external;
          /**
           * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
           * are aware of the ERC721 protocol to prevent tokens from being forever locked.
           *
           * Requirements:
           *
           * - `from` cannot be the zero address.
           * - `to` cannot be the zero address.
           * - `tokenId` token must exist and be owned by `from`.
           * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
           * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
           *
           * Emits a {Transfer} event.
           */
          function safeTransferFrom(
              address from,
              address to,
              uint256 tokenId
          ) external;
          /**
           * @dev Transfers `tokenId` token from `from` to `to`.
           *
           * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
           * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
           * understand this adds an external call which potentially creates a reentrancy vulnerability.
           *
           * Requirements:
           *
           * - `from` cannot be the zero address.
           * - `to` cannot be the zero address.
           * - `tokenId` token must be owned by `from`.
           * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
           *
           * Emits a {Transfer} event.
           */
          function transferFrom(
              address from,
              address to,
              uint256 tokenId
          ) external;
          /**
           * @dev Gives permission to `to` to transfer `tokenId` token to another account.
           * The approval is cleared when the token is transferred.
           *
           * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
           *
           * Requirements:
           *
           * - The caller must own the token or be an approved operator.
           * - `tokenId` must exist.
           *
           * Emits an {Approval} event.
           */
          function approve(address to, uint256 tokenId) external;
          /**
           * @dev Approve or remove `operator` as an operator for the caller.
           * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
           *
           * Requirements:
           *
           * - The `operator` cannot be the caller.
           *
           * Emits an {ApprovalForAll} event.
           */
          function setApprovalForAll(address operator, bool _approved) external;
          /**
           * @dev Returns the account approved for `tokenId` token.
           *
           * Requirements:
           *
           * - `tokenId` must exist.
           */
          function getApproved(uint256 tokenId) external view returns (address operator);
          /**
           * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
           *
           * See {setApprovalForAll}
           */
          function isApprovedForAll(address owner, address operator) external view returns (bool);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.7.0) (token/ERC1155/IERC1155.sol)
      pragma solidity ^0.8.0;
      import "../../utils/introspection/IERC165.sol";
      /**
       * @dev Required interface of an ERC1155 compliant contract, as defined in the
       * https://eips.ethereum.org/EIPS/eip-1155[EIP].
       *
       * _Available since v3.1._
       */
      interface IERC1155 is IERC165 {
          /**
           * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
           */
          event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
          /**
           * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
           * transfers.
           */
          event TransferBatch(
              address indexed operator,
              address indexed from,
              address indexed to,
              uint256[] ids,
              uint256[] values
          );
          /**
           * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
           * `approved`.
           */
          event ApprovalForAll(address indexed account, address indexed operator, bool approved);
          /**
           * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
           *
           * If an {URI} event was emitted for `id`, the standard
           * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
           * returned by {IERC1155MetadataURI-uri}.
           */
          event URI(string value, uint256 indexed id);
          /**
           * @dev Returns the amount of tokens of token type `id` owned by `account`.
           *
           * Requirements:
           *
           * - `account` cannot be the zero address.
           */
          function balanceOf(address account, uint256 id) external view returns (uint256);
          /**
           * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
           *
           * Requirements:
           *
           * - `accounts` and `ids` must have the same length.
           */
          function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
              external
              view
              returns (uint256[] memory);
          /**
           * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
           *
           * Emits an {ApprovalForAll} event.
           *
           * Requirements:
           *
           * - `operator` cannot be the caller.
           */
          function setApprovalForAll(address operator, bool approved) external;
          /**
           * @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
           *
           * See {setApprovalForAll}.
           */
          function isApprovedForAll(address account, address operator) external view returns (bool);
          /**
           * @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
           *
           * Emits a {TransferSingle} event.
           *
           * Requirements:
           *
           * - `to` cannot be the zero address.
           * - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.
           * - `from` must have a balance of tokens of type `id` of at least `amount`.
           * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
           * acceptance magic value.
           */
          function safeTransferFrom(
              address from,
              address to,
              uint256 id,
              uint256 amount,
              bytes calldata data
          ) external;
          /**
           * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
           *
           * Emits a {TransferBatch} event.
           *
           * Requirements:
           *
           * - `ids` and `amounts` must have the same length.
           * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
           * acceptance magic value.
           */
          function safeBatchTransferFrom(
              address from,
              address to,
              uint256[] calldata ids,
              uint256[] calldata amounts,
              bytes calldata data
          ) external;
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts v4.4.1 (token/ERC721/utils/ERC721Holder.sol)
      pragma solidity ^0.8.0;
      import "../IERC721Receiver.sol";
      /**
       * @dev Implementation of the {IERC721Receiver} interface.
       *
       * Accepts all token transfers.
       * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}.
       */
      contract ERC721Holder is IERC721Receiver {
          /**
           * @dev See {IERC721Receiver-onERC721Received}.
           *
           * Always returns `IERC721Receiver.onERC721Received.selector`.
           */
          function onERC721Received(
              address,
              address,
              uint256,
              bytes memory
          ) public virtual override returns (bytes4) {
              return this.onERC721Received.selector;
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/utils/ERC1155Holder.sol)
      pragma solidity ^0.8.0;
      import "./ERC1155Receiver.sol";
      /**
       * Simple implementation of `ERC1155Receiver` that will allow a contract to hold ERC1155 tokens.
       *
       * IMPORTANT: When inheriting this contract, you must include a way to use the received tokens, otherwise they will be
       * stuck.
       *
       * @dev _Available since v3.1._
       */
      contract ERC1155Holder is ERC1155Receiver {
          function onERC1155Received(
              address,
              address,
              uint256,
              uint256,
              bytes memory
          ) public virtual override returns (bytes4) {
              return this.onERC1155Received.selector;
          }
          function onERC1155BatchReceived(
              address,
              address,
              uint256[] memory,
              uint256[] memory,
              bytes memory
          ) public virtual override returns (bytes4) {
              return this.onERC1155BatchReceived.selector;
          }
      }
      // SPDX-License-Identifier: GPL-3.0-only
      pragma solidity ^0.8.16;
      import "../libraries/StorageAPI.sol";
      abstract contract ACL {
          using StorageAPI for bytes32;
          error NotPermitted();
          modifier isPermitted(bytes32 role) {
              bool permitted = _getPermission(role, msg.sender); // TODO: support GSN/Account abstraction
              if (!permitted) revert NotPermitted();
              _;
          }
          // @notice Gets user permission for a role
          // @param role The bytes32 value of the role
          // @param account The address of the account
          // @return The permission status
          function getPermission(bytes32 role, address account) external view returns (bool) {
              return _getPermission(role, account);
          }
          // @notice Internal function to get user permission for a role
          // @param role The bytes32 value of the role
          // @param account The address of the account
          // @return The permission status
          function _getPermission(bytes32 role, address account) internal view returns (bool) {
              bytes32 key = _getKey(role, account);
              return key.getBool();
          }
          // @notice Internal function to get the key for the storage slot
          // @param role The bytes32 value of the role
          // @param account The address of the account
          // @return The bytes32 storage slot
          function _getKey(bytes32 role, address account) internal pure returns (bytes32) {
              return keccak256(abi.encode(role, account));
          }
      }
      // SPDX-License-Identifier: GPL-3.0-only
      pragma solidity ^0.8.16;
      abstract contract Roles {
          // Using same slot generation technique as eip-1967 -- https://eips.ethereum.org/EIPS/eip-1967
          bytes32 public constant OWNER_ROLE = bytes32(uint256(keccak256("enso.access.roles.owner")) - 1);
          bytes32 public constant EXECUTOR_ROLE = bytes32(uint256(keccak256("enso.access.roles.executor")) - 1);
          bytes32 public constant MODULE_ROLE = bytes32(uint256(keccak256("enso.access.roles.module")) - 1);
      }// SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
      pragma solidity ^0.8.0;
      /**
       * @dev Interface of the ERC20 standard as defined in the EIP.
       */
      interface IERC20 {
          /**
           * @dev Emitted when `value` tokens are moved from one account (`from`) to
           * another (`to`).
           *
           * Note that `value` may be zero.
           */
          event Transfer(address indexed from, address indexed to, uint256 value);
          /**
           * @dev Emitted when the allowance of a `spender` for an `owner` is set by
           * a call to {approve}. `value` is the new allowance.
           */
          event Approval(address indexed owner, address indexed spender, uint256 value);
          /**
           * @dev Returns the amount of tokens in existence.
           */
          function totalSupply() external view returns (uint256);
          /**
           * @dev Returns the amount of tokens owned by `account`.
           */
          function balanceOf(address account) external view returns (uint256);
          /**
           * @dev Moves `amount` tokens from the caller's account to `to`.
           *
           * Returns a boolean value indicating whether the operation succeeded.
           *
           * Emits a {Transfer} event.
           */
          function transfer(address to, uint256 amount) external returns (bool);
          /**
           * @dev Returns the remaining number of tokens that `spender` will be
           * allowed to spend on behalf of `owner` through {transferFrom}. This is
           * zero by default.
           *
           * This value changes when {approve} or {transferFrom} are called.
           */
          function allowance(address owner, address spender) external view returns (uint256);
          /**
           * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
           *
           * Returns a boolean value indicating whether the operation succeeded.
           *
           * IMPORTANT: Beware that changing an allowance with this method brings the risk
           * that someone may use both the old and the new allowance by unfortunate
           * transaction ordering. One possible solution to mitigate this race
           * condition is to first reduce the spender's allowance to 0 and set the
           * desired value afterwards:
           * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
           *
           * Emits an {Approval} event.
           */
          function approve(address spender, uint256 amount) external returns (bool);
          /**
           * @dev Moves `amount` tokens from `from` to `to` using the
           * allowance mechanism. `amount` is then deducted from the caller's
           * allowance.
           *
           * Returns a boolean value indicating whether the operation succeeded.
           *
           * Emits a {Transfer} event.
           */
          function transferFrom(
              address from,
              address to,
              uint256 amount
          ) external returns (bool);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
      pragma solidity ^0.8.0;
      /**
       * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
       * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
       *
       * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
       * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
       * need to send a transaction, and thus is not required to hold Ether at all.
       */
      interface IERC20Permit {
          /**
           * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
           * given ``owner``'s signed approval.
           *
           * IMPORTANT: The same issues {IERC20-approve} has related to transaction
           * ordering also apply here.
           *
           * Emits an {Approval} event.
           *
           * Requirements:
           *
           * - `spender` cannot be the zero address.
           * - `deadline` must be a timestamp in the future.
           * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
           * over the EIP712-formatted function arguments.
           * - the signature must use ``owner``'s current nonce (see {nonces}).
           *
           * For more information on the signature format, see the
           * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
           * section].
           */
          function permit(
              address owner,
              address spender,
              uint256 value,
              uint256 deadline,
              uint8 v,
              bytes32 r,
              bytes32 s
          ) external;
          /**
           * @dev Returns the current nonce for `owner`. This value must be
           * included whenever a signature is generated for {permit}.
           *
           * Every successful call to {permit} increases ``owner``'s nonce by one. This
           * prevents a signature from being used multiple times.
           */
          function nonces(address owner) external view returns (uint256);
          /**
           * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
           */
          // solhint-disable-next-line func-name-mixedcase
          function DOMAIN_SEPARATOR() external view returns (bytes32);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)
      pragma solidity ^0.8.1;
      /**
       * @dev Collection of functions related to the address type
       */
      library Address {
          /**
           * @dev Returns true if `account` is a contract.
           *
           * [IMPORTANT]
           * ====
           * It is unsafe to assume that an address for which this function returns
           * false is an externally-owned account (EOA) and not a contract.
           *
           * Among others, `isContract` will return false for the following
           * types of addresses:
           *
           *  - an externally-owned account
           *  - a contract in construction
           *  - an address where a contract will be created
           *  - an address where a contract lived, but was destroyed
           * ====
           *
           * [IMPORTANT]
           * ====
           * You shouldn't rely on `isContract` to protect against flash loan attacks!
           *
           * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
           * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
           * constructor.
           * ====
           */
          function isContract(address account) internal view returns (bool) {
              // This method relies on extcodesize/address.code.length, which returns 0
              // for contracts in construction, since the code is only stored at the end
              // of the constructor execution.
              return account.code.length > 0;
          }
          /**
           * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
           * `recipient`, forwarding all available gas and reverting on errors.
           *
           * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
           * of certain opcodes, possibly making contracts go over the 2300 gas limit
           * imposed by `transfer`, making them unable to receive funds via
           * `transfer`. {sendValue} removes this limitation.
           *
           * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
           *
           * IMPORTANT: because control is transferred to `recipient`, care must be
           * taken to not create reentrancy vulnerabilities. Consider using
           * {ReentrancyGuard} or the
           * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
           */
          function sendValue(address payable recipient, uint256 amount) internal {
              require(address(this).balance >= amount, "Address: insufficient balance");
              (bool success, ) = recipient.call{value: amount}("");
              require(success, "Address: unable to send value, recipient may have reverted");
          }
          /**
           * @dev Performs a Solidity function call using a low level `call`. A
           * plain `call` is an unsafe replacement for a function call: use this
           * function instead.
           *
           * If `target` reverts with a revert reason, it is bubbled up by this
           * function (like regular Solidity function calls).
           *
           * Returns the raw returned data. To convert to the expected return value,
           * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
           *
           * Requirements:
           *
           * - `target` must be a contract.
           * - calling `target` with `data` must not revert.
           *
           * _Available since v3.1._
           */
          function functionCall(address target, bytes memory data) internal returns (bytes memory) {
              return functionCallWithValue(target, data, 0, "Address: low-level call failed");
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
           * `errorMessage` as a fallback revert reason when `target` reverts.
           *
           * _Available since v3.1._
           */
          function functionCall(
              address target,
              bytes memory data,
              string memory errorMessage
          ) internal returns (bytes memory) {
              return functionCallWithValue(target, data, 0, errorMessage);
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
           * but also transferring `value` wei to `target`.
           *
           * Requirements:
           *
           * - the calling contract must have an ETH balance of at least `value`.
           * - the called Solidity function must be `payable`.
           *
           * _Available since v3.1._
           */
          function functionCallWithValue(
              address target,
              bytes memory data,
              uint256 value
          ) internal returns (bytes memory) {
              return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
          }
          /**
           * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
           * with `errorMessage` as a fallback revert reason when `target` reverts.
           *
           * _Available since v3.1._
           */
          function functionCallWithValue(
              address target,
              bytes memory data,
              uint256 value,
              string memory errorMessage
          ) internal returns (bytes memory) {
              require(address(this).balance >= value, "Address: insufficient balance for call");
              (bool success, bytes memory returndata) = target.call{value: value}(data);
              return verifyCallResultFromTarget(target, success, returndata, errorMessage);
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
           * but performing a static call.
           *
           * _Available since v3.3._
           */
          function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
              return functionStaticCall(target, data, "Address: low-level static call failed");
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
           * but performing a static call.
           *
           * _Available since v3.3._
           */
          function functionStaticCall(
              address target,
              bytes memory data,
              string memory errorMessage
          ) internal view returns (bytes memory) {
              (bool success, bytes memory returndata) = target.staticcall(data);
              return verifyCallResultFromTarget(target, success, returndata, errorMessage);
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
           * but performing a delegate call.
           *
           * _Available since v3.4._
           */
          function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
              return functionDelegateCall(target, data, "Address: low-level delegate call failed");
          }
          /**
           * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
           * but performing a delegate call.
           *
           * _Available since v3.4._
           */
          function functionDelegateCall(
              address target,
              bytes memory data,
              string memory errorMessage
          ) internal returns (bytes memory) {
              (bool success, bytes memory returndata) = target.delegatecall(data);
              return verifyCallResultFromTarget(target, success, returndata, errorMessage);
          }
          /**
           * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
           * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
           *
           * _Available since v4.8._
           */
          function verifyCallResultFromTarget(
              address target,
              bool success,
              bytes memory returndata,
              string memory errorMessage
          ) internal view returns (bytes memory) {
              if (success) {
                  if (returndata.length == 0) {
                      // only check isContract if the call was successful and the return data is empty
                      // otherwise we already know that it was a contract
                      require(isContract(target), "Address: call to non-contract");
                  }
                  return returndata;
              } else {
                  _revert(returndata, errorMessage);
              }
          }
          /**
           * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
           * revert reason or using the provided one.
           *
           * _Available since v4.3._
           */
          function verifyCallResult(
              bool success,
              bytes memory returndata,
              string memory errorMessage
          ) internal pure returns (bytes memory) {
              if (success) {
                  return returndata;
              } else {
                  _revert(returndata, errorMessage);
              }
          }
          function _revert(bytes memory returndata, string memory errorMessage) private pure {
              // Look for revert reason and bubble it up if present
              if (returndata.length > 0) {
                  // The easiest way to bubble the revert reason is using memory via assembly
                  /// @solidity memory-safe-assembly
                  assembly {
                      let returndata_size := mload(returndata)
                      revert(add(32, returndata), returndata_size)
                  }
              } else {
                  revert(errorMessage);
              }
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
      pragma solidity ^0.8.0;
      /**
       * @dev Interface of the ERC165 standard, as defined in the
       * https://eips.ethereum.org/EIPS/eip-165[EIP].
       *
       * Implementers can declare support of contract interfaces, which can then be
       * queried by others ({ERC165Checker}).
       *
       * For an implementation, see {ERC165}.
       */
      interface IERC165 {
          /**
           * @dev Returns true if this contract implements the interface defined by
           * `interfaceId`. See the corresponding
           * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
           * to learn more about how these ids are created.
           *
           * This function call must use less than 30 000 gas.
           */
          function supportsInterface(bytes4 interfaceId) external view returns (bool);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v4.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 v4.4.1 (token/ERC1155/utils/ERC1155Receiver.sol)
      pragma solidity ^0.8.0;
      import "../IERC1155Receiver.sol";
      import "../../../utils/introspection/ERC165.sol";
      /**
       * @dev _Available since v3.1._
       */
      abstract contract ERC1155Receiver is ERC165, IERC1155Receiver {
          /**
           * @dev See {IERC165-supportsInterface}.
           */
          function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
              return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);
          }
      }
      // SPDX-License-Identifier: GPL-3.0-only
      pragma solidity ^0.8.16;
      library StorageAPI {
          function setBytes(bytes32 key, bytes memory data) internal {
              bytes32 slot = keccak256(abi.encodePacked(key));
              assembly {
                  let length := mload(data)
                  switch gt(length, 0x1F)
                  case 0x00 {
                      sstore(key, or(mload(add(data, 0x20)), mul(length, 2)))
                  }
                  case 0x01 {
                      sstore(key, add(mul(length, 2), 1))
                      for {
                          let i := 0
                      } lt(mul(i, 0x20), length) {
                          i := add(i, 0x01)
                      } {
                          sstore(add(slot, i), mload(add(data, mul(add(i, 1), 0x20))))
                      }
                  }
              }
          }
          function setBytes32(bytes32 key, bytes32 val) internal {
              assembly {
                  sstore(key, val)
              }
          }
          function setAddress(bytes32 key, address a) internal {
              assembly {
                  sstore(key, a)
              }
          }
          function setUint256(bytes32 key, uint256 val) internal {
              assembly {
                  sstore(key, val)
              }
          }
          function setInt256(bytes32 key, int256 val) internal {
              assembly {
                  sstore(key, val)
              }
          }
          function setBool(bytes32 key, bool val) internal {
              assembly {
                  sstore(key, val)
              }
          }
          function getBytes(bytes32 key) internal view returns (bytes memory data) {
              bytes32 slot = keccak256(abi.encodePacked(key));
              assembly {
                  let length := sload(key)
                  switch and(length, 0x01)
                  case 0x00 {
                      let decodedLength := div(and(length, 0xFF), 2)
                      mstore(data, decodedLength)
                      mstore(add(data, 0x20), and(length, not(0xFF)))
                      mstore(0x40, add(data, 0x40))
                  }
                  case 0x01 {
                      let decodedLength := div(length, 2)
                      let i := 0
                      mstore(data, decodedLength)
                      for {
                      } lt(mul(i, 0x20), decodedLength) {
                          i := add(i, 0x01)
                      } {
                          mstore(add(add(data, 0x20), mul(i, 0x20)), sload(add(slot, i)))
                      }
                      mstore(0x40, add(data, add(0x20, mul(i, 0x20))))
                  }
              }
          }
          function getBytes32(bytes32 key) internal view returns (bytes32 val) {
              assembly {
                  val := sload(key)
              }
          }
          function getAddress(bytes32 key) internal view returns (address a) {
              assembly {
                  a := sload(key)
              }
          }
          function getUint256(bytes32 key) internal view returns (uint256 val) {
              assembly {
                  val := sload(key)
              }
          }
          function getInt256(bytes32 key) internal view returns (int256 val) {
              assembly {
                  val := sload(key)
              }
          }
          function getBool(bytes32 key) internal view returns (bool val) {
              assembly {
                  val := sload(key)
              }
          }
      }
      // 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: MIT
      // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
      pragma solidity ^0.8.0;
      import "./IERC165.sol";
      /**
       * @dev Implementation of the {IERC165} interface.
       *
       * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
       * for the additional interface id that will be supported. For example:
       *
       * ```solidity
       * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
       *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
       * }
       * ```
       *
       * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
       */
      abstract contract ERC165 is IERC165 {
          /**
           * @dev See {IERC165-supportsInterface}.
           */
          function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
              return interfaceId == type(IERC165).interfaceId;
          }
      }
      

      File 4 of 4: EnsoShortcutsHelpers
      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.16;
      /**
       * @dev SignedMathHelpers contract is recommended to use only in Shortcuts passed to EnsoWallet.
       *
       * This contract functions allow to dynamically get the data during Shortcut transaction execution
       * that usually would be read between transactions
       */
      contract EnsoShortcutsHelpers {
          uint256 public constant VERSION = 3;
          /**
           * @dev Returns the ether balance of given `balanceAddress`.
           */
          function getBalance(address balanceAddress) external view returns (uint256 balance) {
              return address(balanceAddress).balance;
          }
          /**
           * @dev Returns the current block timestamp.
           */
          function getBlockTimestamp() external view returns (uint256 timestamp) {
              return block.timestamp;
          }
          /**
           * @dev Reverts depending on a truth condition
           */
          function check(bool condition) external pure {
              if (!condition) revert("Condition not met");
          }
          /**
           * @dev Returns a value depending on a truth condition
           */
          function toggle(bool condition, uint256 a, uint256 b) external pure returns (uint256) {
              if (condition) {
                  return a;
              } else {
                  return b;
              }
          }
          /**
           * @dev Returns the inverse bool
           */
          function not(bool condition) external pure returns (bool) {
              return !condition;
          }
          /**
           * @dev Returns bool for a == b
           */
          function isEqual(uint256 a, uint256 b) external pure returns (bool) {
              return a == b;
          }
          /**
           * @dev Returns bool for a < b
           */
          function isLessThan(uint256 a, uint256 b) external pure returns (bool) {
              return a < b;
          }
          /**
           * @dev Returns bool for a <= b
           */
          function isEqualOrLessThan(uint256 a, uint256 b) external pure returns (bool) {
              return a <= b;
          }
          /**
           * @dev Returns bool for a > b
           */
          function isGreaterThan(uint256 a, uint256 b) external pure returns (bool) {
              return a > b;
          }
          /**
           * @dev Returns bool for a >= b
           */
          function isEqualOrGreaterThan(uint256 a, uint256 b) external pure returns (bool) {
              return a >= b;
          }
          /**
           * @dev Returns bool for a == b
           */
          function isAddressEqual(address a, address b) external pure returns (bool) {
              return a == b;
          }
          /**
           * @dev Returns `input` bytes as string.
           */
          function bytesToString(bytes calldata input) external pure returns (string memory) {
              return string(abi.encodePacked(input));
          }
          /**
           * @dev Returns `input` bytes as uint256.
           */
          function bytesToUint256(bytes calldata input) external pure returns (uint256) {
              require(input.length == 32, "EnsoShortcutsHelpers: input length is not 32 bytes");
              return uint256(bytes32(input));
          }
          /**
           * @dev Returns `input` bytes as bytes32.
           */
          function bytesToBytes32(bytes calldata input) external pure returns (bytes32) {
              return bytes32(input);
          }
          /**
           * @dev Returns `input` bytes32 as uint256.
           */
          function bytes32ToUint256(bytes32 input) external pure returns (uint256) {
              return uint256(input);
          }
          /**
           * @dev Returns `input` bytes32 as address.
           */
          function bytes32ToAddress(bytes32 input) external pure returns (address) {
              return address(uint160(uint256(input)));
          }
          /**
           * @dev Returns uint256 `value` as int256.
           */
          function uint256ToInt256(uint256 value) public pure returns (int256) {
              require(value <= uint256(type(int256).max), "Value does not fit in an int256");
              return int256(value);
          }
          /**
           * @dev Returns int256 `value` as uint256.
           */
          function int256ToUint256(int256 value) public pure returns (uint256) {
              require(value >= 0, "Value must be positive");
              return uint256(value);
          }
      }