Skip to content
Verified contractExactMIT

TokenPortal

Address0xaa3091862373b4ae9cd25ffc94defa4bbc5f59a6
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.27

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.27+commit.40a35a09
Language
solidity
Optimization
Yes, 200 runs
EVM version
prague
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,335,553
Creation transaction
0x0401364c75…2223a878b7

29 files

src/TokenPortal.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.27;

import {IERC20} from '@oz/token/ERC20/IERC20.sol';
import {SafeERC20} from '@oz/token/ERC20/utils/SafeERC20.sol';
import {Initializable} from '@oz/proxy/utils/Initializable.sol';
import {UUPSUpgradeable} from '@oz/proxy/utils/UUPSUpgradeable.sol';
import {Pausable} from '@oz/utils/Pausable.sol';
import {ReentrancyGuardTransient} from '@oz/utils/ReentrancyGuardTransient.sol';

// Messaging
import {IRegistry} from './IRegistry.sol';
import {IInbox} from './IInbox.sol';
import {IOutbox} from './IOutbox.sol';
import {IRollup} from './IRollup.sol';
import {DataStructures} from './DataStructures.sol';
import {Hash} from './Hash.sol';

// Compliance
import {ZKPassportWhitelist} from './ZKPassportWhitelist.sol';

/**
 * @title TokenPortal
 * @notice L1 Portal contract for bridging ERC20 tokens between Ethereum and Aztec L2
 * @dev This contract is upgradeable via UUPS pattern. Only the owner can perform upgrades.
 * @dev The contract can be paused by the owner in case of emergency.
 */
