Skip to content
Verified contractPartialMIT

ZeroXAggregationRouter

Address0xca371277ca6d98596fde7a6dfbdf31e5fb1a5bfa
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.34

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.34+commit.80d5c536
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,009,492
Creation transaction
0x4e872b190d…d97207fbe6
Libraries
src/swap/ZeroXAggregationRouter.sol:SwapAdminLib0x5dd0…3109ed

22 files

src/swap/ZeroXAggregationRouter.sol

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

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {Ownable2StepUpgradeable} from "@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol";
import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";

import {TransientPin} from "./TransientPin.sol";
import {SwapAdminLib} from "./SwapAdminLib.sol";
import {
    ICLPool,
    ISolidlyPool,
    IDODOV2Pool,
    IWooPPV2,
    IWETH9,
    IV4PoolManager,
    V4PoolKey,
    V4SwapParams
} from "./interfaces/IVenues.sol";

/// @title ZeroXAggregationRouter
/// @notice Executes a pre-computed multi-venue swap route across whitelisted
///         pools, atomically, with a floor on what the user receives.
///
/// @dev # Four invariants
///
/// Each is mechanically checkable, which is what makes them useful to a
/// reviewer rather than decorative.
///
/// | | Invariant | How to check it |
/// |---|---|---|
/// | **I1** | The router never executes caller-supplied calldata. | `grep -nE '\.call[({]' src/swap/ZeroXAggregationRouter.sol` finds exactly two sites, both plain ETH sends with EMPTY calldata: the WETH unwrap in {_settle} and {rescueNative}. |
/// | **I2** | The router never grants an ERC-20 allowance to anyone. | `grep -n 'approve(' src/swap/ZeroXAggregationRouter.sol` returns nothing. |
/// | **I3** | No outbound transfer amount is derived from `balanceOf(address(this))`. Every one is a delta tracked inside the current call. | `balanceOf(address(this))` appears only inside subtractions, never as a transfer amount — except {rescueTokens}. |
/// | **I4** | Between transactions the router holds zero of every token and zero ETH. | Fork tests assert post-swap balances equal pre-swap. |
///
/// **I3 is the load-bearing one.** "Sweep the dust" written as
/// `transfer(recipient, balanceOf(this))` turns any stranded balance — a
/// griefer's donation, a prior partial fill — into a free withdrawal for
/// whoever calls `swap` next. Sweep the *tracked residual*, never the balance.
///
/// # Why there is no generic executor
///
/// A {Hop} is `{pool, zeroForOne}` and nothing else. Venue, tokens and curve
/// selector are read from the on-chain allowlist, never from calldata. That
/// deletes an entire bug class: there is no field a caller can lie about that
/// this contract acts on unchecked.
///
/// The alternative — a generic `Call[] {target, value, data}` — is drained by
/// one call: `target = USDC, data = transferFrom(victim, attacker, ...)`.
/// Selector blocklists do not work, because you cannot enumerate every token's
/// transfer-like selector and `permit`-style functions let an attacker mint the
/// allowance mid-call.
///
/// The honest cost: **every new venue is a contract change** — a new enum
/// member, a new branch, a new audit, a redeploy. Generic aggregators accept
/// the drain risk to ship venues as off-chain config, and mitigate it by
/// holding no approvals (1inch uses a separate spender contract). This takes
/// the other end of that trade: we hold an approval for one transaction and
/// have no generic executor, so there is nothing to steal *and* nothing to
/// isolate. If venue velocity ever becomes the binding constraint, the right
/// migration is the separate-spender shape, **not** adding `Call[]` here.
///
/// # Upgradeability, and what it costs
///
/// This is a **UUPS proxy**, so the router keeps one address across versions —
/// the backend's pinned destination, the allowlist, and every outstanding
/// allowance survive an upgrade.
///
/// State the risk plainly, because it is the largest one here: users grant
/// this router an ERC-20 allowance, so whoever can upgrade it can replace
/// {swap} with a function that moves those allowances wherever they like. The
/// upgrade key is therefore strictly more powerful than every other admin
/// control in this file combined, and none of the bounds below — `MAX_FEE_BPS`,
/// the factory attestation, the guardian's asymmetry — constrain it at all.
///
/// Three things narrow it:
///
/// 1. **The owner should be a timelock, not an EOA and not a bare multisig.**
///    An upgrade users can see coming is one they can revoke their allowance
///    ahead of. The deploy scripts take the owner as an explicit argument for
///    this reason and log it.
/// 2. **{_authorizeUpgrade} pins WETH.** `weth` is an implementation immutable,
///    not storage, so an upgrade is the one moment it could change — and a
///    router pointed at an attacker's "WETH" mishandles every native swap. A
///    new implementation carrying a different WETH is rejected.
/// 3. **{renounceOwnership} still reverts.** An ownerless UUPS proxy can never
///    be upgraded, paused, or rescued again.
///
/// The alternative — an immutable router, migrated by deploying a new address —
/// removes the upgrade key entirely but leaves every user's allowance pointing
/// at the old contract until they re-approve. That was this contract's original
/// shape; upgradeability is a deliberate trade of one risk for the other.
///
/// # Storage
///
/// Append-only. New variables go at the END of the block below, before
/// `__gap`, and `__gap` shrinks by the number of slots consumed. Inserting or
/// reordering a variable re-points every subsequent slot and corrupts live
/// state on the first upgrade.
contract ZeroXAggregationRouter is
    Initializable,
    UUPSUpgradeable,
    Ownable2StepUpgradeable,
    PausableUpgradeable,
    ReentrancyGuardUpgradeable
{
    using SafeERC20 for IERC20;

    // -----------------------------------------------------------------------
    // Types
    // -----------------------------------------------------------------------

    /// @dev `NONE` MUST be zero so an unregistered pool reads as invalid rather
    ///      than as whichever venue happens to sit at index 0. Members are
    ///      APPEND-ONLY: the enum's uint8 values live in storage inside
    ///      {PoolInfo}, so inserting one re-labels every pool registered after
    ///      that position.
    enum Venue {
        NONE,
        UNIV3,
        SLIPSTREAM,
        SOLIDLY_V2,
        WOOFI,
        DODO,
        /// @dev Uniswap v4. Not a pool contract: the singleton PoolManager keys
        ///      pools by `keccak256(abi.encode(V4PoolKey))`. The allowlist keys
        ///      such a pool by a HANDLE — the first 20 bytes of that pool id —
        ///      so a {Hop} stays `{pool, zeroForOne, sqrtPriceLimitX96}` and
        ///      the `swap` ABI does not move. See {registerUniV4}.
        UNIV4
    }

    /// @notice What the allowlist knows about a pool. Written only by
    ///         {registerPool}, and every field is read FROM the pool or its
    ///         factory rather than supplied by anyone.
    struct PoolInfo {
        Venue venue;
        bool enabled;
        /// @dev Solidly curve selector. Meaningless for other venues.
        bool stable;
        /// @dev DODO orientation: true when `token0` is the pool's BASE token.
        ///      DODO sells base and quote with different functions, and nothing
        ///      about the sorted token order reveals which is which.
        bool baseIsToken0;
        address token0;
        address token1;
    }

    /// @notice One hop. The ENTIRE caller-supplied description of a swap step.
    struct Hop {
        address pool;
        bool zeroForOne;
        /// @dev The price at which this hop STOPS, as Uniswap's Q64.96 sqrt
        ///      ratio. `0` means "no limit" and reproduces the behaviour this
        ///      router had before limits existed.
        ///
        ///      A limit is a BOUND, not a target: the pool swaps until its
        ///      marginal price reaches this and then stops, consuming less
        ///      than it was offered. What happens to the remainder is
        ///      {SwapDescription.partiallyFillable}'s decision, not this
        ///      field's.
        ///
        ///      Only concentrated-liquidity venues can enforce it. A non-zero
        ///      limit on any other venue REVERTS rather than being ignored —
        ///      silently dropping a caller's price protection is the worst
        ///      available outcome, because they priced the trade believing they
        ///      had it.
        uint160 sqrtPriceLimitX96;
    }

    /// @notice One parallel path through the route.
    /// @dev `portionBps` is in the ABI from day one even though the off-chain
    ///      router emits exactly one path at 10000 today. Split routing is a
    ///      later phase and we are not paying for a second audit to add a field.
    struct Path {
        uint16 portionBps;
        Hop[] hops;
    }

    struct SwapDescription {
        /// @dev {NATIVE} for ETH.
        address tokenIn;
        address tokenOut;
        address recipient;
        uint256 amountIn;
        uint256 minAmountOut;
        uint256 deadline;
        /// @dev The caller's accepted protocol-fee ceiling, in bps. Turns a fee
        ///      raised between quoting and mining into a legible error at the
        ///      top of the function rather than a confusing shortfall after all
        ///      the gas is spent.
        uint16 maxFeeBps;
        /// @dev Whether a short fill is acceptable. CoW's vocabulary, and the
        ///      same meaning.
        ///
        ///      `false` is fill-or-kill: a pool consuming less than it was
        ///      offered reverts the whole transaction. That is the right
        ///      default because it is the behaviour every existing caller
        ///      already gets, and because a plan whose later steps depend on
        ///      the full output is broken by a partial fill in a way that is
        ///      expensive to discover afterwards.
        ///
        ///      `true` is immediate-or-cancel: take what clears at or better
        ///      than the limit, refund the rest to the PAYER, and report both.
        ///      Choose it by whether the rest of the caller's plan can absorb a
        ///      smaller fill, never by preference.
        bool partiallyFillable;
    }

    // -----------------------------------------------------------------------
    // Constants
    // -----------------------------------------------------------------------

    /// @notice Sentinel for native ETH.
    /// @dev Deliberately NOT `address(0)`. A zero address is what an
    ///      uninitialised struct field holds, so `address(0)` as a sentinel
    ///      means a caller who forgets to set `tokenIn` silently asks for a
    ///      native-ETH swap. This value cannot be produced by omission.
    address public constant NATIVE = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // @audit chain specific

    uint256 internal constant BPS = 10_000;

    /// @notice Hard ceiling on the protocol fee.
    /// @dev A `constant`, not storage, specifically so that a compromised owner
    ///      cannot raise it. The owner can move the fee within this bound and
    ///      nowhere near 100%.
    uint16 public constant MAX_FEE_BPS = 100;

    /// @notice Fee the router launches with, in bps. Owner-adjustable up to
    ///         {MAX_FEE_BPS} afterwards.
    /// @dev Set at construction rather than left at zero so the deployed
    ///      contract and the off-chain quoter agree from block one. A router
    ///      that starts at 0 and is raised later would silently invalidate
    ///      every quote taken before the change — which `desc.maxFeeBps` turns
    ///      into a revert rather than a loss, but a revert the user did not
    ///      need to experience.
    uint16 public constant DEFAULT_FEE_BPS = 3;

    /// @dev Uniswap V3 tick-math bounds. The pool asserts a STRICT inequality
    ///      against the limit, which is why callers pass these +/- 1 rather
    ///      than the bounds themselves. Identical across Uniswap V3,
    ///      PancakeSwap V3, Slipstream — and Uniswap v4, whose TickMath carries
    ///      the same two values under new names (MIN/MAX_SQRT_PRICE).
    uint160 internal constant MIN_SQRT_RATIO = 4_295_128_739;
    uint160 internal constant MAX_SQRT_RATIO = 1_461_446_703_485_210_103_287_273_052_203_988_822_378_723_970_342;

    // -----------------------------------------------------------------------
    // Storage
    // -----------------------------------------------------------------------

    /// @notice WETH for this chain. Immutable: a mutable WETH address would let
    ///         an owner point native handling at a contract they control.
    IWETH9 public immutable weth;

    /// @notice The Uniswap v4 PoolManager for this chain, or `address(0)` on a
    ///         chain that has none — {registerUniV4} then refuses.
    /// @dev Immutable for the same reason `weth` is: `_swapUniV4` transfers the
    ///      hop's input to this address and trusts it to pay the output, so a
    ///      storage-settable manager would let an owner point every v4 hop at a
    ///      contract they control. {_authorizeUpgrade} pins it across upgrades
    ///      the way it pins WETH, with one asymmetry: a router deployed before
    ///      v4 existed on its chain (zero) may INTRODUCE a manager, but a
    ///      non-zero manager can never move.
    IV4PoolManager public immutable poolManager;

    /// @notice pool => what we know about it.
    mapping(address => PoolInfo) public pools;

    /// @notice factory => the venue it mints.
    /// @dev The trust root. Moving it from pools (hundreds, churning) to
    ///      factories (a handful, stable) is what makes {registerPool}
    ///      permissionless-capable without trusting the registrant.
    mapping(address => Venue) public factoryVenue;

    /// @notice Pools the guardian has blocked. Cleared ONLY by the owner.
    /// @dev Separate from `PoolInfo.enabled` on purpose. `registerPool` is
    ///      permissionless-capable and overwrites the whole struct, so an
    ///      `enabled` bit living inside that struct can be reset by anyone
    ///      simply re-registering — a guardian's disable would lose the race to
    ///      a back-run in the same block. This flag is outside the struct and
    ///      registration cannot touch it.
    mapping(address => bool) public blocked;

    /// @notice WooPP contract => sorted-pair key => served.
    /// @dev WooFi is the one venue where a single address serves many pairs, so
    ///      it needs a second dimension the other venues do not.
    mapping(address => mapping(bytes32 => bool)) public wooPairs;

    /// @notice Hot key allowed to DISABLE and PAUSE, but never to enable.
    /// @dev Authority is deliberately asymmetric. Granting access needs a
    ///      multisig; revoking it must happen in minutes, not after a quorum.
    address public guardian;

    /// @notice When true, anyone may register a pool the factory attests to.
    /// @dev Ships false so the on-chain set exactly mirrors the curated
    ///      off-chain whitelist. Flipping it makes the on-chain set a SUPERSET
    ///      of that list — defensible, since the factory attests the curve is
    ///      honest, but a policy change rather than a config tweak.
    bool public permissionlessRegistration; // @audit risky

    uint16 public feeBps;
    address public feeRecipient;

    /// @notice WooPP => sorted-pair key => has this pair EVER been registered.
    /// @dev A second mapping rather than a flag inside `wooPairs`, because one
    ///      bool cannot distinguish "never registered" from "registered, then
    ///      disabled by the guardian". {registerWooFi} needs that distinction to
    ///      avoid re-arming a pair an incident response just took out of service.
    ///      Appended at the END of the block and `__gap` shrunk by one, per the
    ///      append-only rule above.
    mapping(address => mapping(bytes32 => bool)) public wooPairKnown;

    /// @notice v4 handle => the full pool key it stands for.
    /// @dev The handle (first 20 bytes of the pool id) is what {Hop.pool} and
    ///      the `pools` allowlist carry; this mapping is what `_swapUniV4`
    ///      swaps with. A handle whose key here is empty and whose `pools`
    ///      entry says UNIV4 is impossible — {_registerUniV4} writes both.
    ///      `PoolInfo.token0/token1` for a v4 pool hold the EFFECTIVE tokens
    ///      (native ETH recorded as WETH) so path continuity works unchanged;
    ///      the raw currencies, `address(0)` included, live only here.
    ///      Appended at the END of the block, `__gap` shrunk by one.
    mapping(address => V4PoolKey) public v4Keys;

    // -----------------------------------------------------------------------
    // Events
    // -----------------------------------------------------------------------

    /// @notice One per swap. The money row.
    /// @notice A `partiallyFillable` swap that did not take the whole input.
    /// @param payer Who sent the input, and who the remainder went back to.
    /// @param tokenIn The token offered and refunded.
    /// @param offered What the payer handed over.
    /// @param filled What actually traded. `offered - filled` was refunded.
    /// @dev Emitted ALONGSIDE {Swapped}, not instead of it. A consumer
    ///      tracking volume reads `Swapped`; one reconciling a caller's balance
    ///      needs to know a refund happened and cannot infer it from `Swapped`
    ///      alone, which reports only what traded.
    event PartiallyFilled(address indexed payer, address indexed tokenIn, uint256 offered, uint256 filled);

    event Swapped(
        address indexed sender,
        address indexed tokenIn,
        address indexed tokenOut,
        address recipient,
        uint256 amountIn,
        uint256 amountOut,
        uint256 feeAmount,
        uint256 pathCount,
        uint256 hopCount
    );

    /// @notice One per hop, for routing attribution.
    /// @dev ~1,900 gas each and worth it: per-hop realised slippage is the
    ///      phase-2 routing-quality metric and nothing else can produce it.
    ///
    ///      Indexer correlation rule: every `Routed` for a swap precedes that
    ///      swap's `Swapped` in the same transaction. Group by "the `Routed`
    ///      logs since the previous `Swapped`, ordered by log index" — which
    ///      survives a passkey batch containing several swaps — and use
    ///      `hopCount` to ASSERT the grouping rather than assume it.
    event Routed(
        address indexed pool,
        Venue indexed venue,
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 amountOut
    );

    event PoolRegistered(address indexed pool, Venue indexed venue, address token0, address token1);
    event PoolReRegistered(address indexed pool, Venue indexed venue);
    event PoolBlockedSet(address indexed pool, bool blocked);
    event WooPairRegistered(address indexed wooPP, address token0, address token1);
    event WooPairEnabledSet(address indexed wooPP, address token0, address token1, bool enabled);
    event WooPairReRegistered(address indexed wooPP, address token0, address token1);
    event PoolEnabledSet(address indexed pool, bool enabled);
    event FactoryVenueSet(address indexed factory, Venue indexed venue);
    event GuardianSet(address indexed previous, address indexed current);
    event PermissionlessRegistrationSet(bool enabled);
    event FeeSet(uint16 feeBps, address indexed feeRecipient);
    event Rescued(address indexed token, address indexed to, uint256 amount);

    // -----------------------------------------------------------------------
    // Errors
    // -----------------------------------------------------------------------

    error ZeroAddress();
    error DeadlineExpired();
    error InvalidAmount();
    error IdenticalTokens();
    error NoPaths();
    error PortionsMustSumToBps();
    error EmptyPath();
    error PoolNotAllowlisted(address pool);
    error PoolDisabled(address pool);
    error PoolBlocked(address pool);
    error PoolAlreadyRegistered(address pool);
    error NotAWooPPForPair(address wooPP);
    error WooPairNotRegistered(address wooPP);
    error WooFiMustBeTerminalHop();
    error PartialFill(address pool, uint256 consumed, uint256 expected);
    /// @dev Raised when a hop AFTER the first stops at its price limit. Its
    ///      shortfall is an intermediate token the payer never held, so there
    ///      is nowhere honest to put it: handing it over gives them an asset
    ///      they did not ask for, keeping it strands value here. The route
    ///      cannot be filled at the price asked for, and refusing is what a
    ///      limit is for.
    error PartialFillOnLaterHop(address pool, uint256 consumed, uint256 offered);
    /// @dev A price limit on a venue that cannot enforce one. Refused rather
    ///      than ignored: the caller priced their trade believing they had that
    ///      protection.
    error PriceLimitUnsupported(address pool);
    error ZeroOutput(address pool);
    error PathDiscontinuity();
    error PathStartMismatch();
    error PathEndMismatch();
    error InsufficientOutput(uint256 received, uint256 required);
    error FeeTooHigh(uint16 current, uint16 accepted);
    error FeeAboveMax();
    error FeeRecipientRequired();
    error UnknownFactory(address factory);
    error FactoryRoundTripFailed(address pool);
    error RegistrationClosed();
    error NotOwnerOrGuardian();
    error NativeAmountMismatch();
    error NativeNotExpected();
    error NativeToNative();
    error UnexpectedNative();
    error VenueUnsupported();
    error NothingReceived();
    error WethMismatch();
    error RecipientIsRouter();
    error LengthMismatch();
    /// @dev A v4 registration on a chain whose router was deployed with no
    ///      PoolManager.
    error V4NotConfigured();
    /// @dev A v4 key naming a hook contract. Hooks can take their own deltas,
    ///      change the fee mid-swap, or re-enter — any of which breaks the
    ///      quote-equals-execution property and reopens the surface the
    ///      allowlist exists to close. Refused at registration, permanently.
    error V4HooksNotSupported();
    /// @dev A v4 key the PoolManager holds no state for. The pool id is the
    ///      hash of the key, so "initialised" is the whole attestation: a key
    ///      with a non-zero price is exactly the key some `initialize` call
    ///      was given.
    error V4PoolNotInitialized();
    /// @dev A v4 key whose currencies are not in ascending order — such a key
    ///      can never have been initialised, so name the actual mistake.
    error V4CurrenciesUnsorted();
    /// @dev A v4 key whose fee exceeds the LP-fee ceiling — the dynamic-fee
    ///      sentinel included.
    error V4FeeInvalid();
    /// @dev An upgrade carrying a different PoolManager. Same shape as
    ///      {WethMismatch}: the one moment an immutable could change is the
    ///      one moment it must not.
    error PoolManagerMismatch();

    // -----------------------------------------------------------------------
    // Construction
    // -----------------------------------------------------------------------

    /// @param weth_ WETH for the chain this implementation will serve.
    /// @param poolManager_ The chain's Uniswap v4 PoolManager, or `address(0)`
    ///        on a chain without one — v4 registration then refuses and every
    ///        other venue is unaffected.
    /// @dev `weth` stays an IMMUTABLE rather than becoming storage, which is
    ///      the one place this contract deviates from the usual UUPS shape.
    ///      Immutables live in the implementation's bytecode, so the proxy
    ///      reads it correctly through `delegatecall` — and keeping it out of
    ///      storage means no owner, compromised or otherwise, can point native
    ///      handling at a contract they control. `poolManager` is an immutable
    ///      for the same reason — see its declaration.
    ///
    ///      The cost is that every upgrade must redeploy with the SAME WETH
    ///      and the same PoolManager. {_authorizeUpgrade} enforces both rather
    ///      than trusting a runbook.
    /// @custom:oz-upgrades-unsafe-allow constructor state-variable-immutable
    constructor(address weth_, address poolManager_) {
        if (weth_ == address(0)) revert ZeroAddress();
        weth = IWETH9(weth_);
        poolManager = IV4PoolManager(poolManager_);
        // Without this, anyone can `initialize` the IMPLEMENTATION and become
        // its owner. That does not touch proxy state, but it does hand them
        // `upgradeToAndCall` on the implementation itself, which for UUPS is a
        // `delegatecall` they control — the shape that bricked the Parity
        // multisig.
        _disableInitializers();
    }

    /// @notice One-time setup of the PROXY's state.
    /// @param owner_ Upgrade and admin authority. Should be a timelock — see
    ///        the contract-level notes on what this key can do.
    /// @param guardian_ Hot key that may disable pools and pause, never enable.
    /// @param feeRecipient_ Where the protocol fee lands.
    function initialize(address owner_, address guardian_, address feeRecipient_) external initializer {
        if (owner_ == address(0)) revert ZeroAddress();
        // A non-zero launch fee needs somewhere to go. Requiring it here rather
        // than tolerating a zero recipient means the proxy cannot be
        // initialised into a state where every swap reverts on the fee
        // transfer.
        if (feeRecipient_ == address(0)) revert FeeRecipientRequired();

        __UUPSUpgradeable_init();
        __Ownable2Step_init();
        __Pausable_init();
        __ReentrancyGuard_init();

        guardian = guardian_;
        feeBps = DEFAULT_FEE_BPS;
        feeRecipient = feeRecipient_;

        _transferOwnership(owner_);
        emit GuardianSet(address(0), guardian_);
        emit FeeSet(DEFAULT_FEE_BPS, feeRecipient_);
    }

    /// @dev Gate on the upgrade key. Two checks beyond `onlyOwner`:
    ///
    ///      **The new implementation must carry the same WETH.** `weth` is an
    ///      implementation immutable, so an upgrade is the only moment it can
    ///      change. A router pointed at an attacker's "WETH" wraps user ETH
    ///      into a contract they control and unwraps nothing back. Reading
    ///      `weth()` on the implementation ADDRESS (a plain call, not a
    ///      delegatecall) reads that implementation's own immutable, which is
    ///      exactly the value the proxy would start using.
    ///
    ///      **It must actually be this contract.** A `weth()` that answers
    ///      correctly is cheap to fake, but combined with the `proxiableUUID`
    ///      check UUPSUpgradeable already performs, an implementation has to be
    ///      a real UUPS contract agreeing on both to pass.
    function _authorizeUpgrade(address newImplementation) internal view override onlyOwner {
        if (newImplementation == address(0)) revert ZeroAddress();
        if (address(ZeroXAggregationRouter(payable(newImplementation)).weth()) != address(weth)) {
            revert WethMismatch();
        }
        // Pinned like WETH, with one asymmetry: a router deployed before v4
        // existed on its chain (manager zero) may INTRODUCE one — nothing was
        // registered against zero, so nothing can be re-pointed — but once a
        // manager is set, an upgrade carrying a different one is re-pointing
        // every registered v4 pool's settlement at a new contract and is
        // refused. An older implementation without `poolManager()` reverts the
        // staticcall and therefore the upgrade: a v4-aware router cannot be
        // downgraded to one that would strand its v4 allowlist entries.
        if (address(poolManager) != address(0)) {
            if (
                address(ZeroXAggregationRouter(payable(newImplementation)).poolManager()) != address(poolManager)
            ) {
                revert PoolManagerMismatch();
            }
        }
    }

    modifier onlyOwnerOrGuardian() {
        if (msg.sender != owner() && msg.sender != guardian) revert NotOwnerOrGuardian();
        _;
    }

    // -----------------------------------------------------------------------
    // The money path
    // -----------------------------------------------------------------------

    /// @notice Execute a route and pay the recipient at least `minAmountOut`.
    /// @dev Ordering inside this function is deliberate:
    ///      validate -> pull -> execute -> measure -> fee -> floor -> pay.
    ///      The floor is checked on the POST-fee amount; see {_settle}.
    function swap(SwapDescription calldata desc, Path[] calldata paths)
        external
        payable
        nonReentrant
        whenNotPaused
        returns (uint256 amountOut)
    {
        if (block.timestamp > desc.deadline) revert DeadlineExpired();
        if (desc.amountIn == 0) revert InvalidAmount();
        if (desc.recipient == address(0)) revert ZeroAddress();
        // Paying ourselves makes {_settle}'s recipient-side delta measure zero,
        // so its `delivered` backstop degenerates to `0 < 0`, the entire output
        // is stranded here, and `Swapped` still reports it as delivered. That
        // falsifies I4 and is never what a caller means.
        if (desc.recipient == address(this)) revert RecipientIsRouter();
        // Compared AFTER normalisation. `{tokenIn: NATIVE, tokenOut: WETH}`
        // passes a raw comparison — NATIVE is not WETH — but both normalise to
        // WETH, so the swap would wrap the principal, measure a delta against a
        // balance that already contains it, and strand the funds. Normalising
        // first collapses that alias into the check that already exists.
        if (_effective(desc.tokenIn) == _effective(desc.tokenOut)) revert IdenticalTokens();
        // Read the live fee ONCE and bound it by what the caller accepted. A
        // fee raised between building and mining this transaction now reverts
        // legibly here instead of surfacing as a confusing shortfall later.
        uint16 fee = feeBps;
        if (fee > desc.maxFeeBps) revert FeeTooHigh(fee, desc.maxFeeBps);

        uint256 received = _pullInput(desc);
        (uint256 grossOut, uint256 hopCount, uint256 refunded) = _executePaths(desc, paths, received);
        amountOut = _settle(desc, grossOut, fee);

        // `received - refunded`, not `received`: the event must report what was
        // actually SOLD. Reporting the offered amount on a partial fill would
        // make every downstream consumer — accounting, analytics, the fee
        // reconciliation — compute a price against an input that never traded.
        emit Swapped(
            msg.sender,
            desc.tokenIn,
            desc.tokenOut,
            desc.recipient,
            received - refunded,
            amountOut,
            grossOut - amountOut,
            paths.length,
            hopCount
        );
        if (refunded != 0) emit PartiallyFilled(msg.sender, desc.tokenIn, received, received - refunded);
    }

    /// @dev NATIVE resolves to WETH; everything else is itself.
    function _effective(address token) private view returns (address) {
        return token == NATIVE ? address(weth) : token;
    }

    /// @dev Pulls the input and returns what ACTUALLY arrived.
    ///      Everything downstream uses this figure, never `desc.amountIn` — the
    ///      two differ under a fee-on-transfer token, and using the requested
    ///      amount would try to spend tokens the router does not hold.
    function _pullInput(SwapDescription calldata desc) private returns (uint256 received) {
        if (desc.tokenIn == NATIVE) {
            if (msg.value != desc.amountIn) revert NativeAmountMismatch();
            weth.deposit{value: msg.value}();
            // WETH is not fee-on-transfer, so the deposit is exact by
            // construction. Measured anyway rather than assumed, because this
            // is the one place the invariant is cheap to keep honest.
            received = msg.value;
        } else {
            if (msg.value != 0) revert NativeNotExpected();
            address token = desc.tokenIn;
            uint256 before = IERC20(token).balanceOf(address(this));
            IERC20(token).safeTransferFrom(msg.sender, address(this), desc.amountIn);
            received = IERC20(token).balanceOf(address(this)) - before;
        }
        if (received == 0) revert NothingReceived();
    }

    /// @dev Runs every path and returns the total measured output.
    function _executePaths(SwapDescription calldata desc, Path[] calldata paths, uint256 received)
        private
        returns (uint256 grossOut, uint256 hopCount, uint256 refunded)
    {
        uint256 pathCount = paths.length;
        if (pathCount == 0) revert NoPaths();

        // Validated BEFORE anything executes. Accumulating the sum inside the
        // execution loop let an over-allocating vector spend real money and then
        // revert with an arithmetic panic out of `received - spent`, instead of
        // the error that names the actual problem — after burning the gas for
        // the whole route.
        uint256 portionSum;
        for (uint256 i; i < pathCount; ++i) {
            if (paths[i].hops.length == 0) revert EmptyPath();
            portionSum += paths[i].portionBps;
        }
        if (portionSum != BPS) revert PortionsMustSumToBps();

        address tokenInEff = _effective(desc.tokenIn);
        address tokenOutEff = _effective(desc.tokenOut);

        uint256 outBefore = IERC20(tokenOutEff).balanceOf(address(this));

        uint256 spent;
        for (uint256 i; i < pathCount; ++i) {
            Path calldata p = paths[i];
            // The LAST path absorbs the rounding remainder so no wei is
            // stranded in this contract. Splitting `received` by bps otherwise
            // leaves dust that I4 would then have to explain.
            uint256 pathIn = i == pathCount - 1 ? received - spent : (received * p.portionBps) / BPS;
            if (pathIn == 0) revert InvalidAmount();
            spent += pathIn;

            hopCount += p.hops.length;
            uint256 consumedIn = _executePath(p, pathIn, tokenInEff, tokenOutEff, desc.partiallyFillable);
            // Accumulated across paths, so a split route where only one leg
            // hits its limit still returns exactly what went unspent.
            refunded += pathIn - consumedIn;
        }

        // The ONLY place output is measured, and it is a delta rather than a
        // balance. See invariant I3.
        grossOut = IERC20(tokenOutEff).balanceOf(address(this)) - outBefore;

        // Hand the unspent input back to the PAYER, not to `desc.recipient`.
        //
        // They are different parties in the general case, and the input is the
        // payer's money: `desc.recipient` was named to receive the OUTPUT of a
        // trade. Sending them the unsold remainder of someone else's tokens
        // would be a transfer nobody authorised.
        //
        // Native input is refunded as ETH, because that is what the payer sent.
        // Returning WETH would silently change the asset they get back.
        if (refunded != 0) {
            if (desc.tokenIn == NATIVE) {
                weth.withdraw(refunded);
                (bool ok,) = msg.sender.call{value: refunded}("");
                if (!ok) revert NothingReceived();
            } else {
                IERC20(tokenInEff).safeTransfer(msg.sender, refunded);
            }
        }
    }

    /// @dev One path, hop by hop. Each hop's output funds the next.
    function _executePath(
        Path calldata p,
        uint256 amountIn,
        address tokenInEff,
        address tokenOutEff,
        bool partiallyFillable
    ) private returns (uint256 consumedIn) {
        uint256 hops = p.hops.length;
        address currentToken = tokenInEff;
        uint256 currentAmount = amountIn;

        for (uint256 j; j < hops; ++j) {
            Hop calldata h = p.hops[j];
            PoolInfo memory info = pools[h.pool];
            if (info.venue == Venue.NONE) revert PoolNotAllowlisted(h.pool);
            if (!info.enabled || blocked[h.pool]) revert PoolDisabled(h.pool);

            address hopIn;
            address hopOut;
            if (info.venue == Venue.WOOFI) {
                // WooFi's PoolInfo tokens are NOT authoritative — one contract
                // serves many pairs and the struct only remembers the first.
                // The input is whatever this hop received; the output has to
                // come from somewhere, and a {Hop} carries no token field.
                //
                // So a WooFi hop must be TERMINAL, where the output is pinned
                // by `desc.tokenOut`. That covers every WooFi route the
                // off-chain router actually produces (it wins as a single hop),
                // and refusing the ambiguous case beats guessing at it.
                if (j != hops - 1) revert WooFiMustBeTerminalHop();
                hopIn = currentToken;
                hopOut = tokenOutEff;
                (address a0, address a1) = hopIn < hopOut ? (hopIn, hopOut) : (hopOut, hopIn);
                if (!wooPairs[h.pool][_pairKey(a0, a1)]) revert WooPairNotRegistered(h.pool);
            } else {
                (hopIn, hopOut) = h.zeroForOne ? (info.token0, info.token1) : (info.token1, info.token0);
            }

            // Continuity, checked per hop rather than trusted. Without this a
            // caller could chain pools that do not connect and the router would
            // spend tokens it holds for an unrelated reason.
            if (j == 0) {
                if (hopIn != tokenInEff) revert PathStartMismatch();
            } else if (hopIn != currentToken) {
                revert PathDiscontinuity();
            }

            // The FINAL hop always lands in this contract, never in
            // `desc.recipient`: the balance-delta measurement has to happen
            // somewhere we control, the fee needs one custody point, and
            // parallel paths converging on the same token need one measurement.
            // **Only the first hop may truncate**, and this one-line
            // difference is the whole of multi-hop partial fill.
            //
            // Every hop still carries its own price limit, so the route's price
            // is bounded at every leg — the alternative of limiting only the
            // entry hop leaves the rest of the route unguaranteed and is
            // rejected. What differs is what a bound limit is ALLOWED to do:
            //
            //   * hop 0 truncating leaves unspent `tokenIn`, which is the
            //     payer's own money and goes straight back to them;
            //   * a later hop truncating would leave an INTERMEDIATE token the
            //     payer never held. Handing it over gives them an asset they
            //     did not ask for; keeping it strands value here and falsifies
            //     I4. Neither is acceptable, so it reverts instead.
            //
            // The protection is not weakened by that: a later hop whose limit
            // binds means the route cannot be filled at the price asked for,
            // and refusing is exactly what a limit is for. The caller gets
            // nothing rather than a bad price.
            //
            // Sizing stays off-chain. The solver picks the per-hop limits from
            // the depth it can see; this contract only enforces them. CoW's
            // settlement contract draws the same line — it checks the result
            // against the limit and records what executed, it does not compute
            // how much fits.
            (uint256 out, uint256 hopConsumed) =
                _executeHop(info, h.pool, hopIn, hopOut, currentAmount, h.sqrtPriceLimitX96, partiallyFillable);

            if (j == 0) {
                consumedIn = hopConsumed;
            } else if (hopConsumed != currentAmount) {
                // Judged HERE rather than inside the hop, so the error can say
                // which hop failed and why. A caller who asked for
                // `partiallyFillable` and got a bare `PartialFill` would
                // reasonably conclude the flag was ignored; this tells them the
                // truth — partial was allowed, and it was allowed in the one
                // place a shortfall can be given back.
                revert PartialFillOnLaterHop(h.pool, hopConsumed, currentAmount);
            }

            emit Routed(h.pool, info.venue, hopIn, hopOut, currentAmount, out);
            currentToken = hopOut;
            currentAmount = out;
        }

        if (currentToken != tokenOutEff) revert PathEndMismatch();
    }

    /// @dev Dispatch to the venue. Returns the MEASURED output of this hop.
    function _executeHop(
        PoolInfo memory info,
        address pool,
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint160 sqrtPriceLimitX96,
        bool partiallyFillable
    ) private returns (uint256 out, uint256 consumed) {
        uint256 before = IERC20(tokenOut).balanceOf(address(this));

        // Every venue that cannot self-limit consumes everything it is given,
        // so `consumed` defaults to the full amount and only the CL branch
        // narrows it.
        consumed = amountIn;

        if (info.venue == Venue.UNIV3 || info.venue == Venue.SLIPSTREAM) {
            consumed = _swapConcentrated(pool, tokenIn, amountIn, info.token0 == tokenIn, sqrtPriceLimitX96, partiallyFillable);
        } else if (info.venue == Venue.UNIV4) {
            // Concentrated liquidity too, so it sits ABOVE the price-limit
            // refusal below: v4 honours a per-hop limit exactly as V3 does.
            consumed = _swapUniV4(pool, amountIn, info.token0 == tokenIn, sqrtPriceLimitX96, partiallyFillable);
        } else if (sqrtPriceLimitX96 != 0) {
            // Refused, never ignored. Only concentrated liquidity can stop at a
            // price; Solidly, DODO and WooFi consume whatever they are given.
            //
            // Dropping the limit silently is the worst option available: the
            // caller priced the trade believing they were protected, and the
            // failure is invisible until they read the fill. Reverting costs
            // them a transaction; ignoring costs them the difference between
            // their limit and whatever the pool felt like paying.
            revert PriceLimitUnsupported(pool);
        } else if (info.venue == Venue.SOLIDLY_V2) {
            _swapSolidly(pool, tokenIn, tokenOut, amountIn, info);
        } else if (info.venue == Venue.DODO) {
            _swapDodo(pool, tokenIn, amountIn, info);
        } else if (info.venue == Venue.WOOFI) {
            _swapWooFi(pool, tokenIn, tokenOut, amountIn);
        } else {
            revert VenueUnsupported();
        }

        // Measured, never taken from the venue's return value. A venue that
        // reports one number and transfers another cannot mislead the floor.
        out = IERC20(tokenOut).balanceOf(address(this)) - before;

        // A zero fill on a PUSH-funded venue is an unrecoverable donation: the
        // input has already left this contract and nothing came back. DODO in
        // particular returns 0 rather than reverting when it cannot serve the
        // direction asked of it, so nothing else catches this. The CL venues
        // cannot reach here with zero — their callback would not have run.
        //
        // A price limit that binds so hard nothing fills lands here too, and it
        // is right that it reverts: a caller asked for a price the market
        // cannot pay, and telling them so beats a zero-output success they have
        // to detect themselves.
        if (out == 0) revert ZeroOutput(pool);
    }

    // -----------------------------------------------------------------------
    // Venue executors
    // -----------------------------------------------------------------------

    /// @dev Uniswap V3 / PancakeSwap V3 / Slipstream. The pool PULLS via a
    ///      callback, so the pin is armed immediately before the call and must
    ///      be consumed by the time it returns.
    function _swapConcentrated(
        address pool,
        address tokenIn,
        uint256 amountIn,
        bool zeroForOne,
        uint160 sqrtPriceLimitX96,
        bool partiallyFillable
    ) private returns (uint256 consumed) {
        TransientPin.arm(pool, tokenIn, amountIn);
        (int256 a0, int256 a1) = ICLPool(pool)
            .swap(
                address(this),
                zeroForOne,
                // POSITIVE means exact input. Negative would mean exact output,
                // which this router never asks a pool for.
                int256(amountIn),
                // The caller's limit, or the no-limit sentinel when they set
                // none. The sentinel is deliberately NOT `0`: zero is out of
                // the pool's valid range and it reverts on it, so the two have
                // to be translated here rather than passed through.
                sqrtPriceLimitX96 == 0
                    ? (zeroForOne ? MIN_SQRT_RATIO + 1 : MAX_SQRT_RATIO - 1)
                    : sqrtPriceLimitX96,
                // Empty. The callback derives everything from the pin, so there is
                // nothing here for a hostile pool to forge.
                bytes("")
            );
        // Positive proof the callback ran exactly once, and the guarantee that
        // no pin survives into the next call of a batched transaction.
        TransientPin.requireConsumed();

        // A CL pool exits its loop with input REMAINING when in-range
        // liquidity runs out, or when it reaches the caller's price limit. It
        // can therefore legitimately consume less than it was offered.
        //
        // This line is now the ONLY guard on that, and it is deliberate. The
        // pin used to reject an honest short fill first, by requiring the
        // callback to ask for exactly what was armed; it is a ceiling now, so
        // both the honest case (pool asks for less and reports less) and the
        // hostile one (pool asks for everything and reports less) arrive here
        // and are judged by the same rule. That is the "change in BOTH places"
        // this comment used to promise.
        //
        // Fill-or-kill still fails loudly, which keeps every existing caller's
        // behaviour byte for byte. Under `partiallyFillable` the shortfall is
        // returned to the payer by {_executePaths}; nothing is stranded here
        // either way, so I4 holds in both modes.
        consumed = uint256(zeroForOne ? a0 : a1);
        if (!partiallyFillable && consumed != amountIn) {
            revert PartialFill(pool, consumed, amountIn);
        }
    }

    /// @dev Aerodrome v2 and other Solidly forks. PUSH funded: transfer first,
    ///      then swap. `data` is empty, so `IPoolCallee.hook` never fires and
    ///      the pool has no path back into this contract.
    function _swapSolidly(address pool, address tokenIn, address tokenOut, uint256 amountIn, PoolInfo memory info)
        private
    {
        IERC20(tokenIn).safeTransfer(pool, amountIn);

        // `balanceOf(pool) - reserveIn` is the authoritative input: it is the
        // same quantity the pool's own K-check uses, so it stays correct under
        // fee-on-transfer, under pre-funding, and under third-party donation.
        (uint256 r0, uint256 r1,) = ISolidlyPool(pool).getReserves();
        bool inIsToken0 = tokenIn == info.token0;
        uint256 reserveIn = inIsToken0 ? r0 : r1;
        uint256 actualIn = IERC20(tokenIn).balanceOf(pool) - reserveIn;

        uint256 out = ISolidlyPool(pool).getAmountOut(actualIn, tokenIn);
        (uint256 amount0Out, uint256 amount1Out) = inIsToken0 ? (uint256(0), out) : (out, uint256(0));
        ISolidlyPool(pool).swap(amount0Out, amount1Out, address(this), bytes(""));
        // `tokenOut` is unused here beyond documenting intent; the pool decides
        // which side it pays from the amountOut arguments above.
        tokenOut;
    }

    /// @dev DODO V2. PUSH funded, and base/quote oriented: the two directions
    ///      are DIFFERENT FUNCTIONS. `baseIsToken0` comes from the allowlist,
    ///      where it was read from the pool itself during registration.
    function _swapDodo(address pool, address tokenIn, uint256 amountIn, PoolInfo memory info) private {
        IERC20(tokenIn).safeTransfer(pool, amountIn);
        address base = info.baseIsToken0 ? info.token0 : info.token1;
        if (tokenIn == base) {
            IDODOV2Pool(pool).sellBase(address(this));
        } else {
            IDODOV2Pool(pool).sellQuote(address(this));
        }
    }

    /// @dev WooFi WooPPV2. PUSH funded like the others.
    ///      `minToAmount` is 0 here ON PURPOSE: the only floor that matters is
    ///      the route-level `minAmountOut` checked in {_settle}, and a per-hop
    ///      floor would make an otherwise fine route revert on an intermediate
    ///      leg. `rebateTo` is this contract; it is a referral credit and
    ///      cannot redirect output.
    function _swapWooFi(address pool, address tokenIn, address tokenOut, uint256 amountIn) private {
        IERC20(tokenIn).safeTransfer(pool, amountIn);
        IWooPPV2(pool).swap(tokenIn, tokenOut, amountIn, 0, address(this), address(this));
    }

    /// @dev Uniswap v4. Neither PUSH nor PULL: the swap runs inside a
    ///      flash-accounting session the router opens on the singleton
    ///      PoolManager, and {unlockCallback} settles both sides before the
    ///      session may close — the manager itself reverts the whole hop if
    ///      any delta is left unsettled, which makes I4 enforced by the venue
    ///      rather than merely asserted by our tests.
    ///
    ///      One session per hop, not per route. A route-wide session would
    ///      save a little gas and cost the entire hop-loop architecture: the
    ///      continuity checks, the per-hop `Routed` event, and mixed-venue
    ///      paths (a v3 hop cannot run inside a v4 unlock without this
    ///      contract becoming a different design).
    ///
    ///      The pin is armed with the RAW input currency — `address(0)` for
    ///      native — and the callback settles whatever the pin says, bounded
    ///      by what it was armed with. Everything else the callback needs
    ///      travels through `unlock`'s data parameter, which the manager
    ///      hands back verbatim; it is trustworthy because the manager only
    ///      ever calls back the account that called `unlock`.
    function _swapUniV4(
        address handle,
        uint256 amountIn,
        bool zeroForOne,
        uint160 sqrtPriceLimitX96,
        bool partiallyFillable
    ) private returns (uint256 consumed) {
        V4PoolKey memory key = v4Keys[handle];
        address currencyIn = zeroForOne ? key.currency0 : key.currency1;

        TransientPin.arm(address(poolManager), currencyIn, amountIn);
        bytes memory result = poolManager.unlock(abi.encode(key, zeroForOne, amountIn, sqrtPriceLimitX96));
        // Positive proof the callback ran exactly once — same guarantee, same
        // batched-transaction hygiene, as the concentrated-liquidity path.
        TransientPin.requireConsumed();

        consumed = abi.decode(result, (uint256));
        // The same judgment `_swapConcentrated` applies: v4 exits with input
        // remaining when in-range liquidity runs out or the price limit
        // binds. Fill-or-kill refuses the short fill; under
        // `partiallyFillable` the shortfall goes back to the payer in
        // {_executePaths}.
        if (!partiallyFillable && consumed != amountIn) {
            revert PartialFill(handle, consumed, amountIn);
        }
    }

    // -----------------------------------------------------------------------
    // Callbacks
    // -----------------------------------------------------------------------

    /// @notice Uniswap V3 and Aerodrome Slipstream pay themselves through this.
    /// @dev NOT `nonReentrant`. It runs inside `pool.swap`, inside the `swap()`
    ///      frame that already holds the lock, so guarding it too would make
    ///      every concentrated-liquidity swap revert. Someone will try to "fix"
    ///      that during a later hardening pass; this comment is why they should
    ///      not. Its security comes from the pin, not the guard.
    function uniswapV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata) external {
        _payCallback(amount0Delta, amount1Delta);
    }

    /// @notice PancakeSwap V3 renamed the callback, so it needs its own entry
    ///         point with a different selector. Same body, same authentication.
    function pancakeV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata) external {
        _payCallback(amount0Delta, amount1Delta);
    }

    /// @notice The Uniswap v4 PoolManager re-enters here inside
    ///         {_swapUniV4}'s `unlock` call.
    /// @dev NOT `nonReentrant`, for the same reason {uniswapV3SwapCallback} is
    ///      not: it runs inside the `swap()` frame that already holds the
    ///      lock. Its security comes from two places — the explicit
    ///      `msg.sender` check below, and the pin, which is one-shot, bounds
    ///      the amount, and fixes the currency being paid.
    ///
    ///      Sign conventions here are INVERTED from the V3 callback and that
    ///      is v4's doing, not a choice: `amountSpecified` is NEGATIVE for
    ///      exact input, and in the returned delta a NEGATIVE amount is owed
    ///      to the pool where V3's positive one was.
    function unlockCallback(bytes calldata data) external returns (bytes memory) {
        // Checked before anything executes, not just before anything is paid.
        // Without it, any caller could drive this function's PoolManager
        // calls; they would revert outside an unlock session, but "reverts
        // today" is not an authentication.
        if (msg.sender != address(poolManager)) revert TransientPin.UnauthorizedCallback();

        (V4PoolKey memory key, bool zeroForOne, uint256 amountIn, uint160 limit) =
            abi.decode(data, (V4PoolKey, bool, uint256, uint160));

        int256 delta = poolManager.swap(
            key,
            V4SwapParams({
                zeroForOne: zeroForOne,
                // NEGATIVE means exact input in v4 — the mirror image of the
                // V3 pools' convention used in {_swapConcentrated}.
                amountSpecified: -int256(amountIn),
                // The same sentinel translation as V3: zero is not a valid
                // sqrt price and the pool reverts on it, so "no limit" becomes
                // the directional bound. v4's TickMath carries V3's values.
                sqrtPriceLimitX96: limit == 0 ? (zeroForOne ? MIN_SQRT_RATIO + 1 : MAX_SQRT_RATIO - 1) : limit
            }),
            // Empty on principle: this router registers only hookless pools,
            // so there is nothing to say and nobody listening.
            bytes("")
        );

        // BalanceDelta: amount0 in the upper 128 bits, amount1 in the lower,
        // both signed, from this contract's perspective.
        int128 a0;
        int128 a1;
        assembly ("memory-safe") {
            a0 := sar(128, delta)
            a1 := signextend(15, delta)
        }
        (int128 inDelta, int128 outDelta) = zeroForOne ? (a0, a1) : (a1, a0);
        // A hookless pool cannot owe us on the input side or charge us on the
        // output side of an exact-input swap. Checked anyway: these two signs
        // are the entire settlement logic's foundation.
        if (inDelta > 0 || outDelta < 0) revert InvalidAmount();
        uint256 owed = uint256(uint128(-inDelta));
        uint256 received = uint256(uint128(outDelta));

        // Authenticates against the pin, bounds `owed` by what was armed,
        // fixes the currency being paid, and CLEARS the pin — all before any
        // value moves, exactly as the V3 callback orders it.
        address currencyIn = TransientPin.consume(msg.sender, owed);

        if (currencyIn == address(0)) {
            // The route runs on WETH internally; v4's native pools run on ETH.
            // The two meet here and nowhere else: unwrap exactly what is owed,
            // settle it as msg.value.
            weth.withdraw(owed);
            poolManager.settle{value: owed}();
        } else {
            // ERC-20 settlement is sync -> transfer -> settle. A plain
            // transfer, never an approval — invariant I2 holds in v4 too.
            poolManager.sync(currencyIn);
            IERC20(currencyIn).safeTransfer(address(poolManager), owed);
            poolManager.settle();
        }

        address currencyOut = zeroForOne ? key.currency1 : key.currency0;
        if (currencyOut == address(0)) {
            // Take ETH, wrap it immediately: the hop loop measures its output
            // as a WETH balance delta like every other hop's.
            poolManager.take(address(0), address(this), received);
            weth.deposit{value: received}();
        } else {
            poolManager.take(currencyOut, address(this), received);
        }

        return abi.encode(owed);
    }

    /// @dev A POSITIVE delta is what we owe the pool; a negative one is what it
    ///      sent us. Exactly one is positive for a single-sided exact-input
    ///      swap.
    function _payCallback(int256 amount0Delta, int256 amount1Delta) private {
        uint256 owed = amount0Delta > 0 ? uint256(amount0Delta) : (amount1Delta > 0 ? uint256(amount1Delta) : 0);
        if (owed == 0) revert InvalidAmount();

        // Authenticates the caller, bounds the amount, and CLEARS the pin —
        // all before the transfer below, so a token with a transfer hook
        // re-enters into a disarmed router.
        address token = TransientPin.consume(msg.sender, owed);
        IERC20(token).safeTransfer(msg.sender, owed);
    }

    // -----------------------------------------------------------------------
    // Settlement
    // -----------------------------------------------------------------------

    /// @dev Fee, floor, payout — in that order, and the order is the point.
    ///
    ///      `minAmountOut` is checked on the POST-fee amount. `feeBps` is
    ///      mutable, so a transaction built and signed while it was 0 can mine
    ///      after the owner sets it to 25. If the fee came off AFTER the floor
    ///      check, that user silently receives less than their signature was
    ///      predicated on — the classic surprise-fee finding. Checking the
    ///      floor on `gross - fee` makes such a transaction REVERT instead, so
    ///      the guaranteed minimum is a real guarantee.
    function _settle(SwapDescription calldata desc, uint256 grossOut, uint16 fee) private returns (uint256 userOut) {
        uint256 feeAmount = fee == 0 ? 0 : (grossOut * fee) / BPS;
        userOut = grossOut - feeAmount;
        if (userOut < desc.minAmountOut) revert InsufficientOutput(userOut, desc.minAmountOut);

        address tokenOutEff = _effective(desc.tokenOut);

        // Transferred immediately rather than accrued. An accrued balance would
        // break I4 and would leave I3 as the only thing between a griefer and
        // the protocol's fees.
        if (feeAmount != 0) {
            IERC20(tokenOutEff).safeTransfer(feeRecipient, feeAmount);
        }

        if (desc.tokenOut == NATIVE) {
            weth.withdraw(userOut);
            // One of exactly TWO value-bearing external calls here; {rescueNative}
            // is the other. Both send ETH with empty calldata.
            (bool ok,) = desc.recipient.call{value: userOut}("");
            if (!ok) revert NothingReceived();
        } else {
            // Measured at the RECIPIENT, not asserted from our own arithmetic.
            // A transfer-taxed `tokenOut` would otherwise pass the floor check
            // above and deliver strictly less, with no revert anywhere. The
            // token whitelist is meant to exclude such tokens; this makes that
            // policy enforced rather than assumed.
            uint256 rBefore = IERC20(tokenOutEff).balanceOf(desc.recipient);
            IERC20(tokenOutEff).safeTransfer(desc.recipient, userOut);
            uint256 delivered = IERC20(tokenOutEff).balanceOf(desc.recipient) - rBefore;
            if (delivered < desc.minAmountOut) revert InsufficientOutput(delivered, desc.minAmountOut);
        }
    }

    /// @notice Accepts ETH only from WETH and — when v4 is configured — the
    ///         PoolManager, whose `take` of a native currency pays this way.
    /// @dev Anything else would be an untracked donation that I4 then has to
    ///      explain, and {rescueNative} would have to be able to remove.
    ///      `poolManager` can be `address(0)`; `msg.sender` never is.
    receive() external payable {
        if (msg.sender != address(weth) && msg.sender != address(poolManager)) revert UnexpectedNative();
    }

    // -----------------------------------------------------------------------
    // Pre-flight views
    // -----------------------------------------------------------------------

    /// @notice Batch-check pools before building a transaction.
    /// @dev The point is to move a revert off the money path. A route naming a
    ///      pool that was disabled since it was quoted costs the user gas and
    ///      an opaque failure; the backend calls this once and re-routes
    ///      instead. One `eth_call`, two SLOADs per pool, no execution.
    function poolsRoutable(address[] calldata candidates) external view returns (bool[] memory ok) {
        ok = new bool[](candidates.length);
        for (uint256 i; i < candidates.length; ++i) {
            PoolInfo storage info = pools[candidates[i]];
            ok[i] = info.venue != Venue.NONE && info.enabled && !blocked[candidates[i]];
        }
    }

    /// @notice Dry-run every non-executing check {swap} would apply.
    /// @dev Returns a reason string rather than reverting, so a caller learns
    ///      WHICH rule a route breaks in one call instead of bisecting reverts.
    ///      Deliberately does not simulate the swap: output depends on live
    ///      pool state, and a view that pretended otherwise would be a worse
    ///      lie than no view at all. Use `/v1/quote` for amounts.
    /// @return valid True when {swap} would get past validation.
    /// @return reason Empty when valid; otherwise the first rule broken.
    function validateRoute(SwapDescription calldata desc, Path[] calldata paths)
        external
        view
        returns (bool valid, string memory reason)
    {
        return SwapAdminLib.validateRoute(
            pools, blocked, wooPairs, desc, paths, address(this), address(weth), feeBps, paused()
        );
    }

    /// @notice The fee a swap would pay right now, for display.
    /// @dev So a UI can show "you receive X after a 0.1% fee" without
    ///      simulating anything. Reading the LIVE fee, not a cached one, is the
    ///      point: it is the number `swap` will actually apply this block.
    function quoteFee(uint256 grossOut) external view returns (uint16 bps, uint256 feeAmount, uint256 userReceives) {
        bps = feeBps;
        feeAmount = bps == 0 ? 0 : (grossOut * bps) / BPS;
        userReceives = grossOut - feeAmount;
    }

    // -----------------------------------------------------------------------
    // Allowlist
    // -----------------------------------------------------------------------

    /// @notice Register a pool, proving it to the factory rather than trusting
    ///         the registrant.
    /// @dev The round-trip is what makes the pool's self-declared `factory()`
    ///      unforgeable: a fake pool would have to make a REAL factory return
    ///      its address, and only that factory's `createPool` can do that.
    ///      This is also what removes the "every new pool needs an owner
    ///      transaction" cost that makes on-chain allowlists look expensive.
    function registerPool(address pool) external whenNotPaused {
        _requireRegistrationOpen();
        _registerPool(pool);
    }

    /// @notice Register many pools in one call. Atomic: one bad address reverts
    ///         the whole batch. Empty is a no-op. Same auth as {registerPool}.
    function registerPools(address[] calldata poolList) external whenNotPaused {
        _requireRegistrationOpen();
        uint256 n = poolList.length;
        for (uint256 i; i < n; ++i) {
            _registerPool(poolList[i]);
        }
    }

    function _requireRegistrationOpen() private view {
        if (!permissionlessRegistration && msg.sender != owner()) revert RegistrationClosed();
    }

    function _registerPool(address pool) private {
        SwapAdminLib.registerPool(pools, factoryVenue, blocked, pool);
    }

    /// @notice Register a Uniswap v4 pool by its key.
    /// @dev There is no factory to round-trip, and none is needed: the pool id
    ///      IS `keccak256(abi.encode(key))`, so a key the PoolManager holds a
    ///      non-zero price for is exactly the key some `initialize` call was
    ///      given. Self-attesting, with nothing for the registrant to lie
    ///      about — the same property the factory round-trip buys elsewhere,
    ///      which is why this shares {registerPool}'s auth rather than the
    ///      owner-only escape hatches'.
    ///
    ///      What is REFUSED is policy, not plumbing: hooked pools. A hook can
    ///      take its own deltas, change its fee between quoting and mining, or
    ///      re-enter the router mid-swap. Each of those breaks the
    ///      quote-equals-execution property this system is built around, so
    ///      `hooks == address(0)` is a registration invariant, not a default.
    ///
    ///      A native-currency pool (`currency0 == address(0)`) is recorded
    ///      with WETH as its effective token0. The route always runs on WETH
    ///      internally; {unlockCallback} unwraps and wraps at the manager's
    ///      edge, and nothing outside it ever sees the difference.
    function registerUniV4(V4PoolKey calldata key) external whenNotPaused {
        _requireRegistrationOpen();
        _registerUniV4(key);
    }

    /// @notice Register many v4 pools in one call. Atomic: one bad key reverts
    ///         the whole batch. Empty is a no-op. Same auth as {registerUniV4}.
    function registerUniV4Pools(V4PoolKey[] calldata keys) external whenNotPaused {
        _requireRegistrationOpen();
        uint256 n = keys.length;
        for (uint256 i; i < n; ++i) {
            _registerUniV4(keys[i]);
        }
    }

    /// @notice The handle a v4 key registers under, and its full pool id.
    /// @dev The handle is the FIRST 20 bytes (most significant) of the id.
    ///      Public because the off-chain router, the registration scripts and
    ///      the tests must all derive the identical address; this function is
    ///      the definition they cite.
    function v4Handle(V4PoolKey memory key) public pure returns (address handle, bytes32 poolId) {
        return SwapAdminLib.v4Handle(key);
    }

    function _registerUniV4(V4PoolKey calldata key) private {
        SwapAdminLib.registerUniV4(pools, v4Keys, blocked, key, address(poolManager), address(weth));
    }

    /// @notice Register a DODO V2 pool.
    /// @dev Takes the factory as an ARGUMENT rather than reading `pool.factory()`,
    ///      because DODO pools do not expose one — that is why this cannot go
    ///      through {_attest}. Everything else is still proven rather than
    ///      trusted: base and quote are read from the pool itself, and the
    ///      factory is asked whether it minted this address.
    ///
    ///      Reading the orientation from the pool is the point. Taking
    ///      `baseIsToken0` on the owner's word invites a transposition, and a
    ///      transposed pool pushes the input and then calls the WRONG sell
    ///      function — which DODO answers with 0 rather than a revert, leaving
    ///      the input as unaccounted balance for the next caller to claim.
    function registerDodo(address pool, address factory) external onlyOwner {
        _registerDodo(pool, factory);
    }

    /// @notice Register many DODO V2 pools minted by one factory. Atomic.
    ///         Empty is a no-op. Same auth as {registerDodo}.
    function registerDodos(address factory, address[] calldata poolList) external onlyOwner {
        uint256 n = poolList.length;
        for (uint256 i; i < n; ++i) {
            _registerDodo(poolList[i], factory);
        }
    }

    function _registerDodo(address pool, address factory) private {
        SwapAdminLib.registerDodo(pools, factoryVenue, blocked, pool, factory);
    }

    /// @notice Register a WooFi WooPPV2 pair.
    /// @dev Owner-only and never permissionless, because WooFi has no factory
    ///      to attest against — there is no third party here whose word we can
    ///      check, so the owner's is the only one available. The pair is
    ///      recorded per token pair even though one contract serves them all.
    function registerWooFi(address wooPP, address tokenA, address tokenB) external onlyOwner {
        _registerWooFi(wooPP, tokenA, tokenB);
    }

    /// @notice Register many WooFi pairs against one WooPP. Atomic. Empty is a
    ///         no-op. `tokenA` and `tokenB` must be the same length.
    function registerWooFiPairs(address wooPP, address[] calldata tokenA, address[] calldata tokenB)
        external
        onlyOwner
    {
        if (tokenA.length != tokenB.length) revert LengthMismatch();
        uint256 n = tokenA.length;
        for (uint256 i; i < n; ++i) {
            _registerWooFi(wooPP, tokenA[i], tokenB[i]);
        }
    }

    function _registerWooFi(address wooPP, address tokenA, address tokenB) private {
        SwapAdminLib.registerWooFi(pools, wooPairs, wooPairKnown, factoryVenue, blocked, wooPP, tokenA, tokenB);
    }

    /// @notice Remove one WooFi pair without touching the others.
    function setWooPairEnabled(address wooPP, address tokenA, address tokenB, bool enabled) external {
        if (enabled) {
            if (msg.sender != owner()) revert NotOwnerOrGuardian();
        } else if (msg.sender != owner() && msg.sender != guardian) {
            revert NotOwnerOrGuardian();
        }
        (address t0, address t1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
        bytes32 key = _pairKey(t0, t1);
        // An explicit owner enable marks the pair known, so a later
        // {registerWooFi} treats it as existing and does not re-arm it.
        if (enabled) wooPairKnown[wooPP][key] = true;
        wooPairs[wooPP][key] = enabled;
        emit WooPairEnabledSet(wooPP, t0, t1, enabled);
    }

    function _pairKey(address t0, address t1) private pure returns (bytes32) {
        return keccak256(abi.encodePacked(t0, t1));
    }

    /// @notice Whether this WooPP pair has ever been registered, in either token
    ///         order. Lets the registration script skip pairs already listed
    ///         instead of re-arming one the guardian disabled.
    function isWooPairKnown(address wooPP, address tokenA, address tokenB) external view returns (bool) {
        (address t0, address t1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
        return wooPairKnown[wooPP][_pairKey(t0, t1)];
    }

    /// @notice Register a DODO DPP pool WITHOUT factory attestation.
    ///
    /// @dev Named for what it does not do. This is the escape hatch for DODO DPP
    ///      pools, which expose neither `factory()` nor factory enumeration, so
    ///      no third party can vouch for them and the owner's word is the only
    ///      attestation available. {registerDodo} handles every DODO pool that IS
    ///      reachable through its factory and should be preferred always.
    ///
    ///      It used to be a same-named overload of {registerDodo}, which was a
    ///      trap: two functions, one name, different arities, and silently
    ///      different security properties. An operator who meant the attested
    ///      path and passed three arguments got an unattested registration with
    ///      no error — and since {_swapDodo} PUSHES tokens to the pool before
    ///      calling it, a mistyped address here is unrecoverable.
    ///
    ///      It now enforces the two rules every other registration path obeys:
    ///      a blocked pool cannot be registered, and registration never raises
    ///      `enabled` on a pool that is already known. Without the second, this
    ///      function silently reverted a guardian's `setPoolEnabled(pool, false)`.
    /// @param pool The DODO DPP pool address
    /// @param baseToken The base token — fixes the orientation the sellBase /
    ///        sellQuote dispatch reads
    /// @param quoteToken The quote token
    function registerDodoUnattested(address pool, address baseToken, address quoteToken) external onlyOwner {
        SwapAdminLib.registerDodoUnattested(pools, blocked, pool, baseToken, quoteToken);
    }

    /// @notice Enable or disable a registered pool.
    /// @dev Enabling is owner-only; DISABLING is also open to the guardian.
    ///      Asymmetric on purpose: revoking must be fast, granting must not be.
    function setPoolEnabled(address pool, bool enabled) external {
        if (enabled) {
            if (msg.sender != owner()) revert NotOwnerOrGuardian();
            // A blocked pool cannot be re-enabled without first being
            // unblocked, which is a separate, deliberate owner action.
            if (blocked[pool]) revert PoolBlocked(pool);
        } else if (msg.sender != owner() && msg.sender != guardian) {
            revert NotOwnerOrGuardian();
        }
        if (pools[pool].venue == Venue.NONE) revert PoolNotAllowlisted(pool);
        pools[pool].enabled = enabled;
        emit PoolEnabledSet(pool, enabled);
    }

    /// @notice Block a pool permanently until the owner clears it.
    /// @dev The guardian's real lever. Unlike `setPoolEnabled(_, false)` this
    ///      survives anyone re-registering the pool, so a hot key can take a
    ///      compromised venue out of service and it STAYS out.
    function setBlocked(address pool, bool value) external {
        if (value) {
            if (msg.sender != owner() && msg.sender != guardian) revert NotOwnerOrGuardian();
        } else if (msg.sender != owner()) {
            // Only the owner un-blocks. A guardian that could unblock could
            // undo the very response it holds the key for.
            revert NotOwnerOrGuardian();
        }
        blocked[pool] = value;
        if (value) pools[pool].enabled = false;
        emit PoolBlockedSet(pool, value);
    }

    /// @notice Map a factory to the venue it mints.
    /// @dev The trust root, and a timelock candidate. Registering Aerodrome's
    ///      `FactoryRegistry` here instead of the concrete factories would make
    ///      anything Aerodrome governance registers automatically routable in
    ///      this router — register the concrete factories only.
    function setFactoryVenue(address factory, Venue venue) external onlyOwner {
        if (factory == address(0)) revert ZeroAddress();
        factoryVenue[factory] = venue;
        emit FactoryVenueSet(factory, venue);
    }

    /// @notice Map several factories in ONE transaction.
    /// @dev Same rule as {registerPools}: the trust root is set atomically or
    ///      not at all. Wiring venues one transaction at a time leaves a window
    ///      in which some factories are trusted and others are not, and a
    ///      `registerPools` landing in that window silently drops every pool
    ///      whose factory has not been reached yet — the run reports success
    ///      and the allowlist is short.
    ///
    ///      Deploy cost is the visible part: Base curates six venues, so the
    ///      loop this replaces was six transactions and six base costs on the
    ///      chain where they are paid most often.
    function setFactoryVenues(address[] calldata factories, Venue[] calldata venues) external onlyOwner {
        if (factories.length != venues.length) revert LengthMismatch();
        for (uint256 i; i < factories.length; ++i) {
            if (factories[i] == address(0)) revert ZeroAddress();
            factoryVenue[factories[i]] = venues[i];
            emit FactoryVenueSet(factories[i], venues[i]);
        }
    }

    function setPermissionlessRegistration(bool enabled) external onlyOwner {
        permissionlessRegistration = enabled;
        emit PermissionlessRegistrationSet(enabled);
    }

    // -----------------------------------------------------------------------
    // Admin
    // -----------------------------------------------------------------------

    function setGuardian(address guardian_) external onlyOwner {
        emit GuardianSet(guardian, guardian_);
        guardian = guardian_;
    }

    /// @notice Set the protocol fee, bounded by {MAX_FEE_BPS}.
    function setFee(uint16 feeBps_, address feeRecipient_) external onlyOwner {
        if (feeBps_ > MAX_FEE_BPS) revert FeeAboveMax();
        if (feeBps_ != 0 && feeRecipient_ == address(0)) revert FeeRecipientRequired();
        feeBps = feeBps_;
        feeRecipient = feeRecipient_;
        emit FeeSet(feeBps_, feeRecipient_);
    }

    function pause() external onlyOwnerOrGuardian {
        _pause();
    }

    /// @dev Unpausing is owner-only. A guardian that could unpause could undo
    ///      the very response it was given the key for.
    function unpause() external onlyOwner {
        _unpause();
    }

    /// @notice Recover tokens sent here by mistake.
    /// @dev Acceptable ONLY because of I4: the router holds nothing between
    ///      transactions, and in-flight funds live inside one atomic frame.
    ///      `nonReentrant` here is what makes that true: OpenZeppelin's guard
    ///      only rejects entry into functions that CARRY the modifier, so
    ///      without it a token transfer hook fired mid-swap could rescue the
    ///      funds currently in flight. If an audit pushes back further, the
    ///      tightening is a rescue destination fixed at construction.
    function rescueTokens(address token, address to, uint256 amount) external onlyOwner nonReentrant {
        if (to == address(0)) revert ZeroAddress();
        IERC20(token).safeTransfer(to, amount);
        emit Rescued(token, to, amount);
    }

    function rescueNative(address to, uint256 amount) external onlyOwner nonReentrant {
        if (to == address(0)) revert ZeroAddress();
        (bool ok,) = to.call{value: amount}("");
        if (!ok) revert NothingReceived();
        emit Rescued(address(0), to, amount);
    }

    /// @dev Overridden to revert. An ownerless router cannot be paused, cannot
    ///      have a pool disabled, cannot be rescued, and — now that this is a
    ///      UUPS proxy — can never be upgraded again either. Every emergency
    ///      control depends on there being an owner.
    function renounceOwnership() public pure override {
        revert("renounce disabled");
    }

    /// @dev Reserved storage. Shrink this by one slot for each variable added
    ///      above, and never insert a variable anywhere but the end.
    uint256[42] private __gap;
}

lib/openzeppelin-contracts-upgradeable/contracts/access/Ownable2StepUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable2Step.sol)

