Skip to content
Verified contractPartialMIT

PeddlesRouteSwapRouter

Address0x3a6a8e21fc09d27fc3f9ad57e012da69032149d4
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
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,374,084
Creation transaction
0x25e81afe5f…3e79b95bd4

src/PeddlesRouteSwapRouter.sol

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

/*

               _______  _______  ______   ______   _        _______
      (  ____ )(  ____ \(  __  \ (  __  \ ( \      (  ____ \(  ____ \
      | (    )|| (    \/| (  \  )| (  \  )| (      | (    \/| (    \/
      | (____)|| (__    | |   ) || |   ) || |      | (__    | (_____
      |  _____)|  __)   | |   | || |   | || |      |  __)   (_____  )
      | (      | (      | |   ) || |   ) || |      | (            ) |
      | )      | (____/\| (__/  )| (__/  )| (____/\| (____/\/\____) |
      |/       (_______/(______/ (______/ (_______/(_______/\_______)


      THE STOCK-PAIRED LAUNCHPAD

      Launch tokens and NFTs paired against tokenised stocks.
      100% of supply goes to liquidity, locked from block zero.
      Holders earn the stock you are paired to.

      Website     https://peddles.xyz
      X           https://x.com/PeddlesX
      Telegram    https://t.me/peddlesnews


*/

interface IRouteERC20 {
    function transfer(address to, uint256 amount) external returns (bool);
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
    function approve(address spender, uint256 amount) external returns (bool);
    function balanceOf(address owner) external view returns (uint256);
}

interface IRouteWETH is IRouteERC20 {
    function deposit() external payable;
    function withdraw(uint256) external;
}

interface IRouteStockLaunchpad {
    function coins(address token)
        external
        view
        returns (
            address creator,
            address quote,
            bytes32 poolId,
            uint256 positionId,
            uint64 createdAt,
            bool tokenIsCurrency0
        );
    function quoteConfig(address quote) external view returns (bool allowed, bool configured, int24 startTick);
}

interface IRouteStockSwapRouter {
    function poolManager() external view returns (address);
    function launchpad() external view returns (address);
    function buy(address token, uint256 quoteIn, uint256 minTokenOut, address to) external returns (uint256);
    function sell(address token, uint256 tokenIn, uint256 minQuoteOut, address to) external returns (uint256);
}

interface IRouteV4SwapRouter {
    function poolManager() external view returns (address);
    function WETH() external view returns (address);
    function nativeScale() external view returns (uint256);
    function buy(address token, uint256 minOut, address to) external payable returns (uint256);
    function sell(address token, uint256 amountInGross, uint256 minOut, address to) external returns (uint256);
}

struct RoutePoolKey {
    address currency0;
    address currency1;
    uint24 fee;
    int24 tickSpacing;
    address hooks;
}

struct RouteSwapParams {
    bool zeroForOne;
    int256 amountSpecified;
    uint160 sqrtPriceLimitX96;
}

/// @notice One intermediate Uniswap v4 pool on the way between native and a launch's quote asset.
/// `zeroForOne` says which way it is crossed: currency0 in / currency1 out when true.
struct PathHop {
    RoutePoolKey key;
    bool zeroForOne;
}

interface IRoutePoolManager {
    function unlock(bytes calldata data) external returns (bytes memory);
    function swap(RoutePoolKey calldata key, RouteSwapParams calldata params, bytes calldata hookData)
        external
        returns (int256 delta);
    function sync(address currency) external;
    function settle() external payable returns (uint256 paid);
    function take(address currency, address to, uint256 amount) external;
}

/// @notice One PancakeSwap hop between the chain's wrapped native and a launch's quote asset.
/// `fee == 0` selects the V2 pair for (`tokenIn`, `tokenOut`); any other value selects the V3 pool of
/// that fee tier. The pool itself is never supplied by the caller: it is looked up from the
/// immutable factory inside the call, so a spoofed pool cannot be named.
struct PancakeHop {
    address tokenIn;
    address tokenOut;
    uint24 fee;
}

interface IRoutePancakeV3Factory {
    function getPool(address tokenA, address tokenB, uint24 fee) external view returns (address);
}

interface IRoutePancakeV2Factory {
    function getPair(address tokenA, address tokenB) external view returns (address);
}

interface IRoutePancakeV3Pool {
    function swap(
        address recipient,
        bool zeroForOne,
        int256 amountSpecified,
        uint160 sqrtPriceLimitX96,
        bytes calldata data
    ) external returns (int256 amount0, int256 amount1);
}

interface IRoutePancakeV2Pair {
    function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
    function swap(uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data) external;
}

