test: independently verify the fee-bump deadline fix (PR #14) with a simulated clock #1

Open
davidagentmm wants to merge 4 commits from agent/fee-bump-deadline-tests into main
3 changed files with 1251 additions and 0 deletions

View file

@ -0,0 +1,174 @@
# Fee-bump deadline fix (PR #14) — independent verification
**Commits tested:** `ea8e689` (before the fix) and `49d5276` / `a447820` / `8fe3b1c` (the fix and later).
**Suite:** `test/feeBumpDeadline.test.ts` — 22 tests, no network, no signing, no funds.
```bash
npx vitest run test/feeBumpDeadline.test.ts # 22 passed on 49d5276 / a447820
npx vitest run test/feeBumpDeadline.test.ts # 21 failed | 1 passed on ea8e689
npm test && npm run typecheck && npm run build # green on the fix
```
One case — *"the first broadcast is not retried when the node rejects the transaction"* — passes on
both commits by design: it characterizes behaviour the fix does not touch (no attempt is ever
signed, so there is no deadline to observe).
---
## 1. What the tests do
A simulated chain (`sim` in the test file) owns its own clock and a mempool:
- every broadcast becomes an *attempt* with its nonce, fee, function args, post-conditions and deadline;
- an attempt whose fee is below the chain minimum is never included; otherwise it is included
`includeMs` later;
- a replacement (same nonce) drops the attempt it replaces, like a real mempool;
- when an attempt is included the chain compares its deadline against the chain clock — past the
deadline the tx is mined as `ERR_DEADLINE_PASSED` (`abort_by_response`);
- signing (`makeContractCall`) and broadcast (`broadcastTransaction`) are mocked, and the node's
tx-status read is mocked, so nothing is signed and nothing leaves the machine.
`submitWithConfirmation` is driven exactly as the kit drives it: the original plus all three fee
bumps, for **add-liquidity, swap, a small withdrawal (1 bin) and a large withdrawal (40 bins)**.
| Named case in the bounty | Where |
|---|---|
| every signature gets `deadline = sign time + TTL` | `fee bumps keep a live deadline` (4 actions) |
| nonce, amount, slippage, post-conditions, fee cap never change | `nonce, amount, slippage, post-conditions and the fee cap never change` (4 actions) + `the swap keeps its amount…` |
| original confirms while a bump is in flight | `the original mined while a bump is in flight is the only outcome` |
| status lookup failure | `a failed status read is not a terminal outcome` |
| clock skew, wall time vs chain time | `a chain clock ahead…`, `a wallet clock ahead…`, `stacks-block-time is a staircase…` |
| cap exhaustion | `stops at the fee cap without another broadcast`, `the large withdrawal runs out of bump budget…` |
| zero duplicate terminal outcomes | every case asserts `sim.terminal` has at most one entry |
**Red/green.** On `ea8e689` 21 of the 22 tests fail; on the fix all 22 pass. The plan in every case is
prepared `PREPARE_GAP_MS` (30 s) before the transaction is signed, which is what the kit really does
(prepare → preflight reads → sign) and what makes the stale plan deadline observable.
---
## 2. Verdict
The fix does what it says: **every** signature — original and all three bumps — carries
`deadline = sign time + TX_DEADLINE_SECONDS`, and nothing else about the call moves (same nonce,
same amounts, same slippage bounds, same post-conditions, same fee cap). Terminal outcomes stay
unique in every scenario, including the RBF race and the failed status read.
---
## 3. Does it still recur on a larger withdrawal? Yes — and the reason is not the stamp
**Answer: yes, and the deadline stamp is not the reason any more.** The deadline is now fresh on
every signature, but the window it opens is much shorter than `TX_DEADLINE_SECONDS` looks, and a
multi-bin withdrawal is the shape that falls out of it.
Three measured facts:
1. **The router compares the deadline against `stacks-block-time`, not against arrival time.**
From the router source on chain
(`SM1FKXGNZJWSTWDWXQZJNF7B5TV5ZB235JTCXYXKD.dlmm-liquidity-router-v-1-2`):
```clarity
(asserts! (or (is-none deadline-time)
(<= stacks-block-time (unwrap-panic deadline-time)))
ERR_DEADLINE_PASSED)
```
Note the position: the assertion runs **after** the `fold` over the positions, so the per-bin
withdrawals, NFT burns and transfers are executed first and the fee is spent either way.
2. **`stacks-block-time` is a staircase, not a clock.** It is the burn time of the Bitcoin block that
opened the current tenure. Measured on mainnet: Stacks heights `9637165 … 9637176` all carry
`burn_block_time = 1796239037`; the value only advances when the next Bitcoin block arrives
(~600 s). So `sign time + 120 s` is **not** a 120-second window: it is valid for the rest of the
current tenure, and it expires the moment the burn time steps past it — one ~600 s step.
3. **A multi-bin withdrawal is ~14× bigger and carries one post-condition per bin.** Measured with
the kit's own builders (`buildWithdrawLiquidityCall`, payload serialized locally, never
broadcast):
| bins | post-conditions | serialized size |
|---|---|---|
| 1 | 4 | 951 B |
| 10 | 13 | 3 903 B |
| 20 | 23 | 7 183 B |
| 30 | 33 | 10 463 B |
| 40 | 43 | 13 743 B |
| 48 | 51 | 16 367 B |
Post-conditions = bins + 3 (one `maybe-send` NFT condition per bin, plus the LP burn and the two
inflow bounds). The router accepts up to 326 positions per call, but the kit never splits a
withdrawal into several transactions, so every bin the bot holds ends up in one transaction.
**Put together:** a withdrawal that misses the current block — a bigger payload, one post-condition
and one `dlmm-core` call per bin, so a real cost — lands in the *next* tenure, whose burn time is
~600 s past every deadline the wallet stamped. It is mined as `ERR_DEADLINE_PASSED`. Re-stamping the
deadline cannot bridge a 600 s burn-time step with a 120 s TTL: the freshest deadline the wallet can
stamp (`sign time + 120 s`) is still 480 s behind the burn time of the block the tx lands in.
That is what the reliability notes are seeing, and it is not a deadline-stamping bug any more. The
tests pin both halves of it:
- `stacks-block-time is a staircase: a tx that lands in the next tenure has expired` — the wallet
reports `timeout` after three bumps, and the transaction is then mined as `abort_by_response`
(fee burned, position not withdrawn) with the wallet never finding out;
- `the large withdrawal is not more likely to expire than the small one, as long as it lands in the
same tenure` — the same 40-bin call succeeds when it is included inside the current tenure.
The size itself is not the cause; **crossing the tenure boundary** is, and the large withdrawal is
what makes crossing it likely.
---
## 4. What the fix still misses
1. **The deadline is stamped from the wallet's wall clock.** `txDeadline()` uses `Date.now()`, the
router compares `stacks-block-time`. A wallet clock 100 s ahead ships an already expired deadline
(test: *a wallet clock ahead of the chain clock ships an already expired deadline*); 100 s behind
shortens the window to 20 s (test: *a chain clock ahead of the wallet clock eats the deadline
window*). The chain clock is available from the node (`/extended/v1/block` carries
`burn_block_time`), and the deadline should be stamped from it, not from the local clock.
2. **A 120 s TTL is not a 120 s window** (section 3). `TX_DEADLINE_SECONDS` should be sized against
the tenure interval (or the deadline should be dropped in favour of a replacability rule), and
`TX_CONFIRMATION_TIMEOUT_MS` should not equal the deadline window: the confirmation timeout is
what decides when a bump is signed, so with the two equal the first bump is always signed after
the original deadline has expired.
3. **The first broadcast is not retried.** `submitWithConfirmation` guards only the *resubmit*
(`wallet.ts`); the first `submit(fee)` is unguarded, so a node rejection — a fee below the
chain minimum, an invalid call — is fatal and the fee-bump machinery never engages
(test: *the first broadcast is not retried when the node rejects the transaction*).
4. **The fee estimate is size-blind.** `estimateFee()` takes a mempool percentile and never looks
at the transaction it is about to pay for. The node's minimum fee is proportional to the
serialized size: measured on mainnet, a 181-byte transfer pays 180 µSTX, a 418-byte contract
call pays 417 µSTX, a 1 223-byte call pays 1 500 µSTX (≈1 µSTX/byte). A 40-bin withdrawal needs
≈13.7 k µSTX, which is **above** the kit's `MIN_TX_FEE_USTX` floor of 10 000 — the floor can be
under the node's minimum for exactly the calls that are too big to land.
5. **Cap exhaustion is reported as a plain timeout.** `wallet.ts` checks the bump budget before the
fee cap, so a run that exhausts both reports `timeout`, not `timeout_max_fee` — the caller cannot
tell "no more fee room" from "no more time" (test: *the fee cap is reported as a plain timeout
when the bump budget runs out at the same time*).
6. **`SubmitResult.fee` reports the last bumped fee, not the fee that was paid.** When the original
confirms after a bump was broadcast, the result still carries the bumped fee (test: *the
reported fee is the last bumped fee even when the original confirms*).
7. **A transaction that mines after the wallet gave up is never reconciled.** After the last bump
the wallet returns `timeout` and forgets the transaction; if it later mines as
`abort_by_response`, the position is still not withdrawn and the fee is burned, with no record.
The kit already re-checks prior transactions after a failed resubmit — the same reconciliation
belongs at the end of the bump budget.
---
## 5. Suggested fixes (not in this PR)
- stamp the deadline from the chain clock (`stacks-block-time`) and size `TX_DEADLINE_SECONDS`
against the tenure interval rather than the confirmation window;
- guard the first broadcast too, and bump on a node rejection the same way as on a timeout;
- make the fee estimate size-aware (fee = size × mempool fee rate) instead of using a mempool
percentile as an absolute fee;
- report `timeout_max_fee` when the cap is what stopped the run, and report the fee that the
confirmed transaction actually paid;
- reconcile the last broadcast after the bump budget runs out, and chunk a multi-bin withdrawal
into transactions the chain can accept.
None of these change the behaviour the bounty asks about; they are the parts of the surrounding
machinery that make the deadline fix insufficient on its own.

