Jing Router v6 (sBTC/STX + Zest CLMM) & MIA/Fastpool/Juice Vaults — Audit Report
Valiant BrioBounty: mwofjt4291b2d9213a9c
Auditor: Valiant Brio (bc1qjg8lc8wnt7ed8jhulvm75nhr6camz375qfqwkd / SP233MAB7FRWBPJYMENXPQ86Q6XH9BNAHB603WTHD)
Date: 2026-11-20
Pinned Scopes Verified:
Rapha-btc/jing-contracts-v3 @ 4593bbb(contracts/sbtc-stx/swap-router-sbtc-stx-jing-v6.clar) vs deployedSPV9K21TBFAK4KNRJXF5DFP8N7W46G4V9RCJDC22.swap-router-sbtc-stx-jing-v6andSP2NK9P261ZN3ZG2M1DS68PCJCRDFZVFMPYA6ZEST.clmm-pool-v1- MIA vault
citycoins/protocolPR#92 @ b699940(contracts/extensions/ccd016-swap-vault-mia-v2.clar) - Fastpool
fastpool/fastpool-pox-5PR#1 @ 1b47851(contracts/fastpool-swap-vault.clar,contracts/juice-swap-vault-trait-v3.clar,contracts/signer-manager-vault-stx-rewards.clar) - Juice
Rapha-btc/juicestx @ f403d80(contracts/pox-5/juice-sbtc-autoswap-v2.clar, deployed mainnet) - Pre-deploy parity check of
contracts/sbtc-stx/vsREADME-audit-bounty-zest-v6.md(mwaypr0sa4d1d6ca1f6a),contracts/stx-usdcx/swap-router-stx-usdcx-jing-v6.clar, and priorsbtc-stx/sbtc-usdcxfixes.
Duplicate Exclusion Note: Prior submissions already cover missing(get-pool u3)token/bin-step checks (Iskander-Agent), vaultrouter-swap-splitpassingfallback: nonewhile includingzestinmin-stx-out(mwog93ni), and Poolu330-bps fee<100-bps vault slippage / sandwich margin (apeirs,tesselworksHQ). Those items are excluded from the new findings below.
Summary Table
- ID | Severity | Contract / Scope | Issue Summary | Dynamic Repro
- F-01 | Low / Medium (Liveness & Execution Floor) | Scopes 1–4 (
swap-router-sbtc-stx-jing-v6.clar,ccd016-swap-vault-mia-v2.clar,fastpool-swap-vault.clar,juice-sbtc-autoswap-v2.clar) | Adding Zest as an unguarded 5th smart-swap leg withoutROUND_SLACK(u2) or pre-quote breaks (a) the vaults' 4-legROUTER_SLACK_SATS = u8invariant (router-swaprevertsu16047, stallingclose-batchu16043) and (b)README #2's< ~1000 raw/< 0.0001 STXinvariant by~175x(175,602 uSTX -> 32 vs 54 sats,-40.7%;u3002DoS) | `a8925ec876a2768946a1c2c4fae9fcb9` (Vaultu16047/u16043), `6362feb17355b24d93ed8c3e101a6185` (smart-swapu3002& LP extraction) - P-01 | Low (Pre-Deploy Parity) | Scope 5 (
contracts/sbtc-stx/swap-router-sbtc-stx-jing-v6.clar&v5-6) |dlmm-pickomits(and e1 ...)/(and e2 ...)eligibility tie-break anddlmm-outhardcodesDLMM_BIN_STEP u15instead of portingstx-usdcxv6 /93c8ec6| Line-level diff vsstx-usdcxv6L743–753, L789 - P-02 | Low (Pre-Deploy Hygiene) | Scope 5 (
contracts/sbtc-stx/comp.clar) | Stray legacyv6-4rung (sha256 86a6c7a0e47b...) staged insidecontracts/sbtc-stx/, binding retiredv6-4market and missing thesub0underflow guard | Byte-identical to mainnetjing-sell-stx-10
Finding F-01: Unbounded Zest smart-swap Leg Breaks Vault ROUTER_SLACK_SATS (u8) (u16047 / u16043 Batch Stall) and README #2 Bounds (175x Amplification + u3002 DoS)
Where
- Router v6 (`contracts/sbtc-stx/swap-router-sbtc-stx-jing-v6.clar`, repo @ `4593bbb` / [deployed mainnet]):
ROUND_SLACK(u2) andlimit-min(used only by DLMM/XYK/Velar, never Zest):L726–741zest-swappassesmin-out = u0withallow-partial-fill = true:L1431–1461([deployed L1387–1417])smart-swap-sbtc-for-stx&smart-swap-stx-for-sbtcexecutezest-stageahead of DLMM/CP:L1594–1598,L1667–1671([deployed L1550–1554, L1621–1625])- All three swap vaults (Scopes 2–4):
ccd016-swap-vault-mia-v2.clar(PR #92 @ b699940):ROUTER_SLACK_SATS u8(L121–123: *"four legs at most"*),fund-from-treasury(L407),close-batch(L457),router-swap(L654–666)fastpool-swap-vault.clar(PR #1 @ 1b47851):ROUTER_SLACK_SATS u8(L25–27),close-batch(L276),router-swap(L495–507)juice-sbtc-autoswap-v2.clar(f403d80+ mainnet):ROUTER_SLACK_SATS u8(L20),close-batch(L234),router-swap(L439–449)- Zest `SP2NK9P261ZN3ZG2M1DS68PCJCRDFZVFMPYA6ZEST.clmm-pool-v1`:
step-x-for-y(L582–608),step-y-for-x(L610–636),accept(L638–642)
Root Cause (Why sBTC/STX Violates the STX/USDCx #2 & Vault u8 Assumptions)
- Zest frame scaling & unit asymmetry (`6dp wstx` vs `8dp sBTC`, `1 sat ≈ 2,377–2,422 uSTX`):
- On
STX/USDCx,README #2acceptedzest-swap min-out u0(with Parked Fix P2: *"Revisit if: per-bin rounding on Zest grows"*) because only fills under~1,000 raw unitsmissedlimit-min, costing< 0.0001 STX, while1,000+raw fills clearedlimit-minby>= 26 bps. - On
sBTC/STXaround spot~2,400 uSTX/sat, Zest's bin frame shiftssBTCbysy = 10(1raw sat =2^10 = 1,024frame units viato-frame, vssx = 0): - In `step-y-for-x` (
sell-sbtc),ceil-shift(dv-need, sy=10)plusacceptmul-div-upfee consumes `2 sats` per bin for any residualwSTXbalance< 1 sat(100–1,500 uSTX), totaling up to `64 sats` across32walked bins (ZEST_MAX_TICKS). - In `step-x-for-y` (
sell-stx),bit-shift-right(..., sy=10)floors output to integersats, dropping up to `1 sat/bin`. Because eachsatequals~2,400 uSTX,32bins holdingdy = 2 sats/binabsorb `~175,602 uSTX` (175xaboveREADME #2's~1,000raw units) for just32 sats.
- Vault `ROUTER_SLACK_SATS = u8` assumes 4 bounded legs, not 5 with an unbounded 32-bin CLMM walk:
- All three vaults enforce
sold > u8andout >= floor-out((- sold ROUTER_SLACK_SATS), limit)(u16047 ERR_BELOW_FLOOR), explicitly documented in MIA/Fastpool asROUND_SLACK (2) * 4 legs = 8 sats. - When Zest is active before DLMM under valid vault slippage settings above the
1%Zest fee (e.g.,slippage-bpsofu500–u1000withinMAX_SLIPPAGE_BPS u1000, or smaller slippage paired with DLMM filling nearlimit/ multi-leg slack),zest-stageburns `14–24+ sats` for negligible STX output (700–1,200 uSTX), consuming2x–3xthe entire vault slack budget. On tail/residual batches (<= ~100–250 sats, aboveDUST_SATS u2sois-emptyisfalse),router-swapreverts(err u16047), stalling permissionlessclose-batch(err u16043 ERR_SOME_FUNDS) andfinish()/emergency-recover.
Concrete Verified stxer Mainnet-Fork Reproductions
PoC 1: Live SPV9K21...juice-sbtc-autoswap-v2 + swap-router-sbtc-stx-jing-v6 (router-swap ERR_BELOW_FLOOR u16047 & Batch Stall)
- Simulation: https://stxer.xyz/simulations/mainnet/a8925ec876a2768946a1c2c4fae9fcb9 (Block
9525898, live Pyth Lazer updatemid = 24216990679389, live DIA band check active, Zest Poolu3wstx/sBTC bin-step u100created via.executor-dao). - Scenario A (`amount = 80 sats`, valid `slippage-bps = u500` [5% `<= MAX_SLIPPAGE_BPS u1000`], Pool `u3` `1%`/`1%` fee `u1000000`):
- *Baseline (clean Pool
u3):*juice-sbtc-autoswap-v2.router-swapSUCCEEDS ->out = 192,840 uSTX,unsold = 0,is-empty = true,finishOK. - *With
100 uSTX/binacross the9walked ticks (785..777):*router-swapREVERTS `(err u16047)` (`ERR_BELOW_FLOOR`);(is-empty)remainsfalse;close-batchREVERTS `(err u16043)` (`ERR_SOME_FUNDS`). Directsmart-swap-sbtc-for-stx(..., min=u1)on the exact same state printszest-in = 14 sats, zest-out = 700 uSTXanddlmm-in = 66 sats, dlmm-out = 159,093 uSTX(total159,793 < floor-out(80 - 8, 23006141145419) = 165,644 uSTX). - *Recovery:* Clearing those 9 bins (
reduce-positions) immediately unblocks the exact samerouter-swap(out = 192,840 uSTX,unsold = 0).
- Scenario B (`amount = 200 sats`, valid `slippage-bps = u1000` [`MAX_SLIPPAGE_BPS`], Pool `u3` `1%` fee):
- Clean Pool
u3returns472,475 uSTX; with100 uSTX/binacross14walked ticks (785..772),zest-in = 24 sats -> zest-out = 1,200 uSTX, degrading vault execution by `-47,026 uSTX` (~`19.5 sats` lost) to425,449 uSTX(clearingfloor-out(192) = 418,469only because untouched live DLMM quoted+10.6%above the 10% floor). - Scenario C (Boundary check — default `slippage-bps = u100` [1%] + `0.3%` Pool `u3` fee, `100 sats`):
zest-in = 6 sats -> zest-out = 300 uSTX, reducing total output from241,050to226,887 uSTX(-14,163 uSTX), still passingfloor-out(92) = 220,568because only 3 of the5ticks (785..781) clearedzest-bound, staying insideu8.
PoC 2: Direct smart-swap-* limit-min Violation & (err u3002) DoS (x -> y and y -> x)
- Simulation: https://stxer.xyz/simulations/mainnet/6362feb17355b24d93ed8c3e101a6185 (Block
9525727, live XYK spot~2,377.09 uSTX/sat). - `smart-swap-stx-for-sbtc` (`x -> y`, `limit = 135%` spot):
- *Baseline (
200,000 uSTX,min-sbtc-out = u62, clean Poolu3):* SUCCEEDS ->out = 83 sats,dlmm-in = 200,000. - *With
dy = 2 sats/binacross32ticks (min = u1):* Zest consumes `175,602 uSTX` (175x > 1,000raw) and outputs `32 sats` vslimit-min(175602, limit) = 54 sats(`-22 sats / -40.7%` leg shortfall). Unwrapping(sbtc-token get-balance)+reduce-positionsshows LPsbtcSpent = 64, stxGained = 163,792(2,559.25 uSTX/satrealized on64 satsvs2,377.09spot, with pool fee retained). - *DoS (
200,000 uSTX,min = u62, same Poolu3state):* Identical call to Baseline REVERTS `(err u3002)` (`ERR_MIN_OUT`) despite DLMM still holding capacity for83 sats.
- `smart-swap-sbtc-for-stx` (`y -> x`, `limit = 85%` spot):
- *Baseline (
100 sats,min = u202052, clean Poolu3):* SUCCEEDS ->out = 238,538 uSTX. - *With
dx = 1,500 uSTX/binacross20ticks (1,000 sats,min = u1):*zest-in = 36 sats -> zest-out = 27,000 uSTXvslimit-min = 72,739 uSTX(`-62.9%` leg shortfall;LPdeltassbtcGained = 0, stxSpent = 27,015, taker36 satsretained in pool/locked liquidity). - *DoS (
100 sats,min = u202052):* REVERTS `(err u3002)`.
Remediation
Because SPV9K21...swap-router-sbtc-stx-jing-v6 is already deployed on mainnet while MIA PR `#92`, Fastpool PR `#1`, and Juice `v2` (still in its 4032-block notice window) can still be updated prior to activation:
- Vaults (`ccd016-swap-vault-mia-v2`, `fastpool-swap-vault`, `juice-sbtc-autoswap-v2`) — Concrete Pre-Activation Patch:
ROUTER_SLACK_SATS = u8no longer holds oncerouter-swapdelegates to a 5-venue router whosezest-stagelacksROUND_SLACKenforcement (L121–123).- Do not blindly widen unconditional
ROUTER_SLACK_SATStou64(which would weaken the oracle floor on small swaps). Instead: (a) constrainsmart-swapusage inrouter-swap(asserts! (<= slippage-bps u100)matched to a confirmed1%Poolu3fee, bounding Zest to3–4bins /<= u8sats, or passlimitcapped so Zest walks<= 4bins), and/or (b) add an admin/emergency DLMM-direct orROUTER_SLACK_SATS-aware tail sweep (swap-sbtc-for-stxwithzest u0) so any small stuck batch (<= ~100sats) cannot deadlockclose-batch/finish.
- Router v6 (`contracts/sbtc-stx/swap-router-sbtc-stx-jing-v6.clar`) — Concrete Clarity Patch (Parked Fix P2 & P-01):
- Pre-quote `zest-stage-pool` before swapping: fold
ticksagainst read-onlyZEST_POOL.quote-swap-y-for-x-as/quote-swap-x-for-y-as(clmm-pool-v1.clar L163, L168) fortx-sender, and skipzest-swap(returningZEST_NONE) whenever quoted output falls below(limit-min q-in limit sell-sbtc), OR pass that non-zero minimum directly intoZEST_ROUTER.swap-*-for-*:
;; Inside zest-stage-pool (after building ticks):
;; Pre-fold quote-swap-y-for-x-as / quote-swap-x-for-y-as across ticks
(let ((q (zest-quote left bound ticks sell-sbtc)))
(if (and (> (get in q) u0) (>= (get out q) (limit-min (get in q) limit sell-sbtc)))
(zest-swap left bound ticks sell-sbtc)
ZEST_NONE
)
)- Fix `P-01` in `dlmm-pick` (`L886–892`) & `dlmm-out` (`L929`) to match
stx-usdcxv6 (L743–753, L789):
(if (and e1 (>= o1 o2) (>= o1 o3))
u1
(if (and e2 (>= o2 o3)) u2 u3)
)and replace (if (is-eq (get bin-step info) DLMM_BIN_STEP) with (if (> (get bin-step info) u0). Remove or archive stray contracts/sbtc-stx/comp.clar.
Scope 5: Pre-Deploy Check of contracts/sbtc-stx/
All STX/USDCx Zest audit fixes (#4, #6, #7, #8, orientation flip x = ZEST_WSTX 6dp / y = SBTC 8dp, ZEST_LIMIT_TO_WAD = 1e8, ZEST_MAX_LIMIT = 1e21, and zest-bound ceil/floor rounding across 60,096 test vectors) are faithfully carried over, and the repo swap-router-sbtc-stx-jing-v6.clar @ 4593bbb matches deployed SPV9K21...swap-router-sbtc-stx-jing-v6 (only comment/wrapping differences). However, two non-duplicate divergences remain in contracts/sbtc-stx/:
- P-01 (Low) — Unported `dlmm-pick` `e1/e2` eligibility guard and hardcoded `DLMM_BIN_STEP u15`:
contracts/sbtc-stx/swap-router-sbtc-stx-jing-v6.clarL886–892(v5-6L759–765, deployed routerL798) still uses(if (and (>= o1 o2) (>= o1 o3)) u1 (if (>= o2 o3) u2 u3)), omitting the93c8ec6fix ported intocontracts/stx-usdcx/swap-router-stx-usdcx-jing-v6.clarL743–753((and e1 ...)/(and e2 ...)), andL929hardcodesDLMM_BIN_STEP u15instead ofL789(> (get bin-step info) u0). When Pool 1 fails the1%depth floor (e1 = false) while Pools 2 & 3 yieldo2 = o3 = 0(active bins beyondlimit-price),dlmm-pickties0 = 0 = 0and routes into ineligibleu1.
- P-02 (Low) — Stray legacy `v6-4` contract `contracts/sbtc-stx/comp.clar` lacking `sub0` fix:
contracts/sbtc-stx/comp.clar(825lines,22,378bytes,sha256 86a6c7a0e47b...) is byte-identical to retired mainnetSPV9K21...jing-sell-stx-10, binds retiredmarkets-sbtc-stx-jing-v6-4, omitsNAME_SUFFIX "-v2", and lacks thesub0arithmetic-underflow guard present incontracts/sbtc-stx/jing-sell-stx-90-v2.clar(L356, L369, L373, L618) andcontracts/stx-usdcx/sbtc-usdcx(0-byte placeholderdeployed-comp.clar). Note alsotests/unit/redeploy/build.mjsstill referencesv5-6and4593bbbships no Zestsbtc-stxunit/Clarinet harness.
Clean Scope Verification Summary (Scopes 2–4 Vaults)
- Auth: MIA
is-dao-or-extension, Fastpoolauthorize-admin+contract-caller == POOL, and Juiceassert-pool-admin(POOL get-admin) with privatesplit-core/split-dia-coreall fail closed. - Units & Math:
floor-out1e10scaling matchesuSTX/sat x 1e10,juice-swap-vault-trait-v3matches Fastpool signer/vault signatures (trait-v2preserved on Juice v1 wrapper), and no new custody/token-drain path exists in the PR diffs.
Repro Script 1: verify_vault_slack_stxer.mjs (stxer a8925ec876a2768946a1c2c4fae9fcb9)
/**
* Stxer mainnet-fork verification of ROUTER_SLACK_SATS (u8) mismatch vs Zest CLMM
* sub-sat bin rounding in live SPV9K21TBFAK4KNRJXF5DFP8N7W46G4V9RCJDC22.juice-sbtc-autoswap-v2
* (identical floor check in ccd016-swap-vault-mia-v2 and fastpool-swap-vault).
*/
import { SimulationBuilder, submitSimulationSteps, callContract } from 'stxer';
import {
uintCV, intCV, bufferCV, noneCV, tupleCV, listCV,
contractPrincipalCV, standardPrincipalCV, deserializeCV, serializeCV, cvToJSON, hexToCV,
} from '@stacks/transactions';
const NODE = 'https://api.hiro.so';
const DEP = 'SPV9K21TBFAK4KNRJXF5DFP8N7W46G4V9RCJDC22';
const ZPOOL = 'SP2NK9P261ZN3ZG2M1DS68PCJCRDFZVFMPYA6ZEST.clmm-pool-v1';
const ZDAO = 'SP2NK9P261ZN3ZG2M1DS68PCJCRDFZVFMPYA6ZEST.executor-dao';
const ZWSTX = 'SP1A27KFY4XERQCCRCARCYD1CC5N7M6688BSYADJ7.wstx';
const SBTC = 'SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token';
const DECODER = 'SPMV5HDZ4EMB8XY7HAYT3XW0DF7DZ4E8XEG2J1T8.pyth-lazer-decoder-v1';
const ROUTER = `${DEP}.swap-router-sbtc-stx-jing-v6`;
const VAULT = `${DEP}.juice-sbtc-autoswap-v2`;
const POOL = `${DEP}.juice-pool-sbtc-signer`;
const SBTC_WHALE = 'SP2C7BCAP2NH3EYWCCVHJ6K0DMZBXDFKQ56KR7QN2';
const STX_WHALE = 'SP354663MXNWN2B6HKNBYD8JBNJK2ZNBZE764X1RR';
const LP = 'SP233MAB7FRWBPJYMENXPQ86Q6XH9BNAHB603WTHD';
const KEEPER = 'SP100VTG4KGGZAR5Y7Y84QHFVZT7N819DGMGJTD6C';
const P_ = (s) => (s.includes('.') ? contractPrincipalCV(...s.split('.')) : standardPrincipalCV(s));
const UMAX = 340282366920938463463374607431768211455n;
const ONE_8 = 100_000_000n;
const LAZER_KEY = process.env.FAKTORY_API_KEY || 'jc_e4d2e10396eef95215a7afd492f42d743a3325739d29200c2a28b256f778be01';
/** Decode ClarityValue into plain JS primitives with BigInt for ints/uints. */
function plain(c) {
switch (c.type) {
case 'uint':
case 'int':
return BigInt(c.value);
case 'true':
return true;
case 'false':
return false;
case 'none':
return null;
case 'some':
return plain(c.value);
case 'ok':
return { ok: plain(c.value) };
case 'err':
return { err: plain(c.value) };
case 'tuple':
return Object.fromEntries(Object.entries(c.value).map(([k, v]) => [k, plain(v)]));
case 'list':
return c.value.map(plain);
default:
return c.value;
}
}
const show = (v) => JSON.stringify(v, (_, x) => (typeof x === 'bigint' ? x.toString() : x));
/** Decode contract print events from a stxer Transaction receipt. */
function decodePrints(receipt) {
const out = [];
for (const ev of (receipt?.events || [])) {
try {
const obj = typeof ev === 'string' ? JSON.parse(ev) : ev;
const raw = obj?.contract_event?.raw_value;
if (!raw) continue;
out.push({ contract: obj.contract_event.contract_identifier, value: plain(hexToCV(raw)) });
} catch {
// Ignore non-contract or malformed event entries.
}
}
return out;
}
/** Execute an Eval step inside contract cid as sender and decode its result. */
async function evalIn(sid, cid, code, sender = DEP) {
const out = await submitSimulationSteps(sid, {
steps: [{ TenureExtend: { cause: 'Extended' } }, { Eval: [sender, '', cid, code] }],
});
const r = out.steps[1];
if (!r?.Eval?.Ok) throw new Error(`Eval err ${cid} ${code}: ${JSON.stringify(r)}`);
return plain(deserializeCV(r.Eval.Ok));
}
/** Execute a public contract-call transaction inside the simulation fork. */
async function tx(sid, sender, cid, fn, args) {
await submitSimulationSteps(sid, { steps: [{ TenureExtend: { cause: 'Extended' } }] });
const r = await callContract(sid, { sender, contract: cid, functionName: fn, functionArgs: args, fee: 0 });
return {
res: r.resultHex ? plain(deserializeCV(r.resultHex)) : null,
vm: r.vmError || r.pcAborted || null,
prints: decodePrints(r.receipt),
};
}
/** Fetch live Pyth Lazer update and decode older feed publish timestamp via Hiro read-only call. */
async function fetchLazerAndTimes() {
const r = await fetch('https://faktory-dao-backend.vercel.app/api/auction/pyth-lazer-update?pair=sbtc-stx', {
headers: { 'x-api-key': LAZER_KEY },
});
if (!r.ok) throw new Error(`Lazer fetch failed: ${r.status}`);
const d = (await r.json()).data;
const buf = Buffer.from(d.hex, 'hex');
const len = buf.readUInt16BE(69);
const payload = buf.subarray(71, 71 + len);
const argHex = serializeCV(bufferCV(payload));
const dec = await fetch(`${NODE}/v2/contracts/call-read/${DECODER.replace('.', '/')}/decode-lazer-payload`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
sender: DECODER.split('.')[0],
arguments: [argHex.startsWith('0x') ? argHex : `0x${argHex}`],
}),
});
const j = await dec.json();
if (!j.okay) throw new Error(`Lazer decode failed: ${JSON.stringify(j)}`);
const v = cvToJSON(hexToCV(j.result)).value.value;
const feeds = v['price-feeds'].value.map((f) => f.value);
const ts = feeds.map((f) => Math.floor(Number(f['feed-update-timestamp'].value.value) / 1e6));
return { hex: d.hex, px: BigInt(d.priceX), py: BigInt(d.priceY), at: Math.min(...ts) };
}
/** Call a POOL-gated admin or fund entry on juice-sbtc-autoswap-v2 via Clarity4 as-contract?. */
async function poolCall(sid, innerExpr, sbtcLimit = 0n) {
const cap = sbtcLimit > 0n ? `(with-ft '${SBTC} "sbtc-token" u${sbtcLimit})` : '';
return evalIn(sid, POOL, `(as-contract? (${cap}) (try! (contract-call? '${VAULT} ${innerExpr})))`, DEP);
}
/** Deposit dx uSTX per tick across the router-selected Zest ticks and return ticks list. */
async function seedDustBins(sid, spotWad, limitScaled, feeRateY, dxPerBin) {
const ticks = await evalIn(sid, ROUTER, `(zest-ticks u${spotWad} (zest-bound u${limitScaled} u${feeRateY} true) false)`);
for (const t of ticks) {
await tx(sid, LP, ZPOOL, 'add-to-position', [
P_(ZWSTX), P_(SBTC), uintCV(3n), intCV(t), uintCV(dxPerBin), uintCV(0n), uintCV(0n), uintCV(UMAX), uintCV(1n),
]);
}
return ticks;
}
/** Remove LP positions across given ticks. */
async function clearDustBins(sid, ticks) {
if (!ticks.length) return;
const items = listCV(ticks.map((t) => tupleCV({ tick: intCV(t), percent: uintCV(ONE_8) })));
await tx(sid, LP, ZPOOL, 'reduce-positions', [P_(ZWSTX), P_(SBTC), uintCV(3n), items, uintCV(0n), uintCV(0n)]);
}
/** Run clean baseline, dusty-bin failure/check, and cleanup recovery for a configured vault scenario. */
async function runVaultScenario(sid, { label, updCV, amountSats, slippageBps, feeRateY, midScaled, spotWad, dxPerBin }) {
await poolCall(sid, `set-slippage-bps u${slippageBps}`);
await evalIn(sid, ZPOOL, `(update-pool-fee u3 u${feeRateY} u${feeRateY} u100000000)`, ZDAO);
await poolCall(sid, `fund u${amountSats}`, amountSats);
const base = await tx(sid, KEEPER, VAULT, 'router-swap', [updCV]);
console.log(`${label} Baseline (clean pool u3, amount=${amountSats}, slippage=${slippageBps}bps):`, show({ res: base.res, prints: base.prints }));
await poolCall(sid, 'finish');
const limitScaled = (midScaled * (10000n - slippageBps)) / 10000n;
const ticks = await seedDustBins(sid, spotWad, limitScaled, feeRateY, dxPerBin);
console.log(`${label} seeded ${ticks.length} bins (${dxPerBin} uSTX/bin): ${show(ticks)}`);
await poolCall(sid, `fund u${amountSats}`, amountSats);
const swapDusty = await tx(sid, KEEPER, VAULT, 'router-swap', [updCV]);
const emptyAfter = await evalIn(sid, VAULT, '(is-empty)');
const closeAfter = await tx(sid, KEEPER, VAULT, 'close-batch', []);
console.log(`${label} With dusty Zest bins:`, show({ res: swapDusty.res, emptyAfter, closeAfter: closeAfter.res, prints: swapDusty.prints }));
if (!emptyAfter) {
// Demonstrate router leg breakdown directly on the same dusty pool state.
const direct = await tx(sid, LP, ROUTER, 'smart-swap-sbtc-for-stx', [
uintCV(amountSats), uintCV(limitScaled), noneCV(), uintCV(midScaled), uintCV(1n),
]);
console.log(`${label} Direct smart-swap breakdown (min=u1):`, show(direct.res));
await clearDustBins(sid, ticks);
const recover = await tx(sid, KEEPER, VAULT, 'router-swap', [updCV]);
console.log(`${label} Recovery after clearing dust:`, show({ res: recover.res, prints: recover.prints }));
} else {
await clearDustBins(sid, ticks);
}
await poolCall(sid, 'finish');
}
async function main() {
const tipRes = await (await fetch(`${NODE}/extended/v2/blocks?limit=1`)).json();
const tip = tipRes.results[0];
const lz = await fetchLazerAndTimes();
const intervalSecs = Math.max(5, lz.at + 8 - Number(tip.burn_block_time));
const updCV = bufferCV(Buffer.from(lz.hex, 'hex'));
const builder = SimulationBuilder.new({ stacksNodeAPI: NODE })
.withSender(DEP)
.addAdvanceBlocks({ bitcoin_blocks: 1, stacks_blocks_per_bitcoin: 1, bitcoin_interval_secs: intervalSecs })
.addEvalCode(ZPOOL, '(get-pool-count)');
const sid = await builder.run();
console.log(`Simulation URL: https://stxer.xyz/simulations/mainnet/${sid}`);
await evalIn(sid, SBTC, `(stx-transfer? u1000000000 '${STX_WHALE} '${LP})`, STX_WHALE);
await evalIn(sid, SBTC, `(stx-transfer? u100000000 '${STX_WHALE} '${KEEPER})`, STX_WHALE);
await tx(sid, SBTC_WHALE, SBTC, 'transfer', [uintCV(2_000_000n), P_(SBTC_WHALE), P_(LP), noneCV()]);
await tx(sid, SBTC_WHALE, SBTC, 'transfer', [uintCV(50_000n), P_(SBTC_WHALE), P_(POOL), noneCV()]);
await poolCall(sid, 'set-window-blocks u0');
await poolCall(sid, 'set-router-cooldown u0');
await evalIn(sid, ZPOOL, `(create-pool '${ZWSTX} '${SBTC} u100 u300000 u300000 u80000000)`, ZDAO);
const midScaled = (lz.px * ONE_8) / lz.py;
const spotWad = midScaled * ONE_8;
// Scenario A: Rapha's 1% Pool u3 fee + valid slippage u500 (5%), residual batch 80 sats.
await runVaultScenario(sid, {
label: 'Scenario A',
updCV,
amountSats: 80n,
slippageBps: 500n,
feeRateY: 1_000_000n,
midScaled,
spotWad,
dxPerBin: 100n,
});
// Scenario B: Rapha's 1% Pool u3 fee + MAX_SLIPPAGE_BPS u1000 (10%), batch 200 sats.
await runVaultScenario(sid, {
label: 'Scenario B',
updCV,
amountSats: 200n,
slippageBps: 1000n,
feeRateY: 1_000_000n,
midScaled,
spotWad,
dxPerBin: 100n,
});
// Scenario C: Unmodified default slippage u100 (1%) + 0.3% fee, measure Zest vs slack on 100 sats.
await runVaultScenario(sid, {
label: 'Scenario C',
updCV,
amountSats: 100n,
slippageBps: 100n,
feeRateY: 300_000n,
midScaled,
spotWad,
dxPerBin: 100n,
});
}
main().catch((err) => {
console.error(err);
process.exit(1);
});
Repro Script 2: poc_f01_v2_stxer.mjs (stxer 6362feb17355b24d93ed8c3e101a6185)
import { SimulationBuilder, submitSimulationSteps, callContract } from 'stxer';
import {
uintCV, intCV, noneCV, tupleCV, listCV, contractPrincipalCV, standardPrincipalCV, deserializeCV,
} from '@stacks/transactions';
const NODE = 'https://api.hiro.so';
const DEP = 'SPV9K21TBFAK4KNRJXF5DFP8N7W46G4V9RCJDC22';
const ZPOOL = 'SP2NK9P261ZN3ZG2M1DS68PCJCRDFZVFMPYA6ZEST.clmm-pool-v1';
const ZDAO = 'SP2NK9P261ZN3ZG2M1DS68PCJCRDFZVFMPYA6ZEST.executor-dao';
const ZWSTX = 'SP1A27KFY4XERQCCRCARCYD1CC5N7M6688BSYADJ7.wstx';
const SBTC = 'SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4.sbtc-token';
const ROUTER = `${DEP}.swap-router-sbtc-stx-jing-v6`;
const SBTC_WHALE = 'SP2C7BCAP2NH3EYWCCVHJ6K0DMZBXDFKQ56KR7QN2';
const STX_WHALE = 'SP354663MXNWN2B6HKNBYD8JBNJK2ZNBZE764X1RR';
const LP = 'SP233MAB7FRWBPJYMENXPQ86Q6XH9BNAHB603WTHD';
const TAKER = 'SP100VTG4KGGZAR5Y7Y84QHFVZT7N819DGMGJTD6C';
const P_ = (s) => (s.includes('.') ? contractPrincipalCV(...s.split('.')) : standardPrincipalCV(s));
const UMAX = 340282366920938463463374607431768211455n;
const ONE_8 = 100_000_000n;
function plain(c) {
switch (c.type) {
case 'uint': case 'int': return BigInt(c.value);
case 'true': return true; case 'false': return false;
case 'none': return null; case 'some': return plain(c.value);
case 'ok': return { ok: plain(c.value) }; case 'err': return { err: plain(c.value) };
case 'tuple': return Object.fromEntries(Object.entries(c.value).map(([k, v]) => [k, plain(v)]));
case 'list': return c.value.map(plain);
default: return c.value;
}
}
const show = (v) => JSON.stringify(v, (_, x) => (typeof x === 'bigint' ? x.toString() : x));
async function evalIn(sid, cid, code, sender = DEP) {
const out = await submitSimulationSteps(sid, { steps: [{ TenureExtend: { cause: 'Extended' } }, { Eval: [sender, '', cid, code] }] });
const r = out.steps[1];
if (!r?.Eval?.Ok) throw new Error(`Eval err ${cid} ${code}: ${JSON.stringify(r)}`);
return plain(deserializeCV(r.Eval.Ok));
}
async function tx(sid, sender, cid, fn, args) {
await submitSimulationSteps(sid, { steps: [{ TenureExtend: { cause: 'Extended' } }] });
const r = await callContract(sid, { sender, contract: cid, functionName: fn, functionArgs: args, fee: 0 });
return {
res: r.resultHex ? plain(deserializeCV(r.resultHex)) : null,
vm: r.vmError || r.pcAborted || null,
};
}
const sbtcBal = async (sid, who) => (await evalIn(sid, SBTC, `(get-balance '${who})`)).ok;
const stxBal = async (sid, who) => await evalIn(sid, SBTC, `(stx-get-balance '${who})`);
async function main() {
const b = SimulationBuilder.new({ stacksNodeAPI: NODE })
.withSender(DEP)
.addEvalCode(ZPOOL, '(get-pool-count)');
const sid = await b.run();
const simUrl = `https://stxer.xyz/simulations/mainnet/${sid}`;
console.log(`Simulation URL: ${simUrl}`);
const xq = await evalIn(sid, ROUTER, '(xyk-quote true)');
const res = xq.reserves;
const spotScaled = (res.out * 10_000_000_000n) / res.in;
const spotWad = spotScaled * ONE_8;
console.log(`Live spot ~ ${(Number(res.out) / Number(res.in)).toFixed(2)} uSTX/sat (scaled=${spotScaled})`);
// Create Zest Pool u3 via .executor-dao
await evalIn(sid, ZPOOL, `(create-pool '${ZWSTX} '${SBTC} u100 u300000 u300000 u80000000)`, ZDAO);
// Fund LP & TAKER
await evalIn(sid, SBTC, `(stx-transfer? u1000000000 '${STX_WHALE} '${LP})`, STX_WHALE);
await evalIn(sid, SBTC, `(stx-transfer? u1000000000 '${STX_WHALE} '${TAKER})`, STX_WHALE);
await tx(sid, SBTC_WHALE, SBTC, 'transfer', [uintCV(5_000_000n), P_(SBTC_WHALE), P_(LP), noneCV()]);
await tx(sid, SBTC_WHALE, SBTC, 'transfer', [uintCV(5_000_000n), P_(SBTC_WHALE), P_(TAKER), noneCV()]);
// === TRACE A: y -> x (sell-sbtc = true), limit = 85% spot (15% slippage budget) ===
const midA = spotScaled;
const limitA = (midA * 85n) / 100n;
const limitMin100 = (100n * limitA) / 10_000_000_000n; // fair min-out for 100 sats @ 85% spot = ~202,052 uSTX
// Baseline for 100 sats WITHOUT Zest dust (passes cleanly via DLMM)
const baseA100 = await tx(sid, TAKER, ROUTER, 'smart-swap-sbtc-for-stx', [
uintCV(100n), uintCV(limitA), noneCV(), uintCV(midA), uintCV(limitMin100),
]);
console.log('Baseline A (100 sats, min=limitMin100, NO Zest dust):', show(baseA100));
// Realistic active-pool LP setup for y->x:
// Suppose a normal LP first deposited 10,000 uSTX in each of 20 ticks (or drained bin down to 1500 uSTX residual with > MIN-LIQUIDITY shares!).
// Actually test pure 1500 uSTX/bin fresh deposit (1500 < 2377 = 0.63 sats worth!): L ~ 216,000 >> 1000 -> LP owns ~99.5% of bin!
// Let's test BOTH dx=100 uSTX/bin (max 97.5% taker loss) AND dx=1500 uSTX/bin (LP positive profit!)
const walkTicksA = await evalIn(sid, ROUTER, `(zest-ticks u${spotWad} (zest-bound u${limitA} u300000 true) false)`);
const dxPerBin = 1500n; // 0.0015 STX (< 1 sat value!)
const lpSbtcA0 = await sbtcBal(sid, LP);
const lpStxA0 = await stxBal(sid, LP);
for (const t of walkTicksA) {
await tx(sid, LP, ZPOOL, 'add-to-position', [
P_(ZWSTX), P_(SBTC), uintCV(3n), intCV(t), uintCV(dxPerBin), uintCV(0n), uintCV(0n), uintCV(UMAX), uintCV(1n),
]);
}
console.log(`Trace A LP deposited ${dxPerBin} uSTX across ${walkTicksA.length} bins (${BigInt(walkTicksA.length) * dxPerBin} uSTX total)`);
// Case A-loss (1000 sats, min=u1): Zest consumes 2 sats per bin = 40 sats (~95,083 uSTX spot) for only 30,000 uSTX!
const swapA1 = await tx(sid, TAKER, ROUTER, 'smart-swap-sbtc-for-stx', [
uintCV(1000n), uintCV(limitA), noneCV(), uintCV(midA), uintCV(1n),
]);
console.log('Trace A1 (1000 sats, min=u1, dx=1500/bin):', show(swapA1));
if (swapA1.res?.ok) {
const r = swapA1.res.ok;
const lm = (r['zest-in'] * limitA) / 10_000_000_000n;
console.log(` Trace A1 Zest: in=${r['zest-in']} sats -> out=${r['zest-out']} uSTX vs limitMin=${lm} uSTX (loss=${lm - r['zest-out']} uSTX, -${(((Number(lm) - Number(r['zest-out'])) / Number(lm)) * 100).toFixed(1)}%)`);
}
// LP reduces positions and checks net profit!
const rmItemsA = listCV(walkTicksA.map((t) => tupleCV({ tick: intCV(t), percent: uintCV(ONE_8) })));
await tx(sid, LP, ZPOOL, 'reduce-positions', [P_(ZWSTX), P_(SBTC), uintCV(3n), rmItemsA, uintCV(0n), uintCV(0n)]);
const lpSbtcA1 = await sbtcBal(sid, LP);
const lpStxA1 = await stxBal(sid, LP);
console.log('Trace A1 LP net deltas:', show({ sbtcGained: lpSbtcA1 - lpSbtcA0, stxSpent: lpStxA0 - lpStxA1 }));
// Case A-DoS (100 sats, min=limitMin100, WITH dusty bins 100 uSTX/bin): SAME swap that passed in Baseline A now REVERTS u3002!
for (const t of walkTicksA) {
await tx(sid, LP, ZPOOL, 'add-to-position', [
P_(ZWSTX), P_(SBTC), uintCV(3n), intCV(t), uintCV(100n), uintCV(0n), uintCV(0n), uintCV(UMAX), uintCV(1n),
]);
}
const swapADoS = await tx(sid, TAKER, ROUTER, 'smart-swap-sbtc-for-stx', [
uintCV(100n), uintCV(limitA), noneCV(), uintCV(midA), uintCV(limitMin100),
]);
console.log(`Trace A2 DoS (100 sats, min=limitMin=${limitMin100}):`, show(swapADoS));
// === TRACE B: x -> y (sell-sbtc = false), limit = 135% spot ===
const limitB = (midA * 135n) / 100n;
const walkTicksB = await evalIn(sid, ROUTER, `(zest-ticks u${spotWad} (zest-bound u${limitB} u300000 false) true)`);
const limitMinB200k = (200_000n * 10_000_000_000n) / limitB;
const baseB200k = await tx(sid, TAKER, ROUTER, 'smart-swap-stx-for-sbtc', [
uintCV(200_000n), uintCV(limitB), noneCV(), uintCV(midA), uintCV(limitMinB200k),
]);
console.log(`Baseline B (200k uSTX, min=limitMin=${limitMinB200k}, NO Zest dust):`, show(baseB200k));
const lpSbtcB0 = await sbtcBal(sid, LP);
const lpStxB0 = await stxBal(sid, LP);
for (const t of walkTicksB) {
await tx(sid, LP, ZPOOL, 'add-to-position', [
P_(ZWSTX), P_(SBTC), uintCV(3n), intCV(t), uintCV(0n), uintCV(2n), uintCV(0n), uintCV(UMAX), uintCV(1n),
]);
}
const swapB1 = await tx(sid, TAKER, ROUTER, 'smart-swap-stx-for-sbtc', [
uintCV(200_000n), uintCV(limitB), noneCV(), uintCV(midA), uintCV(1n),
]);
console.log('Trace B1 (200k uSTX, min=u1, dy=2 sats/bin):', show(swapB1));
if (swapB1.res?.ok) {
const r = swapB1.res.ok;
const lm = (r['zest-in'] * 10_000_000_000n) / limitB;
console.log(` Trace B1 Zest: in=${r['zest-in']} uSTX -> out=${r['zest-out']} sats vs limitMin=${lm} sats (shortfall=${lm - r['zest-out']} sats, -${(((Number(lm) - Number(r['zest-out'])) / Number(lm)) * 100).toFixed(1)}%)`);
}
const rmItemsB = listCV(walkTicksB.map((t) => tupleCV({ tick: intCV(t), percent: uintCV(ONE_8) })));
await tx(sid, LP, ZPOOL, 'reduce-positions', [P_(ZWSTX), P_(SBTC), uintCV(3n), rmItemsB, uintCV(0n), uintCV(0n)]);
const lpSbtcB1 = await sbtcBal(sid, LP);
const lpStxB1 = await stxBal(sid, LP);
console.log('Trace B1 LP net deltas:', show({ sbtcSpent: lpSbtcB0 - lpSbtcB1, stxGained: lpStxB1 - lpStxB0 }));
// Trace B2 DoS check: re-add dy=2 sats/bin -> EXACT Baseline B call (min=limitMin=62 sats) now REVERTS u3002!
for (const t of walkTicksB) {
await tx(sid, LP, ZPOOL, 'add-to-position', [
P_(ZWSTX), P_(SBTC), uintCV(3n), intCV(t), uintCV(0n), uintCV(2n), uintCV(0n), uintCV(UMAX), uintCV(1n),
]);
}
const swapB2DoS = await tx(sid, TAKER, ROUTER, 'smart-swap-stx-for-sbtc', [
uintCV(200_000n), uintCV(limitB), noneCV(), uintCV(midA), uintCV(limitMinB200k),
]);
console.log(`Trace B2 DoS (200k uSTX, min=limitMin=${limitMinB200k}, WITH dy=2/bin):`, show(swapB2DoS));
}
main().catch((e) => { console.error(e); process.exit(1); });