/// @title PeddlesRouteSwapRouter — "Pay with ETH" on every launch type
/// @notice Buys and sells any Peddles launch with the chain's native currency, whatever the launch
/// is paired to. A stock-paired token (token/mTSLA, token/USDG, …) can only be traded through
/// `PeddlesStockSwapRouter` with its quote asset in hand; this router gets the caller there from
/// native and back in one transaction:
///
///   buyWithNative:  native -> [hop 1] -> … -> [hop n] -> quote -> PeddlesStockSwapRouter.buy  -> token
///   sellForNative:  token -> PeddlesStockSwapRouter.sell -> quote -> [hop n] -> … -> [hop 1] -> native
///
/// The hops are ordinary Uniswap v4 pools chosen by the caller (the app resolves them off-chain: on
/// Robinhood Chain that is ETH -> stock directly, or WETH -> USDG -> stock, through the same pools
/// the venue's own routers use). Every hop is executed inside ONE PoolManager unlock, so no
/// intermediate asset is ever held between calls: their deltas net to zero in the PoolManager and
/// only the first input is settled and the last output taken. The FINAL leg is always Peddles' own
/// router for that token — the leg that carries the launch's fee hook — so the token's own tax
/// applies exactly once, on that pool, and this router charges nothing of its own (a router never
/// charges on top of the hook).
///
/// NATIVE HOPS. v4 pools can be keyed on the native currency itself (`currency0 == address(0)`),
/// and on Robinhood Chain the deepest stock pools are exactly those (ETH/TSLA, ETH/SPY, ETH/GME,
/// ETH/AAPL, ETH/MSTR …). So a buy path may START with a hop whose input is `address(0)`: the
/// native value is settled into the PoolManager as native, with no wrap. A sell path may END with a
/// hop whose output is `address(0)`: the native is taken from the PoolManager and paid to `to`, with
/// no unwrap. Native is allowed NOWHERE ELSE — as an intermediate currency, as a sell input, or as
/// a buy output — and any such path is refused (`BadPath`) before anything moves. A `WETH`-first
/// (or `WETH`-last) path keeps working exactly as before.
///
/// A token that is not a stock-paired launch (no `coins` record on the launchpad) is WETH-paired
/// or unknown: the whole route is then the direct `PeddlesV4SwapRouter` buy/sell, and a non-empty
/// path is refused (`BadPath`) rather than silently ignored. The V4 router fails closed on a token
/// with no pool.
///
/// EXTERNAL TOKENS (the Terminal). A token the launchpad does NOT know — a vendor-listed token
/// sitting in an ordinary v4 pool on the same chain — trades through `buyExternalWithNative` /
/// `sellExternalForNative`: the same hop machinery, but the path ends AT the token on a buy and
/// starts at it on a sell, with no Peddles leg at all. Every hop is a plain pool the caller chose;
/// this router still charges nothing, still holds nothing at rest, still refuses native anywhere
/// but the ends, and enforces the ONE floor itself on what actually arrived (`balanceOf` delta,
/// so a token that skims its own transfers is floored on what the buyer really gets). A launch
/// the launchpad DOES know is refused here (`NotExternal`): its own router is the leg that
/// carries its fee hook, and this contract never offers a way around it. `EXTERNAL_ROUTES` is
/// the on-chain marker the app reads to know a deployment carries these two entry points.
///
/// ONE slippage floor bounds the whole route: `minTokensOut` on a buy is enforced by the Peddles
/// leg (the last), `minNativeOut` on a sell is enforced here after the last hop. Intermediate hops
/// carry no floors of their own; a hop that only partially fills (a pool that runs out of
/// liquidity) reverts `PartialFill` rather than leaving an intermediate asset behind. If the
/// Peddles leg of a buy partially fills (the pool's token side is exhausted), the quote the pool
/// did not take is refunded to the payer in the quote asset — the same convention as the stock
/// router itself — and `QuoteRefunded` says so. It is not routed back through the hops: a dust
/// remainder can round to zero output on a hop, and a refund path that can revert would block the
/// buy it is meant to protect.
///
/// WHAT "NATIVE" MEANS, PER CHAIN. Fixed at construction from the V4 router's `nativeScale`:
///
///   * `nativeScale == 0` (Sepolia, Robinhood Chain, BSC): `WETH` is a WETH9-style wrapper of the
///     gas token. `msg.value` is wrapped 1:1 for the first hop; a sell's last hop is unwrapped and
///     paid out 1:1. Native in, native out, in wei.
///   * `nativeScale > 0` (Arc: 1e12): there is no wrapper. `WETH` is the 6-decimal USDC ERC-20
///     VIEW of the 18-decimal native balance, so `msg.value` already IS the first hop's input; one
///     quote unit is `nativeScale` wei. The whole units are routed and the sub-unit remainder of
///     `msg.value` (invisible to the ERC-20 interface) is refunded in the same call. A sell pays
///     `out * nativeScale` wei.
///
///   A NATIVE hop is the same on every chain, including Arc: the PoolManager denominates a
///   `currency0 == address(0)` pool in WEI of the gas token, so a native-first buy routes the whole
///   `msg.value` (no scaling, no remainder) and a native-last sell pays the taken wei 1:1. On Arc
///   that means two kinds of USDC pool can exist side by side — native pools in 18-dp wei and
///   `WETH`-view pools in 6-dp units — and the app must pick the hop's key accordingly; the router
///   applies `nativeScale` only to the `WETH`-view legs, never to a native one.
///
/// NO STUCK FUNDS. Nothing is owed by this contract between transactions, and it holds nothing at
/// rest: every asset it touches (native, WETH, each intermediate hop asset, the quote, the launched
/// token) is either delivered, swapped, or refunded to the payer before the call returns; the hop
/// assets only ever exist as in-flight PoolManager deltas inside the unlock. Native arrives here
/// only from `WETH` (an unwrap), the V4 router (its refund of an unfilled buy) or the PoolManager
/// (a native-last hop's `take`), and each is forwarded in the same call. Anything that arrives
/// outside a trade — a forced native send, an ERC-20 pushed here — is a stray, and
/// `sweepStray(asset)` (permissionless, pays only the immutable `treasury`) is its exit. It can
/// never reach in-flight funds because every trade runs under the same reentrancy lock.
///
/// PANCAKESWAP FIRST LEG (BNB Smart Chain). Binance's bStock quote legs trade on PancakeSwap V2/V3,
/// not on Uniswap v4, so the v4 hops above cannot reach them from native. `buyWithNativePancake` /
/// `sellForNativePancake` replace the v4 hops with PancakeSwap hops and keep everything else:
///
///   buyWithNativePancake:  native -> WBNB -> [Pancake hop 1] -> … -> quote -> PeddlesStockSwapRouter.buy  -> token
///   sellForNativePancake:  token -> PeddlesStockSwapRouter.sell -> quote -> [Pancake hop n] -> … -> WBNB -> native
///
/// The token's own pool stays on Uniswap v4 behind the fee hook; only the native <-> quote legs move.
/// Each hop names a token pair and a fee tier, never a pool: the pool is read from the immutable
/// Pancake factory inside the call (`getPool` for V3, `getPair` for V2), and a V3 pool's swap
/// callback is honoured only from the one pool this contract is swapping against at that moment.
/// Each hop must consume its whole input (`PartialFill` otherwise) and its output is measured as a
/// `balanceOf` delta, never taken from the pool's own figure. ONE floor and ONE deadline bound the
/// whole route, as above. Both factories are constructor arguments; a chain without PancakeSwap
/// passes zero and these two entry points refuse (`VenueNotConfigured`). They are only enabled on a
/// WETH9-style chain (`nativeScale == 0`).
///
/// A BARE QUOTE ASSET (the launch form's first buy). `buyExternalWithNativePancake` /
/// `sellExternalForNativePancake` run the same Pancake hops with no Peddles leg at all: native ->
/// WBNB -> hops -> the quote asset itself, delivered to `to`, and back. They take ONLY an asset the
/// launchpad currently ALLOWS as a quote (`quoteConfig(quote).allowed`, read live on every call;
/// `NotQuote` otherwise), so this contract is a way to reach a launch's pairing asset and never a
/// general-purpose PancakeSwap router for arbitrary tokens. The floor is on what ARRIVED here
/// (balance delta), every hop must consume its whole input, and nothing is held at rest.
/// `PANCAKE_QUOTE_ROUTES` is the on-chain marker the app reads before offering them.
///
/// NO OWNER. Every parameter is an immutable read from the two Peddles routers at construction,
/// so the PoolManager, quote wrapper and native scale cannot disagree with the routers it settles
/// through. The two Pancake factories are immutable constructor arguments.
contract PeddlesRouteSwapRouter {
    uint160 private constant MIN_SQRT_PRICE_LIMIT = 4295128740;
    uint160 private constant MAX_SQRT_PRICE_LIMIT = 1461446703485210103287273052203988822378723970341;

    address public immutable poolManager;
    /// @notice The chain's wrapped native (WETH9) — or, when `nativeScale != 0`, the ERC-20 view
    /// of the native balance. Kept under its historical name like the routers it reads it from.
    address public immutable WETH;
    /// @notice 0: `WETH` wraps 1 wei per unit. Otherwise wei per quote base unit (1e12 on Arc).
    uint256 public immutable nativeScale;
    address public immutable stockSwapRouter;
    address public immutable v4SwapRouter;
    /// @notice `PeddlesStockLaunchpad`, read from the stock router; its `coins` table decides
    /// whether a token is stock-paired (and what its quote is).
    address public immutable launchpad;
    /// @notice The only destination `sweepStray` can pay.
    address public immutable treasury;
    /// @notice This deployment carries `buyExternalWithNative` / `sellExternalForNative`. Read by
    /// the app before it offers an external route: a router without it reverts the read, and the
    /// app then offers nothing rather than calldata the router does not understand.
    bool public constant EXTERNAL_ROUTES = true;
    /// @notice This deployment carries `buyWithNativePancake` / `sellForNativePancake`. Whether a
    /// chain can USE them is `pancakeV3Factory` / `pancakeV2Factory` being non-zero.
    bool public constant PANCAKE_ROUTES = true;
    /// @notice This deployment carries `buyExternalWithNativePancake` / `sellExternalForNativePancake`
    /// (a bare launchpad quote asset through PancakeSwap). Read by the app before it offers one.
    bool public constant PANCAKE_QUOTE_ROUTES = true;
    /// @notice PancakeSwap V3 factory, or address(0) where V3 hops are disabled. Immutable.
    address public immutable pancakeV3Factory;
    /// @notice PancakeSwap V2 factory, or address(0) where V2 hops are disabled. Immutable.
    address public immutable pancakeV2Factory;
    /// @dev Pancake V2's swap fee, 0.25%: `PancakePair.swap` checks K with `amountIn * 25 / 10_000`
    /// withheld. A factory whose pairs charge more refuses the swap (`K`); nothing is mispriced.
    uint256 private constant PANCAKE_V2_FEE_KEEP = 9_975;

    uint256 private locked;
    /// @dev Set only for the duration of this contract's own `unlock`, so the callback cannot be
    /// reached by anything but the PoolManager answering a call this contract made.
    bool private expectingCallback;
    /// @dev The one Pancake V3 pool whose `pancakeV3SwapCallback` is honoured, set only around this
    /// contract's own `swap` call on it and cleared by the callback itself.
    address private pancakePool;

    error Locked();
    error InvalidAddress();
    error InvalidAmount();
    error ConfigMismatch();
    error Expired();
    error BadPath();
    error PartialFill();
    error Slippage();
    error NoOutput();
    error BadCallback();
    error TransferFailed();
    error NativeTransferFailed();
    error NativeNotAllowed();
    error NothingToSweep();
    error NotExternal();
    error VenueNotConfigured();
    error NoPool();
    error NotQuote();

    event BoughtWithNative(address indexed payer, address indexed token, uint256 nativeIn, uint256 tokenOut, address to);
    event SoldForNative(address indexed payer, address indexed token, uint256 tokenIn, uint256 nativeOut, address to);
    event NativeRefunded(address indexed payer, uint256 amount);
    event QuoteRefunded(address indexed payer, address indexed quote, uint256 amount);
    event StraySwept(address indexed asset, address indexed to, uint256 amount);

    modifier nonReentrant() {
        if (locked != 0) revert Locked();
        locked = 1;
        _;
        locked = 0;
    }

    /// @param stockSwapRouter_ `PeddlesStockSwapRouter` for this chain (the final leg of every
    /// stock-paired route). Its `poolManager` and `launchpad` are adopted.
    /// @param v4SwapRouter_ `PeddlesV4SwapRouter` for this chain (the whole route for a WETH-paired
    /// token). Its `WETH` and `nativeScale` are adopted; its `poolManager` must match the stock
    /// router's, or the two routers are not from one deployment.
    /// @param treasury_ where `sweepStray` pays strays. Immutable.
    /// @param pancakeV3Factory_ PancakeSwap V3 factory on this chain, or address(0) (no V3 hops).
    /// @param pancakeV2Factory_ PancakeSwap V2 factory on this chain, or address(0) (no V2 hops).
    /// Either, when set, must have code, and the chain must be a WETH9-style one (`nativeScale == 0`).
    constructor(
        address stockSwapRouter_,
        address v4SwapRouter_,
        address treasury_,
        address pancakeV3Factory_,
        address pancakeV2Factory_
    ) {
        if (stockSwapRouter_ == address(0) || v4SwapRouter_ == address(0) || treasury_ == address(0)) {
            revert InvalidAddress();
        }
        address pm = IRouteStockSwapRouter(stockSwapRouter_).poolManager();
        if (pm == address(0) || IRouteV4SwapRouter(v4SwapRouter_).poolManager() != pm) revert ConfigMismatch();
        address weth = IRouteV4SwapRouter(v4SwapRouter_).WETH();
        address pad = IRouteStockSwapRouter(stockSwapRouter_).launchpad();
        if (weth == address(0) || pad == address(0)) revert InvalidAddress();

        uint256 scale = IRouteV4SwapRouter(v4SwapRouter_).nativeScale();
        if (pancakeV3Factory_ != address(0) || pancakeV2Factory_ != address(0)) {
            if (scale != 0) revert ConfigMismatch();
            if (pancakeV3Factory_ != address(0) && pancakeV3Factory_.code.length == 0) revert InvalidAddress();
            if (pancakeV2Factory_ != address(0) && pancakeV2Factory_.code.length == 0) revert InvalidAddress();
        }
        pancakeV3Factory = pancakeV3Factory_;
        pancakeV2Factory = pancakeV2Factory_;

        poolManager = pm;
        WETH = weth;
        nativeScale = scale;
        launchpad = pad;
        stockSwapRouter = stockSwapRouter_;
        v4SwapRouter = v4SwapRouter_;
        treasury = treasury_;
    }

    /// @dev Native arrives here only as an unwrap (`WETH.withdraw`), as the V4 router's refund of an
    /// unfilled native buy, or as the PoolManager paying out a native-last hop (`take`); all three
    /// are forwarded in the same call. Anything else is refused, so the only native that can sit
    /// here is a forced send, which `sweepStray` exits.
    receive() external payable {
        if (msg.sender != WETH && msg.sender != v4SwapRouter && msg.sender != poolManager) revert NativeNotAllowed();
    }

    // ---- Trading -------------------------------------------------------------

    /// @notice Buy `token` with native currency, routed through `hops` to the token's quote asset
    /// and then through Peddles' own router for that token.
    /// @param token the launched token.
    /// @param hops the pools from `WETH` — or from the native currency itself, when the first hop's
    /// input is `address(0)` — to the token's quote, in order. MUST be empty for a WETH-paired token
    /// (its route is the direct V4 router buy). Native is allowed only as the first hop's input.
    /// @param minTokensOut the ONE slippage floor, in token base units.
    /// @param to receives the tokens. Any native not spent (a sub-unit remainder on a native-view
    /// chain, or the V4 router's refund of an unfilled buy) goes back to the caller as native; quote
    /// the Peddles leg did not consume goes back to the caller in the quote asset.
    /// @param deadline unix time after which the call reverts `Expired`.
    function buyWithNative(address token, PathHop[] calldata hops, uint256 minTokensOut, address to, uint256 deadline)
        external
        payable
        nonReentrant
        returns (uint256 tokenOut)
    {
        if (block.timestamp > deadline) revert Expired();
        if (token == address(0) || to == address(0)) revert InvalidAddress();
        if (msg.value == 0) revert InvalidAmount();
        // Native this call did not bring. Everything above it at the end is the caller's refund.
        uint256 nativeBefore = address(this).balance - msg.value;

        address quote = _quoteOf(token);
        if (quote == address(0)) {
            if (hops.length != 0) revert BadPath();
            tokenOut = IRouteV4SwapRouter(v4SwapRouter).buy{value: msg.value}(token, minTokensOut, to);
        } else {
            bool nativeFirst = hops.length != 0 && _hopInput(hops[0]) == address(0);
            _checkPath(hops, nativeFirst ? address(0) : WETH, quote, nativeFirst, false);
            tokenOut = _buyStock(token, quote, hops, minTokensOut, to, nativeFirst);
        }
        _refundNative(nativeBefore);
        emit BoughtWithNative(msg.sender, token, msg.value, tokenOut, to);
    }

    /// @notice Sell `amountIn` of `token` for native currency: through Peddles' own router to the
    /// token's quote, then through `hops` back to `WETH`, unwrapped and paid to `to`.
    /// @param hops the pools from the token's quote to `WETH` — or to the native currency itself,
    /// when the last hop's output is `address(0)` — in order (the REVERSE of a buy path). MUST be
    /// empty for a WETH-paired token. Native is allowed only as the last hop's output.
    /// @param minNativeOut the ONE slippage floor, in native wei on every chain.
    /// @return nativeOut native wei paid to `to`. Tokens the Peddles router did not consume
    /// (a partial fill) go back to the caller.
    function sellForNative(
        address token,
        uint256 amountIn,
        PathHop[] calldata hops,
        uint256 minNativeOut,
        address to,
        uint256 deadline
    ) external nonReentrant returns (uint256 nativeOut) {
        if (block.timestamp > deadline) revert Expired();
        if (token == address(0) || to == address(0)) revert InvalidAddress();
        if (amountIn == 0) revert InvalidAmount();

        // The path is checked before anything is pulled, so a wrong one costs only gas.
        address quote = _quoteOf(token);
        bool nativeLast = hops.length != 0 && _hopOutput(hops[hops.length - 1]) == address(0);
        if (quote == address(0)) {
            if (hops.length != 0) revert BadPath();
        } else {
            _checkPath(hops, quote, nativeLast ? address(0) : WETH, false, nativeLast);
        }

        uint256 tokenBefore = IRouteERC20(token).balanceOf(address(this));
        _safeTransferFrom(token, msg.sender, address(this), amountIn);
        // What actually arrived is what is sold; a token that skims its own transfers cannot make
        // this contract sell more than it holds.
        amountIn = IRouteERC20(token).balanceOf(address(this)) - tokenBefore;

        if (quote == address(0)) {
            _approve(token, v4SwapRouter, amountIn);
            nativeOut = IRouteV4SwapRouter(v4SwapRouter).sell(token, amountIn, minNativeOut, to);
        } else {
            nativeOut = _sellStock(token, amountIn, hops, minNativeOut, to, nativeLast);
        }

        // NO STUCK INPUT. Both Peddles routers refund what a thin pool did not consume to their
        // caller, which is this contract; it goes straight on to the seller.
        uint256 unspent = IRouteERC20(token).balanceOf(address(this)) - tokenBefore;
        if (unspent > 0) _safeTransfer(token, msg.sender, unspent);
        emit SoldForNative(msg.sender, token, amountIn, nativeOut, to);
    }

    // ---- External tokens ---------------------------------------------------------

    /// @notice Buy `token` — one the launchpad does NOT know — with native currency, through `hops`
    /// that end at the token itself. No Peddles leg: the last hop's output IS the token.
    /// @param token the token bought. Refused (`NotExternal`) when the launchpad has a `coins`
    /// record for it: a launch trades through its own router and its own fee hook.
    /// @param hops the pools from `WETH` — or from the native currency, when the first hop's input
    /// is `address(0)` — to `token`, in order. Never empty. Native is allowed only as the first
    /// hop's input.
    /// @param minTokensOut the ONE floor, in token base units, on what actually ARRIVES here for `to`.
    /// @param to receives the tokens. Native the route did not spend (a sub-unit remainder on a
    /// native-view chain) goes back to the caller.
    /// @param deadline unix time after which the call reverts `Expired`.
    function buyExternalWithNative(
        address token,
        PathHop[] calldata hops,
        uint256 minTokensOut,
        address to,
        uint256 deadline
    ) external payable nonReentrant returns (uint256 tokenOut) {
        if (block.timestamp > deadline) revert Expired();
        if (token == address(0) || to == address(0)) revert InvalidAddress();
        if (msg.value == 0) revert InvalidAmount();
        if (hops.length == 0 || token == WETH) revert BadPath();
        if (_quoteOf(token) != address(0)) revert NotExternal();
        uint256 nativeBefore = address(this).balance - msg.value;

        bool nativeFirst = _hopInput(hops[0]) == address(0);
        _checkPath(hops, nativeFirst ? address(0) : WETH, token, nativeFirst, false);

        // What ARRIVED is what is delivered and floored — never the pool's own figure, which a
        // token that skims its transfers overstates.
        uint256 tokenBefore = IRouteERC20(token).balanceOf(address(this));
        _runHops(hops, nativeFirst ? msg.value : _wrap(msg.value));
        tokenOut = IRouteERC20(token).balanceOf(address(this)) - tokenBefore;
        if (tokenOut == 0) revert NoOutput();
        if (tokenOut < minTokensOut) revert Slippage();
        _safeTransfer(token, to, tokenOut);

        _refundNative(nativeBefore);
        emit BoughtWithNative(msg.sender, token, msg.value, tokenOut, to);
    }

    /// @notice Sell `amountIn` of `token` — one the launchpad does NOT know — for native currency,
    /// through `hops` that start at the token and end at `WETH` (unwrapped) or at the native
    /// currency itself (paid 1:1 in wei).
    /// @param hops the pools from `token` to `WETH` — or to the native currency, when the last
    /// hop's output is `address(0)` — in order. Never empty. Native is allowed only as the last
    /// hop's output.
    /// @param minNativeOut the ONE floor, in native wei on every chain.
    /// @return nativeOut native wei paid to `to`. Every hop must consume its whole input
    /// (`PartialFill` otherwise), so nothing of the seller's is ever left here.
    function sellExternalForNative(
        address token,
        uint256 amountIn,
        PathHop[] calldata hops,
        uint256 minNativeOut,
        address to,
        uint256 deadline
    ) external nonReentrant returns (uint256 nativeOut) {
        if (block.timestamp > deadline) revert Expired();
        if (token == address(0) || to == address(0)) revert InvalidAddress();
        if (amountIn == 0) revert InvalidAmount();
        if (hops.length == 0 || token == WETH) revert BadPath();
        if (_quoteOf(token) != address(0)) revert NotExternal();

        // The path is checked before anything is pulled, so a wrong one costs only gas.
        bool nativeLast = _hopOutput(hops[hops.length - 1]) == address(0);
        _checkPath(hops, token, nativeLast ? address(0) : WETH, false, nativeLast);

        uint256 tokenBefore = IRouteERC20(token).balanceOf(address(this));
        _safeTransferFrom(token, msg.sender, address(this), amountIn);
        // What actually arrived is what is sold.
        amountIn = IRouteERC20(token).balanceOf(address(this)) - tokenBefore;

        uint256 out = _runHops(hops, amountIn);
        nativeOut = nativeLast ? out : _unwrap(out);
        if (nativeOut < minNativeOut) revert Slippage();
        _sendNative(to, nativeOut);
        emit SoldForNative(msg.sender, token, amountIn, nativeOut, to);
    }

    // ---- PancakeSwap first leg -----------------------------------------------------

    /// @notice Buy a STOCK-PAIRED launch with native currency, reaching its quote asset through
    /// PancakeSwap: native -> `WETH` (wrapped) -> `hops` -> quote -> Peddles' own router -> token.
    /// @param token a stock-paired launch. Anything else is refused (`BadPath`): a WETH-paired
    /// launch has no quote leg to reach and trades through `buyWithNative` with no hops.
    /// @param hops PancakeSwap hops from `WETH` to the token's quote, in order. Never empty.
    /// @param minTokensOut the ONE slippage floor, in token base units, enforced by the Peddles leg.
    /// @param to receives the tokens. Quote the Peddles leg did not consume goes back to the caller
    /// in the quote asset, as on `buyWithNative`.
    function buyWithNativePancake(
        address token,
        PancakeHop[] calldata hops,
        uint256 minTokensOut,
        address to,
        uint256 deadline
    ) external payable nonReentrant returns (uint256 tokenOut) {
        if (block.timestamp > deadline) revert Expired();
        if (token == address(0) || to == address(0)) revert InvalidAddress();
        if (msg.value == 0) revert InvalidAmount();
        address quote = _quoteOf(token);
        if (quote == address(0)) revert BadPath();
        _checkPancakePath(hops, WETH, quote);
        uint256 nativeBefore = address(this).balance - msg.value;

        uint256 quoteIn = _runPancake(hops, _wrap(msg.value));
        tokenOut = _buyStockLeg(token, quote, quoteIn, minTokensOut, to);

        _refundNative(nativeBefore);
        emit BoughtWithNative(msg.sender, token, msg.value, tokenOut, to);
    }

    /// @notice Sell `amountIn` of a STOCK-PAIRED launch for native currency: Peddles' own router to
    /// the quote, then `hops` on PancakeSwap back to `WETH`, unwrapped and paid to `to`.
    /// @param hops PancakeSwap hops from the token's quote to `WETH`, in order. Never empty.
    /// @param minNativeOut the ONE slippage floor, in native wei.
    /// @return nativeOut native wei paid to `to`. Tokens the Peddles router did not consume go back
    /// to the caller.
    function sellForNativePancake(
        address token,
        uint256 amountIn,
        PancakeHop[] calldata hops,
        uint256 minNativeOut,
        address to,
        uint256 deadline
    ) external nonReentrant returns (uint256 nativeOut) {
        if (block.timestamp > deadline) revert Expired();
        if (token == address(0) || to == address(0)) revert InvalidAddress();
        if (amountIn == 0) revert InvalidAmount();
        address quote = _quoteOf(token);
        if (quote == address(0)) revert BadPath();
        // The path is checked before anything is pulled, so a wrong one costs only gas.
        _checkPancakePath(hops, quote, WETH);

        uint256 tokenBefore = IRouteERC20(token).balanceOf(address(this));
        _safeTransferFrom(token, msg.sender, address(this), amountIn);
        amountIn = IRouteERC20(token).balanceOf(address(this)) - tokenBefore;

        // What the Peddles leg actually paid here, never its return value.
        uint256 quoteBefore = IRouteERC20(quote).balanceOf(address(this));
        _approve(token, stockSwapRouter, amountIn);
        IRouteStockSwapRouter(stockSwapRouter).sell(token, amountIn, 0, address(this));
        uint256 quoteOut = IRouteERC20(quote).balanceOf(address(this)) - quoteBefore;

        nativeOut = _unwrap(_runPancake(hops, quoteOut));
        if (nativeOut < minNativeOut) revert Slippage();
        _sendNative(to, nativeOut);

        uint256 unspent = IRouteERC20(token).balanceOf(address(this)) - tokenBefore;
        if (unspent > 0) _safeTransfer(token, msg.sender, unspent);
        emit SoldForNative(msg.sender, token, amountIn, nativeOut, to);
    }

    /// @notice Buy a launchpad QUOTE ASSET itself (e.g. a bStock) with native currency through
    /// PancakeSwap: native -> `WETH` (wrapped) -> `hops` -> `quote`, paid to `to`. No Peddles leg.
    /// @param quote an asset the launchpad allows as a quote right now; anything else `NotQuote`.
    /// @param hops PancakeSwap hops from `WETH` to `quote`, in order. Never empty.
    /// @param minQuoteOut the ONE floor, in `quote` base units, on what ARRIVED here.
    /// @param deadline unix time after which the call reverts `Expired`.
    function buyExternalWithNativePancake(
        address quote,
        PancakeHop[] calldata hops,
        uint256 minQuoteOut,
        address to,
        uint256 deadline
    ) external payable nonReentrant returns (uint256 quoteOut) {
        if (block.timestamp > deadline) revert Expired();
        if (to == address(0)) revert InvalidAddress();
        if (msg.value == 0) revert InvalidAmount();
        _checkQuoteAsset(quote);
        _checkPancakePath(hops, WETH, quote);

        // A balance delta measured around the last hop: what arrived, never the pool's figure. The
        // Pancake legs only run on a wrapper chain, so the whole `msg.value` is wrapped and none is left.
        quoteOut = _runPancake(hops, _wrap(msg.value));
        if (quoteOut < minQuoteOut) revert Slippage();
        _safeTransfer(quote, to, quoteOut);
        emit BoughtWithNative(msg.sender, quote, msg.value, quoteOut, to);
    }

    /// @notice Sell `amountIn` of a launchpad QUOTE ASSET for native currency through PancakeSwap:
    /// `quote` -> `hops` -> `WETH`, unwrapped and paid to `to`. No Peddles leg.
    /// @param quote an asset the launchpad allows as a quote right now; anything else `NotQuote`.
    /// @param hops PancakeSwap hops from `quote` to `WETH`, in order. Never empty.
    /// @param minNativeOut the ONE floor, in native wei.
    /// @return nativeOut native wei paid to `to`. Every hop consumes its whole input, so nothing of
    /// the seller's is left here.
    function sellExternalForNativePancake(
        address quote,
        uint256 amountIn,
        PancakeHop[] calldata hops,
        uint256 minNativeOut,
        address to,
        uint256 deadline
    ) external nonReentrant returns (uint256 nativeOut) {
        if (block.timestamp > deadline) revert Expired();
        if (to == address(0)) revert InvalidAddress();
        if (amountIn == 0) revert InvalidAmount();
        _checkQuoteAsset(quote);
        // The path is checked before anything is pulled, so a wrong one costs only gas.
        _checkPancakePath(hops, quote, WETH);

        uint256 before = IRouteERC20(quote).balanceOf(address(this));
        _safeTransferFrom(quote, msg.sender, address(this), amountIn);
        // What actually arrived is what is sold.
        amountIn = IRouteERC20(quote).balanceOf(address(this)) - before;

        nativeOut = _unwrap(_runPancake(hops, amountIn));
        if (nativeOut < minNativeOut) revert Slippage();
        _sendNative(to, nativeOut);
        emit SoldForNative(msg.sender, quote, amountIn, nativeOut, to);
    }

    /// @notice Pancake V3's swap callback. Pays the pool exactly the input this contract asked it to
    /// swap, and only to the pool it is swapping against right now (factory-resolved, set just
    /// before the swap and cleared here, so a second or foreign call is refused).
    function pancakeV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata data) external {
        if (msg.sender != pancakePool || msg.sender == address(0)) revert BadCallback();
        pancakePool = address(0);
        (address tokenIn, bool zeroForOne, uint256 amountIn) = abi.decode(data, (address, bool, uint256));
        int256 owed = zeroForOne ? amount0Delta : amount1Delta;
        // Exact input or nothing: a pool that stopped at the price limit asks for less.
        if (owed <= 0 || uint256(owed) != amountIn) revert PartialFill();
        _safeTransfer(tokenIn, msg.sender, amountIn);
    }

    /// @notice PERMISSIONLESS. Push a stray balance of `asset` (address(0) = native) to `treasury`.
    /// Nothing is owed here between transactions, so anything found at rest is a stray; and every
    /// trade runs under the reentrancy lock, so this can never run while funds are in flight.
    /// On a native-view chain the native and the `WETH` interface are one balance: sweeping either
    /// moves the same pot, and neither can strand the other.
    function sweepStray(address asset) external nonReentrant returns (uint256 amount) {
        if (asset == address(0)) {
            amount = address(this).balance;
            if (amount == 0) revert NothingToSweep();
            _sendNative(treasury, amount);
        } else {
            amount = IRouteERC20(asset).balanceOf(address(this));
            if (amount == 0) revert NothingToSweep();
            _safeTransfer(asset, treasury, amount);
        }
        emit StraySwept(asset, treasury, amount);
    }

    // ---- Route legs ------------------------------------------------------------

    /// @dev native -> hops -> quote -> stock router. Quote the stock router hands back (a partial
    /// final fill) is refunded to the payer in kind, so nothing stays here. A native-first path
    /// settles `msg.value` itself into the first hop; otherwise it is wrapped (or, on a native-view
    /// chain, scaled) into `WETH` first.
    function _buyStock(
        address token,
        address quote,
        PathHop[] calldata hops,
        uint256 minTokensOut,
        address to,
        bool nativeFirst
    ) private returns (uint256 tokenOut) {
        uint256 quoteIn = _runHops(hops, nativeFirst ? msg.value : _wrap(msg.value));
        tokenOut = _buyStockLeg(token, quote, quoteIn, minTokensOut, to);
    }

    /// @dev `quoteIn` of `quote` held here -> stock router -> token to `to`. Quote the stock router
    /// hands back (a partial final fill) is refunded to the payer in kind.
    function _buyStockLeg(address token, address quote, uint256 quoteIn, uint256 minTokensOut, address to)
        private
        returns (uint256 tokenOut)
    {
        uint256 quoteBefore = IRouteERC20(quote).balanceOf(address(this)) - quoteIn;
        _approve(quote, stockSwapRouter, quoteIn);
        tokenOut = IRouteStockSwapRouter(stockSwapRouter).buy(token, quoteIn, minTokensOut, to);

        uint256 unspent = IRouteERC20(quote).balanceOf(address(this)) - quoteBefore;
        if (unspent > 0) {
            _safeTransfer(quote, msg.sender, unspent);
            emit QuoteRefunded(msg.sender, quote, unspent);
        }
    }

    /// @dev token -> stock router -> quote -> hops -> WETH -> native to `to`. A native-last path
    /// already holds native after the last hop (the PoolManager's `take` paid it here), so there
    /// is nothing to unwrap or scale.
    function _sellStock(
        address token,
        uint256 amountIn,
        PathHop[] calldata hops,
        uint256 minNativeOut,
        address to,
        bool nativeLast
    ) private returns (uint256 nativeOut) {
        _approve(token, stockSwapRouter, amountIn);
        uint256 quoteOut = IRouteStockSwapRouter(stockSwapRouter).sell(token, amountIn, 0, address(this));
        uint256 out = _runHops(hops, quoteOut);
        nativeOut = nativeLast ? out : _unwrap(out);
        if (nativeOut < minNativeOut) revert Slippage();
        _sendNative(to, nativeOut);
    }

    /// @dev Every hop in one unlock. No hops (a launch whose quote IS `WETH`) is the identity.
    function _runHops(PathHop[] calldata hops, uint256 amountIn) private returns (uint256 amountOut) {
        if (amountIn == 0) revert InvalidAmount();
        if (hops.length == 0) return amountIn;
        expectingCallback = true;
        bytes memory ret = IRoutePoolManager(poolManager).unlock(abi.encode(hops, amountIn));
        expectingCallback = false;
        amountOut = abi.decode(ret, (uint256));
        if (amountOut == 0) revert NoOutput();
    }

    function unlockCallback(bytes calldata data) external returns (bytes memory) {
        if (msg.sender != poolManager || !expectingCallback) revert BadCallback();
        (PathHop[] memory hops, uint256 amountIn) = abi.decode(data, (PathHop[], uint256));

        uint256 amount = amountIn;
        for (uint256 i; i < hops.length; ++i) {
            amount = _swapHop(hops[i], amount);
        }
        // Intermediate deltas net to zero; only the ends move tokens.
        PathHop memory first = hops[0];
        PathHop memory last = hops[hops.length - 1];
        _settle(first.zeroForOne ? first.key.currency0 : first.key.currency1, amountIn);
        IRoutePoolManager(poolManager).take(last.zeroForOne ? last.key.currency1 : last.key.currency0, address(this), amount);
        return abi.encode(amount);
    }

    /// @dev Exact-input swap of one hop. The pool must consume the whole input: a partial fill
    /// would leave the difference as an intermediate asset with no owner, so it is refused.
    function _swapHop(PathHop memory hop, uint256 amountIn) private returns (uint256 out) {
        RouteSwapParams memory params = RouteSwapParams({
            zeroForOne: hop.zeroForOne,
            amountSpecified: -int256(amountIn),
            sqrtPriceLimitX96: hop.zeroForOne ? MIN_SQRT_PRICE_LIMIT : MAX_SQRT_PRICE_LIMIT
        });
        int256 delta = IRoutePoolManager(poolManager).swap(hop.key, params, "");
        int128 amount0 = int128(delta >> 128);
        int128 amount1 = int128(delta);
        int128 inputDelta = hop.zeroForOne ? amount0 : amount1;
        int128 outputDelta = hop.zeroForOne ? amount1 : amount0;
        if (inputDelta >= 0) revert InvalidAmount();
        if (outputDelta <= 0) revert NoOutput();
        if (uint256(uint128(-inputDelta)) != amountIn) revert PartialFill();
        out = uint256(uint128(outputDelta));
    }

    // ---- PancakeSwap hops ------------------------------------------------------

    /// @dev Every Pancake hop in order, each with its whole input. Returns what the last hop
    /// delivered here, measured as a balance delta.
    function _runPancake(PancakeHop[] calldata hops, uint256 amountIn) private returns (uint256 amount) {
        amount = amountIn;
        for (uint256 i; i < hops.length; ++i) {
            if (amount == 0) revert InvalidAmount();
            PancakeHop calldata h = hops[i];
            uint256 before = IRouteERC20(h.tokenOut).balanceOf(address(this));
            if (h.fee == 0) _pancakeV2(h.tokenIn, h.tokenOut, amount);
            else _pancakeV3(h.tokenIn, h.tokenOut, h.fee, amount);
            amount = IRouteERC20(h.tokenOut).balanceOf(address(this)) - before;
            if (amount == 0) revert NoOutput();
        }
    }

    /// @dev Exact-input swap on the factory's V3 pool for (tokenIn, tokenOut, fee). The callback
    /// pays exactly `amountIn` or reverts `PartialFill`.
    function _pancakeV3(address tokenIn, address tokenOut, uint24 fee, uint256 amountIn) private {
        address pool = IRoutePancakeV3Factory(pancakeV3Factory).getPool(tokenIn, tokenOut, fee);
        if (pool == address(0)) revert NoPool();
        bool zeroForOne = tokenIn < tokenOut;
        pancakePool = pool;
        IRoutePancakeV3Pool(pool).swap(
            address(this),
            zeroForOne,
            int256(amountIn),
            zeroForOne ? MIN_SQRT_PRICE_LIMIT : MAX_SQRT_PRICE_LIMIT,
            abi.encode(tokenIn, zeroForOne, amountIn)
        );
        // The callback clears it; a pool that returned without calling back took nothing.
        if (pancakePool != address(0)) revert BadCallback();
    }

    /// @dev Exact-input swap on the factory's V2 pair for (tokenIn, tokenOut). The input is pushed
    /// first and what the pair actually received above its reserve is what is priced, so a token
    /// that skims its own transfers is priced on what arrived.
    function _pancakeV2(address tokenIn, address tokenOut, uint256 amountIn) private {
        address pair = IRoutePancakeV2Factory(pancakeV2Factory).getPair(tokenIn, tokenOut);
        if (pair == address(0)) revert NoPool();
        _safeTransfer(tokenIn, pair, amountIn);
        (uint256 r0, uint256 r1,) = IRoutePancakeV2Pair(pair).getReserves();
        bool zeroForOne = tokenIn < tokenOut;
        (uint256 rIn, uint256 rOut) = zeroForOne ? (r0, r1) : (r1, r0);
        uint256 inWithFee = (IRouteERC20(tokenIn).balanceOf(pair) - rIn) * PANCAKE_V2_FEE_KEEP;
        uint256 out = (inWithFee * rOut) / (rIn * 10_000 + inWithFee);
        if (out == 0) revert NoOutput();
        IRoutePancakeV2Pair(pair).swap(zeroForOne ? 0 : out, zeroForOne ? out : 0, address(this), "");
    }

    /// @dev `hops` must chain `from` -> `to`, never be empty, and use only venues configured here.
    function _checkPancakePath(PancakeHop[] calldata hops, address from, address to) private view {
        if (hops.length == 0) revert BadPath();
        address cur = from;
        for (uint256 i; i < hops.length; ++i) {
            PancakeHop calldata h = hops[i];
            if (h.tokenIn != cur || h.tokenOut == cur || h.tokenOut == address(0)) revert BadPath();
            if ((h.fee == 0 ? pancakeV2Factory : pancakeV3Factory) == address(0)) revert VenueNotConfigured();
            cur = h.tokenOut;
        }
        if (cur != to) revert BadPath();
    }

    /// @dev Only an asset the launchpad allows as a quote right now. Read live, so a quote the
    /// launchpad de-lists stops being reachable here in the same block.
    function _checkQuoteAsset(address quote) private view {
        (bool allowed,,) = IRouteStockLaunchpad(launchpad).quoteConfig(quote);
        if (!allowed) revert NotQuote();
    }

    // ---- Path ------------------------------------------------------------------

    /// @dev `hops` must be a chain from `from` to `to`: each hop's input is the previous hop's
    /// output. The native currency (`address(0)`) may appear ONLY as the first hop's input when
    /// `nativeStart` (a buy) or as the last hop's output when `nativeEnd` (a sell); anywhere else it
    /// would be an intermediate native balance, which nothing here settles. Checked before anything
    /// moves, so a wrong path costs only gas.
    function _checkPath(PathHop[] calldata hops, address from, address to, bool nativeStart, bool nativeEnd)
        private
        pure
    {
        address cur = from;
        uint256 last = hops.length; // one past the end; `last - 1` is only read when non-empty
        for (uint256 i; i < last; ++i) {
            PathHop calldata h = hops[i];
            if (h.key.currency0 == h.key.currency1) revert BadPath();
            (address input, address output) =
                h.zeroForOne ? (h.key.currency0, h.key.currency1) : (h.key.currency1, h.key.currency0);
            if (input == address(0) && !(nativeStart && i == 0)) revert BadPath();
            if (output == address(0) && !(nativeEnd && i + 1 == last)) revert BadPath();
            if (input != cur) revert BadPath();
            cur = output;
        }
        if (cur != to) revert BadPath();
    }

    function _hopInput(PathHop calldata h) private pure returns (address) {
        return h.zeroForOne ? h.key.currency0 : h.key.currency1;
    }

    function _hopOutput(PathHop calldata h) private pure returns (address) {
        return h.zeroForOne ? h.key.currency1 : h.key.currency0;
    }

    /// @dev The quote asset of a stock-paired launch, or address(0) for any other token.
    function _quoteOf(address token) private view returns (address quote) {
        address creator;
        (creator, quote,,,,) = IRouteStockLaunchpad(launchpad).coins(token);
        if (creator == address(0)) return address(0);
    }

    // ---- Native <-> quote ------------------------------------------------------

    /// @dev Native wei -> `WETH` units held here. Wraps on a WETH9 chain. On a native-view chain
    /// the value is already the balance; only the whole units are routed, and the remainder is
    /// left as native for the caller's refund rather than refused.
    function _wrap(uint256 nativeAmount) private returns (uint256 units) {
        uint256 scale = nativeScale;
        if (scale == 0) {
            IRouteWETH(WETH).deposit{value: nativeAmount}();
            return nativeAmount;
        }
        units = nativeAmount / scale;
        if (units == 0) revert InvalidAmount();
    }

    /// @dev `WETH` units held here -> native wei held here. Returns the wei amount.
    function _unwrap(uint256 units) private returns (uint256 nativeAmount) {
        uint256 scale = nativeScale;
        if (scale == 0) {
            IRouteWETH(WETH).withdraw(units);
            return units;
        }
        return units * scale;
    }

    /// @dev Send the caller everything above the native balance the call started with.
    function _refundNative(uint256 nativeBefore) private {
        uint256 back = address(this).balance - nativeBefore;
        if (back == 0) return;
        _sendNative(msg.sender, back);
        emit NativeRefunded(msg.sender, back);
    }

    // ---- Settlement + transfers ------------------------------------------------

    /// @dev Pay `amount` of `currency` into the PoolManager. Native (`address(0)`) is settled with
    /// value and no `sync`, as v4 requires; an ERC-20 is synced, transferred and settled.
    function _settle(address currency, uint256 amount) private {
        uint256 paid;
        if (currency == address(0)) {
            paid = IRoutePoolManager(poolManager).settle{value: amount}();
        } else {
            IRoutePoolManager(poolManager).sync(currency);
            _safeTransfer(currency, poolManager, amount);
            paid = IRoutePoolManager(poolManager).settle();
        }
        if (paid != amount) revert TransferFailed();
    }

    function _approve(address token, address spender, uint256 amount) private {
        (bool ok, bytes memory data) =
            token.call(abi.encodeWithSelector(IRouteERC20.approve.selector, spender, amount));
        if (!ok || (data.length != 0 && !abi.decode(data, (bool)))) revert TransferFailed();
    }

    function _safeTransfer(address token, address to, uint256 amount) private {
        (bool ok, bytes memory data) = token.call(abi.encodeWithSelector(IRouteERC20.transfer.selector, to, amount));
        if (!ok || (data.length != 0 && !abi.decode(data, (bool)))) revert TransferFailed();
    }

    function _safeTransferFrom(address token, address from, address to, uint256 amount) private {
        (bool ok, bytes memory data) =
            token.call(abi.encodeWithSelector(IRouteERC20.transferFrom.selector, from, to, amount));
        if (!ok || (data.length != 0 && !abi.decode(data, (bool)))) revert TransferFailed();
    }

    function _sendNative(address to, uint256 amount) private {
        (bool ok,) = payable(to).call{value: amount}("");
        if (!ok) revert NativeTransferFailed();
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": false,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "forge-std/=lib/forge-std/src/",
    "@uniswap/v4-core/=lib/v4-core/",
    "@uniswap/v4-periphery/=lib/v4-periphery/",
    "solady/=lib/solady/",
    "@openzeppelin/contracts/=lib/infinity-core/lib/openzeppelin-contracts/contracts/",
    "permit2/=lib/v4-periphery/lib/permit2/",
    "infinity-core/=lib/infinity-core/",
    "lib/infinity-core/lib/pancake-create3-factory/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/infinity-core/lib/pancake-create3-factory/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/infinity-core/lib/pancake-create3-factory/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/infinity-core/lib/pancake-create3-factory/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/lib/forge-std/:ds-test/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/lib/forge-std/lib/ds-test/src/",
    "lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/lib/forge-std/:ds-test/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/lib/forge-std/lib/ds-test/src/",
    "lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/infinity-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/infinity-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/infinity-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/infinity-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/infinity-core/lib/pancake-create3-factory/lib/openzeppelin-contracts/:erc4626-tests/=lib/infinity-core/lib/pancake-create3-factory/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/infinity-core/lib/pancake-create3-factory/lib/openzeppelin-contracts/:erc4626-tests/=lib/infinity-core/lib/pancake-create3-factory/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/v4-periphery/lib/permit2/lib/forge-std/:ds-test/=lib/v4-periphery/lib/permit2/lib/forge-std/lib/ds-test/src/",
    "lib/v4-periphery/lib/permit2/lib/forge-std/:ds-test/=lib/v4-periphery/lib/permit2/lib/forge-std/lib/ds-test/src/",
    "lib/v4-periphery/lib/permit2/lib/solmate/:ds-test/=lib/v4-periphery/lib/permit2/lib/solmate/lib/ds-test/src/",
    "lib/v4-periphery/lib/permit2/lib/solmate/:ds-test/=lib/v4-periphery/lib/permit2/lib/solmate/lib/ds-test/src/",
    "lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/v4-periphery/lib/v4-core/lib/solmate/:ds-test/=lib/v4-periphery/lib/v4-core/lib/solmate/lib/ds-test/src/",
    "lib/v4-periphery/lib/v4-core/lib/solmate/:ds-test/=lib/v4-periphery/lib/v4-core/lib/solmate/lib/ds-test/src/",
    "lib/infinity-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/infinity-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/infinity-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/infinity-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/infinity-core/lib/pancake-create3-factory/:forge-gas-snapshot/=lib/infinity-core/lib/pancake-create3-factory/lib/forge-gas-snapshot/src/",
    "lib/infinity-core/lib/pancake-create3-factory/:forge-gas-snapshot/=lib/infinity-core/lib/pancake-create3-factory/lib/forge-gas-snapshot/src/",
    "lib/infinity-core/lib/pancake-create3-factory/:openzeppelin-contracts/=lib/infinity-core/lib/pancake-create3-factory/lib/openzeppelin-contracts/",
    "lib/infinity-core/lib/pancake-create3-factory/:openzeppelin-contracts/=lib/infinity-core/lib/pancake-create3-factory/lib/openzeppelin-contracts/",
    "lib/infinity-core/lib/solmate/:ds-test/=lib/infinity-core/lib/solmate/lib/ds-test/src/",
    "lib/infinity-core/lib/solmate/:ds-test/=lib/infinity-core/lib/solmate/lib/ds-test/src/",
    "lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/v4-core/lib/solmate/:ds-test/=lib/v4-core/lib/solmate/lib/ds-test/src/",
    "lib/v4-core/lib/solmate/:ds-test/=lib/v4-core/lib/solmate/lib/ds-test/src/",
    "lib/v4-periphery/lib/permit2/:solmate/=lib/v4-periphery/lib/permit2/lib/solmate/",
    "lib/v4-periphery/lib/permit2/:solmate/=lib/v4-periphery/lib/permit2/lib/solmate/",
    "lib/v4-periphery/lib/permit2/:forge-gas-snapshot/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
    "lib/v4-periphery/lib/permit2/:forge-gas-snapshot/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
    "lib/v4-periphery/lib/permit2/:openzeppelin-contracts/=lib/v4-periphery/lib/permit2/lib/openzeppelin-contracts/",
    "lib/v4-periphery/lib/permit2/:openzeppelin-contracts/=lib/v4-periphery/lib/permit2/lib/openzeppelin-contracts/",
    "lib/v4-periphery/lib/v4-core/:solmate/=lib/v4-periphery/lib/v4-core/lib/solmate/",
    "lib/v4-periphery/lib/v4-core/:solmate/=lib/v4-periphery/lib/v4-core/lib/solmate/",
    "lib/v4-periphery/lib/v4-core/:openzeppelin-contracts/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
    "lib/v4-periphery/lib/v4-core/:openzeppelin-contracts/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
    "lib/infinity-core/:solmate/=lib/infinity-core/lib/solmate/",
    "lib/infinity-core/:solmate/=lib/infinity-core/lib/solmate/",
    "lib/infinity-core/:openzeppelin-contracts/=lib/infinity-core/lib/openzeppelin-contracts/",
    "lib/infinity-core/:openzeppelin-contracts/=lib/infinity-core/lib/openzeppelin-contracts/",
    "lib/v4-core/:solmate/=lib/v4-core/lib/solmate/",
    "lib/v4-core/:solmate/=lib/v4-core/lib/solmate/",
    "lib/v4-core/:openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
    "lib/v4-core/:openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
    "lib/v4-periphery/:v4-core/=lib/v4-periphery/lib/v4-core/src/",
    "lib/v4-periphery/:v4-core/=lib/v4-periphery/lib/v4-core/src/",
    "@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
    "@openzeppelin/=lib/infinity-core/lib/openzeppelin-contracts/",
    "ds-test/=lib/infinity-core/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/infinity-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-gas-snapshot/=lib/infinity-core/lib/forge-gas-snapshot/src/",
    "halmos-cheatcodes/=lib/infinity-core/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "hardhat/=lib/v4-core/node_modules/hardhat/",
    "openzeppelin-contracts/=lib/infinity-core/lib/openzeppelin-contracts/",
    "pancake-create3-factory/=lib/infinity-core/lib/pancake-create3-factory/",
    "solmate/=lib/infinity-core/lib/solmate/",
    "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.