contract TokenPortal is
  Initializable,
  UUPSUpgradeable,
  Pausable,
  ReentrancyGuardTransient
{
  using SafeERC20 for IERC20;

  /// @notice Thrown when attempting to call an owner-only function
  error TokenPortal__Unauthorized();

  /// @notice Thrown when attempting to initialize with an invalid (zero) address
  error TokenPortal__InvalidAddress();

  /// @notice Thrown when attempting to deposit zero amount
  error TokenPortal__InvalidAmount();

  /// @notice Thrown when attempting to withdraw to the zero address
  error TokenPortal__InvalidRecipient();

  /// @notice Thrown when L2 bridge address is not set
  error TokenPortal__L2BridgeNotSet();

  /// @notice Thrown when the Aztec registry returns an invalid rollup address
  error TokenPortal__InvalidRollupAddress();

  /// @notice Thrown when user is not whitelisted
  error TokenPortal__NotWhitelisted();

  /// @notice Thrown when caller is not a trusted forwarder
  error TokenPortal__NotTrustedForwarder();

  /// @notice Thrown when a timelocked operation has not been scheduled, was
  ///         scheduled with different parameters, or its delay has not elapsed
  error TokenPortal__TimelockNotSatisfied();

  /// @notice Thrown when a single deposit exceeds maxPerTx (when set)
  error TokenPortal__ExceedsMaxPerTx();

  /// @notice Thrown when a deposit would push the depositor's cumulative total past maxPerUser (when set)
  error TokenPortal__ExceedsUserLimit();

  /// @notice Thrown when a deposit would push the portal's outstanding bridged
  ///         total past maxTotalBridged (when set)
  error TokenPortal__ExceedsGlobalCap();

  /// @notice Thrown when a depositing or receiving address has been blocked by the owner
  error TokenPortal__AddressBlocked();

  // ============ Events ============

  /**
   * @notice Emitted when tokens are deposited for public consumption on Aztec
   * @param sender The L1 address that initiated the deposit
   * @param to The Aztec address of the recipient
   * @param amount The amount of tokens deposited
   * @param secretHash The hash of the secret for L2 message consumption
   * @param key The key of the entry in the Inbox
   * @param index The leaf index in the L1-to-L2 message tree
   */
  event DepositToAztecPublic(
    address indexed sender,
    bytes32 indexed to,
    uint256 amount,
    bytes32 secretHash,
    bytes32 key,
    uint256 index
  );

  /**
   * @notice Emitted when tokens are deposited for private consumption on Aztec
   * @param sender The L1 address that initiated the deposit
   * @param amount The amount of tokens deposited
   * @param secretHash The hash of the secret for L2 message consumption
   * @param key The key of the entry in the Inbox
   * @param index The leaf index in the L1-to-L2 message tree
   */
  event DepositToAztecPrivate(
    address indexed sender,
    uint256 amount,
    bytes32 secretHash,
    bytes32 key,
    uint256 index
  );

  /**
   * @notice Emitted when tokens are withdrawn from the portal
   * @param recipient The L1 address that received the tokens
   * @param amount The amount of tokens withdrawn
   * @param designatedCaller The address that was allowed to call withdraw (address(0) if anyone)
   */
  event Withdraw(
    address indexed recipient,
    uint256 amount,
    address indexed designatedCaller
  );

  /**
   * @notice Emitted when the L2 bridge address is updated
   * @param oldL2Bridge The previous L2 bridge address
   * @param newL2Bridge The new L2 bridge address
   */
  event L2BridgeUpdated(
    bytes32 indexed oldL2Bridge,
    bytes32 indexed newL2Bridge
  );

  /**
   * @notice Emitted when ownership is transferred
   * @param previousOwner The previous owner address
   * @param newOwner The new owner address
   */
  event OwnershipTransferred(
    address indexed previousOwner,
    address indexed newOwner
  );

  /**
   * @notice Emitted when ownership transfer is initiated
   * @param previousOwner The current owner address
   * @param newOwner The pending new owner address
   */
  event OwnershipTransferStarted(
    address indexed previousOwner,
    address indexed newOwner
  );

  /**
   * @notice Emitted when the whitelist contract is updated
   * @param oldWhitelist The previous whitelist address
   * @param newWhitelist The new whitelist address
   */
  event WhitelistUpdated(
    address indexed oldWhitelist,
    address indexed newWhitelist
  );

  /**
   * @notice Emitted when a trusted forwarder status is updated
   * @param forwarder The forwarder address
   * @param trusted Whether the forwarder is now trusted
   */
  event TrustedForwarderUpdated(
    address indexed forwarder,
    bool trusted
  );

  /**
   * @notice Emitted when the guardian is updated
   * @param previousGuardian The previous guardian address
   * @param newGuardian The new guardian address (address(0) removes the guardian)
   */
  event GuardianUpdated(
    address indexed previousGuardian,
    address indexed newGuardian
  );

  /**
   * @notice Emitted when a timelocked operation is scheduled
   * @param operationType The type of operation scheduled
   * @param param The operation parameter (new implementation, L2 bridge or whitelist)
   * @param executableAt The timestamp at which the operation can be executed
   */
  event OperationScheduled(
    uint8 indexed operationType,
    bytes32 param,
    uint256 executableAt
  );

  /**
   * @notice Emitted when the bridging limits are set (0 = limit disabled)
   * @param maxPerTx Maximum amount per single deposit
   * @param maxPerUser Maximum cumulative amount deposited per L1 address
   * @param maxTotalBridged Maximum outstanding bridged total held by the portal
   */
  event LimitsUpdated(
    uint256 maxPerTx,
    uint256 maxPerUser,
    uint256 maxTotalBridged
  );

  /**
   * @notice Emitted when the owner overwrites a user's cumulative deposit counter
   * @param user The L1 address whose counter was adjusted
   * @param newDeposited The new cumulative deposited value
   */
  event UserDepositedUpdated(
    address indexed user,
    uint256 newDeposited
  );

  /**
   * @notice Emitted when an address is blocked or unblocked
   * @param account The address being blocked or unblocked
   * @param blocked True if the address is now blocked
   */
  event AddressBlockedSet(address indexed account, bool blocked);

  address private _contractOwner;
  address private _pendingOwner;
  IRegistry public registry;
  /// @notice The underlying ERC20 token being bridged
  IERC20 public underlying;
  bytes32 public l2Bridge;
  /// @notice The Aztec rollup contract
  IRollup public rollup;

  /// @notice The Aztec outbox contract for receiving L2->L1 messages
  IOutbox public outbox;

  /// @notice The Aztec inbox contract for sending L1->L2 messages
  IInbox public inbox;

  /// @notice The current rollup version
  uint256 public rollupVersion;

  /// @notice The ZK Passport whitelist contract for compliance checks
  ZKPassportWhitelist public whitelist;

  /// @notice Trusted forwarders that can call depositFor functions
  mapping(address => bool) public trustedForwarders;

  /// @notice Emergency guardian that can pause the portal (address(0) = no guardian).
  ///         Intended to be a fast-reacting key (e.g. an EOA or small multisig) distinct
  ///         from the owner, which should be a timelocked multisig.
  address public guardian;

  /// @notice Timelock delay that must elapse between scheduling and executing a
  ///         sensitive operation (upgrades, L2 bridge and whitelist changes).
  ///         A compile-time constant: this 8h value only applies once THIS
  ///         implementation is live — an upgrade out of an older deployment is
  ///         still governed by that deployment's own delay.
  uint256 public constant TIMELOCK_DELAY = 8 hours;

  /// @notice The operations that require scheduling before they can be executed
  enum OperationType {
    Upgrade,
    L2BridgeUpdate,
    WhitelistUpdate
  }

  /// @notice A scheduled timelocked operation
  struct ScheduledOperation {
    /// @notice The parameter the operation was scheduled with (implementation, L2 bridge or whitelist address)
    bytes32 param;
    /// @notice The timestamp at which the operation becomes executable (0 = nothing scheduled)
    uint64 executableAt;
  }

  /// @notice Scheduled operations by type. Rescheduling a type replaces (and thereby
  ///         cancels) any previously scheduled parameters for that type.
  mapping(uint8 => ScheduledOperation) private _scheduled;

  // ============ Bridging policy (added v1.2.0, occupies former gap slots) ============

  /// @notice Maximum amount a single deposit may bridge. 0 = no per-tx limit.
  uint256 public maxPerTx;

  /// @notice Maximum cumulative amount an L1 address may deposit. 0 = no per-user limit.
  uint256 public maxPerUser;

  /// @notice Maximum outstanding bridged total (deposits minus withdrawals) the
  ///         portal may hold. 0 = no global cap.
  uint256 public maxTotalBridged;

  /// @notice Cumulative amount deposited into the portal (what actually arrived)
  uint256 public totalDeposited;

  /// @notice Cumulative amount withdrawn out of the portal
  uint256 public totalWithdrawn;

  /// @notice Cumulative deposits per L1 address, checked against maxPerUser
  mapping(address => uint256) public userDeposited;

  /// @notice Addresses blocked from depositing and from receiving withdrawals
  mapping(address => bool) public blocked;

  /// @notice Gap for future storage variables (upgradeable pattern)
  uint256[37] private __gap;

  /**
   * @notice Ensures the caller is the owner
   */
  modifier onlyOwner() {
    _checkOwner();
    _;
  }

  /**
   * @notice Ensures the L2 bridge address is set before allowing operations
   */
  modifier whenL2BridgeSet() {
    _checkL2BridgeSet();
    _;
  }

  modifier onlyWhitelisted() {
    _checkWhitelisted(msg.sender);
    _;
  }

  modifier onlyTrustedForwarder() {
    if (!trustedForwarders[msg.sender]) {
      revert TokenPortal__NotTrustedForwarder();
    }
    _;
  }

  function _checkWhitelisted(address _depositor) internal view {
    if (address(whitelist) != address(0)) {
      if (!whitelist.checkWhitelisted(_depositor)) {
        revert TokenPortal__NotWhitelisted();
      }
    }
  }

  /**
   * @notice Revert if the address has been blocked by the owner
   */
  function _checkNotBlocked(address _account) internal view {
    if (blocked[_account]) {
      revert TokenPortal__AddressBlocked();
    }
  }

  /**
   * @notice Enforce the bridging limits for a deposit of `_received` tokens by
   *         `_depositor` and update the counters. Called after the tokens have
   *         been pulled so the checks use the amount actually received; a revert
   *         here rolls the transfer back.
   * @dev A limit value of 0 disables that particular limit.
   */
  function _checkAndUpdateDepositCounters(
    address _depositor,
    uint256 _received
  ) internal {
    if (maxPerTx != 0 && _received > maxPerTx) {
      revert TokenPortal__ExceedsMaxPerTx();
    }
    if (maxPerUser != 0 && userDeposited[_depositor] + _received > maxPerUser) {
      revert TokenPortal__ExceedsUserLimit();
    }
    if (maxTotalBridged != 0 && getNetBridged() + _received > maxTotalBridged) {
      revert TokenPortal__ExceedsGlobalCap();
    }

    userDeposited[_depositor] += _received;
    totalDeposited += _received;
  }

  /**
   * @notice Disables initializers for the implementation contract
   * @dev This prevents the implementation contract from being initialized directly
   */
  constructor() {
    _disableInitializers();
  }

  /**
   * @notice Initialize the portal contract
   * @dev Can only be called once due to Initializable pattern
   * @param owner_ The owner of the contract (should be a multi-sig or timelock)
   * @param _registry The Aztec registry address
   * @param _underlying The underlying ERC20 token address
   * @param _l2Bridge The L2 bridge address on Aztec
   */
  function initialize(
    address owner_,
    address _registry,
    address _underlying,
    bytes32 _l2Bridge
  ) external initializer {
    // Validate inputs
    if (owner_ == address(0)) revert TokenPortal__InvalidAddress();
    if (_registry == address(0)) revert TokenPortal__InvalidAddress();
    if (_underlying == address(0)) revert TokenPortal__InvalidAddress();
    if (_l2Bridge == bytes32(0)) revert TokenPortal__InvalidAddress();

    // Set owner
    _contractOwner = owner_;
    emit OwnershipTransferred(address(0), owner_);

    // Set state variables
    registry = IRegistry(_registry);
    underlying = IERC20(_underlying);
    l2Bridge = _l2Bridge;

    // Fetch rollup-related contracts from registry
    _refreshRollupConnections();
  }
  /**
   * @notice Deposit funds into the portal and adds an L2 message which can only be consumed publicly on Aztec
   * @dev The minted amount on L2 equals the token amount actually received by the portal, so
   *      fee-on-transfer tokens cannot break the 1:1 backing of the L2 wrapped asset.
   * @param _to The Aztec address of the recipient
   * @param _amount The amount to deposit
   * @param _secretHash The hash of the secret consumable message (should be 254 bits)
   * @return key The key of the entry in the Inbox
   * @return index The leaf index in the L1-to-L2 message tree
   */
  function depositToAztecPublic(
    bytes32 _to,
    uint256 _amount,
    bytes32 _secretHash
  )
    external
    whenNotPaused
    whenL2BridgeSet
    onlyWhitelisted
    nonReentrant
    returns (bytes32 key, uint256 index)
  {
    // Validate inputs
    if (_to == bytes32(0)) revert TokenPortal__InvalidAddress();
    if (_amount == 0) revert TokenPortal__InvalidAmount();
    // L2 amounts are u128; larger deposits could never be claimed on L2
    if (_amount > type(uint128).max) revert TokenPortal__InvalidAmount();

    // Bridging policy
    _checkNotBlocked(msg.sender);

    // Preamble
    DataStructures.L2Actor memory actor = DataStructures.L2Actor(
      l2Bridge,
      rollupVersion
    );

    // Hold the tokens in the portal and measure what actually arrived so that
    // fee-on-transfer tokens cannot over-mint the L2 wrapped asset
    uint256 received = _pullAndMeasure(msg.sender, _amount);
    _checkAndUpdateDepositCounters(msg.sender, received);

    // Hash the message content to be reconstructed in the receiving contract
    bytes32 contentHash = Hash.sha256ToField(
      abi.encodeWithSignature('mint_to_public(bytes32,uint256)', _to, received)
    );

    // Send message to rollup
    (key, index) = inbox.sendL2Message(actor, contentHash, _secretHash);

    // Emit event
    emit DepositToAztecPublic(
      msg.sender,
      _to,
      received,
      _secretHash,
      key,
      index
    );

    return (key, index);
  }

  /**
   * @notice Deposit funds into the portal and adds an L2 message which can only be consumed privately on Aztec
   * @dev The minted amount on L2 equals the token amount actually received by the portal, so
   *      fee-on-transfer tokens cannot break the 1:1 backing of the L2 wrapped asset.
   * @param _amount The amount to deposit
   * @param _secretHashForL2MessageConsumption The hash of the secret consumable L1 to L2 message (should be 254 bits)
   * @return key The key of the entry in the Inbox
   * @return index The leaf index in the L1-to-L2 message tree
   */
  function depositToAztecPrivate(
    uint256 _amount,
    bytes32 _secretHashForL2MessageConsumption
  )
    external
    whenNotPaused
    whenL2BridgeSet
    onlyWhitelisted
    nonReentrant
    returns (bytes32 key, uint256 index)
  {
    // Validate inputs
    if (_amount == 0) revert TokenPortal__InvalidAmount();
    // L2 amounts are u128; larger deposits could never be claimed on L2
    if (_amount > type(uint128).max) revert TokenPortal__InvalidAmount();

    // Bridging policy
    _checkNotBlocked(msg.sender);

    // Preamble
    DataStructures.L2Actor memory actor = DataStructures.L2Actor(
      l2Bridge,
      rollupVersion
    );

    // Hold the tokens in the portal and measure what actually arrived so that
    // fee-on-transfer tokens cannot over-mint the L2 wrapped asset
    uint256 received = _pullAndMeasure(msg.sender, _amount);
    _checkAndUpdateDepositCounters(msg.sender, received);

    // Hash the message content to be reconstructed in the receiving contract
    bytes32 contentHash = Hash.sha256ToField(
      abi.encodeWithSignature('mint_to_private(uint256)', received)
    );

    // Send message to rollup
    (key, index) = inbox.sendL2Message(
      actor,
      contentHash,
      _secretHashForL2MessageConsumption
    );

    // Emit event
    emit DepositToAztecPrivate(
      msg.sender,
      received,
      _secretHashForL2MessageConsumption,
      key,
      index
    );

    return (key, index);
  }

  /**
   * @notice Deposit funds on behalf of a depositor for public consumption on Aztec
   * @dev Only callable by trusted forwarders. Whitelist check is on _depositor.
   *      The minted amount on L2 equals the token amount actually received by the portal, so
   *      fee-on-transfer tokens cannot break the 1:1 backing of the L2 wrapped asset.
   * @param _depositor The original depositor address (for whitelist check and event)
   * @param _to The Aztec address of the recipient
   * @param _amount The amount to deposit
   * @param _secretHash The hash of the secret consumable message
   * @return key The key of the entry in the Inbox
   * @return index The leaf index in the L1-to-L2 message tree
   */
  function depositToAztecPublicFor(
    address _depositor,
    bytes32 _to,
    uint256 _amount,
    bytes32 _secretHash
  )
    external
    whenNotPaused
    whenL2BridgeSet
    onlyTrustedForwarder
    nonReentrant
    returns (bytes32 key, uint256 index)
  {
    // Validate inputs
    if (_to == bytes32(0)) revert TokenPortal__InvalidAddress();
    if (_amount == 0) revert TokenPortal__InvalidAmount();
    // L2 amounts are u128; larger deposits could never be claimed on L2
    if (_amount > type(uint128).max) revert TokenPortal__InvalidAmount();

    // Check whitelist on the depositor, not msg.sender
    _checkWhitelisted(_depositor);

    // Bridging policy
    _checkNotBlocked(_depositor);

    // Preamble
    DataStructures.L2Actor memory actor = DataStructures.L2Actor(
      l2Bridge,
      rollupVersion
    );

    // Pull tokens from the trusted forwarder (which already has them) and
    // measure what actually arrived so fee-on-transfer tokens cannot over-mint
    uint256 received = _pullAndMeasure(msg.sender, _amount);
    _checkAndUpdateDepositCounters(_depositor, received);

    // Hash the message content to be reconstructed in the receiving contract
    bytes32 contentHash = Hash.sha256ToField(
      abi.encodeWithSignature('mint_to_public(bytes32,uint256)', _to, received)
    );

    // Send message to rollup
    (key, index) = inbox.sendL2Message(actor, contentHash, _secretHash);

    // Emit event with depositor as sender
    emit DepositToAztecPublic(
      _depositor,
      _to,
      received,
      _secretHash,
      key,
      index
    );

    return (key, index);
  }

  /**
   * @notice Deposit funds on behalf of a depositor for private consumption on Aztec
   * @dev Only callable by trusted forwarders. Whitelist check is on _depositor.
   *      The minted amount on L2 equals the token amount actually received by the portal, so
   *      fee-on-transfer tokens cannot break the 1:1 backing of the L2 wrapped asset.
   * @param _depositor The original depositor address (for whitelist check and event)
   * @param _amount The amount to deposit
   * @param _secretHashForL2MessageConsumption The hash of the secret consumable L1 to L2 message
   * @return key The key of the entry in the Inbox
   * @return index The leaf index in the L1-to-L2 message tree
   */
  function depositToAztecPrivateFor(
    address _depositor,
    uint256 _amount,
    bytes32 _secretHashForL2MessageConsumption
  )
    external
    whenNotPaused
    whenL2BridgeSet
    onlyTrustedForwarder
    nonReentrant
    returns (bytes32 key, uint256 index)
  {
    // Validate inputs
    if (_amount == 0) revert TokenPortal__InvalidAmount();
    // L2 amounts are u128; larger deposits could never be claimed on L2
    if (_amount > type(uint128).max) revert TokenPortal__InvalidAmount();

    // Check whitelist on the depositor
    _checkWhitelisted(_depositor);

    // Bridging policy
    _checkNotBlocked(_depositor);

    // Preamble
    DataStructures.L2Actor memory actor = DataStructures.L2Actor(
      l2Bridge,
      rollupVersion
    );

    // Pull tokens from the trusted forwarder and measure what actually arrived
    // so that fee-on-transfer tokens cannot over-mint
    uint256 received = _pullAndMeasure(msg.sender, _amount);
    _checkAndUpdateDepositCounters(_depositor, received);

    // Hash the message content to be reconstructed in the receiving contract
    bytes32 contentHash = Hash.sha256ToField(
      abi.encodeWithSignature('mint_to_private(uint256)', received)
    );

    // Send message to rollup
    (key, index) = inbox.sendL2Message(
      actor,
      contentHash,
      _secretHashForL2MessageConsumption
    );

    // Emit event with depositor as sender
    emit DepositToAztecPrivate(
      _depositor,
      received,
      _secretHashForL2MessageConsumption,
      key,
      index
    );

    return (key, index);
  }

  /**
   * @notice Withdraw funds from the portal
   * @dev Second part of withdraw, must be initiated from L2 first as it will consume a message from outbox
   * @param _recipient The address to send the funds to
   * @param _amount The amount to withdraw
   * @param _withCaller Flag to use `msg.sender` as caller, otherwise address(0)
   * @param _epoch The epoch containing the message to consume
   * @param _numCheckpointsInEpoch The number of checkpoints of the epoch covered by the
   *        partial-proof root the message is proven against; the outbox reads the root
   *        stored at this depth
   * @param _leafIndex The leaf index in the outbox tree
   * @param _path The sibling path used to prove inclusion of the message
   */
  function withdraw(
    address _recipient,
    uint256 _amount,
    bool _withCaller,
    uint256 _epoch,
    uint256 _numCheckpointsInEpoch,
    uint256 _leafIndex,
    bytes32[] calldata _path
  ) external whenNotPaused whenL2BridgeSet nonReentrant {
    // Validate inputs
    if (_recipient == address(0)) revert TokenPortal__InvalidRecipient();
    if (_amount == 0) revert TokenPortal__InvalidAmount();

    // Bridging policy: blocking a recipient holds their pending exit in the
    // portal until they are unblocked (the outbox message stays unconsumed)
    _checkNotBlocked(_recipient);

    // The purpose of including the function selector is to make the message unique to that specific call
    DataStructures.L2ToL1Msg memory message = DataStructures.L2ToL1Msg({
      sender: DataStructures.L2Actor(l2Bridge, rollupVersion),
      recipient: DataStructures.L1Actor(address(this), block.chainid),
      content: Hash.sha256ToField(
        abi.encodeWithSignature(
          'withdraw(address,uint256,address)',
          _recipient,
          _amount,
          _withCaller ? msg.sender : address(0)
        )
      )
    });

    outbox.consume(message, _epoch, _numCheckpointsInEpoch, _leafIndex, _path);

    // Transfer tokens to recipient
    underlying.safeTransfer(_recipient, _amount);
    totalWithdrawn += _amount;

    emit Withdraw(_recipient, _amount, _withCaller ? msg.sender : address(0));
  }

  // ============ Owner Functions ============

  /**
   * @notice Returns the address of the current owner
   */
  function owner() public view returns (address) {
    return _contractOwner;
  }

  /**
   * @notice Returns the address of the pending owner
   */
  function pendingOwner() public view returns (address) {
    return _pendingOwner;
  }

  /**
   * @notice Starts the ownership transfer of the contract to a new account
   * @dev Replaces the pending transfer if there is one. Can only be called by the current owner.
   * @param newOwner The address of the new owner
   */
  function transferOwnership(address newOwner) external onlyOwner {
    if (newOwner == address(0)) revert TokenPortal__InvalidAddress();
    _pendingOwner = newOwner;
    emit OwnershipTransferStarted(_contractOwner, newOwner);
  }

  /**
   * @notice Transfers ownership of the contract to the pending owner
   * @dev Can only be called by the pending owner
   */
  function acceptOwnership() external {
    if (msg.sender != _pendingOwner) {
      revert TokenPortal__Unauthorized();
    }
    address oldOwner = _contractOwner;
    _contractOwner = _pendingOwner;
    delete _pendingOwner;
    emit OwnershipTransferred(oldOwner, _contractOwner);
  }

  /**
   * @notice Renounces ownership of the contract
   * @dev Leaves the contract without an owner. Can only be called by the current owner.
   */
  function renounceOwnership() external onlyOwner {
    address oldOwner = _contractOwner;
    _contractOwner = address(0);
    delete _pendingOwner;
    emit OwnershipTransferred(oldOwner, address(0));
  }

  // ============ Admin Functions ============

  /**
   * @notice Pause the contract, preventing deposits and withdrawals
   * @dev Callable by the owner OR the guardian. Pausing is intentionally kept out of
   *      the timelock so it can be used for fast incident response.
   */
  function pause() external {
    if (msg.sender != _contractOwner && msg.sender != guardian) {
      revert TokenPortal__Unauthorized();
    }
    _pause();
  }

  /**
   * @notice Unpause the contract, allowing deposits and withdrawals
   * @dev Only callable by the owner
   */
  function unpause() external onlyOwner {
    _unpause();
  }

  /**
   * @notice Update the L2 bridge address
   * @dev Only callable by the owner after the change has been scheduled and the
   *      timelock delay has elapsed. Use with caution as this affects message routing;
   *      ensure no L2->L1 withdrawals are pending before executing.
   * @param _newL2Bridge The new L2 bridge address
   */
  function updateL2Bridge(bytes32 _newL2Bridge) external onlyOwner {
    if (_newL2Bridge == bytes32(0)) revert TokenPortal__InvalidAddress();

    _checkTimelock(uint8(OperationType.L2BridgeUpdate), _newL2Bridge);
    _consumeTimelock(uint8(OperationType.L2BridgeUpdate));

    bytes32 oldL2Bridge = l2Bridge;
    l2Bridge = _newL2Bridge;

    emit L2BridgeUpdated(oldL2Bridge, _newL2Bridge);
  }

  /**
   * @notice Refresh the rollup connections from the registry
   * @dev Call this if the Aztec registry has been updated with a new rollup
   * @dev Only callable by the owner. Kept outside the timelock because it is the
   *      recovery path when the rollup version changes and pending withdrawals
   *      reference the old version. Operational rule: prefer draining all pending
   *      L2->L1 withdrawals before refreshing, since messages pinned to the old
   *      rollupVersion can no longer be consumed afterwards.
   */
  function refreshRollupConnections() external onlyOwner {
    _refreshRollupConnections();
  }

  /**
   * @notice Update the whitelist contract address
   * @dev Only callable by the owner after the change has been scheduled and the
   *      timelock delay has elapsed. Set to address(0) to disable whitelist checking.
   * @param _newWhitelist The new whitelist contract address
   */
  function updateWhitelist(address _newWhitelist) external onlyOwner {
    _checkTimelock(
      uint8(OperationType.WhitelistUpdate),
      bytes32(uint256(uint160(_newWhitelist)))
    );
    _consumeTimelock(uint8(OperationType.WhitelistUpdate));

    address oldWhitelist = address(whitelist);
    whitelist = ZKPassportWhitelist(_newWhitelist);

    emit WhitelistUpdated(oldWhitelist, _newWhitelist);
  }

  /**
   * @notice Set or remove the emergency guardian
   * @dev Only callable by the owner. Set to address(0) to remove the guardian.
   * @param _newGuardian The new guardian address
   */
  function setGuardian(address _newGuardian) external onlyOwner {
    address oldGuardian = guardian;
    guardian = _newGuardian;

    emit GuardianUpdated(oldGuardian, _newGuardian);
  }

  /**
   * @notice Set or remove a trusted forwarder
   * @dev Only callable by the owner. Trusted forwarders can call depositFor functions.
   * @param _forwarder The forwarder address
   * @param _trusted Whether to trust or untrust the forwarder
   */
  function setTrustedForwarder(
    address _forwarder,
    bool _trusted
  ) external onlyOwner {
    if (_forwarder == address(0)) revert TokenPortal__InvalidAddress();
    trustedForwarders[_forwarder] = _trusted;
    emit TrustedForwarderUpdated(_forwarder, _trusted);
  }

  /**
   * @notice Set the bridging limits
   * @dev Only callable by the owner. A value of 0 disables that limit. These are
   *      risk parameters, not code changes, so they are intentionally kept out
   *      of the timelock (like pause). Tightening limits takes effect
   *      immediately; raising them is announced via LimitsUpdated.
   * @param _maxPerTx Maximum amount per single deposit (0 = no limit)
   * @param _maxPerUser Maximum cumulative deposits per L1 address (0 = no limit)
   * @param _maxTotalBridged Maximum outstanding bridged total (0 = no cap)
   */
  function setLimits(
    uint256 _maxPerTx,
    uint256 _maxPerUser,
    uint256 _maxTotalBridged
  ) external onlyOwner {
    maxPerTx = _maxPerTx;
    maxPerUser = _maxPerUser;
    maxTotalBridged = _maxTotalBridged;

    emit LimitsUpdated(_maxPerTx, _maxPerUser, _maxTotalBridged);
  }

  /**
   * @notice Overwrite a user's cumulative deposit counter
   * @dev Only callable by the owner. Escape hatch so a user who legitimately hit
   *      maxPerUser can be manually cleared without touching everyone else.
   * @param _user The L1 address whose counter to overwrite
   * @param _newDeposited The new cumulative deposited value
   */
  function setUserDeposited(
    address _user,
    uint256 _newDeposited
  ) external onlyOwner {
    userDeposited[_user] = _newDeposited;

    emit UserDepositedUpdated(_user, _newDeposited);
  }

  /**
   * @notice Block or unblock addresses from depositing and from receiving withdrawals
   * @dev Only callable by the owner. Blocking a withdrawal recipient holds their
   *      pending L2 exit in the portal until they are unblocked.
   * @param _accounts The addresses to update
   * @param _blocked True to block, false to unblock
   */
  function setBlocked(
    address[] calldata _accounts,
    bool _blocked
  ) external onlyOwner {
    for (uint256 i = 0; i < _accounts.length; i++) {
      if (_accounts[i] == address(0)) revert TokenPortal__InvalidAddress();

      blocked[_accounts[i]] = _blocked;

      emit AddressBlockedSet(_accounts[i], _blocked);
    }
  }

  /**
   * @notice Rescue ERC20 tokens accidentally sent to the contract
   * @dev Only callable by the owner. Cannot rescue the underlying bridge token.
   * @param _token The token to rescue
   * @param _to The address to send the tokens to
   * @param _amount The amount to rescue
   */
  function rescueTokens(
    address _token,
    address _to,
    uint256 _amount
  ) external onlyOwner {
    if (_token == address(0)) revert TokenPortal__InvalidAddress();
    if (_to == address(0)) revert TokenPortal__InvalidAddress();
    if (_amount == 0) revert TokenPortal__InvalidAmount();
    if (_token == address(underlying)) revert TokenPortal__InvalidAddress();

    IERC20(_token).safeTransfer(_to, _amount);
  }

  // ============ Timelock Functions ============

  /**
   * @notice Schedule a sensitive operation so it can be executed after TIMELOCK_DELAY
   * @dev Only callable by the owner. Rescheduling an operation type replaces (and thereby
   *      cancels) any previously scheduled parameters for that type.
   * @param _operationType The type of operation to schedule
   * @param _param The parameter the operation will be executed with
   */
  function scheduleOperation(
    uint8 _operationType,
    bytes32 _param
  ) external onlyOwner {
    if (_operationType > uint8(OperationType.WhitelistUpdate)) {
      revert TokenPortal__InvalidAddress();
    }

    _scheduled[_operationType] = ScheduledOperation({
      param: _param,
      executableAt: uint64(block.timestamp) + uint64(TIMELOCK_DELAY)
    });

    emit OperationScheduled(
      _operationType,
      _param,
      block.timestamp + TIMELOCK_DELAY
    );
  }

  /**
   * @notice Check whether a scheduled operation can be executed
   * @param _operationType The type of operation
   * @return True if the operation is scheduled with the given parameter and its delay has elapsed
   */
  function isOperationReady(
    uint8 _operationType,
    bytes32 _param
  ) external view returns (bool) {
    ScheduledOperation memory op = _scheduled[_operationType];
    return
      op.executableAt != 0 &&
      op.param == _param &&
      block.timestamp >= op.executableAt;
  }

  /**
   * @notice Pull `_amount` of the underlying from `_from` and return the amount
   *         actually received by the portal, so fee-on-transfer tokens cannot
   *         over-mint the L2 wrapped asset.
   */
  function _pullAndMeasure(
    address _from,
    uint256 _amount
  ) internal returns (uint256) {
    uint256 balanceBefore = underlying.balanceOf(address(this));
    underlying.safeTransferFrom(_from, address(this), _amount);
    uint256 received = underlying.balanceOf(address(this)) - balanceBefore;
    if (received == 0) revert TokenPortal__InvalidAmount();
    return received;
  }

  /**
   * @notice Revert unless the operation was scheduled with these parameters and its delay has elapsed
   */
  function _checkTimelock(uint8 _operationType, bytes32 _param) internal view {
    ScheduledOperation memory op = _scheduled[_operationType];
    if (
      op.executableAt == 0 ||
      op.param != _param ||
      block.timestamp < op.executableAt
    ) {
      revert TokenPortal__TimelockNotSatisfied();
    }
  }

  /**
   * @notice Consume a scheduled operation after successful execution
   */
  function _consumeTimelock(uint8 _operationType) internal {
    delete _scheduled[_operationType];
  }

  // ============ View Functions ============

  /**
   * @notice Outstanding bridged total held by the portal (deposits minus withdrawals)
   * @dev Used for the maxTotalBridged cap and for admin sanity monitoring: this
   *      should always equal the portal's underlying token balance unless
   *      someone transferred tokens to the portal directly.
   */
  function getNetBridged() public view returns (uint256) {
    return totalDeposited - totalWithdrawn;
  }

  /**
   * @notice Get the version of the contract
   * @return The version string
   */
  function version() external pure returns (string memory) {
    return '1.2.0';
  }

  /**
   * @notice Check if the caller is the owner
   */
  function _checkOwner() internal view {
    if (msg.sender != _contractOwner) {
      revert TokenPortal__Unauthorized();
    }
  }

  /**
   * @notice Check if the L2 bridge is set
   */
  function _checkL2BridgeSet() internal view {
    if (l2Bridge == bytes32(0)) {
      revert TokenPortal__L2BridgeNotSet();
    }
  }

  /**
   * @notice Authorize an upgrade to a new implementation
   * @dev Only callable by the owner, and only after the upgrade has been scheduled
   *      and TIMELOCK_DELAY has elapsed. The delay gives users time to observe the
   *      scheduled implementation and exit before it goes live.
   * @param _newImplementation The address of the new implementation
   */
  function _authorizeUpgrade(
    address _newImplementation
  ) internal override onlyOwner {
    bytes32 param = bytes32(uint256(uint160(_newImplementation)));
    _checkTimelock(uint8(OperationType.Upgrade), param);
    _consumeTimelock(uint8(OperationType.Upgrade));
  }

  /**
   * @notice Refresh the rollup, outbox, inbox, and version from the registry
   * @dev Internal function to update Aztec connection state
   */
  function _refreshRollupConnections() internal {
    IRollup newRollup = IRollup(address(registry.getCanonicalRollup()));
    if (address(newRollup) == address(0))
      revert TokenPortal__InvalidRollupAddress();

    rollup = newRollup;
    outbox = rollup.getOutbox();
    inbox = rollup.getInbox();
    rollupVersion = rollup.getVersion();
  }
}

lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)

pragma solidity >=0.6.2;

import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)

pragma solidity >=0.4.16;

import {IERC165} from "../utils/introspection/IERC165.sol";

lib/openzeppelin-contracts/contracts/interfaces/IERC1967.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1967.sol)

pragma solidity >=0.4.11;

/**
 * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
 */
interface IERC1967 {
    /**
     * @dev Emitted when the implementation is upgraded.
     */
    event Upgraded(address indexed implementation);

    /**
     * @dev Emitted when the admin account has changed.
     */
    event AdminChanged(address previousAdmin, address newAdmin);

    /**
     * @dev Emitted when the beacon is changed.
     */
    event BeaconUpgraded(address indexed beacon);
}

lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)

pragma solidity >=0.4.16;

import {IERC20} from "../token/ERC20/IERC20.sol";

lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/draft-IERC1822.sol)

pragma solidity >=0.4.16;

/**
 * @dev ERC-1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
 * proxy whose upgrades are fully controlled by the current implementation.
 */
interface IERC1822Proxiable {
    /**
     * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
     * address.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy.
     */
    function proxiableUUID() external view returns (bytes32);
}

lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (proxy/ERC1967/ERC1967Utils.sol)

pragma solidity ^0.8.21;

import {IBeacon} from "../beacon/IBeacon.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";