pragma solidity ^0.8.0;

import "./OwnableUpgradeable.sol";
import "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module which provides access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership} and {acceptOwnership}.
 *
 * This module is used through inheritance. It will make available all functions
 * from parent (Ownable).
 */
abstract contract Ownable2StepUpgradeable is Initializable, OwnableUpgradeable {
    function __Ownable2Step_init() internal onlyInitializing {
        __Ownable_init_unchained();
    }

    function __Ownable2Step_init_unchained() internal onlyInitializing {
    }
    address private _pendingOwner;

    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);

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

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

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual override {
        delete _pendingOwner;
        super._transferOwnership(newOwner);
    }

    /**
     * @dev The new owner accepts the ownership transfer.
     */
    function acceptOwnership() public virtual {
        address sender = _msgSender();
        require(pendingOwner() == sender, "Ownable2Step: caller is not the new owner");
        _transferOwnership(sender);
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}

lib/openzeppelin-contracts-upgradeable/contracts/access/OwnableUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)

pragma solidity ^0.8.0;

import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    function __Ownable_init() internal onlyInitializing {
        __Ownable_init_unchained();
    }

    function __Ownable_init_unchained() internal onlyInitializing {
        _transferOwnership(_msgSender());
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}

lib/openzeppelin-contracts-upgradeable/contracts/interfaces/IERC1967Upgradeable.sol

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