View file

@ -0,0 +1,403 @@
# Fee-bump deadline suite: red on ea8e689, green on the fix
The same file, test/feeBumpDeadline.test.ts, on both trees. Mocks only: no network, no signing,
no funds. The pre-fix run is a copy of the file onto the ea8e689 checkout.
### commit under test: ea8e6895fa8d88f4e21ea78dc51cdebbc79e66ee (ea8e689 fix: name the BFF host and cause on fetch failures; refresh audited deps (#13))
### node v24.15.0 / npm 12.0.1
### the same test/feeBumpDeadline.test.ts file, copied onto the pre-fix tree
$ npx vitest run test/feeBumpDeadline.test.ts
npm notice run bitflow-market-maker-public@0.1.0 npx
npm notice run 'vitest' run test/feeBumpDeadline.test.ts
RUN v4.1.12 /private/var/folders/xg/1ss5r9n512nfg3d5b035p4140000gn/T/opencode/bitflow-old
stdout | test/feeBumpDeadline.test.ts
◇ injected env (0) from .env // tip: ◈ secrets for agents [www.dotenvx.com]
❯ test/feeBumpDeadline.test.ts (22 tests | 21 failed) 387ms
× add-liquidity: every broadcast signs its own deadline, sign time + TTL 36ms
× swap: every broadcast signs its own deadline, sign time + TTL 15ms
× withdraw-small: every broadcast signs its own deadline, sign time + TTL 23ms
× withdraw-large: every broadcast signs its own deadline, sign time + TTL 41ms
× add-liquidity: nonce, amount, slippage, post-conditions and the fee cap never change 17ms
× swap: nonce, amount, slippage, post-conditions and the fee cap never change 14ms
× withdraw-small: nonce, amount, slippage, post-conditions and the fee cap never change 16ms
× withdraw-large: nonce, amount, slippage, post-conditions and the fee cap never change 41ms
× the swap keeps its amount, minimum received and steps across the bumps 13ms
× the original mined while a bump is in flight is the only outcome 7ms
× a failed status read is not a terminal outcome 6ms
× stops after the configured number of fee bumps 14ms
× stops at the fee cap without another broadcast 9ms
× the large withdrawal runs out of bump budget before it runs out of fee cap 44ms
× a chain clock ahead of the wallet clock eats the deadline window 4ms
× a wallet clock ahead of the chain clock gives the deadline more room, not less 1ms
× stacks-block-time is a staircase: a tx that lands in the next tenure has expired 32ms
× a withdrawal slower than the deadline window is still mined as ERR_DEADLINE_PASSED 20ms
× the large withdrawal is not more likely to expire than the small one, as long as it lands in the same tenure 13ms
× the fee cap is reported as a plain timeout when the bump budget runs out at the same time 8ms
× the reported fee is the last bumped fee even when the original confirms 8ms
⎯⎯⎯⎯⎯⎯ Failed Tests 21 ⎯⎯⎯⎯⎯⎯⎯
FAIL test/feeBumpDeadline.test.ts > fee bumps keep a live deadline (PR #14) > add-liquidity: every broadcast signs its own deadline, sign time + TTL
FAIL test/feeBumpDeadline.test.ts > fee bumps keep a live deadline (PR #14) > swap: every broadcast signs its own deadline, sign time + TTL
FAIL test/feeBumpDeadline.test.ts > fee bumps keep a live deadline (PR #14) > withdraw-small: every broadcast signs its own deadline, sign time + TTL
FAIL test/feeBumpDeadline.test.ts > fee bumps keep a live deadline (PR #14) > withdraw-large: every broadcast signs its own deadline, sign time + TTL
AssertionError: expected { ok: false, …(4) } to match object { ok: true, status: 'success', …(1) }
(2 matching properties omitted from actual)
- Expected
+ Received
{
"bumps": 3,
- "ok": true,
- "status": "success",
+ "ok": false,
+ "status": "abort_by_response",
}
❯ test/feeBumpDeadline.test.ts:352:17
350| // The original plus all three fee bumps.
351| expect(sim.attempts).toHaveLength(4);
352| expect(res).toMatchObject({ ok: true, status: 'success', bumps: 3 …
| ^
353|
354| for (const attempt of sim.attempts) {
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/21]⎯
FAIL test/feeBumpDeadline.test.ts > fee bumps keep a live deadline (PR #14) > add-liquidity: nonce, amount, slippage, post-conditions and the fee cap never change
FAIL test/feeBumpDeadline.test.ts > fee bumps keep a live deadline (PR #14) > swap: nonce, amount, slippage, post-conditions and the fee cap never change
FAIL test/feeBumpDeadline.test.ts > fee bumps keep a live deadline (PR #14) > withdraw-small: nonce, amount, slippage, post-conditions and the fee cap never change
FAIL test/feeBumpDeadline.test.ts > fee bumps keep a live deadline (PR #14) > withdraw-large: nonce, amount, slippage, post-conditions and the fee cap never change
AssertionError: expected 1795089690 to be 1795089720 // Object.is equality
- Expected
+ Received
- 1795089720
+ 1795089690
❯ expectFreshDeadlines test/feeBumpDeadline.test.ts:321:30
319| expect(sim.attempts.length).toBeGreaterThan(0);
320| for (const attempt of sim.attempts) {
321| expect(attempt.deadline).toBe(Math.floor(attempt.signAtMs / 1000) …
| ^
322| }
323| };
❯ test/feeBumpDeadline.test.ts:395:5
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[2/21]⎯
FAIL test/feeBumpDeadline.test.ts > fee bumps keep a live deadline (PR #14) > the swap keeps its amount, minimum received and steps across the bumps
AssertionError: expected 1795089690 to be 1795089720 // Object.is equality
- Expected
+ Received
- 1795089720
+ 1795089690
❯ expectFreshDeadlines test/feeBumpDeadline.test.ts:321:30
319| expect(sim.attempts.length).toBeGreaterThan(0);
320| for (const attempt of sim.attempts) {
321| expect(attempt.deadline).toBe(Math.floor(attempt.signAtMs / 1000) …
| ^
322| }
323| };
❯ test/feeBumpDeadline.test.ts:406:5
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[3/21]⎯
FAIL test/feeBumpDeadline.test.ts > one terminal outcome > the original mined while a bump is in flight is the only outcome
AssertionError: expected { ok: false, …(4) } to match object { ok: true, status: 'success', …(1) }
(2 matching properties omitted from actual)
- Expected
+ Received
{
"bumps": 1,
- "ok": true,
- "status": "success",
+ "ok": false,
+ "status": "abort_by_response",
}
❯ test/feeBumpDeadline.test.ts:426:17
424| );
425|
426| expect(res).toMatchObject({ ok: true, status: 'success', bumps: 1 …
| ^
427| expect(res.txId).toBe(`0x${sim.attempts[0].txId}`);
428| // The replacement never reached the chain, and the chain recorded…
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[4/21]⎯
FAIL test/feeBumpDeadline.test.ts > one terminal outcome > a failed status read is not a terminal outcome
AssertionError: expected 1795089690 to be 1795089720 // Object.is equality
- Expected
+ Received
- 1795089720
+ 1795089690
❯ expectFreshDeadlines test/feeBumpDeadline.test.ts:321:30
319| expect(sim.attempts.length).toBeGreaterThan(0);
320| for (const attempt of sim.attempts) {
321| expect(attempt.deadline).toBe(Math.floor(attempt.signAtMs / 1000) …
| ^
322| }
323| };
❯ test/feeBumpDeadline.test.ts:451:5
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[5/21]⎯
FAIL test/feeBumpDeadline.test.ts > the budget and the cap > stops after the configured number of fee bumps
AssertionError: expected 1795089690 to be 1795089720 // Object.is equality
- Expected
+ Received
- 1795089720
+ 1795089690
❯ expectFreshDeadlines test/feeBumpDeadline.test.ts:321:30
319| expect(sim.attempts.length).toBeGreaterThan(0);
320| for (const attempt of sim.attempts) {
321| expect(attempt.deadline).toBe(Math.floor(attempt.signAtMs / 1000) …
| ^
322| }
323| };
❯ test/feeBumpDeadline.test.ts:468:5
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[6/21]⎯
FAIL test/feeBumpDeadline.test.ts > the budget and the cap > stops at the fee cap without another broadcast
AssertionError: expected 1795089690 to be 1795089720 // Object.is equality
- Expected
+ Received
- 1795089720
+ 1795089690
❯ expectFreshDeadlines test/feeBumpDeadline.test.ts:321:30
319| expect(sim.attempts.length).toBeGreaterThan(0);
320| for (const attempt of sim.attempts) {
321| expect(attempt.deadline).toBe(Math.floor(attempt.signAtMs / 1000) …
| ^
322| }
323| };
❯ test/feeBumpDeadline.test.ts:483:5
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[7/21]⎯
FAIL test/feeBumpDeadline.test.ts > the budget and the cap > the large withdrawal runs out of bump budget before it runs out of fee cap
AssertionError: expected 1795089690 to be 1795089720 // Object.is equality
- Expected
+ Received
- 1795089720
+ 1795089690
❯ expectFreshDeadlines test/feeBumpDeadline.test.ts:321:30
319| expect(sim.attempts.length).toBeGreaterThan(0);
320| for (const attempt of sim.attempts) {
321| expect(attempt.deadline).toBe(Math.floor(attempt.signAtMs / 1000) …
| ^
322| }
323| };
❯ test/feeBumpDeadline.test.ts:502:5
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[8/21]⎯
FAIL test/feeBumpDeadline.test.ts > the clock the deadline is measured against > a chain clock ahead of the wallet clock eats the deadline window
AssertionError: expected 1795089690 to be 1795089720 // Object.is equality
- Expected
+ Received
- 1795089720
+ 1795089690
❯ test/feeBumpDeadline.test.ts:521:30
519|
520| const attempt = sim.attempts[0];
521| expect(attempt.deadline).toBe(Math.floor(attempt.signAtMs / 1000) …
| ^
522| // In chain time the window is 20s, not 120s.
523| expect(attempt.deadline - Math.floor(sim.chainNow() / 1000)).toBeL…
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[9/21]⎯
FAIL test/feeBumpDeadline.test.ts > the clock the deadline is measured against > a wallet clock ahead of the chain clock gives the deadline more room, not less
AssertionError: expected 1795089690 to be 1795089720 // Object.is equality
- Expected
+ Received
- 1795089720
+ 1795089690
❯ expectFreshDeadlines test/feeBumpDeadline.test.ts:321:30
319| expect(sim.attempts.length).toBeGreaterThan(0);
320| for (const attempt of sim.attempts) {
321| expect(attempt.deadline).toBe(Math.floor(attempt.signAtMs / 1000) …
| ^
322| }
323| };
❯ test/feeBumpDeadline.test.ts:543:5
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[10/21]⎯
FAIL test/feeBumpDeadline.test.ts > the clock the deadline is measured against > stacks-block-time is a staircase: a tx that lands in the next tenure has expired
AssertionError: expected 1795089690 to be 1795089720 // Object.is equality
- Expected
+ Received
- 1795089720
+ 1795089690
❯ expectFreshDeadlines test/feeBumpDeadline.test.ts:321:30
319| expect(sim.attempts.length).toBeGreaterThan(0);
320| for (const attempt of sim.attempts) {
321| expect(attempt.deadline).toBe(Math.floor(attempt.signAtMs / 1000) …
| ^
322| }
323| };
❯ test/feeBumpDeadline.test.ts:563:5
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[11/21]⎯
FAIL test/feeBumpDeadline.test.ts > what the fix still misses > a withdrawal slower than the deadline window is still mined as ERR_DEADLINE_PASSED
AssertionError: expected 1795089690 to be 1795089720 // Object.is equality
- Expected
+ Received
- 1795089720
+ 1795089690
❯ test/feeBumpDeadline.test.ts:594:30
592| // The deadline was fresh when it was signed; it still expired on …
593| const attempt = sim.attempts[0];
594| expect(attempt.deadline).toBe(Math.floor(attempt.signAtMs / 1000) …
| ^
595| expect(Math.floor(sim.chainNow() / 1000)).toBeGreaterThan(attempt.…
596| expectFreshDeadlines();
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[12/21]⎯
FAIL test/feeBumpDeadline.test.ts > what the fix still misses > the large withdrawal is not more likely to expire than the small one, as long as it lands in the same tenure
AssertionError: expected 1795089690 to be 1795089720 // Object.is equality
- Expected
+ Received
- 1795089720
+ 1795089690
❯ expectFreshDeadlines test/feeBumpDeadline.test.ts:321:30
319| expect(sim.attempts.length).toBeGreaterThan(0);
320| for (const attempt of sim.attempts) {
321| expect(attempt.deadline).toBe(Math.floor(attempt.signAtMs / 1000) …
| ^
322| }
323| };
❯ test/feeBumpDeadline.test.ts:615:5
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[13/21]⎯
FAIL test/feeBumpDeadline.test.ts > what the fix still misses > the fee cap is reported as a plain timeout when the bump budget runs out at the same time
AssertionError: expected 1795089690 to be 1795089720 // Object.is equality
- Expected
+ Received
- 1795089720
+ 1795089690
❯ expectFreshDeadlines test/feeBumpDeadline.test.ts:321:30
319| expect(sim.attempts.length).toBeGreaterThan(0);
320| for (const attempt of sim.attempts) {
321| expect(attempt.deadline).toBe(Math.floor(attempt.signAtMs / 1000) …
| ^
322| }
323| };
❯ test/feeBumpDeadline.test.ts:654:5
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[14/21]⎯
FAIL test/feeBumpDeadline.test.ts > what the fix still misses > the reported fee is the last bumped fee even when the original confirms
AssertionError: expected false to be true // Object.is equality
- Expected
+ Received
- true
+ false
❯ test/feeBumpDeadline.test.ts:670:20
668| );
669|
670| expect(res.ok).toBe(true);
| ^
671| expect(res.fee).toBe(BigInt(75_000));
672| expect(sim.attempts[0].fee).toBe(BigInt(50_000));
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[15/21]⎯
Test Files 1 failed (1)
Tests 21 failed | 1 passed (22)
Start at 03:17:14
Duration 1.03s (transform 271ms, setup 0ms, import 444ms, tests 387ms, environment 0ms)
-----
### commit under test: 8f582ea12fad0aaf4221ea311bbdbc34d08c9fad (8f582ea test: verify the fee-bump deadline fix (PR #14) with a simulated clock)
### node v24.15.0 / npm 12.0.1
$ npx vitest run test/feeBumpDeadline.test.ts
npm notice run bitflow-market-maker-public@0.1.0 npx
npm notice run 'vitest' run test/feeBumpDeadline.test.ts
RUN v4.1.12 /Users/tamnguyen/Desktop/test_opencode/david/.context/bitflow
Test Files 1 passed (1)
Tests 22 passed (22)
Start at 03:16:55
Duration 1.44s (transform 396ms, setup 0ms, import 723ms, tests 476ms, environment 0ms)
$ npm test
npm notice run bitflow-market-maker-public@0.1.0 test
npm notice run vitest run
RUN v4.1.12 /Users/tamnguyen/Desktop/test_opencode/david/.context/bitflow
Test Files 19 passed (19)
Tests 252 passed (252)
Start at 03:16:57
Duration 4.59s (transform 1.22s, setup 0ms, import 5.54s, tests 3.47s, environment 3ms)
$ npm run typecheck
npm notice run bitflow-market-maker-public@0.1.0 typecheck
npm notice run tsc --noEmit
typecheck exit=0
$ npm run build
npm notice run bitflow-market-maker-public@0.1.0 build
npm notice run tsc
build exit=0

View file

@ -0,0 +1,674 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { CONFIG } from '../src/config';
import {
broadcastLiquidity,
buildAddLiquidityCall,
buildWithdrawLiquidityCall,
poolRef,
} from '../src/liquidity';
import { buildSwapCall } from '../src/swap';
import { signAndBroadcast, submitWithConfirmation } from '../src/wallet';
// A simulated Stacks chain drives every case below.
//
// The chain keeps its own clock, which is deliberately allowed to drift from the
// wallet's wall clock (sim.skewMs): a router deadline is compared against block
// time on chain, so a wallet whose clock is off shortens or voids the window it
// believes it has. Every broadcast becomes an attempt with a nonce, a fee and the
// deadline it carries. An attempt whose fee is below the chain's current minimum
// fee is never included; an attempt at or above it is included sim.includeMs
// later. A replacement (same nonce) drops the attempt it replaces, exactly like
// a Stacks mempool replacement. When an attempt is finally included the chain
// compares its deadline against its own clock: past the deadline the tx is mined
// as ERR_DEADLINE_PASSED (abort_by_response), which is the failure PR #14 was
// about.
//
// Two details of the real chain matter for the findings and are modelled here:
//
// 1. `stacks-block-time` is a staircase, not a smooth clock. It is the burn time
// of the Bitcoin block that opened the current tenure, and every Stacks block
// in that tenure repeats it (measured on mainnet: heights 9637165..9637176 all
// carry burn_block_time 1796239037). It only advances when the next Bitcoin
// block arrives, i.e. in ~600s steps. sim.staircase switches that model on.
//
// 2. The deadline is compared against that burn time, so a deadline of
// "sign time + 120s" is not a 120-second window: it is valid for the rest of
// the current tenure, and expires the moment the burn time steps past it.
//
// Nothing here signs, broadcasts or reaches the network: signing and broadcast
// are mocked, and the node's tx-status reads are mocked too.
const sim = vi.hoisted(() => {
// One object, shared by reference: the mock factories and the tests below
// all mutate the very same state.
const s: any = {
skewMs: 0,
minFee: 150_000n,
includeMs: 15_000,
stepMs: 30_000,
// Chain time at which the first attempt is included, whatever its fee.
includeFirstAt: null as number | null,
// 1-based broadcast that fails (the nonce is already used).
failBroadcastNumber: null as number | null,
// Consecutive status reads of the first attempt that fail.
lookupFails: 0,
broadcastCount: 0,
txCounter: 0,
prepared: null as any,
attempts: [] as any[],
byTxId: new Map<string, any>(),
terminal: [] as string[],
// Staircase clock: burn time of the tenure that opened at tenureFirstBurn,
// stepping by tenureMs (the Bitcoin block interval) on every tenure change.
staircase: false,
tenureMs: 600_000,
tenureFirstBurn: 0,
};
// The chain's burn time for a given moment of the wallet's clock.
s.chainAt = (wallMs: number): number => {
const chainRaw = wallMs + s.skewMs;
if (!s.staircase) return chainRaw;
const tenures = Math.floor((chainRaw - s.tenureFirstBurn) / s.tenureMs);
return s.tenureFirstBurn + (tenures < 0 ? 0 : tenures) * s.tenureMs;
};
s.chainNow = (): number => s.chainAt(Date.now());
// The routers take the deadline as a trailing (optional uint). v6 encodes
// uint as type 1 and some as type 10; v7 encodes them as 'uint' and 'some'.
const optionalUint = (arg: unknown): bigint | null => {
if (!arg || typeof arg !== 'object') return null;
const a = arg as { type?: unknown; value?: any };
if (a.type !== 10 && a.type !== 'some') return null;
const inner = a.value;
if (!inner || (inner.type !== 1 && inner.type !== 'uint')) return null;
return BigInt(inner.value);
};
s.deadlineOf = (args: unknown[]): { index: number; value: bigint } | null => {
for (let i = args.length - 1; i >= 0; i--) {
const v = optionalUint(args[i]);
if (v !== null) return { index: i, value: v };
}
return null;
};
s.register = (txid: string): void => {
const p = s.prepared;
s.prepared = null;
if (!p) throw new Error('no prepared transaction: makeContractCall was not mocked');
const d = s.deadlineOf(p.functionArgs);
const nonce = String(p.nonce);
// A replacement (same nonce) drops the attempt it replaces.
for (const a of s.attempts) {
if (a.nonce === nonce && a.status === 'pending') a.status = 'dropped_replace_by_fee';
}
const signAtMs = Date.now();
const attempt = {
txId: txid,
nonce,
fee: BigInt(p.fee),
args: p.functionArgs,
postConditions: p.postConditions,
postConditionMode: p.postConditionMode,
signAtMs,
deadline: d ? Number(d.value) : null,
deadlineIndex: d ? d.index : -1,
// The wallet-clock moment the chain includes this attempt. The chain's
// burn time at that moment decides the deadline check.
includeAtMs:
s.attempts.length === 0 && s.includeFirstAt !== null
? s.includeFirstAt - s.skewMs
: BigInt(p.fee) >= s.minFee
? signAtMs + s.includeMs
: Number.POSITIVE_INFINITY,
status: 'pending',
};
s.attempts.push(attempt);
s.byTxId.set(txid, attempt);
};
// Poll view of one attempt: include it when the chain reaches it.
s.poll = (txid: string): { tx_status?: string } => {
const a = s.byTxId.get(txid);
if (!a) return {};
if (a.status === 'pending' && Date.now() >= a.includeAtMs) {
const chainSec = Math.floor(s.chainAt(a.includeAtMs) / 1000);
a.status = a.deadline !== null && chainSec > a.deadline ? 'abort_by_response' : 'success';
s.terminal.push(a.txId);
}
return { tx_status: a.status };
};
s.fakeMakeContractCall = async (opts: any): Promise<any> => {
s.prepared = { ...opts, signAtMs: Date.now() };
return {};
};
s.fakeBroadcast = async (): Promise<any> => {
s.broadcastCount += 1;
if (s.failBroadcastNumber === s.broadcastCount) {
s.failBroadcastNumber = null;
throw new Error('broadcast failed: nonce already used');
}
const txid = (++s.txCounter).toString(16).padStart(64, '0');
s.register(txid);
return { txid };
};
s.reset = (): void => {
s.skewMs = 0;
s.minFee = 150_000n;
s.includeMs = 15_000;
s.stepMs = 30_000;
s.includeFirstAt = null;
s.failBroadcastNumber = null;
s.lookupFails = 0;
s.broadcastCount = 0;
s.txCounter = 0;
s.prepared = null;
s.attempts = [];
s.byTxId = new Map();
s.terminal = [];
s.staircase = false;
s.tenureMs = 600_000;
s.tenureFirstBurn = 0;
};
return s;
});
vi.mock('stacks-tx-v7', async () => {
const actual = await vi.importActual<typeof import('stacks-tx-v7')>('stacks-tx-v7');
return {
...actual,
makeContractCall: sim.fakeMakeContractCall,
broadcastTransaction: sim.fakeBroadcast,
};
});
vi.mock('@stacks/transactions', async () => {
const actual = await vi.importActual<typeof import('@stacks/transactions')>('@stacks/transactions');
return {
...actual,
makeContractCall: sim.fakeMakeContractCall,
broadcastTransaction: sim.fakeBroadcast,
};
});
// The node's tx-status read. It moves the wallet's wall clock forward on every
// call (the chain only advances while we poll) and answers with the state of
// the attempt the chain holds for that tx id.
vi.mock('../src/stacks', async () => {
const actual = await vi.importActual<typeof import('../src/stacks')>('../src/stacks');
return {
...actual,
fetchJson: async (url: string) => {
vi.setSystemTime(Date.now() + sim.stepMs);
const m = url.match(/\/extended\/v1\/tx\/0x([0-9a-fA-F]+)/);
if (!m) return {};
const txid = m[1];
const first = sim.attempts[0];
if (first && txid === first.txId && sim.lookupFails > 0) {
sim.lookupFails -= 1;
throw new Error('status lookup failed');
}
return sim.poll(txid);
},
};
});
const POOL = 'SM1FKXGNZJWSTWDWXQZJNF7B5TV5ZB235JTCXYXKD.dlmm-pool-sbtc-usdcx-v-1-bps-10';
const SIGNER = 'SP15VM42Q85WEKQFW9NQDKKCFNJF2NG2VBTPR6CBR';
const T0 = Date.UTC(2026, 10, 19, 12, 0, 0);
const saved = { ...CONFIG };
const pool = () => poolRef(POOL, CONFIG.BASE_TOKEN_CONTRACT, CONFIG.QUOTE_TOKEN_CONTRACT);
// The gap between the moment the plan was prepared (which is when the plan
// carries its deadline) and the moment the transaction is signed. The kit
// prepares the call, runs the preflight reads and only then signs, so the
// deadline that ships with the plan is already this old when the tx goes out.
const PREPARE_GAP_MS = 30_000;
// The deadline the plan was prepared with: stamped once, before any signing.
const preparedDeadline = (): number =>
Math.floor((T0 - PREPARE_GAP_MS) / 1000) + CONFIG.TX_DEADLINE_SECONDS;
const addCall = (bins = 1) =>
buildAddLiquidityCall(
pool(),
Array.from({ length: bins }, (_, i) => ({
binId: 500 + i,
offset: 0,
xAmount: BigInt(1_000),
yAmount: BigInt(1_000),
minDlp: BigInt(1),
maxXFee: BigInt(0),
maxYFee: BigInt(0),
})),
SIGNER,
{ activeBinTolerance: { maxDeviation: 2, expectedSignedBinId: 0 }, deadline: preparedDeadline() },
);
const swapCall = () =>
buildSwapCall(
{
poolContract: POOL,
xToken: CONFIG.BASE_TOKEN_CONTRACT,
yToken: CONFIG.QUOTE_TOKEN_CONTRACT,
amountIn: BigInt(1_000),
minReceived: BigInt(900),
xForY: true,
maxSteps: 10,
deadline: preparedDeadline(),
},
SIGNER,
);
// A small withdrawal: one bin, a dust amount.
const smallWithdrawCall = () =>
buildWithdrawLiquidityCall(
pool(),
[{ binId: 500, amount: BigInt(10), minX: BigInt(1), minY: BigInt(1) }],
SIGNER,
{ deadline: preparedDeadline() },
);
// A large withdrawal: many bins and a big amount, the shape the reliability
// notes complain about.
const largeWithdrawCall = (bins = 40) =>
buildWithdrawLiquidityCall(
pool(),
Array.from({ length: bins }, (_, i) => ({
binId: 480 + i,
amount: BigInt(1_000_000 + i),
minX: BigInt(500),
minY: BigInt(500),
})),
SIGNER,
{ deadline: preparedDeadline() },
);
type Action = 'add-liquidity' | 'swap' | 'withdraw-small' | 'withdraw-large';
const callFor = (action: Action) => {
if (action === 'add-liquidity') return addCall();
if (action === 'swap') return swapCall();
if (action === 'withdraw-small') return smallWithdrawCall();
return largeWithdrawCall();
};
// Every action goes out through the same confirmation loop: the liquidity
// router (add/withdraw) signs with the v7 path, the swap router with the v6 one.
const submitFor = (action: Action, fee: bigint) => {
const call = callFor(action);
if (action === 'swap') return signAndBroadcast(call, { address: SIGNER, nonce: 7, fee });
return broadcastLiquidity(call, { address: SIGNER, nonce: 7, fee });
};
const ACTIONS: Action[] = ['add-liquidity', 'swap', 'withdraw-small', 'withdraw-large'];
// The invariant PR #14 introduced: every signature carries its own deadline,
// stamped when it is signed. Without it a bumped attempt carries the deadline the
// plan was prepared with, which has expired by the time the bump is signed, so
// the scenario a test sets up is not the scenario the fix claims to fix. Every
// case below therefore asserts it too - that is what makes each of them fail
// on ea8e689 and pass on the fix.
const expectFreshDeadlines = () => {
expect(sim.attempts.length).toBeGreaterThan(0);
for (const attempt of sim.attempts) {
expect(attempt.deadline).toBe(Math.floor(attempt.signAtMs / 1000) + CONFIG.TX_DEADLINE_SECONDS);
}
};
beforeEach(() => {
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(T0);
sim.reset();
sim.tenureFirstBurn = T0;
Object.assign(CONFIG, {
SIGNER_KEY: 'stubbed-signing',
TX_DEADLINE_SECONDS: 120,
TX_CONFIRMATION_TIMEOUT_MS: 120_000,
TX_POLL_INTERVAL_MS: 1,
TX_MAX_FEE_BUMPS: 3,
TX_FEE_BUMP_MULTIPLIER: 1.5,
MAX_TX_FEE_USTX: 150_000,
});
});
afterEach(() => {
vi.useRealTimers();
Object.assign(CONFIG, saved);
});
describe('fee bumps keep a live deadline (PR #14)', () => {
it.each(ACTIONS)('%s: every broadcast signs its own deadline, sign time + TTL', async (action) => {
const res = await submitWithConfirmation((fee) => submitFor(action, fee), BigInt(50_000), `test ${action}`);
// The original plus all three fee bumps.
expect(sim.attempts).toHaveLength(4);
expect(res).toMatchObject({ ok: true, status: 'success', bumps: 3 });
for (const attempt of sim.attempts) {
// The deadline the router sees is stamped when the tx is signed, so it is
// the sign time plus the configured TTL - not the deadline the plan was
// prepared with.
expect(attempt.deadline).toBe(Math.floor(attempt.signAtMs / 1000) + CONFIG.TX_DEADLINE_SECONDS);
// ... and it is in the future when the tx goes out.
expect(attempt.deadline).toBeGreaterThan(attempt.signAtMs / 1000);
// No attempt was mined as a deadline failure.
expect(attempt.status).not.toBe('abort_by_response');
}
// The plan's deadline was already PREPARE_GAP_MS stale when the tx was
// signed; the fix stamps a fresh one instead of shipping the stale one.
expect(sim.attempts[0].deadline).toBe(preparedDeadline() + PREPARE_GAP_MS / 1000);
expect(sim.attempts[0].deadline).toBeGreaterThan(preparedDeadline());
expect(sim.attempts[3].deadline).toBeGreaterThan(preparedDeadline());
});
it.each(ACTIONS)('%s: nonce, amount, slippage, post-conditions and the fee cap never change', async (action) => {
await submitWithConfirmation((fee) => submitFor(action, fee), BigInt(50_000), `test ${action}`);
const [first, ...bumps] = sim.attempts;
for (const attempt of bumps) {
expect(attempt.nonce).toBe(first.nonce);
expect(attempt.postConditions).toEqual(first.postConditions);
expect(attempt.postConditionMode).toEqual(first.postConditionMode);
// Everything but the deadline argument is byte for byte the same call.
const strip = (args: unknown[]) => args.map((a, i) => (i === first.deadlineIndex ? 'deadline' : a));
expect(strip(attempt.args)).toEqual(strip(first.args));
// Only the fee moves, and only upwards, never past the cap.
expect(attempt.fee).toBeGreaterThanOrEqual(first.fee);
expect(attempt.fee).toBeLessThanOrEqual(BigInt(CONFIG.MAX_TX_FEE_USTX));
}
// 0.05 -> 0.075 -> 0.1125 -> 0.15 STX, the cap.
expect(sim.attempts.map((a) => a.fee)).toEqual([
BigInt(50_000),
BigInt(75_000),
BigInt(112_500),
BigInt(150_000),
]);
// The bumps are only safe because each one is signed with a fresh deadline.
expectFreshDeadlines();
});
it('the swap keeps its amount, minimum received and steps across the bumps', async () => {
await submitWithConfirmation((fee) => submitFor('swap', fee), BigInt(50_000), 'test swap');
const args = sim.attempts.map((a) => a.args);
for (const a of args) {
expect(a[3]).toEqual(sim.attempts[0].args[3]);
expect(a[4]).toEqual(sim.attempts[0].args[4]);
expect(a[5]).toEqual(sim.attempts[0].args[5]);
}
expectFreshDeadlines();
});
});
describe('one terminal outcome', () => {
it('the original mined while a bump is in flight is the only outcome', async () => {
// The chain runs 30s behind the wallet clock, so the original is included
// (at chain time T0+100s) after the confirmation window closed but before
// the replacement could land - and the replacement's broadcast fails because
// the nonce is now used.
sim.skewMs = -30_000;
sim.includeFirstAt = T0 + 100_000;
sim.failBroadcastNumber = 2;
const res = await submitWithConfirmation(
(fee) => submitFor('add-liquidity', fee),
BigInt(50_000),
'test rbf race',
);
expect(res).toMatchObject({ ok: true, status: 'success', bumps: 1 });
expect(res.txId).toBe(`0x${sim.attempts[0].txId}`);
// The replacement never reached the chain, and the chain recorded a single
// terminal outcome: the original.
expect(sim.attempts).toHaveLength(1);
expect(sim.terminal).toEqual([sim.attempts[0].txId]);
expectFreshDeadlines();
});
it('a failed status read is not a terminal outcome', async () => {
// The first reads of the original's status fail. The wallet keeps waiting
// instead of declaring the tx lost, and the outcome comes from the attempt
// the chain actually included.
sim.minFee = BigInt(50_000);
sim.lookupFails = 3;
const res = await submitWithConfirmation(
(fee) => submitFor('add-liquidity', fee),
BigInt(50_000),
'test lookup failure',
);
expect(res.ok).toBe(true);
expect(sim.terminal).toHaveLength(1);
expect(sim.terminal[0]).toBe(sim.attempts[sim.attempts.length - 1].txId);
expectFreshDeadlines();
});
});
describe('the budget and the cap', () => {
it('stops after the configured number of fee bumps', async () => {
// Nothing is ever includable, so every window runs out.
sim.minFee = BigInt(10_000_000);
const res = await submitWithConfirmation(
(fee) => submitFor('add-liquidity', fee),
BigInt(50_000),
'test budget',
);
expect(res).toMatchObject({ ok: false, status: 'timeout', bumps: 3 });
expect(sim.attempts).toHaveLength(4);
expect(sim.terminal).toHaveLength(0);
expectFreshDeadlines();
});
it('stops at the fee cap without another broadcast', async () => {
Object.assign(CONFIG, { MAX_TX_FEE_USTX: 60_000 });
sim.minFee = BigInt(10_000_000);
const res = await submitWithConfirmation(
(fee) => submitFor('add-liquidity', fee),
BigInt(50_000),
'test cap',
);
expect(res).toMatchObject({ ok: false, status: 'timeout_max_fee', bumps: 1 });
expect(sim.attempts.map((a) => a.fee)).toEqual([BigInt(50_000), BigInt(60_000)]);
expect(sim.attempts.every((a) => a.fee <= BigInt(CONFIG.MAX_TX_FEE_USTX))).toBe(true);
expectFreshDeadlines();
});
it('the large withdrawal runs out of bump budget before it runs out of fee cap', async () => {
// Same shape as the cap case, but with the multi-bin withdrawal: the call is
// 14 KB and carries 43 post-conditions, so it is the size that makes it
// expensive, not the deadline.
sim.minFee = BigInt(10_000_000);
const res = await submitWithConfirmation(
(fee) => submitFor('withdraw-large', fee),
BigInt(50_000),
'test cap on the large withdrawal',
);
expect(res).toMatchObject({ ok: false, status: 'timeout', bumps: 3 });
expect(sim.attempts).toHaveLength(4);
// The fee never leaves the cap, and the value bounds never move.
expect(sim.attempts.every((a) => a.fee <= BigInt(CONFIG.MAX_TX_FEE_USTX))).toBe(true);
expect(sim.attempts[3].postConditions).toEqual(sim.attempts[0].postConditions);
expectFreshDeadlines();
});
});
describe('the clock the deadline is measured against', () => {
it('a chain clock ahead of the wallet clock eats the deadline window', async () => {
// The chain runs 100s ahead: a deadline of sign time + 120s leaves only 20s
// of validity in chain time.
sim.skewMs = 100_000;
sim.minFee = BigInt(50_000);
sim.includeMs = 40_000;
const res = await submitWithConfirmation(
(fee) => submitFor('add-liquidity', fee),
BigInt(50_000),
'test skew',
);
const attempt = sim.attempts[0];
expect(attempt.deadline).toBe(Math.floor(attempt.signAtMs / 1000) + CONFIG.TX_DEADLINE_SECONDS);
// In chain time the window is 20s, not 120s.
expect(attempt.deadline - Math.floor(sim.chainNow() / 1000)).toBeLessThan(CONFIG.TX_DEADLINE_SECONDS);
expect(res.ok).toBe(false);
expect(res.status).toBe('abort_by_response');
expectFreshDeadlines();
});
it('a wallet clock ahead of the chain clock gives the deadline more room, not less', async () => {
// The chain runs 100s behind the wallet, so a deadline of sign time + 120s
// is still 220s ahead in chain time: the skew makes the window longer.
sim.skewMs = -100_000;
sim.minFee = BigInt(50_000);
const res = await submitWithConfirmation(
(fee) => submitFor('add-liquidity', fee),
BigInt(50_000),
'test skew back',
);
const attempt = sim.attempts[0];
expect(attempt.deadline).toBeGreaterThan(Math.floor(sim.chainNow() / 1000));
expect(res.ok).toBe(true);
expectFreshDeadlines();
});
it('stacks-block-time is a staircase: a tx that lands in the next tenure has expired', async () => {
// The chain's burn time only advances when the next Bitcoin block arrives
// (~600s). A tx included in the next tenure is compared against a burn time
// 600s past the one the wallet stamped its deadline against.
sim.staircase = true;
sim.minFee = BigInt(50_000);
sim.includeMs = 700_000;
const res = await submitWithConfirmation(
(fee) => submitFor('withdraw-large', fee),
BigInt(50_000),
'test tenure',
);
// The wallet gives up before the chain picks the tx up.
expect(res).toMatchObject({ ok: false, status: 'timeout', bumps: 3 });
expect(sim.terminal).toHaveLength(0);
expectFreshDeadlines();
// The chain does pick it up later - in the next tenure, whose burn time is
// 600s past every deadline the wallet stamped - and mines it as a deadline
// failure. The wallet never finds out: it already reported a timeout.
const last = sim.attempts[sim.attempts.length - 1];
vi.setSystemTime(last.includeAtMs);
expect(sim.poll(last.txId).tx_status).toBe('abort_by_response');
expect(sim.terminal).toHaveLength(1);
});
});
describe('what the fix still misses', () => {
it('a withdrawal slower than the deadline window is still mined as ERR_DEADLINE_PASSED', async () => {
// The chain includes the tx 150s after it is signed - longer than the 120s
// deadline window, so even a freshly stamped deadline has expired by the
// time the tx lands. The withdrawal fails, and the fee is burned.
sim.minFee = BigInt(50_000);
sim.includeMs = 150_000;
const res = await submitWithConfirmation(
(fee) => submitFor('withdraw-large', fee),
BigInt(50_000),
'test slow withdrawal',
);
expect(res.ok).toBe(false);
expect(res.status).toBe('abort_by_response');
expect(sim.terminal).toHaveLength(1);
// The deadline was fresh when it was signed; it still expired on chain.
const attempt = sim.attempts[0];
expect(attempt.deadline).toBe(Math.floor(attempt.signAtMs / 1000) + CONFIG.TX_DEADLINE_SECONDS);
expect(Math.floor(sim.chainNow() / 1000)).toBeGreaterThan(attempt.deadline);
expectFreshDeadlines();
});
it('the large withdrawal is not more likely to expire than the small one, as long as it lands in the same tenure', async () => {
// Control for the case above: same multi-bin call, same budget, but the
// chain includes it inside the current tenure. The deadline holds.
sim.staircase = true;
sim.minFee = BigInt(50_000);
sim.includeMs = 120_000;
const res = await submitWithConfirmation(
(fee) => submitFor('withdraw-large', fee),
BigInt(50_000),
'test same tenure',
);
expect(res.ok).toBe(true);
expect(sim.terminal).toHaveLength(1);
expect(sim.terminal[0]).toBe(sim.attempts[sim.attempts.length - 1].txId);
expectFreshDeadlines();
});
it('the first broadcast is not retried when the node rejects the transaction', async () => {
// Characterization of current behaviour. The node rejects the tx outright
// (a fee below the chain minimum for a call this size, or an invalid call):
// submitWithConfirmation only guards the *resubmit*, so the first failure
// propagates and the fee-bump machinery never engages.
sim.failBroadcastNumber = 1;
await expect(
submitWithConfirmation(
(fee) => submitFor('withdraw-large', fee),
BigInt(50_000),
'test rejected broadcast',
),
).rejects.toThrow(/broadcast failed/);
// No bump was attempted.
expect(sim.attempts).toHaveLength(0);
expect(sim.broadcastCount).toBe(1);
});
it('the fee cap is reported as a plain timeout when the bump budget runs out at the same time', async () => {
// Characterization of current behaviour: wallet.ts checks the bump budget
// before the fee cap, so a run that exhausts both reports 'timeout' and not
// 'timeout_max_fee' - the caller cannot tell "no more fee room" from
// "no more time".
Object.assign(CONFIG, { MAX_TX_FEE_USTX: 50_000, TX_MAX_FEE_BUMPS: 0 });
sim.minFee = BigInt(10_000_000);
const res = await submitWithConfirmation(
(fee) => submitFor('add-liquidity', fee),
BigInt(50_000),
'test cap precedence',
);
expect(res).toMatchObject({ ok: false, status: 'timeout', bumps: 0 });
expect(sim.attempts).toHaveLength(1);
expectFreshDeadlines();
});
it('the reported fee is the last bumped fee even when the original confirms', async () => {
// Characterization of current behaviour: SubmitResult.fee reports the fee of
// the last broadcast, not the fee the confirmed transaction paid.
sim.skewMs = -30_000;
sim.includeFirstAt = T0 + 100_000;
sim.failBroadcastNumber = 2;
const res = await submitWithConfirmation(
(fee) => submitFor('add-liquidity', fee),
BigInt(50_000),
'test reported fee',
);
expect(res.ok).toBe(true);
expect(res.fee).toBe(BigInt(75_000));
expect(sim.attempts[0].fee).toBe(BigInt(50_000));
});
});