/**
 * @dev This library provides getters and event emitting update functions for
 * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.
 */
library ERC1967Utils {
    /**
     * @dev Storage slot with the address of the current implementation.
     * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

    /**
     * @dev The `implementation` of the proxy is invalid.
     */
    error ERC1967InvalidImplementation(address implementation);

    /**
     * @dev The `admin` of the proxy is invalid.
     */
    error ERC1967InvalidAdmin(address admin);

    /**
     * @dev The `beacon` of the proxy is invalid.
     */
    error ERC1967InvalidBeacon(address beacon);

    /**
     * @dev An upgrade function sees `msg.value > 0` that may be lost.
     */
    error ERC1967NonPayable();

    /**
     * @dev Returns the current implementation address.
     */
    function getImplementation() internal view returns (address) {
        return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
    }

    /**
     * @dev Stores a new address in the ERC-1967 implementation slot.
     */
    function _setImplementation(address newImplementation) private {
        if (newImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(newImplementation);
        }
        StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
    }

    /**
     * @dev Performs implementation upgrade with additional setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) internal {
        _setImplementation(newImplementation);
        emit IERC1967.Upgraded(newImplementation);

        if (data.length > 0) {
            Address.functionDelegateCall(newImplementation, data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Storage slot with the admin of the contract.
     * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;

    /**
     * @dev Returns the current admin.
     *
     * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
     * the https://ethereum.org/developers/docs/apis/json-rpc/#eth_getstorageat[`eth_getStorageAt`] RPC call.
     * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
     */
    function getAdmin() internal view returns (address) {
        return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
    }

    /**
     * @dev Stores a new address in the ERC-1967 admin slot.
     */
    function _setAdmin(address newAdmin) private {
        if (newAdmin == address(0)) {
            revert ERC1967InvalidAdmin(address(0));
        }
        StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
    }

    /**
     * @dev Changes the admin of the proxy.
     *
     * Emits an {IERC1967-AdminChanged} event.
     */
    function changeAdmin(address newAdmin) internal {
        emit IERC1967.AdminChanged(getAdmin(), newAdmin);
        _setAdmin(newAdmin);
    }

    /**
     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
     * This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;

    /**
     * @dev Returns the current beacon.
     */
    function getBeacon() internal view returns (address) {
        return StorageSlot.getAddressSlot(BEACON_SLOT).value;
    }

    /**
     * @dev Stores a new beacon in the ERC-1967 beacon slot.
     */
    function _setBeacon(address newBeacon) private {
        if (newBeacon.code.length == 0) {
            revert ERC1967InvalidBeacon(newBeacon);
        }

        StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;

        address beaconImplementation = IBeacon(newBeacon).implementation();
        if (beaconImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(beaconImplementation);
        }
    }

    /**
     * @dev Change the beacon and trigger a setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-BeaconUpgraded} event.
     *
     * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
     * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
     * efficiency.
     */
    function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
        _setBeacon(newBeacon);
        emit IERC1967.BeaconUpgraded(newBeacon);

        if (data.length > 0) {
            Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
     * if an upgrade doesn't perform an initialization call.
     */
    function _checkNonPayable() private {
        if (msg.value > 0) {
            revert ERC1967NonPayable();
        }
    }
}

lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (proxy/beacon/IBeacon.sol)

pragma solidity >=0.4.16;

/**
 * @dev This is the interface that {BeaconProxy} expects of its beacon.
 */
interface IBeacon {
    /**
     * @dev Must return an address that can be used as a delegate call target.
     *
     * {UpgradeableBeacon} will check that this address is a contract.
     */
    function implementation() external view returns (address);
}

lib/openzeppelin-contracts/contracts/proxy/utils/Initializable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Storage of the initializable contract.
     *
     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
     * when using with upgradeable contracts.
     *
     * @custom:storage-location erc7201:openzeppelin.storage.Initializable
     */
    struct InitializableStorage {
        /**
         * @dev Indicates that the contract has been initialized.
         */
        uint64 _initialized;
        /**
         * @dev Indicates that the contract is in the process of being initialized.
         */
        bool _initializing;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;

    /**
     * @dev The contract is already initialized.
     */
    error InvalidInitialization();

    /**
     * @dev The contract is not initializing.
     */
    error NotInitializing();

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint64 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
     * production.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        // Cache values to avoid duplicated sloads
        bool isTopLevelCall = !$._initializing;
        uint64 initialized = $._initialized;

        // Allowed calls:
        // - initialSetup: the contract is not in the initializing state and no previous version was
        //                 initialized
        // - construction: the contract is initialized at version 1 (no reinitialization) and the
        //                 current contract is just being deployed
        bool initialSetup = initialized == 0 && isTopLevelCall;
        bool construction = initialized == 1 && address(this).code.length == 0;

        if (!initialSetup && !construction) {
            revert InvalidInitialization();
        }
        $._initialized = 1;
        if (isTopLevelCall) {
            $._initializing = true;
        }
        _;
        if (isTopLevelCall) {
            $._initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint64 version) {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing || $._initialized >= version) {
            revert InvalidInitialization();
        }
        $._initialized = version;
        $._initializing = true;
        _;
        $._initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        _checkInitializing();
        _;
    }

    /**
     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
     */
    function _checkInitializing() internal view virtual {
        if (!_isInitializing()) {
            revert NotInitializing();
        }
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing) {
            revert InvalidInitialization();
        }
        if ($._initialized != type(uint64).max) {
            $._initialized = type(uint64).max;
            emit Initialized(type(uint64).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint64) {
        return _getInitializableStorage()._initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _getInitializableStorage()._initializing;
    }

    /**
     * @dev Pointer to storage slot. Allows integrators to override it with a custom storage location.
     *
     * NOTE: Consider following the ERC-7201 formula to derive storage locations.
     */
    function _initializableStorageSlot() internal pure virtual returns (bytes32) {
        return INITIALIZABLE_STORAGE;
    }

    /**
     * @dev Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        bytes32 slot = _initializableStorageSlot();
        assembly {
            $.slot := slot
        }
    }
}

lib/openzeppelin-contracts/contracts/proxy/utils/UUPSUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (proxy/utils/UUPSUpgradeable.sol)

pragma solidity ^0.8.22;

import {IERC1822Proxiable} from "../../interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "../ERC1967/ERC1967Utils.sol";

/**
 * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
 * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
 *
 * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
 * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
 * `UUPSUpgradeable` with a custom implementation of upgrades.
 *
 * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
 *
 * @custom:stateless
 */
abstract contract UUPSUpgradeable is IERC1822Proxiable {
    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
    address private immutable __self = address(this);

    /**
     * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
     * and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
     * while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
     * If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
     * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
     * during an upgrade.
     */
    string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";

    /**
     * @dev The call is from an unauthorized context.
     */
    error UUPSUnauthorizedCallContext();

    /**
     * @dev The storage `slot` is unsupported as a UUID.
     */
    error UUPSUnsupportedProxiableUUID(bytes32 slot);

    /**
     * @dev Check that the execution is being performed through a delegatecall call and that the execution context is
     * a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
     * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
     * function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
     * fail.
     */
    modifier onlyProxy() {
        _checkProxy();
        _;
    }

    /**
     * @dev Check that the execution is not being performed through a delegate call. This allows a function to be
     * callable on the implementing contract but not through proxies.
     */
    modifier notDelegated() {
        _checkNotDelegated();
        _;
    }

    /**
     * @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the
     * implementation. It is used to validate the implementation's compatibility when performing an upgrade.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
     */
    function proxiableUUID() external view notDelegated returns (bytes32) {
        return ERC1967Utils.IMPLEMENTATION_SLOT;
    }

    /**
     * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
     * encoded in `data`.
     *
     * Calls {_authorizeUpgrade}.
     *
     * Emits an {Upgraded} event.
     *
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
        _authorizeUpgrade(newImplementation);
        _upgradeToAndCallUUPS(newImplementation, data);
    }

    /**
     * @dev Reverts if the execution is not performed via delegatecall or the execution
     * context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
     */
    function _checkProxy() internal view virtual {
        if (
            address(this) == __self || // Must be called through delegatecall
            ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
        ) {
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Reverts if the execution is performed via delegatecall.
     * See {notDelegated}.
     */
    function _checkNotDelegated() internal view virtual {
        if (address(this) != __self) {
            // Must not be called through delegatecall
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
     * {upgradeToAndCall}.
     *
     * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
     *
     * ```solidity
     * function _authorizeUpgrade(address) internal onlyOwner {}
     * ```
     */
    function _authorizeUpgrade(address newImplementation) internal virtual;

    /**
     * @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
     *
     * As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
     * is expected to be the implementation slot in ERC-1967.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
        try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
            if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
                revert UUPSUnsupportedProxiableUUID(slot);
            }
            ERC1967Utils.upgradeToAndCall(newImplementation, data);
        } catch {
            // The implementation is not UUPS
            revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
        }
    }
}

lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
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 value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens 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 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` 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 value) external returns (bool);
}

lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 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 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @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 {
        if (!_safeTransfer(token, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @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 {
        if (!_safeTransferFrom(token, from, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _safeTransfer(token, to, value, false);
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _safeTransferFrom(token, from, to, value, false);
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        if (!_safeApprove(token, spender, value, false)) {
            if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
            if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Oppositely, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity `token.transfer(to, value)` call, 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 to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.transfer.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(to, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }

    /**
     * @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, 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 from The sender of the tokens
     * @param to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value,
        bool bubble
    ) private returns (bool success) {
        bytes4 selector = IERC20.transferFrom.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(from, shr(96, not(0))))
            mstore(0x24, and(to, shr(96, not(0))))
            mstore(0x44, value)
            success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
            mstore(0x60, 0)
        }
    }

    /**
     * @dev Imitates a Solidity `token.approve(spender, value)` call, 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 spender The spender of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.approve.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(spender, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/Address.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/Address.sol)

pragma solidity ^0.8.20;

import {Errors} from "./Errors.sol";
import {LowLevelCall} from "./LowLevelCall.sol";

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @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.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert Errors.InsufficientBalance(address(this).balance, amount);
        }
        if (LowLevelCall.callNoReturn(recipient, amount, "")) {
            // call successful, nothing to do
            return;
        } else if (LowLevelCall.returnDataSize() > 0) {
            LowLevelCall.bubbleRevert();
        } else {
            revert Errors.FailedCall();
        }
    }

    /**
     * @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 or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {Errors.FailedCall} error.
     *
     * 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.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @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`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        bool success = LowLevelCall.callNoReturn(target, value, data);
        if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
            return LowLevelCall.returnData();
        } else if (success) {
            revert AddressEmptyCode(target);
        } else if (LowLevelCall.returnDataSize() > 0) {
            LowLevelCall.bubbleRevert();
        } else {
            revert Errors.FailedCall();
        }
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        bool success = LowLevelCall.staticcallNoReturn(target, data);
        if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
            return LowLevelCall.returnData();
        } else if (success) {
            revert AddressEmptyCode(target);
        } else if (LowLevelCall.returnDataSize() > 0) {
            LowLevelCall.bubbleRevert();
        } else {
            revert Errors.FailedCall();
        }
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        bool success = LowLevelCall.delegatecallNoReturn(target, data);
        if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
            return LowLevelCall.returnData();
        } else if (success) {
            revert AddressEmptyCode(target);
        } else if (LowLevelCall.returnDataSize() > 0) {
            LowLevelCall.bubbleRevert();
        } else {
            revert Errors.FailedCall();
        }
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
     * of an unsuccessful call.
     *
     * NOTE: This function is DEPRECATED and may be removed in the next major release.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        // only check if target is a contract if the call was successful and the return data is empty
        // otherwise we already know that it was a contract
        if (success && (returndata.length > 0 || target.code.length > 0)) {
            return returndata;
        } else if (success) {
            revert AddressEmptyCode(target);
        } else if (returndata.length > 0) {
            LowLevelCall.bubbleRevert(returndata);
        } else {
            revert Errors.FailedCall();
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {Errors.FailedCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else if (returndata.length > 0) {
            LowLevelCall.bubbleRevert(returndata);
        } else {
            revert Errors.FailedCall();
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

lib/openzeppelin-contracts/contracts/utils/Errors.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)

pragma solidity ^0.8.20;

/**
 * @dev Collection of common custom errors used in multiple contracts
 *
 * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
 * It is recommended to avoid relying on the error API for critical functionality.
 *
 * _Available since v5.1._
 */
library Errors {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error InsufficientBalance(uint256 balance, uint256 needed);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedCall();

    /**
     * @dev The deployment failed.
     */
    error FailedDeployment();

    /**
     * @dev A necessary precompile is missing.
     */
    error MissingPrecompile(address);
}

lib/openzeppelin-contracts/contracts/utils/LowLevelCall.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/LowLevelCall.sol)

pragma solidity ^0.8.20;

/**
 * @dev Library of low level call functions that implement different calling strategies to deal with the return data.
 *
 * WARNING: Using this library requires an advanced understanding of Solidity and how the EVM works. It is recommended
 * to use the {Address} library instead.
 */
library LowLevelCall {
    /// @dev Performs a Solidity function call using a low level `call` and ignoring the return data.
    function callNoReturn(address target, bytes memory data) internal returns (bool success) {
        return callNoReturn(target, 0, data);
    }

    /// @dev Same as {callNoReturn-address-bytes}, but allows specifying the value to be sent in the call.
    function callNoReturn(address target, uint256 value, bytes memory data) internal returns (bool success) {
        assembly ("memory-safe") {
            success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x00)
        }
    }

    /// @dev Performs a Solidity function call using a low level `call` and returns the first 64 bytes of the result
    /// in the scratch space of memory. Useful for functions that return a tuple of single-word values.
    ///
    /// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
    /// and this function doesn't zero it out.
    function callReturn64Bytes(
        address target,
        bytes memory data
    ) internal returns (bool success, bytes32 result1, bytes32 result2) {
        return callReturn64Bytes(target, 0, data);
    }

    /// @dev Same as {callReturn64Bytes-address-bytes}, but allows specifying the value to be sent in the call.
    function callReturn64Bytes(
        address target,
        uint256 value,
        bytes memory data
    ) internal returns (bool success, bytes32 result1, bytes32 result2) {
        assembly ("memory-safe") {
            success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x40)
            result1 := mload(0x00)
            result2 := mload(0x20)
        }
    }

    /// @dev Performs a Solidity function call using a low level `staticcall` and ignoring the return data.
    function staticcallNoReturn(address target, bytes memory data) internal view returns (bool success) {
        assembly ("memory-safe") {
            success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)
        }
    }

    /// @dev Performs a Solidity function call using a low level `staticcall` and returns the first 64 bytes of the result
    /// in the scratch space of memory. Useful for functions that return a tuple of single-word values.
    ///
    /// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
    /// and this function doesn't zero it out.
    function staticcallReturn64Bytes(
        address target,
        bytes memory data
    ) internal view returns (bool success, bytes32 result1, bytes32 result2) {
        assembly ("memory-safe") {
            success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)
            result1 := mload(0x00)
            result2 := mload(0x20)
        }
    }

    /// @dev Performs a Solidity function call using a low level `delegatecall` and ignoring the return data.
    function delegatecallNoReturn(address target, bytes memory data) internal returns (bool success) {
        assembly ("memory-safe") {
            success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)
        }
    }

    /// @dev Performs a Solidity function call using a low level `delegatecall` and returns the first 64 bytes of the result
    /// in the scratch space of memory. Useful for functions that return a tuple of single-word values.
    ///
    /// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
    /// and this function doesn't zero it out.
    function delegatecallReturn64Bytes(
        address target,
        bytes memory data
    ) internal returns (bool success, bytes32 result1, bytes32 result2) {
        assembly ("memory-safe") {
            success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)
            result1 := mload(0x00)
            result2 := mload(0x20)
        }
    }

    /// @dev Returns the size of the return data buffer.
    function returnDataSize() internal pure returns (uint256 size) {
        assembly ("memory-safe") {
            size := returndatasize()
        }
    }

    /// @dev Returns a buffer containing the return data from the last call.
    function returnData() internal pure returns (bytes memory result) {
        assembly ("memory-safe") {
            result := mload(0x40)
            mstore(result, returndatasize())
            returndatacopy(add(result, 0x20), 0x00, returndatasize())
            mstore(0x40, add(result, add(0x20, returndatasize())))
        }
    }

    /// @dev Revert with the return data from the last call.
    function bubbleRevert() internal pure {
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            returndatacopy(fmp, 0x00, returndatasize())
            revert(fmp, returndatasize())
        }
    }

    function bubbleRevert(bytes memory returndata) internal pure {
        assembly ("memory-safe") {
            revert(add(returndata, 0x20), mload(returndata))
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/Pausable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Pausable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    bool private _paused;

    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    /**
     * @dev The operation failed because the contract is paused.
     */
    error EnforcedPause();

    /**
     * @dev The operation failed because the contract is not paused.
     */
    error ExpectedPause();

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        if (paused()) {
            revert EnforcedPause();
        }
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        if (!paused()) {
            revert ExpectedPause();
        }
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}

lib/openzeppelin-contracts/contracts/utils/ReentrancyGuardTransient.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/ReentrancyGuardTransient.sol)