pragma solidity ^0.8.0;

/**
 * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
 *
 * _Available since v4.8.3._
 */
interface IERC1967Upgradeable {
    /**
     * @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-upgradeable/contracts/interfaces/draft-IERC1822Upgradeable.sol

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

pragma solidity ^0.8.0;

/**
 * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
 * proxy whose upgrades are fully controlled by the current implementation.
 */
interface IERC1822ProxiableUpgradeable {
    /**
     * @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-upgradeable/contracts/proxy/ERC1967/ERC1967UpgradeUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/ERC1967/ERC1967Upgrade.sol)

pragma solidity ^0.8.2;

import "../beacon/IBeaconUpgradeable.sol";
import "../../interfaces/IERC1967Upgradeable.sol";
import "../../interfaces/draft-IERC1822Upgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/StorageSlotUpgradeable.sol";
import "../utils/Initializable.sol";

/**
 * @dev This abstract contract provides getters and event emitting update functions for
 * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
 *
 * _Available since v4.1._
 */
abstract contract ERC1967UpgradeUpgradeable is Initializable, IERC1967Upgradeable {
    function __ERC1967Upgrade_init() internal onlyInitializing {
    }

    function __ERC1967Upgrade_init_unchained() internal onlyInitializing {
    }
    // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
    bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;

    /**
     * @dev Storage slot with the address of the current implementation.
     * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
     * validated in the constructor.
     */
    bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

    /**
     * @dev Returns the current implementation address.
     */
    function _getImplementation() internal view returns (address) {
        return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
    }

    /**
     * @dev Stores a new address in the EIP1967 implementation slot.
     */
    function _setImplementation(address newImplementation) private {
        require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
        StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
    }

    /**
     * @dev Perform implementation upgrade
     *
     * Emits an {Upgraded} event.
     */
    function _upgradeTo(address newImplementation) internal {
        _setImplementation(newImplementation);
        emit Upgraded(newImplementation);
    }

    /**
     * @dev Perform implementation upgrade with additional setup call.
     *
     * Emits an {Upgraded} event.
     */
    function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal {
        _upgradeTo(newImplementation);
        if (data.length > 0 || forceCall) {
            AddressUpgradeable.functionDelegateCall(newImplementation, data);
        }
    }

    /**
     * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
     *
     * Emits an {Upgraded} event.
     */
    function _upgradeToAndCallUUPS(address newImplementation, bytes memory data, bool forceCall) internal {
        // Upgrades from old implementations will perform a rollback test. This test requires the new
        // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
        // this special case will break upgrade paths from old UUPS implementation to new ones.
        if (StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT).value) {
            _setImplementation(newImplementation);
        } else {
            try IERC1822ProxiableUpgradeable(newImplementation).proxiableUUID() returns (bytes32 slot) {
                require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID");
            } catch {
                revert("ERC1967Upgrade: new implementation is not UUPS");
            }
            _upgradeToAndCall(newImplementation, data, forceCall);
        }
    }

