V4 positions

Plan, register, read, transfer and withdraw Mesh V4 positions, held as NFTs and made of in-place bins.

A V4 position is a set of MeshBinV4 bins owned by one NFT. Whoever holds the NFT controls every bin: withdrawing, repricing and moving liquidity all need it, and sending the NFT sends the position. Each bin is one UTXO at one grid level. It holds BCH and the pair's token and trades in place: every fill recreates the same UTXO at the same address with new balances.

Trading needs nothing new. POST /api/v1/quote, /router/quote and the solver route through V4 bins together with V3 pools and Cauldron, and a quote's hops[].contract shows MeshBinV4.

All V4 routes are under /api/v1/v4. Amounts are strings of base units (sats or token units). Categories are 64-hex in display order. Write routes are rate-limited per client (V4_RATE_LIMIT_PER_MIN, default 30).

The flow

  1. Pick a seed. This is a UTXO in the LP's wallet that is output #0 of its transaction. Its txid becomes the position's category, i.e. the NFT's token ID. If the wallet has none, send yourself a small amount first: that transaction's output 0 is a seed.
  2. Preview the position.
  3. Build the genesis. Input 0 is the seed. Add funding inputs (BCH, plus the token if there are ask bins). Then add the preview's outputs in order, followed by your change. Sign and broadcast.
  4. Register the genesis.

POST /api/v1/v4/positions/preview

Plan a position: bins on the price grid, the NFT, the exact genesis outputs and the metadata. Nothing is stored except the plan's registry (for pinning).

Parameter In Type Required Description
tokenCat body string yes The token the position trades against BCH (64-hex category).
binStepBps body number no Grid step in basis points, 1–1000. Default 100 (1%). Level i of step s is (1 + s/10000)^i sats per token unit.
lowIndex / highIndex body number no The range as grid levels (at most 128 bins). Or give lowPrice / highPrice in sats per token unit (snapped to the nearest level).
marketIndex body number yes Bins at or below this level start as BCH bids; above it, token asks. Or marketPrice.
depositSats body string no BCH for the bid bins (each gets at least 2,000 sats or is left out).
depositTokens body string no Tokens for the ask bins. Each ask bin also carries 1,000 sats.
shape body string no spot (even), curve (most near the market) or bidask (most at the edges). Default spot.
strength body string no gentle, standard (default) or aggressive.
seedTxid body string yes Txid whose output #0 the wallet spends at input 0. It becomes the position's category.
owner body string yes Cashaddr the NFT goes to (token-aware or not).
name body string no Shown by wallets (BCMR). Default: 'Mesh range <low>–<high> sats/unit'.

Genesis outputs, in this order (the server checks them when you register):

# Role What it is
0 identity 800 sats to Mesh's metadata key. Whoever spends output 0 can publish new metadata for the position, so Mesh keeps it, and transfers of the position never touch it
1 nft The position NFT: a mutable NFT of the new category with the v1 commitment, to owner
2… bin One output per bin: its P2SH32 locking bytecode, its sats and, for ask bins, its tokens
last metadata OP_RETURN 'BCMR' <sha256> 'ipfs://<cid>': where wallets find the position's name and fields

Add change outputs after these. A bin buys at its own level and sells one level up, so each round trip through it earns one grid step.

POST /api/v1/v4/positions/:category/metadata

Pin the planned BCMR registry on IPFS. Only registries the server planned (or registered) can be pinned. The provider must return the same CID the genesis publishes, or nothing is published.

Parameter In Type Required Description
category path string yes The position category (the seed txid).

The CID is computed from the registry's exact bytes (CIDv1, raw, sha2-256), so the genesis can carry it before anything is uploaded. Pinning can happen before or after broadcast, or be repeated with another provider. Servers set METADATA_PIN_PROVIDER=pinata with PINATA_JWT, or kubo with IPFS_API_URL (and IPFS_API_TOKEN) for any Kubo-compatible endpoint, such as Filebase or your own node.

GET /api/v1/v4/metadata/:category.json

The registry file itself, exactly as published (its sha256 is the one on chain). CORS open.

POST /api/v1/v4/positions

Register a broadcast genesis. The server reads it from the chain and checks: input 0 spends an output #0 (the category is its txid); exactly one NFT of the category, not minting, with no fungible amount; a valid v1 commitment; every listed bin names the category and is funded in this transaction. The bins then quote and fill at once.

