diff --git a/docs/onboarding-friction-points.md b/docs/onboarding-friction-points.md new file mode 100644 index 0000000..cbff1d5 --- /dev/null +++ b/docs/onboarding-friction-points.md @@ -0,0 +1,65 @@ +# Onboarding friction points (dry-run walkthrough) + +A first-time onboarding of the kit on 2026-12-03: clone, install, run one dry-run tick per +pool. Everything below was hit on the way, with the measured numbers. + +| # | Friction point | Where | Effect | Status | +|---|---|---|---|---| +| 1 | The v2 inventory read answers **503 `NODE_POSITION_SELECTION_MOVED`** while the engine re-selects the node that holds the wallet's position. The kit reads the 503 as a failed snapshot. | `src/bitflow.ts` (`readCurrentBins`) | The whole tick freezes (`snapshot_fetch_failed` → `GUARDRAIL api_error` → `decision="frozen"`), the wallet's position stays unknown for that tick, and the error counts toward the api-error breaker (5 in a row halts the bot). | **Fixed in this PR** | +| 2 | The generic fetch helper retries **every** failure the same way — a permanent 4xx (a wrong `POOL_ID`) is retried 4 times with 1/2/4 s backoff before it is reported. | `src/stacks.ts` (`retry`, `fetchJson`) | A typo costs ~7 s of wall clock and still fails. | Not fixed (out of scope) | +| 3 | To learn the error code of a 503 the kit has to **read the body by hand**, with a second request to the same URL, because the fetch helper drops the body. | `src/bitflow.ts` | One extra request per degraded answer, and the retry decision the helper makes is blind to the code. | Fixed together with #1 (the body is read once and drives the retry) | +| 4 | One wallet per pool, even in dry run: the README says each process needs its own account, but the example env files ship an empty `SIGNER_ADDRESS` and the same address is what a user copies into both. | `README.md`, `.env.*.example` | Running both competition pools from one signer is what the README warns against, and nothing in the example files says so. | Not fixed (docs) | +| 5 | `npm install` blocks install scripts by default (npm 12), so esbuild's postinstall never runs. | npm 12 + `npm warn install-scripts` | `npm test`, `npm run typecheck`, `npm run build` and `npm run tick` all work anyway (tsx does not need the esbuild binary), but `npm run ui` builds the page with esbuild. | Not fixed (npm's policy, not the kit's) | + +## #1 in detail + +The BFF does not answer the same thing twice in a row for the same wallet and pool. Measured +on 2026-12-03 against `app/v2/users/{addr}/positions/{pool}/current-bins` +(wallet `SP1X05NQY8PXDJKM5ZFM8ZY71VW84NAEHC2AK9Q1Y`, both competition pools, read every 3 s for +two and a half minutes — 40 reads): + +``` +2 x 503 (03:10:38, 03:10:42) 33 x 200 1 x 503 (03:12:15) 3 x 200 1 x 503 (03:13:09) +``` + +4 of the 40 reads were degraded, in runs of 2, 1 and 1. Minutes earlier the same request had +failed in three consecutive dry-run ticks (03:08:43, 03:08:57, 03:09:10 local, 4 attempts each +over ~7 s — 12 degraded answers in a row) and answered 200 seconds later. The body says why: + +```json +{"detail":{"error_code":"POSITION_DATA_DEGRADED"},"errorCode":"NODE_POSITION_SELECTION_MOVED"} +``` + +The position data is *degraded*, i.e. temporarily inconsistent, not absent. So the answer to +read is "not right now", and reading it again is the correct response. + +## What this PR changes + +`readCurrentBins` waits the degraded answer out instead of failing the tick: + +- a 503 whose body carries a transient code (`NODE_POSITION_SELECTION_MOVED`) is retried after a + 2 s pause, for up to `BFF_INVENTORY_RETRY_MS` (default 30 s — longer than the worst degraded + window measured above); +- the retry is bounded, so a position that stays degraded still fails the tick and still counts + toward the api-error breaker; +- reading an *empty* book instead would be the wrong answer: the bot would redeploy over + liquidity it already owns, which is exactly what the fresh/complete/tip-lag rules in + `README.md` exist to prevent. + +Config: + +``` +BFF_INVENTORY_RETRY_MS=30000 +``` + +## How to check + +```bash +npm test # 19 files, 254 tests +npm run typecheck +npm run build +``` + +The new test in `test/bff.test.ts` (*"reads the position again instead of freezing the tick"*) +fails on `main` and passes with this change: it answers 503 `NODE_POSITION_SELECTION_MOVED` +twice, then the real payload, and asserts the read succeeds. diff --git a/docs/onboarding-walkthrough.txt b/docs/onboarding-walkthrough.txt new file mode 100644 index 0000000..e41844e --- /dev/null +++ b/docs/onboarding-walkthrough.txt @@ -0,0 +1,110 @@ +# Onboarding walkthrough: clone -> install -> dry-run tick on both pools +# Wall clock is UTC. The kit's own log lines are printed in the process timezone (UTC here). +# EXECUTION_MODE=dry_run throughout. The signer address was empty on chain and nothing was +# signed or broadcast: every tick ended in a decision, never in a transaction. +# Reproduce: git clone https://github.com/BitflowFinance/bitflow-market-maker-public.git + +=== bounty 2 walkthrough: clone -> install -> dry-run ticks === +started_utc=2026-12-02T20:06:29Z +node=v24.15.0 npm=12.0.1 +[2026-12-02T20:06:29Z] $ git clone https://github.com/BitflowFinance/bitflow-market-maker-public.git +[2026-12-02T20:06:31Z] clone done: a447820 +[2026-12-02T20:06:31Z] $ npm install + +added 124 packages, and audited 125 packages in 8s + +34 packages are looking for funding + run `npm fund` for details + +found 0 vulnerabilities +npm warn install-scripts 3 packages had install scripts blocked because they are not covered by allowScripts: +npm warn install-scripts esbuild@0.25.12 (postinstall: node install.js) +npm warn install-scripts fsevents@2.3.3 (install: (install scripts present)) +npm warn install-scripts esbuild@0.28.1 (postinstall: node install.js) +npm warn install-scripts +npm warn install-scripts Run `npm install-scripts ls` to review, or `npm install-scripts approve ` to allow. +[2026-12-02T20:06:39Z] npm install done +[2026-12-02T20:06:59Z] $ cp .env.sbtc.example .env.sbtc && set SIGNER_ADDRESS=SP1X05NQY8PXDJKM5ZFM8ZY71VW84NAEHC2AK9Q1Y (dry run: no key needed) +[2026-12-02T20:06:59Z] $ npm test + +{"level":30,"time":1795089600000,"pid":37363,"hostname":"iMac.local","msg":"[wallet] test add broadcast tx=0x0000000000000000000000000000000000000000000000000000000000000001 fee=0.05"} +{"level":30,"time":1795089722000,"pid":37363,"hostname":"iMac.local","msg":"[wallet] test add still pending; replace-by-fee attempt 1 new_fee=0.075"} +{"level":30,"time":1795089844000,"pid":37363,"hostname":"iMac.local","msg":"[wallet] test add still pending; replace-by-fee attempt 2 new_fee=0.1125"} +{"level":30,"time":1795090027000,"pid":37363,"hostname":"iMac.local","msg":"[wallet] test add still pending; replace-by-fee attempt 3 new_fee=0.15"} +{"level":40,"time":1796242024371,"pid":37364,"hostname":"iMac.local","msg":"[metrics] baseline reset -- PnL re-baselines on the next valued tick"} +{"level":40,"time":1796242024374,"pid":37364,"hostname":"iMac.local","msg":"[metrics] baseline reset -- PnL re-baselines on the next valued tick"} +{"level":40,"time":1796242025309,"pid":37381,"hostname":"iMac.local","msg":"[liquidity] ladder liquidity missing for 1 bin(s); read shares on-chain bins=\"664\""} +{"level":40,"time":1796242025311,"pid":37381,"hostname":"iMac.local","msg":"[liquidity] ladder liquidity missing for 2 bin(s); read shares on-chain bins=\"665,666\""} + + Test Files 18 passed (18) + Tests 230 passed (230) + Start at 03:06:59 + Duration 6.23s (transform 2.67s, setup 0ms, import 7.50s, tests 3.56s, environment 3ms) + +[2026-12-02T20:07:06Z] npm test exit=0 +[2026-12-02T20:07:23Z] $ npm run tick -- --pool sbtc +npm notice run bitflow-market-maker-public@0.1.0 tick +npm notice run tsx src/index.ts --once --pool sbtc +◇ injected env (30) from .env.sbtc // tip: ◈ encrypted .env [www.dotenvx.com] +[20:07:24.499] INFO: [index] starting environment="dev" mode="dry_run" pool="SM1FKXGNZJWSTWDWXQZJNF7B5TV5ZB235JTCXYXKD.dlmm-pool-sbtc-usdcx-v-1-bps-10" strategy="sbtc-usdcx-curve" profile="sbtc" env_file="/.env.sbtc" signer="SP1X05NQY8PXDJKM5ZFM8ZY71VW84NAEHC2AK9Q1Y" +[20:07:25.316] INFO: [index] BFF reachable url="https://bff.bitflowapis.finance/api" +[20:07:26.467] INFO: [index] token_meta resolved base=sbtc-token/8d quote=usdcx-token/6d +[20:07:26.468] INFO: [mm] tick_start id=1 mode="dry_run" pool="SM1FKXGNZJWSTWDWXQZJNF7B5TV5ZB235JTCXYXKD.dlmm-pool-sbtc-usdcx-v-1-bps-10" +[20:07:37.995] INFO: [mm] active_bin id=396 bin_step=10 usdcx-token=1986.341205 sbtc-token=0.00713516 active_bin_price=596.592394 +[20:07:37.995] INFO: [mm] wallet usdcx-token=0 sbtc-token=0 owned_bins=0 +[20:07:37.995] INFO: [mm] conversion=swap_only (rebalance via pool swaps) +[20:07:37.996] INFO: [mm] ref price=59691.00 age_ms=0 vol=0.00000 f=0.000 (f*=0.38 soft=0.52 hard=0.67) bid_frac=1.50 width=6 size=0.45 active_bin=396 active_price=596.592394 ref_price_micro=596.910000 d_bps=5 active_imbalance_bps=6469 our_skew_bps=0 +[20:07:37.996] INFO: [mm] inventory f=0.000 < f*=0.38; cash-heavy, leaning bids (bid_frac=1.50) to re-accumulate V passively (M6) +[20:07:37.996] INFO: [mm] DECISION=rebalance type=reposition reposition: initial deploy (no liquidity); rebuild curve on active bin 396 +[20:07:37.997] INFO: [plan] plan type=reposition target_bin=396 steps=1 reason="reposition: initial deploy (no liquidity); rebuild curve on active bin 396" +[20:07:37.997] INFO: [plan] step 1/1 add_shaped_liquidity offsets=[-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6] size_fraction=0.45 bid_fraction=1.5 estimated=true -- deploy 13-bin curve (half_width=6 decay=0.6 size=0.45 bid_frac=1.50) centered on active bin 396 +[20:07:37.997] INFO: [mm] dry_run: plan logged, no transactions sent +[20:07:37.997] INFO: [mm] tick_end id=1 decision="rebalance" duration="11.53s" +[2026-12-02T20:07:38Z] tick sbtc exit=0 duration=15s +[2026-12-02T20:08:10Z] $ npm run tick -- --pool stx +npm notice run bitflow-market-maker-public@0.1.0 tick +npm notice run tsx src/index.ts --once --pool stx +◇ injected env (32) from .env.stx // tip: ⌁ auth for agents [www.vestauth.com] +[20:08:11.504] INFO: [index] starting environment="dev" mode="dry_run" pool="SM1FKXGNZJWSTWDWXQZJNF7B5TV5ZB235JTCXYXKD.dlmm-pool-stx-usdcx-v-1-bps-10" strategy="stx-usdcx-curve" profile="stx" env_file="/.env.stx" signer="SP1X05NQY8PXDJKM5ZFM8ZY71VW84NAEHC2AK9Q1Y" +[20:08:12.242] INFO: [index] BFF reachable url="https://bff.bitflowapis.finance/api" +[20:08:13.409] INFO: [index] token_meta resolved base=stx/6d quote=usdcx-token/6d +[20:08:13.410] INFO: [mm] tick_start id=1 mode="dry_run" pool="SM1FKXGNZJWSTWDWXQZJNF7B5TV5ZB235JTCXYXKD.dlmm-pool-stx-usdcx-v-1-bps-10" +[20:08:23.415] WARN: [mm] GUARDRAIL api_error count=1/5 reason="snapshot_fetch_failed: 503 Service Unavailable (https://bff.bitflowapis.finance/api/app/v2/users/SP1X05NQY8PXDJKM5ZFM8ZY71VW84NAEHC2AK9Q1Y/positions/SM1FKXGNZJWSTWDWXQZJNF7B5TV5ZB235JTCXYXKD.dlmm-pool-stx-usdcx-v-1-bps-10/current-bins) code="NODE_POSITION_SELECTION_MOVED"" +[20:08:23.415] INFO: [mm] tick_end id=1 decision="frozen" duration="10.01s" +[2026-12-02T20:08:23Z] tick stx exit=0 duration=13s +[2026-12-02T20:08:29Z] $ npm run tick -- --pool stx (retry 1) +[20:08:43.713] WARN: [mm] GUARDRAIL api_error count=1/5 reason="snapshot_fetch_failed: 503 Service Unavailable (https://bff.bitflowapis.finance/api/app/v2/users/SP1X05NQY8PXDJKM5ZFM8ZY71VW84NAEHC2AK9Q1Y/positions/SM1FKXGNZJWSTWDWXQZJNF7B5TV5ZB235JTCXYXKD.dlmm-pool-stx-usdcx-v-1-bps-10/current-bins) code="NODE_POSITION_SELECTION_MOVED"" +[20:08:43.713] INFO: [mm] tick_end id=1 decision="frozen" duration="10.63s" +[2026-12-02T20:08:44Z] $ npm run tick -- --pool stx (retry 2) +[20:08:57.446] WARN: [mm] GUARDRAIL api_error count=1/5 reason="snapshot_fetch_failed: 503 Service Unavailable (https://bff.bitflowapis.finance/api/app/v2/users/SP1X05NQY8PXDJKM5ZFM8ZY71VW84NAEHC2AK9Q1Y/positions/SM1FKXGNZJWSTWDWXQZJNF7B5TV5ZB235JTCXYXKD.dlmm-pool-stx-usdcx-v-1-bps-10/current-bins) code="NODE_POSITION_SELECTION_MOVED"" +[20:08:57.446] INFO: [mm] tick_end id=1 decision="frozen" duration="10s" +[2026-12-02T20:08:57Z] $ npm run tick -- --pool stx (retry 3) +[20:09:10.398] WARN: [mm] GUARDRAIL api_error count=1/5 reason="snapshot_fetch_failed: 503 Service Unavailable (https://bff.bitflowapis.finance/api/app/v2/users/SP1X05NQY8PXDJKM5ZFM8ZY71VW84NAEHC2AK9Q1Y/positions/SM1FKXGNZJWSTWDWXQZJNF7B5TV5ZB235JTCXYXKD.dlmm-pool-stx-usdcx-v-1-bps-10/current-bins) code="NODE_POSITION_SELECTION_MOVED"" +[20:09:10.398] INFO: [mm] tick_end id=1 decision="frozen" duration="9.97s" + +=== after the fix (branch agent/fix-bff-degraded-position, applied with git am) === +[2026-12-02T20:15:32Z] $ npm run tick -- --pool sbtc +[20:15:35.994] INFO: [mm] tick_start id=1 mode="dry_run" pool="SM1FKXGNZJWSTWDWXQZJNF7B5TV5ZB235JTCXYXKD.dlmm-pool-sbtc-usdcx-v-1-bps-10" +[20:15:39.863] INFO: [mm] active_bin id=396 bin_step=10 usdcx-token=1986.341205 sbtc-token=0.00713516 active_bin_price=596.592394 +[20:15:39.863] INFO: [mm] wallet usdcx-token=0 sbtc-token=0 owned_bins=0 +[20:15:39.863] INFO: [mm] conversion=swap_only (rebalance via pool swaps) +[20:15:39.864] INFO: [mm] ref price=59688.00 age_ms=0 vol=0.00000 f=0.000 (f*=0.38 soft=0.52 hard=0.67) bid_frac=1.50 width=6 size=0.45 active_bin=396 active_price=596.592394 ref_price_micro=596.880000 d_bps=5 active_imbalance_bps=6469 our_skew_bps=0 +[20:15:39.864] INFO: [mm] tick_end id=1 decision="rebalance" duration="3.87s" +[2026-12-02T20:15:40Z] tick sbtc exit=0 duration=8s +[2026-12-02T20:15:40Z] $ npm run tick -- --pool stx +[20:15:43.204] INFO: [mm] tick_start id=1 mode="dry_run" pool="SM1FKXGNZJWSTWDWXQZJNF7B5TV5ZB235JTCXYXKD.dlmm-pool-stx-usdcx-v-1-bps-10" +[20:15:45.905] INFO: [mm] active_bin id=448 bin_step=10 usdcx-token=1953.779633 stx=10064.064843 active_bin_price=0.260692 +[20:15:45.905] INFO: [mm] wallet usdcx-token=0 stx=0 owned_bins=0 +[20:15:45.905] INFO: [mm] conversion=swap_only (rebalance via pool swaps) +[20:15:45.906] INFO: [mm] ref price=0.26 age_ms=0 vol=0.00000 f=0.000 (f*=0.38 soft=0.52 hard=0.67) bid_frac=1.50 width=13 size=0.35 active_bin=448 active_price=0.260692 ref_price_micro=0.261329 d_bps=24 active_imbalance_bps=1475 our_skew_bps=0 +[20:15:45.906] INFO: [mm] tick_end id=1 decision="rebalance" duration="2.7s" +[2026-12-02T20:15:46Z] tick stx exit=0 duration=6s +[2026-12-02T20:15:52Z] $ npm test && npm run typecheck && npm run build (with the fix) + Test Files 18 passed (18) + Tests 232 passed (232) +npm notice run bitflow-market-maker-public@0.1.0 typecheck +npm notice run tsc --noEmit +typecheck exit=0 +npm notice run bitflow-market-maker-public@0.1.0 build +npm notice run tsc +build exit=0 diff --git a/src/bitflow.ts b/src/bitflow.ts index e0e3303..f307380 100644 --- a/src/bitflow.ts +++ b/src/bitflow.ts @@ -314,18 +314,39 @@ export const walletNeverAddedLiquidity = async (address: string): Promise => { - try { - return await fetchJson(url, CONFIG.BFF_API_KEY); - } catch (err) { - if (!(err as Error).message.startsWith('503')) throw err; - // v2 answers 503 NODE_POSITION_NOT_REGISTERED, not an empty list, for a - // wallet the engine has never seen in this pool. fetchJson drops the body, - // so read the code once more before deciding. - const res = await fetch(url, { headers: CONFIG.BFF_API_KEY ? { 'X-API-Key': CONFIG.BFF_API_KEY } : {} }); - const body = (await res.json().catch(() => ({}))) as CurrentBinsResponse; - if (body.errorCode === 'NODE_POSITION_NOT_REGISTERED' && (await walletNeverAddedLiquidity(address))) return null; - throw new Error(`${(err as Error).message} code="${body.errorCode || ''}"`); + const giveUpAt = Date.now() + CONFIG.BFF_INVENTORY_RETRY_MS; + for (;;) { + try { + return await fetchJson(url, CONFIG.BFF_API_KEY); + } catch (err) { + if (!(err as Error).message.startsWith('503')) throw err; + // v2 answers 503 NODE_POSITION_NOT_REGISTERED, not an empty list, for a + // wallet the engine has never seen in this pool. fetchJson drops the body, + // so read the code once more before deciding. + const body = (await fetch(url, { headers: CONFIG.BFF_API_KEY ? { 'X-API-Key': CONFIG.BFF_API_KEY } : {} }) + .then((res) => res.json()) + .catch(() => ({}))) as CurrentBinsResponse; + if (body.errorCode === 'NODE_POSITION_NOT_REGISTERED' && (await walletNeverAddedLiquidity(address))) return null; + // A degraded position is a transient answer, not a final one: wait it out + // and read again rather than freezing the tick on a hiccup. Reading an + // empty book instead would be the wrong answer - the bot would redeploy + // over liquidity it already owns. + if (TRANSIENT_POSITION_CODES.has(body.errorCode || '') && Date.now() < giveUpAt) { + await new Promise((resolve) => setTimeout(resolve, INVENTORY_RETRY_INTERVAL_MS)); + continue; + } + throw new Error(`${(err as Error).message} code="${body.errorCode || ''}"`); + } } }; diff --git a/src/config.ts b/src/config.ts index 6f10aa9..7a87c79 100644 --- a/src/config.ts +++ b/src/config.ts @@ -59,6 +59,10 @@ export interface AppConfig { // Max blocks the v2 engine's state may trail the chain tip before we hold the // tick. 0 = only trade on a fully caught-up view (Bitflow's own guidance). BFF_MAX_TIP_LAG: number; + // How long a degraded inventory answer (503 NODE_POSITION_SELECTION_MOVED) + // is waited out before the read is called a failure. The BFF answers that + // way for a few seconds while it re-selects the node holding the position. + BFF_INVENTORY_RETRY_MS: number; STACKS_NODE_URL: string; STACKS_NODE_KEY: string; @@ -180,6 +184,7 @@ export const CONFIG: AppConfig = { BFF_API_KEY: process.env.BFF_API_KEY || '', BFF_API_VERSION: process.env.BFF_API_VERSION === 'v1' ? 'v1' : 'v2', BFF_MAX_TIP_LAG: Math.max(0, Number(process.env.BFF_MAX_TIP_LAG || 0)), + BFF_INVENTORY_RETRY_MS: Math.max(0, Number(process.env.BFF_INVENTORY_RETRY_MS || 30000)), STACKS_NODE_URL: process.env.STACKS_NODE_URL || '', STACKS_NODE_KEY: process.env.STACKS_NODE_KEY || '', diff --git a/test/bff.test.ts b/test/bff.test.ts index 0bc890d..ca0c01b 100644 --- a/test/bff.test.ts +++ b/test/bff.test.ts @@ -347,6 +347,52 @@ describe('a wallet with no position yet', () => { }); }); +describe('a degraded position answer', () => { + // The BFF answers 503 NODE_POSITION_SELECTION_MOVED while it re-selects the + // node that holds the wallet's position. Measured against the live BFF on + // 2026-12-03: the same wallet and pool answer 503 for 5-30s and then 200. + const degraded = { + ok: false, + status: 503, + statusText: 'Service Unavailable', + json: async () => ({ errorCode: 'NODE_POSITION_SELECTION_MOVED', detail: { error_code: 'POSITION_DATA_DEGRADED' } }), + }; + + it('reads the position again instead of freezing the tick', async () => { + CONFIG.BFF_API_VERSION = 'v2'; + const fallback = route(); + let degradedCalls = 0; + const fetchMock = vi.fn(async (url: string) => { + if (!url.includes('/current-bins')) return fallback(url); + degradedCalls += 1; + // The engine answers degraded twice, then settles. + if (degradedCalls <= 2) return degraded; + return ok(fixtures.v2.currentBins); + }); + vi.stubGlobal('fetch', fetchMock); + + vi.useFakeTimers(); + try { + const pending = fetchUserBins(POOL, SIGNER); + // Let the retry interval elapse; the read has to survive the wait. + for (let i = 0; i < 12; i += 1) await vi.advanceTimersByTimeAsync(250); + await expect(pending).resolves.toHaveLength(6); + } finally { + vi.useRealTimers(); + } + expect(degradedCalls).toBeGreaterThan(2); + }); + + it('still fails when the position stays degraded past the retry budget', async () => { + CONFIG.BFF_API_VERSION = 'v2'; + CONFIG.BFF_INVENTORY_RETRY_MS = 0; + vi.stubGlobal('fetch', route({ '/current-bins': degraded })); + + await expect(fetchUserBins(POOL, SIGNER)).rejects.toThrow(/NODE_POSITION_SELECTION_MOVED/); + CONFIG.BFF_INVENTORY_RETRY_MS = 30_000; + }); +}); + describe('unknown pool', () => { it('fails on success: false instead of reading an empty pool', async () => { CONFIG.BFF_API_VERSION = 'v2';