    /**
     * @dev Storage slot with the admin of the contract.
     * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
     * validated in the constructor.
     */
    bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;

    /**
     * @dev Returns the current admin.
     */
    function _getAdmin() internal view returns (address) {
        return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
    }

    /**
     * @dev Stores a new address in the EIP1967 admin slot.
     */
    function _setAdmin(address newAdmin) private {
        require(newAdmin != address(0), "ERC1967: new admin is the zero address");
        StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
    }

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

    /**
     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
     * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
     */
    bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;

    /**
     * @dev Returns the current beacon.
     */
    function _getBeacon() internal view returns (address) {
        return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
    }

    /**
     * @dev Stores a new beacon in the EIP1967 beacon slot.
     */
    function _setBeacon(address newBeacon) private {
        require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
        require(
            AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
            "ERC1967: beacon implementation is not a contract"
        );
        StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
    }

    /**
     * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
     * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
     *
     * Emits a {BeaconUpgraded} event.
     */
    function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal {
        _setBeacon(newBeacon);
        emit BeaconUpgraded(newBeacon);
        if (data.length > 0 || forceCall) {
            AddressUpgradeable.functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
        }
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}

lib/openzeppelin-contracts-upgradeable/contracts/proxy/beacon/IBeaconUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)

pragma solidity ^0.8.0;

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

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

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

pragma solidity ^0.8.2;

import "../../utils/AddressUpgradeable.sol";

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

