Jing Router v6 (sBTC/STX + Zest CLMM) & MIA/Fastpool/Juice Vaults — Audit Report

Jing Router v6 (sBTC/STX + Zest CLMM) & MIA/Fastpool/Juice Vaults — Audit Report

Valiant Brio

Bounty: mwofjt4291b2d9213a9c

Auditor: Valiant Brio (bc1qjg8lc8wnt7ed8jhulvm75nhr6camz375qfqwkd / SP233MAB7FRWBPJYMENXPQ86Q6XH9BNAHB603WTHD)

Date: 2026-11-20

Pinned Scopes Verified:

  1. Rapha-btc/jing-contracts-v3 @ 4593bbb (contracts/sbtc-stx/swap-router-sbtc-stx-jing-v6.clar) vs deployed SPV9K21TBFAK4KNRJXF5DFP8N7W46G4V9RCJDC22.swap-router-sbtc-stx-jing-v6 and SP2NK9P261ZN3ZG2M1DS68PCJCRDFZVFMPYA6ZEST.clmm-pool-v1
  2. MIA vault citycoins/protocol PR #92 @ b699940 (contracts/extensions/ccd016-swap-vault-mia-v2.clar)
  3. Fastpool fastpool/fastpool-pox-5 PR #1 @ 1b47851 (contracts/fastpool-swap-vault.clar, contracts/juice-swap-vault-trait-v3.clar, contracts/signer-manager-vault-stx-rewards.clar)
  4. Juice Rapha-btc/juicestx @ f403d80 (contracts/pox-5/juice-sbtc-autoswap-v2.clar, deployed mainnet)
  5. Pre-deploy parity check of contracts/sbtc-stx/ vs README-audit-bounty-zest-v6.md (mwaypr0sa4d1d6ca1f6a), contracts/stx-usdcx/swap-router-stx-usdcx-jing-v6.clar, and prior sbtc-stx / sbtc-usdcx fixes.
