Skip to content
Verified contractPartialMIT

PeddlesV4SwapRouter

Address0xdaa33f9591757734e5e676f41f3d292f1cdf1978
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,008
Creation transaction
0xf241cd3b50…69d3bebdcf

src/PeddlesV4SwapRouter.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 IPeddlesV4RouterERC20 {
    function transfer(address to, uint256 amount) external returns (bool);
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
    function balanceOf(address owner) external view returns (uint256);
}

interface IPeddlesV4RouterWETH is IPeddlesV4RouterERC20 {
    function deposit() external payable;
    function withdraw(uint256) external;
}

interface IPeddlesCreatorFeeHookMinimal {
    function creatorFeeBpsFor(address token) external view returns (uint16);
    function recordCreatorFee(address token, uint256 amount) external;
    function recordCreatorShare(address token, uint256 amount) external;
    function recordCreatorFeeToken(address token, uint256 amount) external;
}

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

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

interface IPeddlesV4PoolManager {
    function unlock(bytes calldata data) external returns (bytes memory);
    function swap(PeddlesV4PoolKey calldata key, PeddlesV4SwapParams 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 Minimal Peddles token/quote Uniswap v4 router for active pools.
/// buy():  native -> quote -> token
/// sell(): token -> quote -> native
///
/// NATIVE IN, NATIVE OUT, ON EVERY CHAIN. `buy` takes `msg.value` and `sell` pays native, and both
/// `minOut` (sell) and the returned `out` (sell) are NATIVE WEI. Only the pool leg is in the quote
/// ERC-20 (`WETH`, kept under its historical name). How native becomes the quote is fixed per chain
/// at construction by `nativeScale`:
///
///   * `nativeScale == 0`: the quote is a WETH9-style wrapper (Sepolia, Robinhood Chain). Native is
///     wrapped with `deposit` and unwrapped with `withdraw`, one wei per base unit.
///   * `nativeScale  > 0`: the quote is an ERC-20 VIEW of the native balance (Arc: native USDC has 18
///     decimals, the ERC-20 at 0x3600...0000 has 6, and `balanceOf == floor(native / 1e12)`). There is
///     nothing to wrap: `msg.value` already IS the quote balance. One quote base unit is `nativeScale`
///     wei, so `buy` refuses a `msg.value` that is not a whole number of quote units; a remainder
///     would be invisible to the quote interface and could never be swapped or refunded exactly.
///     Every native payment out is a whole number of quote units, so no dust is ever created here.
///     The router's own fee must be 0 in this mode (a hooked router's already is): the native and
///     quote treasury ledgers would be two claims on one balance.
contract PeddlesV4SwapRouter {
    uint24 public constant LP_FEE = 10000; // 1%
    int24 public constant TICK_SPACING = 200;
    uint16 public constant MAX_CREATOR_FEE_BPS = 500;

    // Router trade fee (bps of the trade). Owner-settable within [0, MAX_FEE_BPS]; hard-capped
    // so it can never be set abusively. Default 1.5%. STORAGE, not constant, so tuning is a
    // setter call. Read via feeBps() for backward compatibility.
    uint16 public constant MAX_FEE_BPS = 500; // 5% hard cap on the trade fee
    uint16 public tradeFeeBps = 100; // 1% platform trade fee

    // Creator/treasury split of the per-token creator fee. A CONSTANT since 2026-09-16: the setter
    // was an owner lever with no effect on a hooked router (whose fee is forced to 0) and a live one
    // on a hookless configuration. Kept as a public getter for ABI compatibility.
    uint16 public constant creatorShareBps = 5_000;

    // Buyback-and-burn flywheel: an owner-settable slice of the treasury's WETH cut is diverted
    // to the flywheel instead of the treasury. Off by default (flywheel == 0).
    uint16 public constant MAX_FLYWHEEL_SHARE_BPS = 10_000;
    address public flywheel;
    uint16 public flywheelShareBps;

    uint160 private constant MIN_SQRT_PRICE_LIMIT = 4295128740;
    uint160 private constant MAX_SQRT_PRICE_LIMIT = 1461446703485210103287273052203988822378723970341;

    address public owner;
    address public treasury;
    address public immutable poolManager;
    address public immutable WETH;
    // `hook` is the CreatorFeeHook LEDGER the router records creator fees into (out-of-band); it is
    // NOT the pool's on-chain v4 hook. RETIRED for hooked deployments: with `poolHook` set, the router
    // fee is forced to 0 (`FeeStackingForbidden`), so no creator slice is ever carved and the ledger
    // receives nothing — deploy it as address(0). `poolHook` is the hooks field of the traded pool's key and
    // must match how the pool was created (address(0) = hookless, the default). Conflating the two
    // pointed the router at a non-existent pool and made hookless-pool trades revert.
    /// IMMUTABLE since 2026-09-16 (`setHook` removed): a re-pointable ledger was an owner lever over
    /// where a hookless router's creator slice went, and inert on the hooked deployment.
    address public immutable hook;
    /// @notice The on-chain v4 hook of every pool this router trades. IMMUTABLE: a settable pool
    /// hook re-pointed every buy and sell (clog releases and dev buys included) at a different pool
    /// key — one anybody can create at any price — in a single owner transaction.
    address public immutable poolHook;

    /// @notice How native maps onto the quote. 0: the quote is a WETH9 wrapper (deposit/withdraw,
    /// 1 wei per base unit). Non-zero: the quote is an ERC-20 view of the native balance and one
    /// quote base unit is `nativeScale` wei (1e12 on Arc). See the contract notice.
    uint256 public immutable nativeScale;

    uint256 public ethFeeCollected;
    uint256 public wethFeeCollected;
    uint256 public creatorFeeCollectedWeth;

    // ---- Treasury auto-sweep (batching) -------------------------------------------------
    // Every trade still routes 100% of the treasury cut to the treasury, but it is BATCHED:
    // the cut is accrued per asset and pushed automatically by the first trade that brings the
    // pending balance to or above that asset's threshold. A dust trade therefore does not pay
    // for its own transfer; the trade that crosses the line pays it, and pushes the WHOLE
    // accrued amount. No keeper and no manual step are required.
    //
    // Assets are keyed by address; address(0) is native ETH (the buy-side fee).
    //
    // DECIMALS: a threshold is expressed in the ASSET'S OWN BASE UNITS. Never assume 18.
    // treasuryThresholdOverride semantics:
    //   0 = no override, use DEFAULT_TREASURY_THRESHOLD
    //   1 = push on every trade (any non-zero cut is >= 1), i.e. batching off for that asset
    //   n = accrue until the pending balance reaches n base units
    //
    /// @notice Default sweep minimum, in base units, FOR 18-DECIMAL ASSETS ONLY (native ETH and
    /// WETH here). 0.01 ether == 1e16 wei. A 6-decimal quote (e.g. USDG on Robinhood Chain) would
    /// read this as 10,000,000,000 whole tokens — an operator MUST configure such an asset
    /// explicitly with setTreasuryThreshold(asset, 0.01 * 10**6 = 10_000). Never assume 18.
    uint256 public constant DEFAULT_TREASURY_THRESHOLD = 0.01 ether; // 1e16 base units (18dp)

    mapping(address => uint256) public pendingTreasury;
    mapping(address => uint256) public treasuryThresholdOverride;

    uint256 private locked;

    error NotOwner();
    error Locked();
    error InvalidAddress();
    error InvalidFee();
    error InvalidAmount();
    error Slippage();
    error NoOutput();
    error BadCallback();
    error TransferFailed();
    error EthTransferFailed();
    error EthNotAllowed();
    error NothingPending();
    error ReservedBalance();
    /// @notice A router that trades HOOKED pools must not also charge its own fee: the hook already
    /// taxes every swap, so a router fee on top would bill the trader twice for one trade.
    error FeeStackingForbidden();

    event RouterFeeCollected(address indexed payer, address indexed currency, uint256 amount);
    event CreatorFeeCollected(address indexed payer, address indexed token, address indexed hook, uint256 amount);
    event FeeBpsUpdated(uint16 feeBps);
    event CreatorFeeSplitUpdated(uint16 creatorShareBps);
    event FlywheelUpdated(address indexed flywheel);
    event FlywheelShareUpdated(uint16 flywheelShareBps);
    event FlywheelFunded(address indexed flywheel, address indexed currency, uint256 amount);
    event TreasuryThresholdUpdated(address indexed asset, uint256 threshold);
    event TreasuryAccrued(address indexed asset, uint256 amount, uint256 pending);
    event TreasurySwept(address indexed asset, address indexed to, uint256 amount, bool automatic);

    modifier onlyOwner() {
        if (msg.sender != owner) revert NotOwner();
        _;
    }

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

    /// @param initialOwner The administrative owner. AN EXPLICIT PARAMETER, NOT `msg.sender`:
    /// this router's address is CREATE2-mined for the `1978` vanity suffix, and under CREATE2
    /// `msg.sender` is the deterministic-deployment proxy (0x4e59b448...), which nobody controls.
    /// Taking the owner from `msg.sender` would deploy a permanently unadministrable router.
    /// @param _poolHook the hooks field of every traded pool key (address(0) = hookless). A hooked
    /// router must charge nothing itself (`FeeStackingForbidden`).
    /// @param _nativeScale 0 for a WETH9-style quote; otherwise wei per quote base unit of a quote that
    /// is an ERC-20 view of native (1e12 on Arc). A non-zero scale requires a zero router fee.
    constructor(
        address initialOwner,
        address _treasury,
        address _poolManager,
        address _weth,
        address _hook,
        uint16 _feeBps,
        address _poolHook,
        uint256 _nativeScale
    ) {
        if (initialOwner == address(0)) revert InvalidAddress();
        if (_treasury == address(0) || _poolManager == address(0) || _weth == address(0)) revert InvalidAddress();
        if (_feeBps > MAX_FEE_BPS) revert InvalidFee();
        if ((_poolHook != address(0) || _nativeScale != 0) && _feeBps != 0) revert FeeStackingForbidden();
        nativeScale = _nativeScale;
        poolHook = _poolHook;
        tradeFeeBps = _feeBps;
        owner = initialOwner;
        treasury = _treasury;
        poolManager = _poolManager;
        WETH = _weth;
        hook = _hook;
    }

    receive() external payable {
        if (msg.sender != WETH) revert EthNotAllowed();
    }

    function setTreasury(address _treasury) external onlyOwner {
        if (_treasury == address(0)) revert InvalidAddress();
        treasury = _treasury;
    }

    function feeBps() external view returns (uint16) {
        return tradeFeeBps;
    }

    /// @notice Owner-settable router trade fee, hard-capped at MAX_FEE_BPS (5%).
    function setFeeBps(uint16 _feeBps) external onlyOwner {
        if (_feeBps > MAX_FEE_BPS) revert InvalidFee();
        // A hooked router may only charge nothing — see `FeeStackingForbidden`. Nor may a router whose
        // quote is a view of native: its native and quote treasury ledgers would share one balance.
        if (_feeBps != 0 && (poolHook != address(0) || nativeScale != 0)) revert FeeStackingForbidden();
        tradeFeeBps = _feeBps;
        emit FeeBpsUpdated(_feeBps);
    }

    /// @notice Set the buyback-and-burn flywheel; address(0) disables flywheel routing.
    function setFlywheel(address _flywheel) external onlyOwner {
        flywheel = _flywheel;
        emit FlywheelUpdated(_flywheel);
    }

    /// @notice Set the fraction of the treasury cut routed to the flywheel (bps).
    function setFlywheelShareBps(uint16 _bps) external onlyOwner {
        if (_bps > MAX_FLYWHEEL_SHARE_BPS) revert InvalidFee();
        flywheelShareBps = _bps;
        emit FlywheelShareUpdated(_bps);
    }

    // ---- Treasury threshold config + auto-sweep -------------------------------------------

    /// @notice Effective sweep threshold for `asset`, in that asset's BASE UNITS.
    /// address(0) is native ETH.
    function treasuryThresholdFor(address asset) public view returns (uint256) {
        uint256 t = treasuryThresholdOverride[asset];
        return t == 0 ? DEFAULT_TREASURY_THRESHOLD : t;
    }

    /// @notice Set the per-asset auto-sweep minimum, in that asset's OWN base units.
    /// @dev Cannot redirect funds — only the amount at which the accrued cut is pushed to
    /// `treasury`. Pass 0 to fall back to DEFAULT_TREASURY_THRESHOLD, 1 to push on every trade.
    function setTreasuryThreshold(address asset, uint256 threshold) external onlyOwner {
        treasuryThresholdOverride[asset] = threshold;
        emit TreasuryThresholdUpdated(asset, threshold);
    }

    /// @dev Add `amount` to the asset's pending treasury balance and push the WHOLE pending
    /// balance to `treasury` as soon as it reaches that asset's threshold.
    function _accrueTreasury(address asset, uint256 amount) internal {
        if (amount == 0) return;
        uint256 pending = pendingTreasury[asset] + amount;
        if (pending >= treasuryThresholdFor(asset)) {
            pendingTreasury[asset] = 0;
            _payTreasury(asset, pending);
            emit TreasurySwept(asset, treasury, pending, true);
        } else {
            pendingTreasury[asset] = pending;
            emit TreasuryAccrued(asset, amount, pending);
        }
    }

    /// @dev The only way value leaves the pending-treasury ledger. Pays `treasury` and nobody else.
    function _payTreasury(address asset, uint256 amount) internal {
        if (asset == address(0)) _safeTransferETH(treasury, amount);
        else _safeTransfer(asset, treasury, amount);
    }

    /// @notice PERMISSIONLESS. Push an asset's pending treasury balance to `treasury` regardless
    /// of threshold, so a below-threshold balance can never be trapped. There is no recipient
    /// parameter by design: the funds can only ever go to `treasury`.
    function sweepTreasury(address asset) external nonReentrant returns (uint256 amount) {
        amount = pendingTreasury[asset];
        if (amount == 0) revert NothingPending();
        pendingTreasury[asset] = 0;
        _payTreasury(asset, amount);
        emit TreasurySwept(asset, treasury, amount, false);
    }

    /// @dev Route WETH treasury cut: flywheelShareBps to the flywheel (immediately, unchanged),
    /// remainder accrued for the treasury and auto-pushed once it clears the threshold.
    function _routeTreasuryWeth(uint256 amount) internal {
        if (amount == 0) return;
        address fw = flywheel;
        uint16 share = flywheelShareBps;
        uint256 toFlywheel;
        if (fw != address(0) && share > 0) toFlywheel = (amount * share) / 10000;
        if (toFlywheel > 0) {
            _safeTransfer(WETH, fw, toFlywheel);
            emit FlywheelFunded(fw, WETH, toFlywheel);
        }
        uint256 toTreasury = amount - toFlywheel;
        _accrueTreasury(WETH, toTreasury);
    }

    /// @dev Route a native-ETH treasury cut: wrap the flywheel slice to WETH and send it to the
    ///      flywheel; send the remainder as ETH to treasury. Keeps the flywheel WETH-denominated.
    function _routeTreasuryEth(uint256 amount) internal {
        if (amount == 0) return;
        address fw = flywheel;
        uint16 share = flywheelShareBps;
        uint256 toFlywheel;
        if (fw != address(0) && share > 0) toFlywheel = (amount * share) / 10000;
        if (toFlywheel > 0) {
            // Unreachable when nativeScale != 0 (the router fee is forced to 0 there).
            IPeddlesV4RouterWETH(WETH).deposit{value: toFlywheel}();
            _safeTransfer(WETH, fw, toFlywheel);
            emit FlywheelFunded(fw, WETH, toFlywheel);
        }
        uint256 toTreasury = amount - toFlywheel;
        _accrueTreasury(address(0), toTreasury);
    }

    function transferOwnership(address nextOwner) external onlyOwner {
        if (nextOwner == address(0)) revert InvalidAddress();
        owner = nextOwner;
    }

    function buy(address token, uint256 minOut, address to) external payable nonReentrant returns (uint256 out) {
        if (token == address(0) || to == address(0)) revert InvalidAddress();
        if (msg.value == 0) revert InvalidAmount();

        // ---- ONE fee, then split (2026-09-03) ----
        // The trade fee and the creator fee used to be two SEPARATE charges that stacked, so a
        // buyer paid tradeFeeBps + creatorFeeBps. There is now a single fee of tradeFeeBps which
        // is split creator/treasury by creatorShareBps. The buyer pays exactly tradeFeeBps.
        uint256 totalFee = (msg.value * tradeFeeBps) / 10000;
        uint256 amountIn = msg.value - totalFee;
        if (amountIn == 0) revert InvalidAmount();

        // Treasury takes the exact REMAINDER of the one fee, never a second independent
        // multiplication — integer truncation can therefore never strand dust in the router.
        uint256 creatorPortion = _creatorEnabled(token) ? (totalFee * creatorShareBps) / 10000 : 0;
        uint256 treasuryCut = totalFee - creatorPortion;

        if (treasuryCut > 0) {
            ethFeeCollected += treasuryCut;
            _routeTreasuryEth(treasuryCut);
        }
        if (totalFee > 0) emit RouterFeeCollected(msg.sender, address(0), totalFee);

        // Convert the swap input plus the creator's slice to the quote (the hook ledger is
        // quote-denominated). `wrapped` is in quote base units. `quoteBefore` is the balance this call
        // did not bring, measured AFTER the conversion so it is right in both modes: in view mode
        // `msg.value` was already part of the balance before the first line of this function ran.
        uint256 wrapped = _wrap(amountIn + creatorPortion);
        uint256 quoteBefore = IPeddlesV4RouterERC20(WETH).balanceOf(address(this)) - wrapped;
        if (creatorPortion > 0) _recordCreatorShare(token, creatorPortion);

        PeddlesV4PoolKey memory key = _poolKey(token);
        bool zeroForOne = key.currency0 == WETH;
        // Fee-free in view mode, so there `wrapped` is exactly the swap input in quote units.
        out = _swapExactInput(key, zeroForOne, nativeScale == 0 ? amountIn : wrapped, minOut, to);

        // NO STUCK INPUT. A swap that exhausts the pool's liquidity fills partially and settles only
        // what it consumed; the rest of the input would otherwise sit here with no refund path but
        // the owner's rescue. Measured as a DELTA so no pending treasury WETH is touched. Refunded as
        // native, a whole number of quote units, so nothing sub-unit is left behind.
        uint256 unspent = IPeddlesV4RouterERC20(WETH).balanceOf(address(this)) - quoteBefore;
        if (unspent > 0) _safeTransferETH(msg.sender, _unwrap(unspent));
    }

    function sell(address token, uint256 amountInGross, uint256 minOut, address to) external nonReentrant returns (uint256 out) {
        if (token == address(0) || to == address(0)) revert InvalidAddress();
        if (amountInGross == 0) revert InvalidAmount();

        uint256 tokenBefore = IPeddlesV4RouterERC20(token).balanceOf(address(this));
        _safeTransferFrom(token, msg.sender, address(this), amountInGross);

        PeddlesV4PoolKey memory key = _poolKey(token);
        bool zeroForOne = key.currency0 == token;

        // ---- ONE fee, then split (2026-09-03) ----
        // Taken from the TOKEN up front (before swapping) so the creator's share stays
        // denominated in the token. There is no second fee on the WETH proceeds any more: the
        // seller pays exactly tradeFeeBps, split creatorShareBps / remainder.
        uint256 totalFeeToken = (amountInGross * tradeFeeBps) / 10000;
        uint256 creatorPortionToken = _creatorEnabled(token) ? (totalFeeToken * creatorShareBps) / 10000 : 0;
        uint256 treasuryPortionToken = totalFeeToken - creatorPortionToken;
        if (creatorPortionToken > 0) _recordCreatorFeeToken(token, creatorPortionToken);

        // Swap the user's tokens (net of the one fee) -> WETH.
        uint256 tokenToSwap = amountInGross - totalFeeToken;
        if (tokenToSwap == 0) revert InvalidAmount();
        uint256 grossOut = _swapExactInput(key, zeroForOne, tokenToSwap, 0, address(this));
        if (grossOut == 0) revert NoOutput();

        // `minOut` and `out` are NATIVE wei on every chain (identical to quote units on a WETH chain).
        out = nativeScale == 0 ? grossOut : grossOut * nativeScale;
        if (out < minOut) revert Slippage();

        // Swap the treasury's token portion -> WETH -> treasury (via flywheel split, batched).
        if (treasuryPortionToken > 0) {
            uint256 treasuryOut = _swapExactInput(key, zeroForOne, treasuryPortionToken, 0, address(this));
            if (treasuryOut > 0) {
                wethFeeCollected += treasuryOut;
                _routeTreasuryWeth(treasuryOut);
                emit RouterFeeCollected(msg.sender, WETH, treasuryOut);
            }
        }
        _safeTransferETH(to, _unwrap(grossOut));

        // NO STUCK INPUT. A sell into a pool that runs out of quote-side liquidity fills partially and
        // the PoolManager settles only what it consumed. The unconsumed tokens go back to the seller
        // instead of staying here, where only the owner's rescue could reach them. Delta-measured.
        uint256 unspentToken = IPeddlesV4RouterERC20(token).balanceOf(address(this)) - tokenBefore;
        if (unspentToken > 0) _safeTransfer(token, msg.sender, unspentToken);
    }

    function unlockCallback(bytes calldata data) external returns (bytes memory) {
        if (msg.sender != poolManager) revert BadCallback();

        (PeddlesV4PoolKey memory key, bool zeroForOne, uint256 amountIn, uint256 minOut, address recipient) =
            abi.decode(data, (PeddlesV4PoolKey, bool, uint256, uint256, address));

        PeddlesV4SwapParams memory params = PeddlesV4SwapParams({
            zeroForOne: zeroForOne,
            amountSpecified: -int256(amountIn),
            sqrtPriceLimitX96: zeroForOne ? MIN_SQRT_PRICE_LIMIT : MAX_SQRT_PRICE_LIMIT
        });

        int256 delta = IPeddlesV4PoolManager(poolManager).swap(key, params, "");
        int128 amount0 = int128(delta >> 128);
        int128 amount1 = int128(delta);

        int128 inputDelta = zeroForOne ? amount0 : amount1;
        int128 outputDelta = zeroForOne ? amount1 : amount0;
        if (inputDelta >= 0) revert InvalidAmount();
        if (outputDelta <= 0) revert NoOutput();

        uint256 owed = uint256(uint128(-inputDelta));
        uint256 out = uint256(uint128(outputDelta));
        if (out < minOut) revert Slippage();

        address inputCurrency = zeroForOne ? key.currency0 : key.currency1;
        address outputCurrency = zeroForOne ? key.currency1 : key.currency0;

        _settle(inputCurrency, owed);
        IPeddlesV4PoolManager(poolManager).take(outputCurrency, recipient, out);

        return abi.encode(out);
    }

    function _swapExactInput(
        PeddlesV4PoolKey memory key,
        bool zeroForOne,
        uint256 amountIn,
        uint256 minOut,
        address recipient
    ) internal returns (uint256 out) {
        bytes memory ret = IPeddlesV4PoolManager(poolManager).unlock(
            abi.encode(key, zeroForOne, amountIn, minOut, recipient)
        );
        out = abi.decode(ret, (uint256));
    }

    /// @notice The creator's slice of the ONE fee, in bps of the trade (UI helper).
    /// @dev A token's hook config no longer sets a SEPARATE charge — its non-zero feeBps only
    /// says "this token has a creator to pay". The amount is always creatorShareBps of tradeFeeBps.
    function effectiveCreatorFeeBps(address token) external view returns (uint16) {
        if (!_creatorEnabled(token)) return 0;
        return uint16((uint256(tradeFeeBps) * creatorShareBps) / 10000);
    }

    /// @dev True when there is a hook ledger with a creator configured for `token`.
    function _creatorEnabled(address token) internal view returns (bool) {
        address h = hook;
        if (h == address(0)) return false;
        try IPeddlesCreatorFeeHookMinimal(h).creatorFeeBpsFor(token) returns (uint16 bps) {
            return bps != 0;
        } catch {
            return false;
        }
    }

    /// @dev Move the creator's already-split WETH slice into the hook ledger. Uses
    /// recordCreatorShare (100% credit) — recordCreatorFee would split it a SECOND time.
    function _recordCreatorShare(address token, uint256 amount) internal {
        if (amount == 0) return;
        address h = hook;
        if (h == address(0)) return;
        _safeTransfer(WETH, h, amount);
        IPeddlesCreatorFeeHookMinimal(h).recordCreatorShare(token, amount);
        creatorFeeCollectedWeth += amount;
        emit CreatorFeeCollected(msg.sender, token, h, amount);
    }

    // Record the creator's TOKEN-denominated fee share (charged on sells). The 50% creator
    // portion is transferred to the hook here; the 50% treasury portion is swapped to WETH
    // by sell() before this is called, so the treasury is always paid in WETH.
    function _recordCreatorFeeToken(address token, uint256 amount) internal {
        if (amount == 0) return;
        address h = hook;
        if (h == address(0)) return;
        _safeTransfer(token, h, amount);
        IPeddlesCreatorFeeHookMinimal(h).recordCreatorFeeToken(token, amount);
        emit CreatorFeeCollected(msg.sender, token, h, amount);
    }

    /// @dev Native wei -> quote base units held by this router. WETH mode wraps 1:1. View mode wraps
    /// nothing (the native IS the quote balance) and refuses a remainder below one quote unit.
    function _wrap(uint256 nativeAmount) internal returns (uint256) {
        uint256 scale = nativeScale;
        if (scale == 0) {
            IPeddlesV4RouterWETH(WETH).deposit{value: nativeAmount}();
            return nativeAmount;
        }
        if (nativeAmount % scale != 0) revert InvalidAmount();
        return nativeAmount / scale;
    }

    /// @dev Quote base units held by this router -> native wei ready to send. WETH mode unwraps 1:1;
    /// view mode has nothing to unwrap (sending the native moves the same balance).
    function _unwrap(uint256 quoteAmount) internal returns (uint256) {
        uint256 scale = nativeScale;
        if (scale == 0) {
            IPeddlesV4RouterWETH(WETH).withdraw(quoteAmount);
            return quoteAmount;
        }
        return quoteAmount * scale;
    }

    function _poolKey(address token) internal view returns (PeddlesV4PoolKey memory key) {
        if (uint160(token) < uint160(WETH)) {
            key = PeddlesV4PoolKey(token, WETH, LP_FEE, TICK_SPACING, poolHook);
        } else {
            key = PeddlesV4PoolKey(WETH, token, LP_FEE, TICK_SPACING, poolHook);
        }
    }

    function _settle(address currency, uint256 amount) internal {
        IPeddlesV4PoolManager(poolManager).sync(currency);
        _safeTransfer(currency, poolManager, amount);
        // L-2 audit fix (2026-07-14): verify the PoolManager credited exactly what we transferred.
        uint256 paid = IPeddlesV4PoolManager(poolManager).settle();
        require(paid == amount, "SETTLE_MISMATCH");
    }

    function _safeTransfer(address token, address to, uint256 amount) internal {
        (bool ok, bytes memory data) = token.call(abi.encodeWithSelector(IPeddlesV4RouterERC20.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) internal {
        (bool ok, bytes memory data) = token.call(abi.encodeWithSelector(IPeddlesV4RouterERC20.transferFrom.selector, from, to, amount));
        if (!ok || (data.length != 0 && !abi.decode(data, (bool)))) revert TransferFailed();
    }

    function _safeTransferETH(address to, uint256 amount) internal {
        (bool ok, ) = payable(to).call{value: amount}("");
        if (!ok) revert EthTransferFailed();
    }

    /// @dev Rescue can never reach the accrued treasury ledger: only the balance in excess of
    /// pendingTreasury[token] is rescuable. Anyone can sweepTreasury() first if needed.
    function rescueToken(address token, address to, uint256 amount) external onlyOwner {
        if (to == address(0)) revert InvalidAddress();
        uint256 reserved = pendingTreasury[token];
        if (reserved != 0) {
            uint256 bal = IPeddlesV4RouterERC20(token).balanceOf(address(this));
            if (amount + reserved > bal) revert ReservedBalance();
        }
        _safeTransfer(token, to, amount);
    }

    function rescueETH(address to, uint256 amount) external onlyOwner {
        if (to == address(0)) revert InvalidAddress();
        uint256 reserved = pendingTreasury[address(0)];
        if (reserved != 0 && amount + reserved > address(this).balance) revert ReservedBalance();
        _safeTransferETH(to, amount);
    }
}
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.