    /**
     * @dev Indicates that the contract is in the process of being initialized.
     */
    bool private _initializing;

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

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
     * constructor.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        bool isTopLevelCall = !_initializing;
        require(
            (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
            "Initializable: contract is already initialized"
        );
        _initialized = 1;
        if (isTopLevelCall) {
            _initializing = true;
        }
        _;
        if (isTopLevelCall) {
            _initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: setting the version to 255 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint8 version) {
        require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
        _initialized = version;
        _initializing = true;
        _;
        _initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        require(_initializing, "Initializable: contract is not initializing");
        _;
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        require(!_initializing, "Initializable: contract is initializing");
        if (_initialized != type(uint8).max) {
            _initialized = type(uint8).max;
            emit Initialized(type(uint8).max);
        }
    }

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

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

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

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

pragma solidity ^0.8.0;

import "../../interfaces/draft-IERC1822Upgradeable.sol";
import "../ERC1967/ERC1967UpgradeUpgradeable.sol";
import "./Initializable.sol";

/**
 * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
 * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
 *
 * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
 * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
 * `UUPSUpgradeable` with a custom implementation of upgrades.
 *
 * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
 *
 * _Available since v4.1._
 */
abstract contract UUPSUpgradeable is Initializable, IERC1822ProxiableUpgradeable, ERC1967UpgradeUpgradeable {
    function __UUPSUpgradeable_init() internal onlyInitializing {
    }

    function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
    }
    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
    address private immutable __self = address(this);

    /**
     * @dev Check that the execution is being performed through a delegatecall call and that the execution context is
     * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
     * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
     * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
     * fail.
     */
    modifier onlyProxy() {
        require(address(this) != __self, "Function must be called through delegatecall");
        require(_getImplementation() == __self, "Function must be called through active proxy");
        _;
    }

    /**
     * @dev Check that the execution is not being performed through a delegate call. This allows a function to be
     * callable on the implementing contract but not through proxies.
     */
    modifier notDelegated() {
        require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall");
        _;
    }

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

    /**
     * @dev Upgrade the implementation of the proxy to `newImplementation`.
     *
     * Calls {_authorizeUpgrade}.
     *
     * Emits an {Upgraded} event.
     *
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function upgradeTo(address newImplementation) public virtual onlyProxy {
        _authorizeUpgrade(newImplementation);
        _upgradeToAndCallUUPS(newImplementation, new bytes(0), false);
    }

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

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

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}

lib/openzeppelin-contracts-upgradeable/contracts/security/PausableUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)

pragma solidity ^0.8.0;

import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.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 PausableUpgradeable is Initializable, ContextUpgradeable {
    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

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

    bool private _paused;

    /**
     * @dev Initializes the contract in unpaused state.
     */
    function __Pausable_init() internal onlyInitializing {
        __Pausable_init_unchained();
    }

    function __Pausable_init_unchained() internal onlyInitializing {
        _paused = false;
    }

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

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

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

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        require(!paused(), "Pausable: paused");
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        require(paused(), "Pausable: not paused");
    }

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

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

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}

