Skip to content
Verified contractPartialMIT

PeddlesNftLiquidityReserve

Address0xd1e617c0d65cb67691b72ec954f1371fa10d1978
Balance

0 ETH

 

Transactions

0

 

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,027
Creation transaction
0x78825a3dc4…c97560a718

src/PeddlesNftLiquidityReserve.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 IReserveWETH {
    function deposit() external payable;
    function withdraw(uint256 amount) external;
    function balanceOf(address account) external view returns (uint256);
    function approve(address spender, uint256 amount) external returns (bool);
    function transfer(address to, uint256 amount) external returns (bool);
}

interface IReserveERC20 {
    function balanceOf(address account) external view returns (uint256);
    function transfer(address to, uint256 amount) external returns (bool);
}

interface IReservePermit2 {
    function approve(address token, address spender, uint160 amount, uint48 expiration) external;
}

interface IReservePositionManager {
    function modifyLiquidities(bytes calldata unlockData, uint256 deadline) external payable;
    function nextTokenId() external view returns (uint256);
    function ownerOf(uint256 tokenId) external view returns (address);
}

/// @dev The WETH-path `PeddlesV4LiquidityExecutor`. Read-only here: this contract never calls a
/// state-changing function on it, it only mirrors its pool configuration so the position it mints
/// lands in the SAME pool the launch's locked token position lives in.
interface IReserveExecutor {
    function poolManager() external view returns (address);
    function positionManager() external view returns (address);
    function quoteToken() external view returns (address);
    function hook() external view returns (address);
    function permit2() external view returns (address);
    function fee() external view returns (uint24);
    function tickSpacing() external view returns (int24);
    function registry() external view returns (address);
}

interface IReserveRegistry {
    function isPeddles(address token) external view returns (bool);
    function liquidityOf(address token)
        external
        view
        returns (
            bool active,
            address quoteToken,
            address poolManager,
            address positionManager,
            address hook,
            bytes32 poolId,
            uint256 positionId,
            uint24 fee,
            int24 tickSpacing,
            uint64 activatedAt
        );
    function venueOf(address token) external view returns (uint8);
}

/// @notice A second venue's liquidity funder (e.g. PancakeSwap Infinity), built after this reserve.
/// It mints and permanently holds the collection's quote-only position on its own venue, and returns
/// any native it did not use to this reserve inside `fund`.
interface IReserveVenueFunder {
    function venue() external view returns (uint8);
    function fund(address token, address collection, bytes calldata params) external payable;
}

interface IReserveERC721 {
    function safeTransferFrom(address from, address to, uint256 tokenId) external;
}

interface IReserveNftFactory {
    function isPeddlesCollection(address collection) external view returns (bool);
    function liquidityFundingReceiver() external view returns (address payable);
}

interface IReserveCollection {
    function owner() external view returns (address);
    function graduated() external view returns (bool);
    function graduatedToken() external view returns (address);
}