Parameter In Type Required Description
genesisTxid body string yes Txid of the broadcast genesis.
bins body array yes The bins' params, as in the preview's register.body.bins (1–512).
pairName body string no Label, e.g. BCH/pUSD.

GET /api/v1/v4/positions

Positions. With holder: the positions whose NFT that address holds now, read from the chain. Ownership follows the NFT, so this changes when the NFT is sent.

Parameter In Type Required Description
holder query string no A cashaddr. Returns its positions with the NFT outpoint.
token query string no Only positions of this token (without holder).
limit query number no 1–200, default 50 (without holder).

GET /api/v1/v4/positions/:category

One position: commitment, metadata, totals and every bin with its live UTXO, prices and what it can trade now. valueAtBidSats is what the bins would pay to unwind at their own bids.

Parameter In Type Required Description
category path string yes Position category.
holder query string no If this address holds the NFT, holder is filled in.

GET /api/v1/v4/positions/:category/activity

Every transaction that touched the position's bins, read from the chain (nothing is stored): deposits, fills and withdrawals, newest first. buy = a trader bought tokens from the bin (it received sats), sell = a trader sold tokens to it.

Parameter In Type Required Description
category path string yes Position category.
limit query number no 1–500, default 100.

POST /api/v1/v4/positions/:category/withdraw-plan

An unsigned withdrawal for the NFT holder: the chosen bins are spent through their owner path, the NFT is returned unchanged, and BCH and tokens go to the holder (or to). The fee comes out of the withdrawn sats, so the holder signs only the NFT input.

Parameter In Type Required Description
holder body string yes The address holding the NFT (checked on chain).
bins body array no Bin indexes; all bins when omitted.
to body string no Where the BCH and tokens go. Default: the holder.

To use a withdraw plan, build the transaction with the inputs and outputs in the given order. Each bin input uses its unlockingBytecode as given; it names the NFT input by index (nftInputIndex). Sign the NFT input with the holder's key, then broadcast.

POST /api/v1/v4/migrate/plan

Move a V3 range strategy to a V4 position in one transaction: every live V3 pool is docked (owner signature, as in a V3 rebalance) and the V4 position opens with the same range, step and shape, funded from what the V3 pools hold. A V3 bin spans levels i..i+1 like a V4 bin at level i, so the levels carry over exactly. A range that has drifted into one asset moves with every bin on that side.

Parameter In Type Required Description
strategyId body string yes The V3 strategy (template range).
seedTxid body string yes Txid of the owner's output #0 spent at input 0: the new position's category.
owner body string no Where the NFT goes. Default: the strategy owner's token address.
name body string no Name shown by wallets.

Building the migration: input 0 is the seed. Then come the close UTXOs, each unlocked with the V3 pool's dock(ownerPk, ownerSig), exactly as a V3 rebalance does. Then the v4.outputs in order, with your change last (leftSats less the network fee). Register the V4 position as usual. The V3 strategy's pools are empty afterwards.

GET /api/v1/v4/bins

Every live V4 bin of a token, by price: the V4 part of the order book.

Parameter In Type Required Description
token query string yes 64-hex category.

GET /api/v1/v4/grid

Grid levels and their prices, for picking a range. Use from/to (levels) or fromPrice/toPrice (sats per token unit); at most 500 levels.

Parameter In Type Required Description
step query number no Bin step in bps, 1–1000 (default 100).
from / to query number no Level range.

Building the genesis in code

import { TransactionBuilder, SignatureTemplate } from 'cashscript';
import { hexToBin } from '@bitauth/libauth';

const plan = await (await fetch(`${API}/api/v1/v4/positions/preview`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(req) })).json();
const tb = new TransactionBuilder({ provider });
tb.addInput(seedUtxo, wallet.unlockP2PKH());          // input 0: the seed (txid = plan.category, vout 0)
tb.addInput(tokenUtxo, wallet.unlockP2PKH());         // tokens for the ask bins, if any
for (const o of plan.outputs) {                        // in order: identity, NFT, bins, metadata
  tb.addOutput({
    to: hexToBin(o.lockingBytecode),
    amount: BigInt(o.valueSatoshis),
    ...(o.token ? { token: { category: o.token.category, amount: BigInt(o.token.amount), ...(o.token.nft ? { nft: o.token.nft } : {}) } } : {}),
  });
}
// then token change and BCH change; sign and broadcast, then:
await fetch(`${API}/api/v1/v4/positions`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ genesisTxid, bins: plan.register.body.bins }) });

Notes