lib/openzeppelin-contracts-upgradeable/contracts/security/ReentrancyGuardUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuardUpgradeable is Initializable {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    function __ReentrancyGuard_init() internal onlyInitializing {
        __ReentrancyGuard_init_unchained();
    }

    function __ReentrancyGuard_init_unchained() internal onlyInitializing {
        _status = _NOT_ENTERED;
    }

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

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be _NOT_ENTERED
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }

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

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}

lib/openzeppelin-contracts-upgradeable/contracts/utils/AddressUpgradeable.sol

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

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library AddressUpgradeable {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";

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

    function __Context_init_unchained() internal onlyInitializing {
    }
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

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

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}

lib/openzeppelin-contracts-upgradeable/contracts/utils/StorageSlotUpgradeable.sol

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

pragma solidity ^0.8.0;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._
 * _Available since v4.9 for `string`, `bytes`._
 */
library StorageSlotUpgradeable {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

    /**
     * @dev Moves `amount` tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
}

lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

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

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

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using Address for address;

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(IERC20 token, address spender, uint256 value) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
     * Revert on invalid signature.
     */
    function safePermit(
        IERC20Permit token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        uint256 nonceBefore = token.nonces(owner);
        token.permit(owner, spender, value, deadline, v, r, s);
        uint256 nonceAfter = token.nonces(owner);
        require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return
            success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
    }
}

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

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

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}

src/swap/SwapAdminLib.sol

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

import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";

import {ZeroXAggregationRouter as R} from "./ZeroXAggregationRouter.sol";
import {
    ICLPoolMeta,
    ISlipstreamPoolMeta,
    ISolidlyPool,
    IDODOV2Pool,
    IWooPPV2,
    IPoolFactories,
    ISlipstreamFactory,
    ISolidlyFactory,
    IDODOFactory,
    IV4PoolManager,
    V4PoolKey
} from "./interfaces/IVenues.sol";