/// @title PeddlesNftLiquidityReserve
/// @notice Escrow that turns the 10% "liquidity funding" leg of every NFT mint into REAL
/// quote-side liquidity in the collection's graduated pool, instead of a cash transfer to a
/// treasury address that carried no on-chain obligation to become liquidity.
///
/// WHAT CHANGED, AND WHAT DID NOT
/// ------------------------------
/// Nothing about the 80/10/10 split changed. The creator's 80% and the treasury's 10% are
/// byte-for-byte what they were. The only difference is the DESTINATION of the 10% liquidity leg
/// for BONDING collections: `PeddlesNFTFactory` constructs them with this contract as their
/// `liquidityFundingReceiver`, so the leg accrues here, per collection, instead of leaving the
/// system. ART collections are untouched and still pay the plain treasury address at mint time —
/// an art collection has no graduation and therefore no pool to seed, so accruing its share here
/// would be an inbound path with no outbound purpose.
///
/// GRADUATION IS NOT TOUCHED
/// -------------------------
/// There is deliberately NO call from any graduation orchestrator into this contract. Seeding is a
/// SEPARATE, RETRYABLE transaction (`fundPool`) taken after the collection has graduated and the
/// pool is live. That is the strongest possible reading of "graduation must never revert because of
/// this feature": graduation has no code path into this contract at all, so no state here — an
/// empty reserve, a hostile quote token, a bad tick range, an out-of-gas mint — can affect it.
/// A failed `fundPool` reverts only itself and leaves the reserve exactly where it was.
///
/// NO STUCK FUNDS
/// --------------
/// Every wei that can enter has a way out, on every path:
///   * `fundPool`   — the intended exit: wraps the reserve and mints a quote-only v4 position.
///   * `release`    — pays the reserve to the immutable `liquidityFundingReceiver`, i.e. exactly
///                    where the money went before this contract existed. Callable by the owner or
///                    an operator at any time, and PERMISSIONLESS once `RELEASE_DELAY` has passed
///                    since the collection's first deposit, so the funds are never hostage to a
///                    single key and the exit condition always eventually becomes true. This is
///                    the path for a collection that never graduates, and for one that graduates
///                    to a STOCK pair (see below).
///   * leftovers    — WETH left unspent by a mint is unwrapped and re-credited to the collection's
///                    reserve in the same call, so a conservative liquidity number strands nothing.
///   * `collectAndForwardFees` — permissionless harvest of the minted position's LP fees, paid to
///                    the immutable `liquidityFundingReceiver`. Without it the fees this position
///                    earns would accrue inside Uniswap forever with no claimant.
///   * `sweepUnaccounted` / `rescueToken` — for value forced in outside `receive` (a `selfdestruct`
///                    beneficiary, a stray ERC20 transfer). Both pay the immutable receiver.
///
/// STOCK-PAIRED GRADUATION
/// -----------------------
/// `fundPool` only ever seeds a pool whose quote is the WETH-path executor's `quoteToken`, and it
/// proves that by re-deriving the pool id and matching it against the one the vault registry
/// recorded for the token. A collection graduated through `PeddlesNftStockGraduationOrchestrator`
/// is paired against a tokenised stock, is not in this registry, and therefore cannot be funded
/// here — by construction, not by convention. Converting native currency into a stock token needs
/// a swap, a price source and a slippage policy, none of which belong in a value-holding escrow;
/// that reserve exits through `release` as cash instead.
///
/// THE POSITION IS PERMANENTLY LOCKED
/// ----------------------------------
/// This contract mirrors `PeddlesV4LiquidityExecutor`'s lock invariant exactly. It has no
/// arbitrary-calldata entry point, and the only two PositionManager action sets it can ever emit
/// are built here from compile-time constants:
///   * MINT_POSITION + SETTLE_PAIR  — once per position, in `fundPool`, recipient `address(this)`.
///   * DECREASE_LIQUIDITY + TAKE_PAIR — fee collection only, where the liquidity delta is the
///     constant 0 (in v4 that is exactly "collect fees", it cannot move principal) and the
///     TAKE_PAIR recipient is the constant `address(this)`.
/// It has no path that can BURN_POSITION, decrease real liquidity, `transfer`/`safeTransferFrom`
/// the NFT, `approve` it, or `setApprovalForAll` on the PositionManager. `rescueToken` is ERC20-only
/// and refuses the PositionManager address. Neither the creator, an operator, nor the owner can
/// withdraw the liquidity this contract adds.
contract PeddlesNftLiquidityReserve {
    string public constant VERSION = "PEDDLES_NFT_LIQUIDITY_RESERVE_V1";

    /// @notice The address every exit path pays. Immutable, and read from the NFT factory at
    /// construction so the escrow can never pay somewhere the factory does not already pay.
    address payable public immutable liquidityFundingReceiver;

    /// @notice The `PeddlesNFTFactory` whose bonding collections fund this reserve.
    IReserveNftFactory public immutable nftFactory;

    /// @notice The WETH-path liquidity executor. Consulted for pool configuration only.
    IReserveExecutor public immutable executor;

    /// @notice The executor's pool configuration, SNAPSHOTTED at construction. Every lock check,
    /// approval and pool derivation below reads these, never the executor live: the executor's
    /// PositionManager is what decides which NFT ids `rescueERC721` refuses, so a live read made
    /// the lock only as strong as the executor's configuration.
    address public immutable positionManager;
    address public immutable permit2;
    address public immutable registry;
    address public immutable hook;
    uint24 public immutable fee;
    int24 public immutable tickSpacing;

    /// @notice The quote, snapshotted from `executor.quoteToken()` at construction.
    /// @dev Immutable on purpose: `receive()` must be able to tell an unwrap apart from a mint
    /// deposit without making an external call, because a reverting `receive()` would brick every
    /// NFT mint (`_splitProceeds` sends with `.call` and reverts on failure).
    address public immutable weth;

    /// @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
    /// (Arc's USDC: `balanceOf == floor(native / 1e12)`) and one quote base unit is `nativeScale` wei.
    /// In view mode nothing is wrapped: the reserve's native IS its quote balance, `fundPool` spends
    /// whole quote units of the collection's reserve and the sub-unit remainder stays credited to the
    /// same collection.
    uint256 public immutable nativeScale;

    address public owner;
    mapping(address => bool) public operators;

    /// @notice The second venue's funder and the venue id it serves. WRITE-ONCE and TIMELOCKED.
    ///
    /// @dev A post-deploy slot so a collection that graduates on a venue added later (PancakeSwap
    /// Infinity on BNB Chain) can still turn its 10% reserve into pool depth there. It can never reach
    /// a Uniswap-graduated collection's reserve (the token's registry venue must equal the funder's),
    /// only the collection's own owner can spend a reserve through it, it is set exactly once and gains
    /// effect only `VENUE_FUNDER_DELAY` later, and the universal `release` exit is untouched.
    address public venueFunder;
    uint8 public venueFunderVenue;
    uint64 public venueFunderActiveAt;
    uint64 public constant VENUE_FUNDER_DELAY = 7 days;
    uint8 private constant VENUE_UNISWAP_V4 = 1;

    /// @notice Collection => native currency held for it, in wei. The whole of the accounting.
    mapping(address => uint256) public reserveOf;
    /// @notice Sum of `reserveOf`. Anything above it in `address(this).balance` was forced in.
    uint256 public totalReserved;
    /// @notice Collection => timestamp from which `release` becomes permissionless.
    mapping(address => uint256) public releasableAt;

    /// @notice Collection => v4 position ids this contract minted and holds for it.
    mapping(address => uint256[]) private _positionsOf;

    struct PositionInfo {
        address collection;
        uint24 fee;
        int24 tickSpacing;
        address token;
        address hooks;
    }

    /// @notice Position id => the pool it belongs to. Written once, at mint.
    mapping(uint256 => PositionInfo) public positionInfo;

    /// @notice Delay after a collection's FIRST deposit from which anyone may force `release`.
    /// @dev Long enough that it can never race a real graduation, finite so the exit can never be
    /// blocked by a lost owner key. It is a constant: an owner-tunable delay would be a lever on
    /// somebody else's exit.
    uint256 public constant RELEASE_DELAY = 180 days;

    uint8 private constant ACTION_DECREASE_LIQUIDITY = 0x01;
    uint8 private constant ACTION_MINT_POSITION = 0x02;
    uint8 private constant ACTION_SETTLE_PAIR = 0x0d;
    uint8 private constant ACTION_TAKE_PAIR = 0x11;

    /// @dev Hard-coded liquidity delta for fee collection. A v4 DECREASE_LIQUIDITY of exactly 0
    /// collects accrued fees and touches no principal. No caller, owner included, can change it.
    uint256 private constant FEE_COLLECT_LIQUIDITY_DELTA = 0;

    /// @dev The token side of every mint this contract performs. A quote-ONLY position by
    /// construction: if the supplied range straddles spot the mint would need token, exceed this
    /// bound and revert — which is safe, because `fundPool` is retryable and holds no other state.
    uint128 private constant TOKEN_SIDE_MAX = 0;

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

    error Unauthorized();
    error ReentrantCall();
    error ZeroAddress();
    error NothingReserved();
    error TooEarly();
    error TransferFailed();
    error NotGraduated();
    error PoolMismatch();
    error BadTicks();
    error ZeroLiquidity();
    error AmountTooBig();
    error PositionNotMinted();
    error UnknownPosition();
    error LockedPosition();

    event ERC721Rescued(address indexed collection, uint256 indexed tokenId, address indexed to);
    error QuoteChanged();
    error NoPositionManager();

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
    event OperatorUpdated(address indexed operator, bool allowed);
    event ReserveFunded(address indexed collection, uint256 amount, uint256 newBalance);
    event ReserveReleased(address indexed collection, address indexed to, uint256 amount);
    event QuoteLiquidityAdded(
        address indexed collection,
        address indexed token,
        bytes32 indexed poolId,
        uint256 positionId,
        uint256 quoteSpent,
        uint256 refundedToReserve
    );
    event PositionFeesForwarded(
        uint256 indexed positionId, address indexed to, uint256 amount0, uint256 amount1
    );
    event UnaccountedSwept(address indexed to, uint256 amount);
    event TokenRescued(address indexed token, address indexed to, uint256 amount);
    event VenueFunderSet(address indexed funder, uint8 indexed venue, uint64 activeAt);
    event VenueLiquidityAdded(
        address indexed collection, address indexed token, uint8 indexed venue, uint256 spent, uint256 refundedToReserve
    );

    uint256 private _lock = 1;

    modifier nonReentrant() {
        if (_lock != 1) revert ReentrantCall();
        _lock = 2;
        _;
        _lock = 1;
    }

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

    /// @param initialOwner explicit admin. Never derived from `msg.sender`: the Peddles stack
    /// deploys through the CREATE2 deterministic-deployer proxy, so `msg.sender` here is that proxy.
    /// @param nftFactory_ the `PeddlesNFTFactory` this reserve serves. Its
    /// `liquidityFundingReceiver` becomes this contract's immutable payout address, so the escrow
    /// provably cannot pay anywhere the factory did not already pay.
    /// @param executor_ the WETH-path `PeddlesV4LiquidityExecutor`, read for pool configuration.
    /// @param nativeScale_ 0 for a WETH9-style quote; wei per quote base unit for a quote that is an
    /// ERC-20 view of native (1e12 on Arc). Must match the chain; see `nativeScale`.
    constructor(address initialOwner, address nftFactory_, address executor_, uint256 nativeScale_) {
        if (initialOwner == address(0) || nftFactory_ == address(0) || executor_ == address(0)) {
            revert ZeroAddress();
        }
        owner = initialOwner;
        nativeScale = nativeScale_;
        nftFactory = IReserveNftFactory(nftFactory_);
        executor = IReserveExecutor(executor_);

        address payable receiver = IReserveNftFactory(nftFactory_).liquidityFundingReceiver();
        if (receiver == address(0) || receiver == address(this)) revert ZeroAddress();
        liquidityFundingReceiver = receiver;

        address quote = IReserveExecutor(executor_).quoteToken();
        if (quote == address(0)) revert ZeroAddress();
        weth = quote;

        address posm = IReserveExecutor(executor_).positionManager();
        address registry_ = IReserveExecutor(executor_).registry();
        if (posm == address(0) || registry_ == address(0)) revert ZeroAddress();
        positionManager = posm;
        registry = registry_;
        permit2 = IReserveExecutor(executor_).permit2();
        hook = IReserveExecutor(executor_).hook();
        fee = IReserveExecutor(executor_).fee();
        tickSpacing = IReserveExecutor(executor_).tickSpacing();

        emit OwnershipTransferred(address(0), initialOwner);
    }

    // ------------------------------------------------------------------ admin

    function transferOwnership(address nextOwner) external onlyOwner {
        if (nextOwner == address(0)) revert ZeroAddress();
        emit OwnershipTransferred(owner, nextOwner);
        owner = nextOwner;
    }

    function setOperator(address operator, bool allowed) external onlyOwner {
        if (operator == address(0)) revert ZeroAddress();
        operators[operator] = allowed;
        emit OperatorUpdated(operator, allowed);
    }

    // ---------------------------------------------------------------- inflows

    /// @notice The 10% liquidity leg of a bonding-collection mint arrives here.
    ///
    /// @dev THIS FUNCTION MUST NEVER REVERT. `PeddlesBondingCollection._splitProceeds` sends with
    /// `recipient.call{value: amount}("")` and reverts the whole mint if it fails, so a `require`
    /// here would be a mint-bricking bug. It therefore makes no external call, reads no other
    /// contract, and has no failure branch: it credits and returns.
    ///
    /// Native currency arriving FROM the WETH contract is an unwrap inside `fundPool`, not a
    /// deposit, and is deliberately not credited — `fundPool` re-credits the unwrapped amount to
    /// the correct collection itself.
    receive() external payable {
        if (msg.sender == weth) return;
        // Unspent native returned by the venue funder inside `fundPoolOnVenue`, which re-credits it.
        if (msg.sender == venueFunder) return;
        if (msg.value == 0) return;
        uint256 next = reserveOf[msg.sender] + msg.value;
        reserveOf[msg.sender] = next;
        totalReserved += msg.value;
        if (releasableAt[msg.sender] == 0) releasableAt[msg.sender] = block.timestamp + RELEASE_DELAY;
        emit ReserveFunded(msg.sender, msg.value, next);
    }

    // ----------------------------------------------------------------- views

    function positionsOf(address collection) external view returns (uint256[] memory) {
        return _positionsOf[collection];
    }

    function positionCount(address collection) external view returns (uint256) {
        return _positionsOf[collection].length;
    }

    /// @notice True while a position this contract minted is still owned by this contract.
    /// Front-ends can read this as the on-chain proof behind "seeded liquidity: permanent".
    function lpIsLocked(uint256 positionId) external view returns (bool) {
        if (positionInfo[positionId].token == address(0)) return false;
        return IReservePositionManager(positionManager).ownerOf(positionId) == address(this);
    }

    /// @notice Native currency held that no collection is credited with — only reachable by a
    /// forced transfer (`selfdestruct`, or a coinbase payout), never by `receive`.
    function unaccountedBalance() public view returns (uint256) {
        uint256 bal = address(this).balance;
        uint256 reserved = totalReserved;
        return bal > reserved ? bal - reserved : 0;
    }

    function poolKeyFor(address token) public view returns (PoolKey memory key) {
        address q = weth;
        if (token == address(0) || token == q) revert ZeroAddress();
        (address c0, address c1) = uint160(token) < uint160(q) ? (token, q) : (q, token);
        key = PoolKey({
            currency0: c0,
            currency1: c1,
            fee: fee,
            tickSpacing: tickSpacing,
            hooks: hook
        });
    }

    // ------------------------------------------------------------ the exit(s)

    /// @notice Pay a collection's reserve to the immutable `liquidityFundingReceiver` — exactly
    /// where this money went before this contract existed.
    ///
    /// @dev THE UNIVERSAL EXIT. There is no destination parameter: no caller and no privileged role
    /// can name a payee. Callable by the owner or an operator at any time (for a collection that
    /// graduated to a stock pair, for an abandoned mint, for dust), and by ANYONE once
    /// `RELEASE_DELAY` has elapsed since the collection's first deposit, so a lost owner key cannot
    /// strand it. The permissionless branch is time-gated rather than open precisely so a griefer
    /// cannot front-run a creator's `fundPool` and cash out the seed before it can be deployed.
    function release(address collection) external nonReentrant returns (uint256 amount) {
        if (msg.sender != owner && !operators[msg.sender]) {
            uint256 unlockAt = releasableAt[collection];
            if (unlockAt == 0 || block.timestamp < unlockAt) revert TooEarly();
        }
        amount = reserveOf[collection];
        if (amount == 0) revert NothingReserved();
        reserveOf[collection] = 0;
        totalReserved -= amount;
        _sendNative(liquidityFundingReceiver, amount);
        emit ReserveReleased(collection, liquidityFundingReceiver, amount);
    }

    /// @notice Sweep native currency forced in outside `receive` (a `selfdestruct` beneficiary).
    /// @dev Cannot touch a single wei any collection is credited with: the amount is
    /// `balance - totalReserved`, and the destination is the immutable receiver.
    function sweepUnaccounted() external onlyOwner nonReentrant returns (uint256 amount) {
        amount = unaccountedBalance();
        if (amount == 0) revert NothingReserved();
        _sendNative(liquidityFundingReceiver, amount);
        emit UnaccountedSwept(liquidityFundingReceiver, amount);
    }

    /// @notice Move a stray ERC20 out to the immutable receiver.
    /// @dev ERC20 only, and the PositionManager is refused outright, so this can never reach the
    /// locked position NFT. A v4 PositionManager exposes no `transfer(address,uint256)` anyway.
    ///
    /// NEVER THE NATIVE RESERVE THROUGH ITS OTHER INTERFACE. Where a token is an ERC-20 view of the
    /// native balance (Arc's USDC), transferring it moves the per-collection native reserve past its
    /// books: `totalReserved` would then exceed the balance and the last collections' `release` /
    /// `fundPool` would revert. So any transfer that lowers this contract's native balance reverts.
    /// A stray of such a token is already native here and leaves through `sweepUnaccounted`.
    function rescueToken(address token, uint256 amount) external onlyOwner nonReentrant {
        if (token == positionManager) revert NoPositionManager();
        uint256 nativeBefore = address(this).balance;
        if (!IReserveERC20(token).transfer(liquidityFundingReceiver, amount)) revert TransferFailed();
        if (address(this).balance < nativeBefore) revert TransferFailed();
        emit TokenRescued(token, liquidityFundingReceiver, amount);
    }

    // ------------------------------------------------------- the intended use

    /// @notice Deploy a graduated collection's reserve as REAL quote-side depth in its own pool.
    ///
    /// @dev Wraps the whole reserve to WETH and mints a Uniswap v4 position funded ENTIRELY from
    /// the quote side — the token-side maximum is the compile-time constant 0, so the position is
    /// provably quote-only and this contract never needs, holds, or spends the launched token. The
    /// position NFT is minted to this contract and can never leave it, so the depth it adds sits
    /// under the market permanently; the creator cannot withdraw it, and neither can the protocol.
    ///
    /// Anything the mint does not consume is unwrapped and re-credited to the same collection in
    /// this same call, so an under-sized `liquidity` costs nothing and can simply be retried.
    ///
    /// AUTHORITY: the collection's own owner, read live, and nobody else. The range decides where a
    /// creator's seed sits in the book forever (the position can never be withdrawn), so choosing it
    /// is the creator's call. It used to be open to this contract's owner and operators too, which let
    /// a protocol key lock a collection's whole reserve into a useless range; that shortcut is removed
    /// (2026-09-16). No caller of any kind can name a payee or move value out.
    ///
    /// SAFETY: the pool is not taken on trust. The key is rebuilt from the executor's live config
    /// and its id must equal the one the vault registry recorded when the token's own locked
    /// position was activated. A collection graduated to a stock pair fails that check and must
    /// exit through `release` instead.
    ///
    /// @param collection a graduated bonding collection from this factory
    /// @param tickLower,tickUpper an aligned range strictly on the QUOTE side of spot
    /// @param liquidity the v4 liquidity to mint, computed off-chain from the reserve and the range
    function fundPool(address collection, int24 tickLower, int24 tickUpper, uint128 liquidity)
        external
        nonReentrant
        returns (uint256 positionId, uint256 quoteSpent)
    {
        if (collection == address(0)) revert ZeroAddress();
        if (msg.sender != IReserveCollection(collection).owner()) revert Unauthorized();
        if (!nftFactory.isPeddlesCollection(collection)) revert Unauthorized();
        if (liquidity == 0) revert ZeroLiquidity();

        address token = _graduatedPeddlesToken(collection);
        PoolKey memory key = poolKeyFor(token);
        _requireRegisteredPool(token, key);

        int24 spacing = key.tickSpacing;
        if (tickLower >= tickUpper) revert BadTicks();
        if (spacing <= 0 || tickLower % spacing != 0 || tickUpper % spacing != 0) revert BadTicks();

        uint256 amount = reserveOf[collection];
        if (amount == 0) revert NothingReserved();
        if (amount > type(uint128).max) revert AmountTooBig();
        // Effects before interactions: the reserve is spent now, and whatever the mint leaves is
        // credited back at the end. A revert anywhere below rolls both writes back together.
        reserveOf[collection] = 0;
        totalReserved -= amount;

        uint256 refunded;
        (positionId, quoteSpent, refunded) = _mintQuoteOnlyPosition(token, key, tickLower, tickUpper, liquidity, amount);

        if (refunded != 0) {
            reserveOf[collection] += refunded;
            totalReserved += refunded;
        }

        _positionsOf[collection].push(positionId);
        positionInfo[positionId] = PositionInfo({
            collection: collection,
            fee: key.fee,
            tickSpacing: key.tickSpacing,
            token: token,
            hooks: key.hooks
        });

        emit QuoteLiquidityAdded(
            collection, token, keccak256(abi.encode(key)), positionId, quoteSpent, refunded
        );
    }

    /// @notice Name the second venue's funder. WRITE-ONCE; effective after `VENUE_FUNDER_DELAY`.
    function setVenueFunder(address funder) external onlyOwner {
        if (venueFunderActiveAt != 0) revert Unauthorized();
        if (funder.code.length == 0) revert ZeroAddress();
        uint8 v = IReserveVenueFunder(funder).venue();
        if (v == 0 || v == VENUE_UNISWAP_V4) revert PoolMismatch();
        uint64 activeAt = uint64(block.timestamp) + VENUE_FUNDER_DELAY;
        venueFunder = funder;
        venueFunderVenue = v;
        venueFunderActiveAt = activeAt;
        emit VenueFunderSet(funder, v, activeAt);
    }

    /// @notice Spend a collection's reserve as depth in its graduated pool on the SECOND venue.
    /// Same authority as `fundPool` (the collection's own owner), same graduation proof, and the
    /// token's registry venue must be the funder's venue. Whatever the funder returns is re-credited
    /// to the same collection in this call.
    function fundPoolOnVenue(address collection, bytes calldata params)
        external
        nonReentrant
        returns (uint256 spent)
    {
        address funder = venueFunder;
        uint64 activeAt = venueFunderActiveAt;
        if (activeAt == 0 || block.timestamp < activeAt) revert TooEarly();
        if (collection == address(0)) revert ZeroAddress();
        if (msg.sender != IReserveCollection(collection).owner()) revert Unauthorized();
        if (!nftFactory.isPeddlesCollection(collection)) revert Unauthorized();
        address token = _graduatedPeddlesToken(collection);
        if (IReserveRegistry(registry).venueOf(token) != venueFunderVenue) revert PoolMismatch();

        uint256 amount = reserveOf[collection];
        if (amount == 0) revert NothingReserved();
        reserveOf[collection] = 0;
        totalReserved -= amount;

        uint256 balanceAfterSend = address(this).balance - amount;
        uint256 reservedBefore = totalReserved;
        IReserveVenueFunder(funder).fund{value: amount}(token, collection, params);
        // Anything `receive()` credited to ANOTHER sender during the call is already on the books; it
        // is subtracted so a funder that routes value back through a third contract cannot make the
        // same wei count twice. Only the funder's own return is re-credited to this collection.
        uint256 refunded = (address(this).balance - balanceAfterSend) - (totalReserved - reservedBefore);
        if (refunded > amount) revert AmountTooBig();
        if (refunded != 0) {
            reserveOf[collection] += refunded;
            totalReserved += refunded;
        }
        spent = amount - refunded;
        emit VenueLiquidityAdded(collection, token, venueFunderVenue, spent, refunded);
    }

    /// @dev Kept in its own frame so `fundPool` does not run out of EVM stack slots under via-IR.
    function _mintQuoteOnlyPosition(
        address token,
        PoolKey memory key,
        int24 tickLower,
        int24 tickUpper,
        uint128 liquidity,
        uint256 amount
    ) private returns (uint256 positionId, uint256 quoteSpent, uint256 refunded) {
        address posmAddr = positionManager;
        address quote = weth;
        uint256 scale = nativeScale;

        // `quoteIn` is the reserve in quote base units. WETH mode wraps it 1:1. View mode wraps
        // nothing: the native already is the quote balance, and only whole quote units can be spent,
        // so the sub-unit remainder is never offered to the mint and comes back in `refunded` below.
        uint256 quoteIn;
        if (scale == 0) {
            IReserveWETH(quote).deposit{value: amount}();
            quoteIn = amount;
        } else {
            quoteIn = amount / scale;
        }
        // Everything this call did not bring, measured after the conversion so it is right in both
        // modes (in view mode the whole reserve of every collection is inside this balance).
        uint256 quoteBefore = IReserveWETH(quote).balanceOf(address(this)) - quoteIn;

        _approveQuote(posmAddr, quoteIn);

        // Quote-only by construction: the token side's maximum is the constant 0.
        uint128 amount0Max = key.currency0 == token ? TOKEN_SIDE_MAX : uint128(quoteIn);
        uint128 amount1Max = key.currency1 == token ? TOKEN_SIDE_MAX : uint128(quoteIn);

        bytes memory actions = abi.encodePacked(ACTION_MINT_POSITION, ACTION_SETTLE_PAIR);
        bytes[] memory params = new bytes[](2);
        params[0] =
            abi.encode(key, tickLower, tickUpper, liquidity, amount0Max, amount1Max, address(this), bytes(""));
        params[1] = abi.encode(key.currency0, key.currency1);

        IReservePositionManager posm = IReservePositionManager(posmAddr);
        positionId = posm.nextTokenId();
        posm.modifyLiquidities(abi.encode(actions, params), block.timestamp + 20 minutes);
        if (posm.ownerOf(positionId) != address(this)) revert PositionNotMinted();
        // The NFT is now permanently locked here. No function on this contract can move it.

        _approveQuote(posmAddr, 0);

        // Quote units the mint did not take. `quoteSpent` is reported in quote base units;
        // `refunded` is NATIVE wei, because the reserve is kept in native.
        uint256 leftover = IReserveWETH(quote).balanceOf(address(this)) - quoteBefore;
        quoteSpent = quoteIn - leftover;
        if (scale == 0) {
            refunded = leftover;
            // Back to native so the reserve stays a single denomination with a single exit.
            if (refunded != 0) IReserveWETH(quote).withdraw(refunded);
        } else {
            // Nothing to unwrap. What left this contract is exactly `quoteSpent * scale` wei, so the
            // rest of the reserve, sub-unit remainder included, is still here and is re-credited.
            refunded = amount - quoteSpent * scale;
        }
    }

    /// @dev Approve exactly `amount` of the quote for the PositionManager, through Permit2 when the
    /// deployment uses one. Called again with 0 straight after the mint so no standing allowance is
    /// left behind.
    function _approveQuote(address posmAddr, uint256 amount) private {
        address quote = weth;
        address p2 = permit2;
        if (!IReserveWETH(quote).approve(posmAddr, amount)) revert TransferFailed();
        if (p2 != address(0)) {
            if (amount > type(uint160).max) revert AmountTooBig();
            if (!IReserveWETH(quote).approve(p2, amount)) revert TransferFailed();
            IReservePermit2(p2).approve(quote, posmAddr, uint160(amount), uint48(block.timestamp + 1 hours));
        }
    }

    /// @dev The collection must have graduated through the WETH path into a token this stack's
    /// vault registry knows about. A stock-paired graduation fails here, deliberately.
    function _graduatedPeddlesToken(address collection) private view returns (address token) {
        IReserveCollection c = IReserveCollection(collection);
        if (!c.graduated()) revert NotGraduated();
        token = c.graduatedToken();
        if (token == address(0)) revert NotGraduated();
        if (!IReserveRegistry(registry).isPeddles(token)) revert PoolMismatch();
    }

    /// @dev Prove the key we are about to mint into is the SAME pool the token's own permanently
    /// locked position was activated in. Without this, a config change on the executor could point
    /// the seed at a pool the token does not trade in.
    function _requireRegisteredPool(address token, PoolKey memory key) private view {
        (bool active,,,,, bytes32 registeredPoolId,,,,) = IReserveRegistry(registry).liquidityOf(token);
        if (!active) revert PoolMismatch();
        if (registeredPoolId != keccak256(abi.encode(key))) revert PoolMismatch();
    }

    // --------------------------------------------------------- position fees

    /// @notice Harvest the LP fees the seeded position has earned and forward them to the immutable
    /// `liquidityFundingReceiver`.
    ///
    /// @dev PERMISSIONLESS, and it must exist: the position's principal is locked here forever by
    /// design, but the fees it earns would otherwise accrue inside Uniswap with no claimant, which
    /// is stranded value however it is spelled. There is no destination parameter and no amount
    /// parameter — the action set below is built from constants, the liquidity delta is 0 (in v4,
    /// exactly "collect fees"; it cannot move principal) and the TAKE_PAIR recipient is
    /// `address(this)`, from which the only way onward is the immutable receiver.
    function collectAndForwardFees(uint256 positionId)
        external
        nonReentrant
        returns (uint256 amount0, uint256 amount1)
    {
        PositionInfo memory info = positionInfo[positionId];
        if (info.token == address(0)) revert UnknownPosition();

        // The currencies come from the pool this position was minted into, snapshotted at mint —
        // never re-derived from live executor config, which could since have changed.
        address quote = weth;
        (address c0, address c1) =
            uint160(info.token) < uint160(quote) ? (info.token, quote) : (quote, info.token);

        IReservePositionManager posm = IReservePositionManager(positionManager);
        if (posm.ownerOf(positionId) != address(this)) revert PositionNotMinted();

        uint256 before0 = IReserveERC20(c0).balanceOf(address(this));
        uint256 before1 = IReserveERC20(c1).balanceOf(address(this));

        bytes memory actions = abi.encodePacked(ACTION_DECREASE_LIQUIDITY, ACTION_TAKE_PAIR);
        bytes[] memory params = new bytes[](2);
        // (tokenId, liquidity=0, amount0Min=0, amount1Min=0, hookData) -> collect fees only.
        params[0] = abi.encode(positionId, FEE_COLLECT_LIQUIDITY_DELTA, uint128(0), uint128(0), bytes(""));
        // (currency0, currency1, recipient) -> recipient is hard-coded to this contract.
        params[1] = abi.encode(c0, c1, address(this));

        posm.modifyLiquidities(abi.encode(actions, params), block.timestamp + 20 minutes);

        // The position must still be here afterwards. Belt and braces.
        if (posm.ownerOf(positionId) != address(this)) revert PositionNotMinted();

        amount0 = IReserveERC20(c0).balanceOf(address(this)) - before0;
        amount1 = IReserveERC20(c1).balanceOf(address(this)) - before1;

        if (amount0 != 0 && !IReserveERC20(c0).transfer(liquidityFundingReceiver, amount0)) revert TransferFailed();
        if (amount1 != 0 && !IReserveERC20(c1).transfer(liquidityFundingReceiver, amount1)) revert TransferFailed();

        emit PositionFeesForwarded(positionId, liquidityFundingReceiver, amount0, amount1);
    }

    // -------------------------------------------------------------- internals

    function _sendNative(address payable to, uint256 amount) private {
        (bool ok,) = to.call{value: amount}("");
        if (!ok) revert TransferFailed();
    }

    /// @dev Accept ERC721 safe-transfers so a position can be moved IN. A position this reserve
    /// RECORDED can never leave (see `rescueERC721`); anything else can.
    function onERC721Received(address, address, uint256, bytes calldata) external pure returns (bytes4) {
        return this.onERC721Received.selector;
    }

    /// @notice THE WAY OUT FOR AN ERC721. `onERC721Received` accepts any safe-transfer and nothing
    /// could move one back out: `rescueToken` is ERC-20 shaped and reverts against a PositionManager,
    /// which exposes no `transfer(address,uint256)`. An NFT sent here by mistake was stuck forever.
    ///
    /// The reserve's OWN positions stay put, which was the reason there was no exit at all. That is
    /// now enforced per token id rather than by the absence of a function: `positionInfo` is written
    /// for every position this contract mints for a graduated collection, and any id carrying a
    /// collection is refused. A blanket ban on the PositionManager would be wrong — this contract can
    /// hold a v4 position it never recorded, and that one has no reason to be trapped.
    function rescueERC721(address collection, uint256 tokenId, address to) external onlyOwner {
        if (to == address(0)) revert ZeroAddress();
        // `.token` is the same field `lpIsLocked` treats as "this position is ours", so the
        // rescue and the lock proof can never disagree about which ids are protected.
        if (collection == positionManager && positionInfo[tokenId].token != address(0)) {
            revert LockedPosition();
        }
        IReserveERC721(collection).safeTransferFrom(address(this), to, tokenId);
        emit ERC721Rescued(collection, tokenId, to);
    }
}
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.