pragma solidity ^0.8.24;

import {TransientSlot} from "./TransientSlot.sol";

/**
 * @dev Variant of {ReentrancyGuard} that uses transient storage.
 *
 * NOTE: This variant only works on networks where EIP-1153 is available.
 *
 * _Available since v5.1._
 *
 * @custom:stateless
 */
abstract contract ReentrancyGuardTransient {
    using TransientSlot for *;

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant REENTRANCY_GUARD_STORAGE =
        0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    /**
     * @dev A `view` only version of {nonReentrant}. Use to block view functions
     * from being called, preventing reading from inconsistent contract state.
     *
     * CAUTION: This is a "view" modifier and does not change the reentrancy
     * status. Use it only on view functions. For payable or non-payable functions,
     * use the standard {nonReentrant} modifier instead.
     */
    modifier nonReentrantView() {
        _nonReentrantBeforeView();
        _;
    }

    function _nonReentrantBeforeView() private view {
        if (_reentrancyGuardEntered()) {
            revert ReentrancyGuardReentrantCall();
        }
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, REENTRANCY_GUARD_STORAGE.asBoolean().tload() will be false
        _nonReentrantBeforeView();

        // Any calls to nonReentrant after this point will fail
        _reentrancyGuardStorageSlot().asBoolean().tstore(true);
    }

    function _nonReentrantAfter() private {
        _reentrancyGuardStorageSlot().asBoolean().tstore(false);
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _reentrancyGuardStorageSlot().asBoolean().tload();
    }

    function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
        return REENTRANCY_GUARD_STORAGE;
    }
}

lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.

pragma solidity ^0.8.20;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC-1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(newImplementation.code.length > 0);
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Int256Slot` with member `value` located at `slot`.
     */
    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns a `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/TransientSlot.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/TransientSlot.sol)
// This file was procedurally generated from scripts/generate/templates/TransientSlot.js.

pragma solidity ^0.8.24;

/**
 * @dev Library for reading and writing value-types to specific transient storage slots.
 *
 * Transient slots are often used to store temporary values that are removed after the current transaction.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 *  * Example reading and writing values using transient storage:
 * ```solidity
 * contract Lock {
 *     using TransientSlot for *;
 *
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
 *
 *     modifier locked() {
 *         require(!_LOCK_SLOT.asBoolean().tload());
 *
 *         _LOCK_SLOT.asBoolean().tstore(true);
 *         _;
 *         _LOCK_SLOT.asBoolean().tstore(false);
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library TransientSlot {
    /**
     * @dev UDVT that represents a slot holding an address.
     */
    type AddressSlot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a AddressSlot.
     */
    function asAddress(bytes32 slot) internal pure returns (AddressSlot) {
        return AddressSlot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a bool.
     */
    type BooleanSlot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a BooleanSlot.
     */
    function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) {
        return BooleanSlot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a bytes32.
     */
    type Bytes32Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Bytes32Slot.
     */
    function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) {
        return Bytes32Slot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a uint256.
     */
    type Uint256Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Uint256Slot.
     */
    function asUint256(bytes32 slot) internal pure returns (Uint256Slot) {
        return Uint256Slot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a int256.
     */
    type Int256Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Int256Slot.
     */
    function asInt256(bytes32 slot) internal pure returns (Int256Slot) {
        return Int256Slot.wrap(slot);
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(AddressSlot slot) internal view returns (address value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(AddressSlot slot, address value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(BooleanSlot slot) internal view returns (bool value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(BooleanSlot slot, bool value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Bytes32Slot slot) internal view returns (bytes32 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Bytes32Slot slot, bytes32 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Uint256Slot slot) internal view returns (uint256 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Uint256Slot slot, uint256 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Int256Slot slot) internal view returns (int256 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Int256Slot slot, int256 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * 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[ERC 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);
}

src/DataStructures.sol

// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 Cyphronix Software
pragma solidity ^0.8.27;

/**
 * @title DataStructures
 * @author Cyphronix Software
 * @notice Library that contains data structures used throughout the Aztec protocol
 */
library DataStructures {
  /**
   * @notice Actor on L1.
   * @param actor - The address of the actor
   * @param chainId - The chainId of the actor
   */
  struct L1Actor {
    address actor;
    uint256 chainId;
  }

  /**
   * @notice Actor on L2.
   * @param actor - The aztec address of the actor
   * @param version - The Aztec instance the actor is on
   */
  struct L2Actor {
    bytes32 actor;
    uint256 version;
  }

  /**
   * @notice Struct containing a message from L1 to L2
   * @param sender - The sender of the message
   * @param recipient - The recipient of the message
   * @param content - The content of the message (application specific) padded to bytes32 or hashed if larger.
   * @param secretHash - The secret hash of the message (make it possible to hide when a specific message is consumed on
   * L2).
   * @param index - Global leaf index on the L1 to L2 messages tree.
   */
  struct L1ToL2Msg {
    L1Actor sender;
    L2Actor recipient;
    bytes32 content;
    bytes32 secretHash;
    uint256 index;
  }

  /**
   * @notice Struct containing a message from L2 to L1
   * @param sender - The sender of the message
   * @param recipient - The recipient of the message
   * @param content - The content of the message (application specific) padded to bytes32 or hashed if larger.
   * @dev Not to be confused with L2ToL1Message in Noir circuits
   */
  struct L2ToL1Msg {
    DataStructures.L2Actor sender;
    DataStructures.L1Actor recipient;
    bytes32 content;
  }
}

src/Hash.sol

// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 Cyphronix Software.
pragma solidity ^0.8.27;

import {DataStructures} from "./DataStructures.sol";

/**
 * @title Hash
 * @author Cyphronix Software
 * @notice Library that contains helper functions to compute hashes for data structures and convert to field elements
 * Using sha256 as the hash function since it hits a good balance between gas cost and circuit size.
 */
library Hash {
  /**
   * @notice Computes the sha256 hash of the L1 to L2 message and converts it to a field element
   * @param _message - The L1 to L2 message to hash
   * @return The hash of the provided message as a field element
   */
  function sha256ToField(DataStructures.L1ToL2Msg memory _message) internal pure returns (bytes32) {
    return sha256ToField(
      abi.encode(_message.sender, _message.recipient, _message.content, _message.secretHash, _message.index)
    );
  }

  /**
   * @notice Computes the sha256 hash of the L2 to L1 message and converts it to a field element
   * @param _message - The L2 to L1 message to hash
   * @return The hash of the provided message as a field element
   */
  function sha256ToField(DataStructures.L2ToL1Msg memory _message) internal pure returns (bytes32) {
    return sha256ToField(
      abi.encodePacked(
        _message.sender.actor,
        _message.sender.version,
        _message.recipient.actor,
        _message.recipient.chainId,
        _message.content
      )
    );
  }

  /**
   * @notice Computes the sha256 hash of the provided data and converts it to a field element
   * @dev Truncating one byte to convert the hash to a field element. We prepend a byte rather than cast
   * bytes31(bytes32) to match Noir's to_be_bytes.
   * @param _data - The bytes to hash
   * @return The hash of the provided data as a field element
   */
  function sha256ToField(bytes memory _data) internal pure returns (bytes32) {
    return bytes32(bytes.concat(new bytes(1), bytes31(sha256(_data))));
  }
}

src/IInbox.sol

// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 Cyphronix Software.
pragma solidity ^0.8.27;

import {DataStructures} from "./DataStructures.sol";

/**
 * @title IInbox
 * @author Cyphronix Software
 * @notice Lives on L1 and is used to pass messages into the rollup from L1.
 */
interface IInbox {
  struct InboxState {
    // Rolling hash of all messages inserted into the inbox.
    // Used by clients to check for consistency.
    bytes16 rollingHash;
    // This value is not used much by the contract, but it is useful for synching the node faster
    // as it can more easily figure out if it can just skip looking for events for a time period.
    uint64 totalMessagesInserted;
    // Number of a tree which is currently being filled
    uint64 inProgress;
  }

  /**
   * @notice Emitted when a message is sent
   * @param checkpointNumber - The checkpoint number in which the message is included
   * @param index - The index of the message in the L1 to L2 messages tree
   * @param hash - The hash of the message
   * @param rollingHash - The rolling hash of all messages inserted into the inbox
   */
  event MessageSent(uint256 indexed checkpointNumber, uint256 index, bytes32 indexed hash, bytes16 rollingHash);

  event InboxSynchronized(uint256 indexed inProgress);

  /**
   * @notice Inserts a new message into the Inbox
   * @dev Emits `MessageSent` with data for easy access by the sequencer
   * @param _recipient - The recipient of the message
   * @param _content - The content of the message (application specific)
   * @param _secretHash - The secret hash of the message (make it possible to hide when a specific message is consumed
   * on L2)
   * @return The key of the message in the set and its leaf index in the tree
   */
  function sendL2Message(DataStructures.L2Actor memory _recipient, bytes32 _content, bytes32 _secretHash)
    external
    returns (bytes32, uint256);

  /**
   * @notice Consumes the current tree, and starts a new one if needed
   * @dev Only callable by the rollup contract
   * @dev In the first iteration we return empty tree root because first checkpoint's messages tree is always
   * empty because there has to be a 1 checkpoint lag to prevent sequencer DOS attacks
   * @param _toConsume - The checkpoint number to consume
   * @return The root of the consumed tree
   */
  function consume(uint256 _toConsume) external returns (bytes32);

  function catchUp(uint256 _pendingCheckpointNumber) external;

  function getFeeAssetPortal() external view returns (address);

  function getRoot(uint256 _checkpointNumber) external view returns (bytes32);

  function getState() external view returns (InboxState memory);

  function getTotalMessagesInserted() external view returns (uint64);

  function getInProgress() external view returns (uint64);
}

src/IOutbox.sol

// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 Cyphronix Software.
pragma solidity ^0.8.27;

import {DataStructures} from "./DataStructures.sol";

/**
 * @title IOutbox
 * @author Cyphronix Software
 * @notice Lives on L1 and is used to consume L2 -> L1 messages. Messages are inserted by the Rollup
 * and will be consumed by the portal contracts.
 * @dev Matches the current Aztec Outbox: roots are tracked per epoch, with one slot per proof
 * depth. `getRoots(_epoch)` returns a fixed array of MAX_CHECKPOINTS_PER_EPOCH (32) slots where
 * slot i holds the root inserted for i+1 checkpoints (partial epoch proofs), or bytes32(0) if no
 * proof of that depth has landed yet.
 */
interface IOutbox {
  event RootAdded(uint256 indexed epoch, uint256 indexed numCheckpointsInEpoch, bytes32 root);
  event MessageConsumed(
    uint256 indexed epoch,
    bytes32 indexed root,
    bytes32 indexed messageHash,
    uint256 leafId,
    uint256 numCheckpointsInEpoch
  );

  /**
   * @notice Inserts the root of a merkle tree containing all of the L2 to L1 messages in the
   * first _numCheckpointsInEpoch checkpoints of _epoch.
   * @dev Only callable by the rollup contract
   * @dev Emits `RootAdded` upon inserting the root successfully
   * @param _epoch - The epoch in which the L2 to L1 messages reside
   * @param _numCheckpointsInEpoch - The number of checkpoints of the epoch covered by the proof
   * @param _root - The merkle root of the tree where all the L2 to L1 messages are leaves
   */
  function insert(uint256 _epoch, uint256 _numCheckpointsInEpoch, bytes32 _root) external;

  /**
   * @notice Consumes an entry from the Outbox
   * @dev Only useable by portals / recipients of messages
   * @dev Emits `MessageConsumed` when consuming messages
   * @param _message - The L2 to L1 message
   * @param _epoch - The epoch that contains the message we want to consume
   * @param _numCheckpointsInEpoch - The number of checkpoints covered by the root the message is
   * proven against; the outbox reads the root stored at this depth
   * @param _leafIndex - The index inside the merkle tree where the message is located
   * @param _path - The sibling path used to prove inclusion of the message
   */
  function consume(
    DataStructures.L2ToL1Msg calldata _message,
    uint256 _epoch,
    uint256 _numCheckpointsInEpoch,
    uint256 _leafIndex,
    bytes32[] calldata _path
  ) external;

  /**
   * @notice Checks to see if an L2 to L1 message in a specific epoch has been consumed
   * @dev - This function does not throw. Out-of-bounds access is considered valid, but will always return false
   * @param _epoch - The epoch that contains the message to check
   * @param _leafId - The unique id of the message leaf (2^pathSize + leafIndex)
   */
  function hasMessageBeenConsumedAtEpoch(uint256 _epoch, uint256 _leafId) external view returns (bool);

  /**
   * @notice Fetch the roots stored for a given epoch. Slot i holds the root inserted for i+1
   * checkpoints, or bytes32(0) if no proof of that depth has landed yet.
   * @param _epoch - The epoch to fetch the roots for
   * @return The fixed-size array of per-depth roots
   */
  function getRoots(uint256 _epoch) external view returns (bytes32[32] memory);

  /**
   * @notice Fetch the root stored for a given epoch and checkpoint depth
   * @param _epoch - The epoch to fetch the root for
   * @param _numCheckpointsInEpoch - The number of checkpoints covered by the root
   * @return The root of the merkle tree containing the L2 to L1 messages (0 if not proven)
   */
  function getRootData(uint256 _epoch, uint256 _numCheckpointsInEpoch) external view returns (bytes32);
}

src/IRegistry.sol

// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.27;

import {IRewardDistributor} from "./IRewardDistributor.sol";

interface IHaveVersion {
  function getVersion() external view returns (uint256);
}

interface IRegistry {
  event CanonicalRollupUpdated(address indexed instance, uint256 indexed version);
  event RewardDistributorUpdated(address indexed rewardDistributor);

  function addRollup(IHaveVersion _rollup) external;
  function updateRewardDistributor(address _rewardDistributor) external;

  function getCanonicalRollup() external view returns (IHaveVersion);
  function getRollup(uint256 _chainId) external view returns (IHaveVersion);
  function numberOfVersions() external view returns (uint256);
  function getGovernance() external view returns (address);
  function getRewardDistributor() external view returns (IRewardDistributor);
  function getVersion(uint256 _index) external view returns (uint256);
}

src/IRewardDistributor.sol

// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.27;

interface IRewardDistributor {
  function claim(address _recipient, uint256 _amount, bytes32[] calldata _proof) external;
}

src/IRollup.sol

// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 Cyphronix Software.
pragma solidity ^0.8.27;

import {IInbox} from "./IInbox.sol";
import {IOutbox} from "./IOutbox.sol";
import {IHaveVersion} from "./IRegistry.sol";

/**
 * @notice Minimal Rollup interface required by consumer contracts
 */
interface IRollup is IHaveVersion {
  function getInbox() external view returns (IInbox);
  function getOutbox() external view returns (IOutbox);
}

src/ZKPassportWhitelist.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.27;

import {Initializable} from "@oz/proxy/utils/Initializable.sol";
import {UUPSUpgradeable} from "@oz/proxy/utils/UUPSUpgradeable.sol";

/**
 * @notice The data that can be bound to the proof
 */
struct BoundData {
  // The address of the ID holder
  address senderAddress;
  // The chain id (block.chainid)
  uint256 chainId;
  // The custom data (encoded as ASCII string)
  string customData;
}

/**
 * @notice The data that can be disclosed by the proof
 */
struct DisclosedData {
    // The name of the ID holder (includes the angular brackets from the MRZ)
    string name;
    // The issuing country of the ID
    string issuingCountry;
    // The nationality of the ID holder
    string nationality;
    // The gender of the ID holder
    string gender;
    // The birth date of the ID holder
    string birthDate;
    // The expiry date of the ID
    string expiryDate;
    // The document number of the ID
    string documentNumber;
    // The type of the document
    string documentType;
}

struct ProofVerificationParams {
  bytes32 version;
  ProofVerificationData proofVerificationData;
  bytes committedInputs;
  ServiceConfig serviceConfig;
}

struct ProofVerificationData {
  bytes32 vkeyHash;
  bytes proof;
  bytes32[] publicInputs;
}

struct ServiceConfig {
  uint256 validityPeriodInSeconds;
  string domain;
  string scope;
  bool devMode;
}

enum FaceMatchMode {
  NONE,
  REGULAR,
  STRICT
}

enum OS {
  ANY,
  IOS,
  ANDROID
}

// ============ ZK Passport Interfaces ============

/**
 * @notice The public interface for the ZKPassport verifier contract
 */
interface IZKPassportVerifier {
  /**
   * @notice Verifies a proof from ZKPassport
   * @param params The proof verification parameters
   * @return verified True if the proof is valid, false otherwise
   * @return uniqueIdentifier The unique identifier associated to the identity document that generated the proof
   * @return helper The ZKPassportHelper contract that can be used to verify the information or conditions that are checked by the proof
   */
  function verify(ProofVerificationParams calldata params) external returns (bool verified, bytes32 uniqueIdentifier, IZKPassportHelper helper);
}

/**
 * @notice You can use to helper contract verifying the information or conditions that are checked by the proof
 */
interface IZKPassportHelper {
  /**
   * @notice Verifies that the proof was generated for the given domain and scope
   * @param publicInputs The public inputs of the proof
   * @param domain The domain to check against (must match exactly the domain you specified in the SDK)
   * @param scope The scope to check against (must match exactly the scope you specified in the request using the TypeScript SDK)
   * @return True if the proof was generated for the given domain and scope, false otherwise
   */
  function verifyScopes(bytes32[] calldata publicInputs, string calldata domain, string calldata scope) external pure returns (bool);

  /**
   * @notice Gets the data disclosed by the proof
   * @param committedInputs The committed inputs
   * @param isIDCard Whether the proof is an ID card
   * @return disclosedData The data disclosed by the proof
   */
  function getDisclosedData(bytes calldata committedInputs, bool isIDCard) external pure returns (DisclosedData memory);

  /**
   * @notice Gets the data bound to the proof
   * @param committedInputs The committed inputs
   * @return boundData The data bound to the proof
   */
  function getBoundData(bytes calldata committedInputs) external pure returns (BoundData memory);

  /**
   * @notice Checks if the age is above or equal to the given age
   * @param minAge The age must be above or equal to this age
   * @param committedInputs The committed inputs
   * @return True if the age is above or equal to the given age, false otherwise
   */
  function isAgeAboveOrEqual(uint8 minAge, bytes calldata committedInputs) external pure returns (bool);
}

// ============ ZK Passport Whitelist Contract ============

/**
 * @title ZKPassportWhitelist
 * @notice Whitelist contract that integrates ZK passport verification for compliance
 * @dev This contract is upgradeable via UUPS pattern. Only the owner can perform upgrades.
 * @dev Users must verify their identity with ZK passport to be whitelisted for bridge operations
 */
contract ZKPassportWhitelist is Initializable, UUPSUpgradeable {

  /// @notice Thrown when attempting to call an owner-only function
  error ZKPassportWhitelist__Unauthorized();

  /// @notice Thrown when attempting to initialize with an invalid (zero) address
  error ZKPassportWhitelist__InvalidAddress();

  /// @notice Thrown when proof verification fails
  error ZKPassportWhitelist__ProofVerificationFailed();

  /// @notice Thrown when scope verification fails
  error ZKPassportWhitelist__InvalidScope();

  /// @notice Thrown when age verification fails
  error ZKPassportWhitelist__AgeTooYoung();

  /// @notice Thrown when the sender address doesn't match the bound address
  error ZKPassportWhitelist__SenderMismatch();

  /// @notice Thrown when the chain ID doesn't match
  error ZKPassportWhitelist__ChainIdMismatch();

  /// @notice Thrown when user is already registered
  error ZKPassportWhitelist__AlreadyRegistered();

  /// @notice Thrown when address is not whitelisted
  error ZKPassportWhitelist__NotWhitelisted();

  // ============ Events ============

  /**
   * @notice Emitted when a user successfully registers and gets whitelisted
   * @param user The address of the whitelisted user
   * @param uniqueIdentifier The unique identifier from the ZK passport proof
   * @param nationality The nationality disclosed in the proof
   */
  event UserWhitelisted(address indexed user, bytes32 indexed uniqueIdentifier, string nationality);

  /**
   * @notice Emitted when a user is removed from the whitelist
   * @param user The address of the user
   * @param reason The reason for removal
   */
  event UserRemovedFromWhitelist(address indexed user, string reason);

  /**
   * @notice Emitted when the service configuration is updated
   * @param domain The new domain
   * @param scope The new scope
   */
  event ServiceConfigUpdated(string domain, string scope);

  /**
   * @notice Emitted when the minimum age requirement is updated
   * @param oldMinAge The previous minimum age
   * @param newMinAge The new minimum age
   */
  event MinimumAgeUpdated(uint8 oldMinAge, uint8 newMinAge);

  /**
   * @notice Emitted when a user is whitelisted by admin (without proof)
   * @param user The address of the whitelisted user
   * @param admin The address of the admin who whitelisted the user
   */
  event UserWhitelistedByAdmin(address indexed user, address indexed admin);

  /**
   * @notice Emitted when ownership is transferred
   * @param previousOwner The previous owner address
   * @param newOwner The new owner address
   */
  event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

  // ============ State Variables ============

  address private _contractOwner;
  address private _pendingOwner;

  /// @notice The ZK Passport verifier contract (deterministic address across all chains)
  IZKPassportVerifier public zkPassportVerifier;

  /// @notice The service domain for scope verification
  string public serviceDomain;

  /// @notice The service scope for scope verification
  string public serviceScope;

  /// @notice Minimum age requirement for registration (default: 18)
  uint8 public minimumAge;

  /// @notice Mapping of user addresses to their whitelisted status
  mapping(address => bool) public isWhitelisted;

  /// @notice Mapping of user addresses to their unique ZK passport identifiers
  mapping(address => bytes32) public userIdentifiers;

  /// @notice Mapping of unique identifiers to user addresses (prevents duplicate registrations)
  mapping(bytes32 => address) public identifierToUser;

  /// @notice Gap for future storage variables (upgradeable pattern)
  uint256[43] private __gap;

  // ============ Modifiers ============

  /**
   * @notice Ensures the caller is the owner
   */
  modifier onlyOwner() {
    _checkOwner();
    _;
  }

  // ============ Initialization ============

  /**
   * @notice Disables initializers for the implementation contract
   * @dev This prevents the implementation contract from being initialized directly
   */
  constructor() {
    _disableInitializers();
  }

  /**
   * @notice Initialize the whitelist contract
   * @dev Can only be called once due to Initializable pattern
   * @param owner_ The owner of the contract (should be a multi-sig or timelock)
   * @param _zkPassportVerifier The ZK Passport verifier address (0x1D000001000EFD9a6371f4d90bB8920D5431c0D8)
   * @param _serviceDomain The service domain for scope verification
   * @param _serviceScope The service scope for scope verification
   * @param _minimumAge The minimum age requirement (e.g., 18)
   */
  function initialize(
    address owner_,
    address _zkPassportVerifier,
    string memory _serviceDomain,
    string memory _serviceScope,
    uint8 _minimumAge
  ) external initializer {
    // Validate inputs
    if (owner_ == address(0)) revert ZKPassportWhitelist__InvalidAddress();
    if (_zkPassportVerifier == address(0)) revert ZKPassportWhitelist__InvalidAddress();

    // Set owner
    _contractOwner = owner_;
    emit OwnershipTransferred(address(0), owner_);

    // Set state variables
    zkPassportVerifier = IZKPassportVerifier(_zkPassportVerifier);
    serviceDomain = _serviceDomain;
    serviceScope = _serviceScope;
    minimumAge = _minimumAge;
  }

  // ============ Public Functions ============

  /**
   * @notice Register a user with ZK passport proof
   * @param params The proof verification parameters from ZK passport
   * @param isIDCard Whether the proof is from an ID card (true) or passport (false)
   * @return uniqueIdentifier The unique identifier from the proof
   */
  function register(ProofVerificationParams calldata params, bool isIDCard)
    external
    returns (bytes32 uniqueIdentifier)
  {
    // Check if user is already registered
    if (isWhitelisted[msg.sender]) revert ZKPassportWhitelist__AlreadyRegistered();

    // Verify the proof
    bool verified;
    IZKPassportHelper helper;
    (verified, uniqueIdentifier, helper) = zkPassportVerifier.verify(params);

    if (!verified) revert ZKPassportWhitelist__ProofVerificationFailed();

    // Check the proof was generated using the configured domain and scope
    // if (!helper.verifyScopes(params.proofVerificationData.publicInputs, serviceDomain, serviceScope)) {
    //   revert ZKPassportWhitelist__InvalidScope();
    // }

    // Check if the user meets the minimum age requirement
    if (!helper.isAgeAboveOrEqual(minimumAge, params.committedInputs)) {
      revert ZKPassportWhitelist__AgeTooYoung();
    }

    // Get the bound data to verify the sender address and chain ID
    BoundData memory boundData = helper.getBoundData(params.committedInputs);

    // Make sure the user's address is the one that is calling the contract
    if (boundData.senderAddress != msg.sender) revert ZKPassportWhitelist__SenderMismatch();

    // Make sure the chain id is the same as the current chain
    if (boundData.chainId != block.chainid) revert ZKPassportWhitelist__ChainIdMismatch();

    // Check if this unique identifier has already been used
    if (identifierToUser[uniqueIdentifier] != address(0)) {
      revert ZKPassportWhitelist__AlreadyRegistered();
    }

    // Get the disclosed data to retrieve nationality (optional, for logging)
    DisclosedData memory disclosedData = helper.getDisclosedData(params.committedInputs, isIDCard);

    // Whitelist the user
    isWhitelisted[msg.sender] = true;
    userIdentifiers[msg.sender] = uniqueIdentifier;
    identifierToUser[uniqueIdentifier] = msg.sender;

    emit UserWhitelisted(msg.sender, uniqueIdentifier, disclosedData.nationality);



    return uniqueIdentifier;
  }

  /**
   * @notice Check if an address is whitelisted
   * @param user The address to check
   * @return True if the address is whitelisted, false otherwise
   */
  function checkWhitelisted(address user) external view returns (bool) {
    return isWhitelisted[user];
  }

  /**
   * @notice Require that an address is whitelisted (used by TokenPortal)
   * @param user The address to check
   */
  function requireWhitelisted(address user) external view {
    if (!isWhitelisted[user]) revert ZKPassportWhitelist__NotWhitelisted();
  }

  // ============ Admin Functions ============

  /**
   * @notice Directly whitelist a user without ZK passport proof verification
   * @dev Only callable by the owner. Useful for whitelisting trusted addresses or for testing.
   * @param user The address to whitelist
   */
  function adminWhitelist(address user) external onlyOwner {
    if (user == address(0)) revert ZKPassportWhitelist__InvalidAddress();
    if (isWhitelisted[user]) revert ZKPassportWhitelist__AlreadyRegistered();

    isWhitelisted[user] = true;

    emit UserWhitelistedByAdmin(user, msg.sender);
  }

  /**
   * @notice Remove a user from the whitelist (emergency function)
   * @dev Only callable by the owner
   * @param user The address to remove
   * @param reason The reason for removal
   */
  function removeFromWhitelist(address user, string calldata reason) external onlyOwner {
    if (!isWhitelisted[user]) revert ZKPassportWhitelist__NotWhitelisted();

    bytes32 identifier = userIdentifiers[user];

    isWhitelisted[user] = false;
    delete userIdentifiers[user];
    delete identifierToUser[identifier];

    emit UserRemovedFromWhitelist(user, reason);
  }

  /**
   * @notice Update the service configuration (domain and scope)
   * @dev Only callable by the owner. Use with caution as this affects verification.
   * @param _serviceDomain The new service domain
   * @param _serviceScope The new service scope
   */
  function updateServiceConfig(string calldata _serviceDomain, string calldata _serviceScope)
    external
    onlyOwner
  {
    serviceDomain = _serviceDomain;
    serviceScope = _serviceScope;

    emit ServiceConfigUpdated(_serviceDomain, _serviceScope);
  }

  /**
   * @notice Update the minimum age requirement
   * @dev Only callable by the owner
   * @param _newMinimumAge The new minimum age
   */
  function updateMinimumAge(uint8 _newMinimumAge) external onlyOwner {
    uint8 oldMinAge = minimumAge;
    minimumAge = _newMinimumAge;

    emit MinimumAgeUpdated(oldMinAge, _newMinimumAge);
  }

  // ============ Owner Functions ============

  /**
   * @notice Returns the address of the current owner
   */
  function owner() public view returns (address) {
    return _contractOwner;
  }

  /**
   * @notice Returns the address of the pending owner
   */
  function pendingOwner() public view returns (address) {
    return _pendingOwner;
  }

  /**
   * @notice Starts the ownership transfer of the contract to a new account
   * @dev Replaces the pending transfer if there is one. Can only be called by the current owner.
   * @param newOwner The address of the new owner
   */
  function transferOwnership(address newOwner) external onlyOwner {
    _pendingOwner = newOwner;
  }

  /**
   * @notice Transfers ownership of the contract to the pending owner
   * @dev Can only be called by the pending owner
   */
  function acceptOwnership() external {
    if (msg.sender != _pendingOwner) {
      revert ZKPassportWhitelist__Unauthorized();
    }
    address oldOwner = _contractOwner;
    _contractOwner = _pendingOwner;
    delete _pendingOwner;
    emit OwnershipTransferred(oldOwner, _contractOwner);
  }

  /**
   * @notice Renounces ownership of the contract
   * @dev Leaves the contract without an owner. Can only be called by the current owner.
   */
  function renounceOwnership() external onlyOwner {
    address oldOwner = _contractOwner;
    _contractOwner = address(0);
    delete _pendingOwner;
    emit OwnershipTransferred(oldOwner, address(0));
  }

  // ============ View Functions ============

  /**
   * @notice Get the version of the contract
   * @return The version string
   */
  function version() external pure returns (string memory) {
    return "1.0.0";
  }

  /**
   * @notice Check if the caller is the owner
   */
  function _checkOwner() internal view {
    if (msg.sender != _contractOwner) {
      revert ZKPassportWhitelist__Unauthorized();
    }
  }

  /**
   * @notice Authorize an upgrade to a new implementation
   * @dev Only callable by the owner. Required by UUPSUpgradeable.
   * @param _newImplementation The address of the new implementation
   */
  function _authorizeUpgrade(address _newImplementation) internal override onlyOwner {}
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "prague",
  "remappings": [
    "@oz/=lib/openzeppelin-contracts/contracts/",
    "@aztec/=node_modules/@aztec/l1-contracts/src/",
    "@uniswap/v4-core/=lib/v4-core/",
    "lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/v4-core/lib/openzeppelin-contracts/:forge-std/=lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/src/",
    "lib/v4-core/lib/solmate/:ds-test/=lib/v4-core/lib/solmate/lib/ds-test/src/",
    "lib/openzeppelin-contracts/:erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/openzeppelin-contracts/:forge-std/=lib/openzeppelin-contracts/lib/forge-std/src/",
    "lib/v4-core/:solmate/=lib/v4-core/lib/solmate/",
    "lib/v4-core/:forge-std/=lib/v4-core/lib/forge-std/src/",
    "lib/v4-core/:openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
    "@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
    "@openzeppelin/=lib/v4-core/lib/openzeppelin-contracts/",
    "ds-test/=lib/v4-core/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-std/=lib/openzeppelin-contracts/lib/forge-std/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "hardhat/=lib/v4-core/node_modules/hardhat/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "solmate/=lib/v4-core/lib/solmate/",
    "v4-core/=lib/v4-core/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.