/// @title SwapAdminLib
/// @notice Every allowlist path {ZeroXAggregationRouter} has, plus its
///         route-validation view — lifted out of the router so the router
///         fits under EIP-170.
///
/// @dev # Why this library exists, and what it is NOT allowed to hold
///
/// The router crossed the 24,576-byte contract limit when Uniswap v4 landed
/// (24,175 bytes before, 29,973 after — it had 401 bytes of headroom and v4
/// wanted 5,798). Lowering `optimizer_runs` to 1 recovered 379 bytes of the
/// 5,397 needed, so the deficit is code volume rather than optimiser settings,
/// and something had to move.
///
/// **What moved is exactly the code that is not on the money path.**
/// Registration, attestation and {validateRoute} run once per pool or once per
/// pre-flight; a `DELEGATECALL` hop costs them ~100 gas and nobody notices.
/// {swap} and everything it reaches — the venue executors, the callbacks,
/// {TransientPin}, settlement — stay in the router where they were audited.
/// That boundary is deliberate and worth defending on the next size squeeze:
/// moving a venue executor here would put a delegatecall inside the callback
/// window the pin protects, and would make the four invariants argue across
/// two contracts instead of one.
///
/// # Delegatecall semantics, stated once
///
/// A `public` library function is deployed separately and reached by
/// `DELEGATECALL`, so every function here runs **in the router's storage
/// context**:
///
/// * storage arguments are the router's own mappings, written in place;
/// * `emit` produces a log whose address is the ROUTER, so indexers see no
///   change — which is why the events are re-declared here rather than
///   forwarded through a return value;
/// * `msg.sender` is the router's caller, not the router. Nothing here reads
///   it: **authorisation stays in the router**, checked before the call. A
///   future function that needs `msg.sender` must take it as an argument
///   rather than trusting the context.
///
/// Two things the router has that this library cannot see: `weth` and
/// `poolManager` are implementation IMMUTABLES, which live in the router's
/// bytecode and are invisible across a delegatecall. They are passed as
/// arguments, and the router is the only caller, so they remain unforgeable.
///
/// # Errors and events keep their identity
///
/// Both are re-declared here with the same names and argument types, which is
/// what makes this refactor invisible from outside: a custom error's selector
/// and an event's topic0 are derived from that signature, not from where it
/// was declared. Existing tests asserting
/// `ZeroXAggregationRouter.PoolBlocked.selector` still match a revert raised
/// in this file.
library SwapAdminLib {
    // -----------------------------------------------------------------------
    // Constants, mirrored from the router
    // -----------------------------------------------------------------------

    /// @dev Must equal `ZeroXAggregationRouter.NATIVE`.
    address internal constant NATIVE = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
    uint256 internal constant BPS = 10_000;
    /// @dev v4-core's `StateLibrary.POOLS_SLOT`.
    uint256 internal constant V4_POOLS_SLOT = 6;
    uint24 internal constant V4_MAX_LP_FEE = 1_000_000;
    /// @dev A thousandth of a token, for the WooPP registration probe.
    uint256 internal constant PROBE_DIVISOR = 1_000;

    // -----------------------------------------------------------------------
    // Events — same signatures, therefore same topics, as the router's
    // -----------------------------------------------------------------------

    event PoolRegistered(address indexed pool, R.Venue indexed venue, address token0, address token1);
    event PoolReRegistered(address indexed pool, R.Venue indexed venue);
    event PoolEnabledSet(address indexed pool, bool enabled);
    event WooPairRegistered(address indexed wooPP, address token0, address token1);
    event WooPairReRegistered(address indexed wooPP, address token0, address token1);

    // -----------------------------------------------------------------------
    // Errors — same signatures, therefore same selectors, as the router's
    // -----------------------------------------------------------------------

    error ZeroAddress();
    error IdenticalTokens();
    error PoolBlocked(address pool);
    error PoolAlreadyRegistered(address pool);
    error NotAWooPPForPair(address wooPP);
    error UnknownFactory(address factory);
    error FactoryRoundTripFailed(address pool);
    error VenueUnsupported();
    error V4NotConfigured();
    error V4HooksNotSupported();
    error V4PoolNotInitialized();
    error V4CurrenciesUnsorted();
    error V4FeeInvalid();

    // -----------------------------------------------------------------------
    // Factory-attested registration
    // -----------------------------------------------------------------------

    /// @notice Register a pool its factory can vouch for.
    /// @dev Verbatim the router's former `_registerPool`. Auth was checked by
    ///      the caller; see the note on `msg.sender` above.
    function registerPool(
        mapping(address => R.PoolInfo) storage pools,
        mapping(address => R.Venue) storage factoryVenue,
        mapping(address => bool) storage blocked,
        address pool
    ) public {
        if (pool == address(0)) revert ZeroAddress();
        if (blocked[pool]) revert PoolBlocked(pool);

        R.PoolInfo memory info = _attest(factoryVenue, pool);

        // Registration NEVER raises the enabled flag on a pool that is already
        // known. Re-registering is for refreshing metadata, not for undoing a
        // disable — otherwise anyone could back-run `setPoolEnabled(p, false)`
        // and put a compromised pool straight back into service.
        R.PoolInfo storage prev = pools[pool];
        bool known = prev.venue != R.Venue.NONE;
        info.enabled = known ? prev.enabled : true;

        pools[pool] = info;
        if (known) {
            // A distinct event: otherwise a first listing and a silent
            // re-registration are indistinguishable to an indexer.
            emit PoolReRegistered(pool, info.venue);
        } else {
            emit PoolRegistered(pool, info.venue, info.token0, info.token1);
            emit PoolEnabledSet(pool, true);
        }
    }

    /// @dev Reads the venue from the pool's factory, then re-derives the pool
    ///      from that factory and requires it to match.
    function _attest(mapping(address => R.Venue) storage factoryVenue, address pool)
        private
        view
        returns (R.PoolInfo memory info)
    {
        address factory = ICLPoolMeta(pool).factory();
        R.Venue venue = factoryVenue[factory];
        if (venue == R.Venue.NONE) revert UnknownFactory(factory);

        info.venue = venue;
        info.enabled = true;

        if (venue == R.Venue.UNIV3) {
            address t0 = ICLPoolMeta(pool).token0();
            address t1 = ICLPoolMeta(pool).token1();
            if (IPoolFactories(factory).getPool(t0, t1, ICLPoolMeta(pool).fee()) != pool) {
                revert FactoryRoundTripFailed(pool);
            }
            (info.token0, info.token1) = (t0, t1);
        } else if (venue == R.Venue.SLIPSTREAM) {
            address t0 = ISlipstreamPoolMeta(pool).token0();
            address t1 = ISlipstreamPoolMeta(pool).token1();
            if (ISlipstreamFactory(factory).getPool(t0, t1, ISlipstreamPoolMeta(pool).tickSpacing()) != pool) {
                revert FactoryRoundTripFailed(pool);
            }
            (info.token0, info.token1) = (t0, t1);
        } else if (venue == R.Venue.SOLIDLY_V2) {
            address t0 = ISolidlyPool(pool).token0();
            address t1 = ISolidlyPool(pool).token1();
            bool stable = ISolidlyPool(pool).stable();
            if (ISolidlyFactory(factory).getPool(t0, t1, stable) != pool) revert FactoryRoundTripFailed(pool);
            (info.token0, info.token1, info.stable) = (t0, t1, stable);
        } else {
            // Reached for WOOFI and DODO, neither of which can be attested
            // through this path.
            //
            // DODO V2 pools do NOT expose `factory()` — selector 0xc45a0155 is
            // absent from the deployed implementation, so the very first line
            // of this function reverts with empty returndata for them. They go
            // through {registerDodo}, which takes the factory as an argument
            // and recovers the real containment check.
            //
            // WooFi has no factory and no per-pair pool at all: one contract
            // serves every pair it funds. See {registerWooFi}.
            revert VenueUnsupported();
        }
    }

    // -----------------------------------------------------------------------
    // Uniswap v4
    // -----------------------------------------------------------------------

    /// @notice The handle a v4 key registers under, and its full pool id.
    /// @dev The handle is the FIRST 20 bytes (most significant) of the id.
    ///      The definition the off-chain router, the registration scripts and
    ///      the tests all cite; the router re-exports it.
    function v4Handle(V4PoolKey memory key) public pure returns (address handle, bytes32 poolId) {
        poolId = keccak256(abi.encode(key));
        handle = address(uint160(uint256(poolId) >> 96));
    }

    /// @notice Register a Uniswap v4 pool by its key.
    /// @dev `poolManager` and `weth` are the router's immutables, invisible
    ///      across the delegatecall and therefore passed in.
    function registerUniV4(
        mapping(address => R.PoolInfo) storage pools,
        mapping(address => V4PoolKey) storage v4Keys,
        mapping(address => bool) storage blocked,
        V4PoolKey calldata key,
        address poolManager,
        address weth
    ) public {
        if (poolManager == address(0)) revert V4NotConfigured();
        if (key.hooks != address(0)) revert V4HooksNotSupported();
        if (key.currency0 >= key.currency1) revert V4CurrenciesUnsorted();
        if (key.fee > V4_MAX_LP_FEE) revert V4FeeInvalid();

        (address handle, bytes32 poolId) = v4Handle(key);
        if (blocked[handle]) revert PoolBlocked(handle);

        // The attestation. `Pool.State` lives at
        // `keccak256(poolId . POOLS_SLOT)`; its first word packs the price in
        // its low 160 bits, and a never-initialised pool holds zero there.
        bytes32 slot0 = IV4PoolManager(poolManager).extsload(keccak256(abi.encodePacked(poolId, V4_POOLS_SLOT)));
        if (uint160(uint256(slot0)) == 0) revert V4PoolNotInitialized();

        // Effective tokens: native ETH is recorded as WETH so continuity
        // checks, refunds and settlement all stay in the one wrapped world
        // the router runs on. An ETH/WETH pool maps to WETH/WETH and is
        // refused — routing it would be wrapping wearing a swap's clothes.
        address t0 = key.currency0 == address(0) ? weth : key.currency0;
        address t1 = key.currency1;
        if (t0 == t1) revert IdenticalTokens();

        R.PoolInfo storage prev = pools[handle];
        bool known = prev.venue != R.Venue.NONE;
        if (known) {
            // The handle is 160 bits of a 256-bit hash. Another pool already
            // owning it — a real contract address, or a different v4 key whose
            // id shares the prefix — is a collision this contract refuses to
            // adjudicate rather than silently re-pointing a live route.
            (, bytes32 prevId) = v4Handle(v4Keys[handle]);
            if (prev.venue != R.Venue.UNIV4 || prevId != poolId) revert PoolAlreadyRegistered(handle);
        }

        // Registration NEVER raises `enabled` on a pool that is already known
        // — the same guardian-race rule as {registerPool}.
        pools[handle] = R.PoolInfo({
            venue: R.Venue.UNIV4,
            enabled: known ? prev.enabled : true,
            stable: false,
            baseIsToken0: false,
            token0: t0,
            token1: t1
        });
        v4Keys[handle] = key;

        if (known) {
            emit PoolReRegistered(handle, R.Venue.UNIV4);
        } else {
            emit PoolRegistered(handle, R.Venue.UNIV4, t0, t1);
            emit PoolEnabledSet(handle, true);
        }
    }

    // -----------------------------------------------------------------------
    // DODO
    // -----------------------------------------------------------------------

    /// @dev Containment, not equality: one DODO factory mints several pools per
    ///      pair, so `getDODOPool` returns arrays.
    function _dodoFactoryMints(address factory, address t0, address t1, address pool)
        private
        view
        returns (bool)
    {
        (address[] memory a, address[] memory b) = IDODOFactory(factory).getDODOPoolBidirection(t0, t1);
        for (uint256 i; i < a.length; ++i) {
            if (a[i] == pool) return true;
        }
        for (uint256 i; i < b.length; ++i) {
            if (b[i] == pool) return true;
        }
        return false;
    }

    /// @notice Register a DODO V2 pool, proven against the factory given.
    function registerDodo(
        mapping(address => R.PoolInfo) storage pools,
        mapping(address => R.Venue) storage factoryVenue,
        mapping(address => bool) storage blocked,
        address pool,
        address factory
    ) public {
        if (pool == address(0) || factory == address(0)) revert ZeroAddress();
        if (blocked[pool]) revert PoolBlocked(pool);
        if (factoryVenue[factory] != R.Venue.DODO) revert UnknownFactory(factory);

        address base = IDODOV2Pool(pool)._BASE_TOKEN_();
        address quote = IDODOV2Pool(pool)._QUOTE_TOKEN_();
        if (base == address(0) || quote == address(0)) revert ZeroAddress();
        if (base == quote) revert IdenticalTokens();

        // Sorted like every other venue; the orientation is recorded separately
        // because DODO's own base/quote ordering has nothing to do with address
        // sorting.
        (address t0, address t1) = base < quote ? (base, quote) : (quote, base);
        if (!_dodoFactoryMints(factory, t0, t1, pool)) revert FactoryRoundTripFailed(pool);

        _writeDodo(pools, pool, t0, t1, t0 == base);
    }

    /// @notice Register a DODO DPP pool WITHOUT factory attestation.
    /// @dev The escape hatch for pools that expose neither `factory()` nor
    ///      factory enumeration, so no third party can vouch for them and the
    ///      owner's word is the only attestation available. Named for what it
    ///      does not do; {registerDodo} handles every reachable pool and
    ///      should be preferred always.
    function registerDodoUnattested(
        mapping(address => R.PoolInfo) storage pools,
        mapping(address => bool) storage blocked,
        address pool,
        address baseToken,
        address quoteToken
    ) public {
        if (pool == address(0) || baseToken == address(0) || quoteToken == address(0)) revert ZeroAddress();
        if (baseToken == quoteToken) revert IdenticalTokens();
        if (blocked[pool]) revert PoolBlocked(pool);

        (address t0, address t1) = baseToken < quoteToken ? (baseToken, quoteToken) : (quoteToken, baseToken);
        _writeDodo(pools, pool, t0, t1, t0 == baseToken);
    }

    /// @dev The write both DODO paths share, including the rule that
    ///      registration never re-enables a pool the guardian disabled.
    function _writeDodo(
        mapping(address => R.PoolInfo) storage pools,
        address pool,
        address t0,
        address t1,
        bool baseIsToken0
    ) private {
        R.PoolInfo storage prev = pools[pool];
        bool known = prev.venue != R.Venue.NONE;
        pools[pool] = R.PoolInfo({
            venue: R.Venue.DODO,
            enabled: known ? prev.enabled : true,
            stable: false,
            baseIsToken0: baseIsToken0,
            token0: t0,
            token1: t1
        });
        if (known) {
            emit PoolReRegistered(pool, R.Venue.DODO);
        } else {
            emit PoolRegistered(pool, R.Venue.DODO, t0, t1);
            emit PoolEnabledSet(pool, true);
        }
    }

    // -----------------------------------------------------------------------
    // WooFi
    // -----------------------------------------------------------------------

    function pairKey(address t0, address t1) public pure returns (bytes32) {
        return keccak256(abi.encodePacked(t0, t1));
    }

    /// @notice Register a WooFi WooPPV2 pair.
    /// @dev Owner-only at the router, and never permissionless, because WooFi
    ///      has no factory to attest against — there is no third party here
    ///      whose word we can check.
    function registerWooFi(
        mapping(address => R.PoolInfo) storage pools,
        mapping(address => mapping(bytes32 => bool)) storage wooPairs,
        mapping(address => mapping(bytes32 => bool)) storage wooPairKnown,
        mapping(address => R.Venue) storage factoryVenue,
        mapping(address => bool) storage blocked,
        address wooPP,
        address tokenA,
        address tokenB
    ) public {
        if (wooPP == address(0) || tokenA == address(0) || tokenB == address(0)) revert ZeroAddress();
        if (tokenA == tokenB) revert IdenticalTokens();
        if (blocked[wooPP]) revert PoolBlocked(wooPP);
        if (factoryVenue[wooPP] != R.Venue.WOOFI) revert UnknownFactory(wooPP);

        // ATTESTATION. `factoryVenue` is an owner-set flag and nothing more, so
        // on its own it lets two owner transactions install a fully
        // attacker-controlled "pool" that the WooFi executor pushes tokens to
        // before calling. Prove the target really is a WooPPV2 that prices
        // this pair.
        //
        // Two things this deliberately does NOT do, both of which it used to,
        // and both of which measurement on Arbitrum showed were wrong:
        //
        // **It does not require the quote token to be one of the pair.**
        // WooPPV2 is hub-and-spoke: it holds inventory in many tokens and
        // routes any pair through its quote token INTERNALLY. The live
        // Arbitrum contract quotes WETH -> USDT perfectly well with a quote
        // token of USDC. Requiring the hub to appear in the pair rejected six
        // of the ten funded pairs on that chain.
        //
        // **It does not probe a fixed number of base units.** A flat `1e6`
        // probe is 1e-12 of an 18-decimal token, which prices to zero: measured
        // on Arbitrum it failed even WETH/USDC. The probe scales with the
        // token's own decimals so it means the same thing across a 6- and an
        // 18-decimal pair.
        if (IWooPPV2(wooPP).quoteToken() == address(0)) revert NotAWooPPForPair(wooPP);
        if (!_pricesEitherWay(wooPP, tokenA, tokenB)) revert NotAWooPPForPair(wooPP);

        (address t0, address t1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);

        // Keyed by PAIR, not just by address: one WooPPV2 serves every pair it
        // funds, so a one-slot `PoolInfo` would let the tenth registration
        // silently overwrite the first.
        bytes32 key = pairKey(t0, t1);

        // Registration NEVER re-arms a pair that is already known, for the same
        // reason {registerPool} never re-raises `enabled`.
        bool knownPair = wooPairKnown[wooPP][key];
        if (!knownPair) {
            wooPairKnown[wooPP][key] = true;
            wooPairs[wooPP][key] = true;
        }

        // The struct entry still exists, but only to carry the VENUE for
        // dispatch. Its token0/token1 are the first pair registered and are
        // deliberately not consulted for WooFi hops.
        if (pools[wooPP].venue == R.Venue.NONE) {
            pools[wooPP] = R.PoolInfo({
                venue: R.Venue.WOOFI,
                enabled: true,
                stable: false,
                baseIsToken0: false,
                token0: t0,
                token1: t1
            });
            emit PoolRegistered(wooPP, R.Venue.WOOFI, t0, t1);
            emit PoolEnabledSet(wooPP, true);
        }
        // Distinct events: an indexer, or an on-call reviewer reading logs
        // during an incident, has to be able to tell a first listing from a
        // no-op repeat.
        if (knownPair) emit WooPairReRegistered(wooPP, t0, t1);
        else emit WooPairRegistered(wooPP, t0, t1);
    }

    /// @dev Whether a WooPP prices this pair in AT LEAST ONE direction.
    ///
    ///      One direction, not both, and the reason is measured rather than
    ///      assumed. A single probe size cannot span the value range of a real
    ///      whitelist: on Arbitrum, {PROBE_DIVISOR} of a WBTC is ~$64 and the
    ///      same fraction of an ARB is ~$0.00007. Probing WBTC -> ARB at one
    ///      whole token exceeds WooFi's ARB inventory and REVERTS; probing
    ///      ARB -> WBTC at a thousandth rounds below one satoshi and returns
    ///      ZERO. Both are artefacts of the probe, not of the pair.
    function _pricesEitherWay(address wooPP, address tokenA, address tokenB) private view returns (bool) {
        return _prices(wooPP, tokenA, tokenB) || _prices(wooPP, tokenB, tokenA);
    }

    /// @dev A reverting probe is a `false`, not a bubbled revert: WooFi reverts
    ///      past its inventory, and that must not be indistinguishable from
    ///      "this is not a WooPP".
    function _prices(address wooPP, address from, address to) private view returns (bool) {
        try IERC20Metadata(from).decimals() returns (uint8 d) {
            uint256 probe = 10 ** d / PROBE_DIVISOR;
            if (probe == 0) return false;
            try IWooPPV2(wooPP).query(from, to, probe) returns (uint256 out) {
                return out != 0;
            } catch {
                return false;
            }
        } catch {
            return false;
        }
    }

    // -----------------------------------------------------------------------
    // Pre-flight
    // -----------------------------------------------------------------------

    /// @dev NATIVE resolves to WETH; everything else is itself.
    function _effective(address token, address weth) private pure returns (address) {
        return token == NATIVE ? weth : token;
    }

    /// @notice Dry-run every non-executing check {ZeroXAggregationRouter.swap}
    ///         would apply.
    /// @dev Returns a reason string rather than reverting, so a caller learns
    ///      WHICH rule a route breaks in one call instead of bisecting reverts.
    ///      Deliberately does not simulate the swap: output depends on live
    ///      pool state, and a view that pretended otherwise would be a worse
    ///      lie than no view at all.
    ///
    ///      `router`, `weth`, `feeBps` and `isPaused` are the caller's context,
    ///      passed in because a delegatecall cannot read the router's
    ///      immutables and because `address(this)` here IS the router only by
    ///      delegatecall convention — naming it explicitly keeps the
    ///      recipient-is-the-router check honest under any future call shape.
    function validateRoute(
        mapping(address => R.PoolInfo) storage pools,
        mapping(address => bool) storage blocked,
        mapping(address => mapping(bytes32 => bool)) storage wooPairs,
        R.SwapDescription calldata desc,
        R.Path[] calldata paths,
        address router,
        address weth,
        uint16 feeBps,
        bool isPaused
    ) public view returns (bool valid, string memory reason) {
        if (block.timestamp > desc.deadline) return (false, "deadline expired");
        if (desc.amountIn == 0) return (false, "amountIn is zero");
        if (desc.recipient == address(0)) return (false, "recipient is zero");
        if (desc.recipient == router) return (false, "recipient is the router");
        if (desc.tokenIn == NATIVE && desc.tokenOut == NATIVE) return (false, "native to native");
        // Compared AFTER normalisation, exactly as {swap} does. A RAW comparison
        // passes `{tokenIn: NATIVE, tokenOut: WETH}` — they are different
        // addresses — while {swap} rejects it once both normalise to WETH.
        if (_effective(desc.tokenIn, weth) == _effective(desc.tokenOut, weth)) {
            return (false, "identical tokens");
        }
        if (feeBps > desc.maxFeeBps) return (false, "fee above caller ceiling");
        if (isPaused) return (false, "router paused");
        if (paths.length == 0) return (false, "no paths");

        address tokenInEff = _effective(desc.tokenIn, weth);
        address tokenOutEff = _effective(desc.tokenOut, weth);

        // The same pre-pass {_executePaths} performs, so a bad portion vector is
        // named here instead of being discovered mid-execution.
        uint256 portionSum;
        for (uint256 i; i < paths.length; ++i) {
            if (paths[i].hops.length == 0) return (false, "empty path");
            portionSum += paths[i].portionBps;
        }
        if (portionSum != BPS) return (false, "portions must sum to 10000");

        uint256 spent;
        for (uint256 i; i < paths.length; ++i) {
            R.Path calldata p = paths[i];
            // Models the per-path split the money path applies, including the
            // last-path-absorbs-the-remainder rule. `desc.amountIn` stands in for
            // the measured `received`; the two differ only for a fee-on-transfer
            // tokenIn, which the token whitelist excludes.
            uint256 pathIn = i == paths.length - 1 ? desc.amountIn - spent : (desc.amountIn * p.portionBps) / BPS;
            if (pathIn == 0) return (false, "path input rounds to zero");
            spent += pathIn;

            address currentToken = tokenInEff;
            for (uint256 j; j < p.hops.length; ++j) {
                R.PoolInfo storage info = pools[p.hops[j].pool];
                if (info.venue == R.Venue.NONE) return (false, "pool not allowlisted");
                if (!info.enabled || blocked[p.hops[j].pool]) return (false, "pool disabled");

                address hopIn;
                address hopOut;
                if (info.venue == R.Venue.WOOFI) {
                    if (j != p.hops.length - 1) return (false, "woofi hop must be terminal");
                    hopIn = currentToken;
                    hopOut = tokenOutEff;
                    (address a0, address a1) = hopIn < hopOut ? (hopIn, hopOut) : (hopOut, hopIn);
                    if (!wooPairs[p.hops[j].pool][pairKey(a0, a1)]) return (false, "woofi pair not registered");
                } else {
                    (hopIn, hopOut) = p.hops[j].zeroForOne ? (info.token0, info.token1) : (info.token1, info.token0);
                }
                if (hopIn != currentToken) {
                    return (j == 0 ? (false, "path does not start at tokenIn") : (false, "path discontinuity"));
                }
                currentToken = hopOut;
            }
            if (currentToken != tokenOutEff) return (false, "path does not end at tokenOut");
        }

        return (true, "");
    }
}

src/swap/TransientPin.sol

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