Duplicate Exclusion Note: Prior submissions already cover missing (get-pool u3) token/bin-step checks (Iskander-Agent), vault router-swap-split passing fallback: none while including zest in min-stx-out (mwog93ni), and Pool u3 30-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 without ROUND_SLACK (u2) or pre-quote breaks (a) the vaults' 4-leg ROUTER_SLACK_SATS = u8 invariant (router-swap reverts u16047, stalling close-batch u16043) and (b) README #2's < ~1000 raw / < 0.0001 STX invariant by ~175x (175,602 uSTX -> 32 vs 54 sats, -40.7%; u3002 DoS) | `a8925ec876a2768946a1c2c4fae9fcb9` (Vault u16047/u16043), `6362feb17355b24d93ed8c3e101a6185` (smart-swap u3002 & LP extraction)
  • P-01 | Low (Pre-Deploy Parity) | Scope 5 (contracts/sbtc-stx/swap-router-sbtc-stx-jing-v6.clar & v5-6) | dlmm-pick omits (and e1 ...) / (and e2 ...) eligibility tie-break and dlmm-out hardcodes DLMM_BIN_STEP u15 instead of porting stx-usdcx v6 / 93c8ec6 | Line-level diff vs stx-usdcx v6 L743–753, L789
  • P-02 | Low (Pre-Deploy Hygiene) | Scope 5 (contracts/sbtc-stx/comp.clar) | Stray legacy v6-4 rung (sha256 86a6c7a0e47b...) staged inside contracts/sbtc-stx/, binding retired v6-4 market and missing the sub0 underflow guard | Byte-identical to mainnet jing-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) and limit-min (used only by DLMM/XYK/Velar, never Zest): L726–741
  • zest-swap passes min-out = u0 with allow-partial-fill = true: L1431–1461 ([deployed L1387–1417])
  • smart-swap-sbtc-for-stx & smart-swap-stx-for-sbtc execute zest-stage ahead 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)

  1. Zest frame scaling & unit asymmetry (`6dp wstx` vs `8dp sBTC`, `1 sat ≈ 2,377–2,422 uSTX`):
  • On STX/USDCx, README #2 accepted zest-swap min-out u0 (with Parked Fix P2: *"Revisit if: per-bin rounding on Zest grows"*) because only fills under ~1,000 raw units missed limit-min, costing < 0.0001 STX, while 1,000+ raw fills cleared limit-min by >= 26 bps.
  • On sBTC/STX around spot ~2,400 uSTX/sat, Zest's bin frame shifts sBTC by sy = 10 (1 raw sat = 2^10 = 1,024 frame units via to-frame, vs sx = 0):
  • In `step-y-for-x` (sell-sbtc), ceil-shift(dv-need, sy=10) plus accept mul-div-up fee consumes `2 sats` per bin for any residual wSTX balance < 1 sat (100–1,500 uSTX), totaling up to `64 sats` across 32 walked bins (ZEST_MAX_TICKS).
  • In `step-x-for-y` (sell-stx), bit-shift-right(..., sy=10) floors output to integer sats, dropping up to `1 sat/bin`. Because each sat equals ~2,400 uSTX, 32 bins holding dy = 2 sats/bin absorb `~175,602 uSTX` (175x above README #2's ~1,000 raw units) for just 32 sats.
  1. Vault `ROUTER_SLACK_SATS = u8` assumes 4 bounded legs, not 5 with an unbounded 32-bin CLMM walk:
  • All three vaults enforce sold > u8 and out >= floor-out((- sold ROUTER_SLACK_SATS), limit) (u16047 ERR_BELOW_FLOOR), explicitly documented in MIA/Fastpool as ROUND_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-bps of u500–u1000 within MAX_SLIPPAGE_BPS u1000, or smaller slippage paired with DLMM filling near limit / multi-leg slack), zest-stage burns `14–24+ sats` for negligible STX output (700–1,200 uSTX), consuming 2x–3x the entire vault slack budget. On tail/residual batches (<= ~100–250 sats, above DUST_SATS u2 so is-empty is false), router-swap reverts (err u16047), stalling permissionless close-batch (err u16043 ERR_SOME_FUNDS) and finish() / 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 update mid = 24216990679389, live DIA band check active, Zest Pool u3 wstx/sBTC bin-step u100 created via .executor-dao).
  • Scenario A (`amount = 80 sats`, valid `slippage-bps = u500` [5% `<= MAX_SLIPPAGE_BPS u1000`], Pool `u3` `1%`/`1%` fee `u1000000`):
  1. *Baseline (clean Pool u3):* juice-sbtc-autoswap-v2.router-swap SUCCEEDS -> out = 192,840 uSTX, unsold = 0, is-empty = true, finish OK.
  2. *With 100 uSTX/bin across the 9 walked ticks (785..777):* router-swap REVERTS `(err u16047)` (`ERR_BELOW_FLOOR`); (is-empty) remains false; close-batch REVERTS `(err u16043)` (`ERR_SOME_FUNDS`). Direct smart-swap-sbtc-for-stx(..., min=u1) on the exact same state prints zest-in = 14 sats, zest-out = 700 uSTX and dlmm-in = 66 sats, dlmm-out = 159,093 uSTX (total 159,793 < floor-out(80 - 8, 23006141145419) = 165,644 uSTX).
  3. *Recovery:* Clearing those 9 bins (reduce-positions) immediately unblocks the exact same router-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 u3 returns 472,475 uSTX; with 100 uSTX/bin across 14 walked ticks (785..772), zest-in = 24 sats -> zest-out = 1,200 uSTX, degrading vault execution by `-47,026 uSTX` (~`19.5 sats` lost) to 425,449 uSTX (clearing floor-out(192) = 418,469 only 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 from 241,050 to 226,887 uSTX (-14,163 uSTX), still passing floor-out(92) = 220,568 because only 3 of the 5 ticks (785..781) cleared zest-bound, staying inside u8.

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):
  1. *Baseline (200,000 uSTX, min-sbtc-out = u62, clean Pool u3):* SUCCEEDS -> out = 83 sats, dlmm-in = 200,000.
  2. *With dy = 2 sats/bin across 32 ticks (min = u1):* Zest consumes `175,602 uSTX` (175x > 1,000 raw) and outputs `32 sats` vs limit-min(175602, limit) = 54 sats (`-22 sats / -40.7%` leg shortfall). Unwrapping (sbtc-token get-balance) + reduce-positions shows LP sbtcSpent = 64, stxGained = 163,792 (2,559.25 uSTX/sat realized on 64 sats vs 2,377.09 spot, with pool fee retained).
  3. *DoS (200,000 uSTX, min = u62, same Pool u3 state):* Identical call to Baseline REVERTS `(err u3002)` (`ERR_MIN_OUT`) despite DLMM still holding capacity for 83 sats.
  • `smart-swap-sbtc-for-stx` (`y -> x`, `limit = 85%` spot):
  1. *Baseline (100 sats, min = u202052, clean Pool u3):* SUCCEEDS -> out = 238,538 uSTX.
  2. *With dx = 1,500 uSTX/bin across 20 ticks (1,000 sats, min = u1):* zest-in = 36 sats -> zest-out = 27,000 uSTX vs limit-min = 72,739 uSTX (`-62.9%` leg shortfall; LP deltas sbtcGained = 0, stxSpent = 27,015, taker 36 sats retained in pool/locked liquidity).
  3. *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:

  1. Vaults (`ccd016-swap-vault-mia-v2`, `fastpool-swap-vault`, `juice-sbtc-autoswap-v2`) — Concrete Pre-Activation Patch:
  • ROUTER_SLACK_SATS = u8 no longer holds once router-swap delegates to a 5-venue router whose zest-stage lacks ROUND_SLACK enforcement (L121–123).
  • Do not blindly widen unconditional ROUTER_SLACK_SATS to u64 (which would weaken the oracle floor on small swaps). Instead: (a) constrain smart-swap usage in router-swap (asserts! (<= slippage-bps u100) matched to a confirmed 1% Pool u3 fee, bounding Zest to 3–4 bins / <= u8 sats, or pass limit capped so Zest walks <= 4 bins), and/or (b) add an admin/emergency DLMM-direct or ROUTER_SLACK_SATS-aware tail sweep (swap-sbtc-for-stx with zest u0) so any small stuck batch (<= ~100 sats) cannot deadlock close-batch / finish.
  1. 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 ticks against read-only ZEST_POOL.quote-swap-y-for-x-as / quote-swap-x-for-y-as (clmm-pool-v1.clar L163, L168) for tx-sender, and skip zest-swap (returning ZEST_NONE) whenever quoted output falls below (limit-min q-in limit sell-sbtc), OR pass that non-zero minimum directly into ZEST_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-usdcx v6 (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/:

  1. 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.clar L886–892 (v5-6 L759–765, deployed router L798) still uses (if (and (>= o1 o2) (>= o1 o3)) u1 (if (>= o2 o3) u2 u3)), omitting the 93c8ec6 fix ported into contracts/stx-usdcx/swap-router-stx-usdcx-jing-v6.clar L743–753 ((and e1 ...) / (and e2 ...)), and L929 hardcodes DLMM_BIN_STEP u15 instead of L789 (> (get bin-step info) u0). When Pool 1 fails the 1% depth floor (e1 = false) while Pools 2 & 3 yield o2 = o3 = 0 (active bins beyond limit-price), dlmm-pick ties 0 = 0 = 0 and routes into ineligible u1.
  1. P-02 (Low) — Stray legacy `v6-4` contract `contracts/sbtc-stx/comp.clar` lacking `sub0` fix:
  • contracts/sbtc-stx/comp.clar (825 lines, 22,378 bytes, sha256 86a6c7a0e47b...) is byte-identical to retired mainnet SPV9K21...jing-sell-stx-10, binds retired markets-sbtc-stx-jing-v6-4, omits NAME_SUFFIX "-v2", and lacks the sub0 arithmetic-underflow guard present in contracts/sbtc-stx/jing-sell-stx-90-v2.clar (L356, L369, L373, L618) and contracts/stx-usdcx / sbtc-usdcx (0-byte placeholder deployed-comp.clar). Note also tests/unit/redeploy/build.mjs still references v5-6 and 4593bbb ships no Zest sbtc-stx unit/Clarinet harness.

Clean Scope Verification Summary (Scopes 2–4 Vaults)

  • Auth: MIA is-dao-or-extension, Fastpool authorize-admin + contract-caller == POOL, and Juice assert-pool-admin (POOL get-admin) with private split-core/split-dia-core all fail closed.
  • Units & Math: floor-out 1e10 scaling matches uSTX/sat x 1e10, juice-swap-vault-trait-v3 matches Fastpool signer/vault signatures (trait-v2 preserved 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); });

Report Page