/// @title TransientPin
/// @notice Authenticates concentrated-liquidity swap callbacks by pinning the
///         pool we are currently calling into EIP-1153 transient storage.
///
/// @dev # Why a pin, and not address recomputation
///
/// A CL pool pays itself by calling back into the router. That callback is
/// `external`, and Uniswap V3, PancakeSwap V3 and Aerodrome Slipstream pools
/// are all separate deployments — so "is my caller a real pool?" is not a
/// question the callback can answer from `msg.sender` alone.
///
/// The usual answer is CREATE2 address recomputation: derive the pool address
/// from the factory, the token pair and the init-code hash, and compare. That
/// is rejected here for a specific reason rather than a stylistic one:
/// **Aerodrome's CLFactory deploys pools as minimal-proxy clones of a mutable
/// `poolImplementation()`**. The effective init-code hash is therefore a
/// function of a storage variable on a contract Aerodrome's owner controls.
/// Hardcoding it makes our authentication silently depend on them never
/// touching that slot, and the failure modes are asymmetric: a stale hash
/// makes every swap revert (loud, recoverable), while a poisoned hash in any
/// owner-settable variant makes attacker contracts authenticate (silent,
/// total loss).
///
/// So instead: write down which pool we are about to call, and accept the
/// callback only from that exact address.
///
/// # Why clearing inside the callback matters
///
/// The pin is cleared by the callback itself, BEFORE it transfers anything.
/// Three properties fall out of that ordering, and all three are load-bearing:
///
/// * the callback is strictly **one-shot** — a malicious allowlisted pool that
///   calls back twice finds the pin already gone and reverts;
/// * the subsequent transfer is **CEI-ordered**, so a token with a transfer
///   hook cannot re-enter into a still-armed pin;
/// * after `pool.swap` returns, a cleared pin is **positive proof the callback
///   actually ran**. A pool that took our tokens without calling back, or that
///   returned without swapping, is caught by {requireConsumed}.
///
/// # The transaction-scope hazard
///
/// EIP-1153 slots persist for the whole TRANSACTION, not the call frame. The
/// 0xEquity passkey wallet executes BATCHES — several inner calls in one
/// transaction — so two `swap()` calls can share transient state. A pin left
/// behind by the first would be a valid credential during the second.
///
/// That is why clearing is mandatory rather than hygiene, and why
/// {requireConsumed} exists: no path may leave a pin armed.
library TransientPin {
    /// @dev Distinct, hand-picked slots. Derived from a namespace string so
    ///      they cannot collide with any compiler-assigned transient slot a
    ///      future Solidity version might allocate.
    ///
    ///      _SLOT_POOL is keccak256("0xEquity.AggregationRouter.pin.v1"); the
    ///      other two are the next two words. `test/swap/TransientPin.t.sol`
    ///      recomputes all three and fails if they drift.
    bytes32 private constant _SLOT_POOL = 0xf543c669afe0830d67f16335d44f2795298ec0d204cae4f042e91cdf8a88e3c4;
    bytes32 private constant _SLOT_TOKEN = 0xf543c669afe0830d67f16335d44f2795298ec0d204cae4f042e91cdf8a88e3c5;
    bytes32 private constant _SLOT_MAX_OWED = 0xf543c669afe0830d67f16335d44f2795298ec0d204cae4f042e91cdf8a88e3c6;

    error PinAlreadyArmed();
    error CallbackNotInvoked();
    error UnauthorizedCallback();
    error CallbackAmountMismatch();

    /// @notice Arm the pin immediately before calling `pool.swap`.
    /// @dev Reverts if a pin is already armed. That can only happen if a
    ///      previous swap in this same transaction failed to clear one, which
    ///      is exactly the leak this library exists to make impossible —
    ///      failing loudly beats letting a stale credential stand.
    function arm(address pool, address tokenOwed, uint256 maxOwed) internal {
        assembly ("memory-safe") {
            if tload(_SLOT_POOL) {
                mstore(0x00, 0x565b5de0) // PinAlreadyArmed()
                revert(0x1c, 0x04)
            }
            tstore(_SLOT_POOL, pool)
            tstore(_SLOT_TOKEN, tokenOwed)
            tstore(_SLOT_MAX_OWED, maxOwed)
        }
    }

    /// @notice Consume the pin from inside a swap callback.
    /// @dev Verifies the caller IS the pinned pool and that what it is asking
    ///      for is within the bound we armed, then clears every slot before
    ///      returning — so the caller can transfer afterwards with the pin
    ///      already gone.
    /// @param sender `msg.sender` of the callback.
    /// @param owed How much the pool is asking this router to pay. Must be at
    ///        most the armed amount.
    /// @return token The token owed, as recorded when the pin was armed. Taken
    ///         from transient state rather than from callback arguments, so a
    ///         hostile pool cannot name a different token to drain.
    function consume(address sender, uint256 owed) internal returns (address token) {
        assembly ("memory-safe") {
            let pinned := tload(_SLOT_POOL)
            // A zero pin means no swap is in flight: either a direct call from
            // an EOA, or a second callback from a pool that already used its one.
            if iszero(eq(sender, pinned)) {
                mstore(0x00, 0xf5c6c81a) // UnauthorizedCallback()
                revert(0x1c, 0x04)
            }
            // A CEILING, not equality — and the ceiling is the whole of this
            // library's job here. It bounds what a pinned pool can take; it
            // does not decide whether taking less is acceptable.
            //
            // It was equality while the router refused every partial fill, on
            // the grounds that a `gt` check would accept a short fill and
            // strand the remainder. That reasoning was right and the fix for it
            // is not here: `swap` now either refuses the short fill outright
            // (fill-or-kill) or refunds the remainder to the payer
            // (partiallyFillable). Nothing is stranded either way, and the two
            // concerns are now in the two places that can actually tell them
            // apart — see {ZeroXAggregationRouter._swapConcentrated}.
            //
            // A pool asking for MORE than was armed is still refused here,
            // which is the authentication-adjacent property that matters: the
            // pin caps the router's exposure to a pool it is calling.
            if gt(owed, tload(_SLOT_MAX_OWED)) {
                mstore(0x00, 0xdafc5d75) // CallbackAmountMismatch()
                revert(0x1c, 0x04)
            }
            token := tload(_SLOT_TOKEN)
            // Cleared BEFORE the caller transfers. See the CEI note above.
            tstore(_SLOT_POOL, 0)
            tstore(_SLOT_TOKEN, 0)
            tstore(_SLOT_MAX_OWED, 0)
        }
    }

    /// @notice Assert, after `pool.swap` returns, that the callback ran.
    /// @dev A still-armed pin means the pool never called back — it either did
    ///      nothing, or took a path that skipped payment. Either way the swap
    ///      did not happen as intended and the transaction must not continue.
    ///      This also guarantees no pin survives into the next call of a batch.
    function requireConsumed() internal {
        assembly ("memory-safe") {
            if tload(_SLOT_POOL) {
                // Clear before reverting is pointless (state reverts too), but
                // the check itself is what keeps the batch invariant.
                mstore(0x00, 0x4d23f00a) // CallbackNotInvoked()
                revert(0x1c, 0x04)
            }
        }
    }

    /// @notice Whether a pin is currently armed. Test and assertion helper.
    function isArmed() internal view returns (bool armed) {
        assembly ("memory-safe") {
            armed := iszero(iszero(tload(_SLOT_POOL)))
        }
    }
}

src/swap/interfaces/IVenues.sol

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

/// @title IVenues
/// @notice The minimal external surfaces the aggregation router calls on each
///         venue family, and nothing more.
/// @dev Deliberately hand-written rather than imported from each protocol's
///      package. Three reasons:
///
///      1. The router must call exactly these functions and no others. A full
///         interface import brings in dozens of methods that an auditor then
///         has to rule out by inspection.
///      2. Several of these protocols are not published as installable
///         packages at the version actually deployed on Base/Arbitrum.
///      3. The differences between families are the whole risk surface, and
///         putting them side by side in one file makes them reviewable.
///
///      Every signature here was taken from the deployed contract's selector
///      table, not from documentation.

/// @notice Uniswap V3, PancakeSwap V3 and Aerodrome Slipstream pools.
/// @dev All three share this `swap` signature. They do NOT all share a callback
///      name — see {ISwapCallbacks}.
interface ICLPool {
    /// @param recipient Who receives the output.
    /// @param zeroForOne True to swap token0 -> token1.
    /// @param amountSpecified POSITIVE for exact input, negative for exact
    ///        output. This router only ever passes a positive value.
    /// @param sqrtPriceLimitX96 Price bound. The pool asserts a STRICT
    ///        inequality against it, which is why callers pass
    ///        `MIN_SQRT_RATIO + 1` / `MAX_SQRT_RATIO - 1` rather than the
    ///        bounds themselves.
    /// @param data Forwarded verbatim to the callback. This router always
    ///        passes empty bytes and derives everything from transient state,
    ///        so there is nothing in it for an attacker to forge.
    function swap(
        address recipient,
        bool zeroForOne,
        int256 amountSpecified,
        uint160 sqrtPriceLimitX96,
        bytes calldata data
    ) external returns (int256 amount0, int256 amount1);
}

/// @notice Aerodrome v2 / Solidly-style volatile+stable pools.
/// @dev Funded by PUSH: the router transfers input to the pool and then calls
///      `swap`. There is no callback, provided `data` is empty — see the note
///      on {swap}.
interface ISolidlyPool {
    /// @dev `data.length > 0` makes the pool invoke `IPoolCallee(to).hook(...)`
    ///      on the recipient. The router always passes empty bytes, which is a
    ///      SECURITY choice and not a gas one: it means the pool has no code
    ///      path back into this contract at all.
    function swap(uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data) external;

    /// @dev Returns three `uint256` values, NOT UniV2's packed
    ///      `(uint112, uint112, uint32)`. Decoding it with the UniV2 layout
    ///      yields garbage.
    function getReserves() external view returns (uint256 reserve0, uint256 reserve1, uint256 blockTimestampLast);

    /// @notice Applies the fee AND selects the curve (volatile `x*y>=k` or
    ///         stable `x^3*y + y^3*x >= k`) internally.
    function getAmountOut(uint256 amountIn, address tokenIn) external view returns (uint256);

    function token0() external view returns (address);
    function token1() external view returns (address);
    function stable() external view returns (bool);
    function factory() external view returns (address);
}

/// @notice DODO V2 pools (DVM / DPP / DSP).
/// @dev Funded by PUSH, like Solidly. Base/quote oriented rather than sorted:
///      the two directions are DIFFERENT FUNCTIONS, so the router must know
///      which of the pool's two tokens is the base.
interface IDODOV2Pool {
    /// @notice Sell the BASE token, receive quote. Tokens must already have
    ///         been transferred to the pool.
    function sellBase(address to) external returns (uint256 receiveQuoteAmount);

    /// @notice Sell the QUOTE token, receive base.
    function sellQuote(address to) external returns (uint256 receiveBaseAmount);

    // solhint-disable func-name-mixedcase
    function _BASE_TOKEN_() external view returns (address);
    function _QUOTE_TOKEN_() external view returns (address);
    // solhint-enable func-name-mixedcase
}

/// @notice WooFi WooPPV2 — one contract per chain serving every pair it funds.
/// @dev Oracle-priced rather than curve-priced, and inventory-bounded: it
///      REVERTS past its capacity rather than filling at a bad price.
interface IWooPPV2 {
    /// @param rebateTo Referral credit recipient. The router passes its own
    ///        address; it is not a fund destination and cannot redirect output.
    function swap(
        address fromToken,
        address toToken,
        uint256 fromAmount,
        uint256 minToAmount,
        address to,
        address rebateTo
    ) external returns (uint256 realToAmount);

    function quoteToken() external view returns (address);

    /// @notice Forward-only price read. Used at registration to prove the
    ///         target really is a WooPPV2 that serves the pair.
    function query(address fromToken, address toToken, uint256 fromAmount)
        external
        view
        returns (uint256 toAmount);
}

/// @notice Factory round-trip surfaces used when registering a pool.
/// @dev The round-trip is what makes a pool's self-declared `factory()`
///      unforgeable: a fake pool would have to make a REAL factory return its
///      address, which only that factory's own `createPool` can do.
interface IPoolFactories {
    /// Uniswap V3 / PancakeSwap V3, keyed by fee tier.
    function getPool(address tokenA, address tokenB, uint24 fee) external view returns (address);
}

interface ISlipstreamFactory {
    /// Keyed by tick spacing, not fee.
    function getPool(address tokenA, address tokenB, int24 tickSpacing) external view returns (address);
}

interface ISolidlyFactory {
    /// Keyed by the curve selector.
    function getPool(address tokenA, address tokenB, bool stable) external view returns (address);
}

interface IDODOFactory {
    /// One factory can mint SEVERAL pools per pair, so registration checks
    /// containment in these arrays rather than address equality.
    function getDODOPoolBidirection(address token0, address token1)
        external
        view
        returns (address[] memory baseToken0Pools, address[] memory baseToken1Pools);
}

/// @notice Metadata every CL pool exposes, used during registration.
interface ICLPoolMeta {
    function token0() external view returns (address);
    function token1() external view returns (address);
    function fee() external view returns (uint24);
    function factory() external view returns (address);
}

interface ISlipstreamPoolMeta {
    function token0() external view returns (address);
    function token1() external view returns (address);
    function tickSpacing() external view returns (int24);
    function factory() external view returns (address);
}

/// @notice Minimal WETH surface for native-ETH wrapping.
interface IWETH9 {
    function deposit() external payable;
    function withdraw(uint256) external;
}

/// @notice A Uniswap v4 pool's identity. There is no pool contract: the
///         singleton {IV4PoolManager} keys every pool by the keccak of this
///         struct, so the struct IS the pool.
/// @dev Field-for-field identical to v4-core's `PoolKey` — `Currency` and
///      `IHooks` are both address-backed user types, so `abi.encode` of this
///      struct produces the same bytes and therefore the same pool id. Declared
///      here with plain addresses so the router's ABI surface stays hand-written
///      and reviewable, per this file's header.
/// @param currency0 The numerically lower currency. `address(0)` is NATIVE ETH —
///        v4's convention, not this router's `0xEeee…` sentinel.
/// @param currency1 The numerically higher currency.
/// @param fee LP fee in hundredths of a bip, at most 1_000_000. `0x800000` is
///        v4's dynamic-fee flag and only valid on hooked pools, which this
///        router refuses.
/// @param tickSpacing Tick grid for positions.
/// @param hooks The pool's hook contract. This router registers ONLY pools
///        where this is `address(0)`.
struct V4PoolKey {
    address currency0;
    address currency1;
    uint24 fee;
    int24 tickSpacing;
    address hooks;
}

/// @notice v4-core's `SwapParams`.
/// @dev Note the sign convention is INVERTED from V3: `amountSpecified` is
///      NEGATIVE for exact input. V3's `ICLPool.swap` takes positive for exact
///      input. Every venue-side sign in `_swapUniV4` flips relative to
///      `_swapConcentrated` for the same reason.
struct V4SwapParams {
    bool zeroForOne;
    int256 amountSpecified;
    uint160 sqrtPriceLimitX96;
}

/// @notice The minimal Uniswap v4 PoolManager surface the router uses.
/// @dev Signatures taken from the vendored `lib/v4-core` source, not from
///      documentation. `Currency` parameters are declared as `address` — the
///      user type is address-backed, so selectors and encodings agree.
interface IV4PoolManager {
    /// @notice Opens a flash-accounting session and calls
    ///         `unlockCallback(data)` back on `msg.sender`. Reverts unless
    ///         every currency delta is settled to zero by the time the
    ///         callback returns.
    function unlock(bytes calldata data) external returns (bytes memory);

    /// @notice Swap against a pool. Only callable inside an unlock session.
    /// @return swapDelta v4-core's `BalanceDelta`: amount0 in the upper 128
    ///         bits, amount1 in the lower 128, both signed, both from the
    ///         CALLER's perspective — negative is owed to the pool, positive
    ///         is owed to the caller. Also inverted from V3, where a positive
    ///         delta is what the caller owes.
    function swap(V4PoolKey memory key, V4SwapParams memory params, bytes calldata hookData)
        external
        returns (int256 swapDelta);

    /// @notice Checkpoint the manager's balance of `currency` before an ERC-20
    ///         transfer in; {settle} credits the difference.
    function sync(address currency) external;

    /// @notice Credit the caller with what arrived since {sync} (ERC-20), or
    ///         with `msg.value` (native).
    function settle() external payable returns (uint256 paid);

    /// @notice Pay out a positive delta.
    function take(address currency, address to, uint256 amount) external;

    /// @notice Read one storage slot of the manager. How pool state is read
    ///         without a pool contract: registration derives the pool's state
    ///         slot from its id and requires a non-zero price.
    function extsload(bytes32 slot) external view returns (bytes32 value);
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {
    "src/swap/ZeroXAggregationRouter.sol": {
      "SwapAdminLib": "0x5dd0441be1ca31554d5b5bbacef923bac93109ed"
    }
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "@uniswap/v3-core/=lib/v3-core/",
    "@uniswap/v3-periphery/=lib/v3-periphery/",
    "@uniswap/v4-core/=lib/v4-core/",
    "@uniswap/v4-periphery/=lib/v4-periphery/",
    "@uniswap/lib/=lib/solidity-lib/",
    "@api3/contracts/=lib/contracts/contracts/",
    "solmate/=lib/solmate/",
    "solady/=lib/solady/",
    "abdk-libraries-solidity/=lib/abdk-libraries-solidity/",
    "forge-std/=lib/forge-std/src/",
    "@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
    "ds-test/=lib/solmate/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "forge-gas-snapshot/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "hardhat/=lib/v4-core/node_modules/hardhat/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "openzeppelin/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "permit2/=lib/v4-periphery/lib/permit2/",
    "solidity-lib/=lib/solidity-lib/contracts/",
    "v3-core/=lib/v3-core/",
    "v3-periphery/=lib/v3-periphery/contracts/",
    "v4-core/=lib/v4-core/src/",
    "v4-periphery/=lib/v4-periphery/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.