Roadmap step 8 after inventory: wire createApp with LP wallets +
traded config/tokens, enrich GET / and /api/v1/status (seller, pairs,
postage; platformFeeEnabled false), and add read-only quote routes —
available, inventory, spot, amm discovery, exact-in/out templates, and
settleable ?from|to&feePct templates using local seller+slush CP
reserves. Maker fee on top of the price leg; open CORS; no broadcast.
Details
- Reviewers
Fabien - Group Reviewers
Restricted Project - Commits
- rABC70fb8baae5b1: [alp-dex] Add read-only quote HTTP API
- cd apps/alp-dex && pnpm test
- cd apps/alp-dex && pnpm run build
Diff Detail
- Repository
- rABC Bitcoin ABC
- Lint
Lint Not Applicable - Unit
Tests Not Applicable
Event Timeline
Build Bitcoin ABC Diffs / Diff Testing (ai-review) passed.
CodeRabbit Review
Diff : committed changes only
Compare : HEAD → master
Directory : work
────────────────────────────────────────
(\(\
(• .•) Find bugs once. Once a human tester finds a bug, it should be the last time a human tester finds that bug. Automatic tests should check for it from then on.
────────────────────────────────────────────────────────────────────────
major [Security & Privacy]
→ ]8;;vscode://file//work/apps/alp-dex/src/routes/quotes.ts:85apps/alp-dex/src/routes/quotes.ts:85-88]8;;
Replace message-regex error classification with typed errors.
isClientQuoteError decides the HTTP status from the error text. Two
risks follow from this.
1. Internal failures leak to clients as 400 with the raw message when the
text contains common words such as must be or Invalid. Example: a
chronik or wallet library error that says "Invalid response" becomes a 400
client error with the library message in the body.
2. A future rename of a validation message silently converts a 400 into a
500.
Throw a dedicated error type from the validation paths and classify on
that type instead.
♻️ Sketch of a typed-error approach
// src/methods/errors.ts
export class ClientError extends Error {}
// quotes.ts
-const isClientQuoteError = (message: string): boolean =>
- /positive|less than|must be|Invalid|not in traded|not a traded|exceeds|decimal|empty|n\/a|too small|CP reserves/i.test(
- message,
- );
+const isClientQuoteError = (error: unknown): boolean =>
+ error instanceof ClientError;
Then each catch block uses isClientQuoteError(error) and only echoes
error.message for ClientError.────────────────────────────────────────────────────────────────────────
minor [Functional Correctness]
→ ]8;;vscode://file//work/apps/alp-dex/src/routes/quotes.ts:65apps/alp-dex/src/routes/quotes.ts:65-76]8;;
Reject non-numeric and repeated feePct values explicitly.
parseFloat accepts trailing garbage. parseFloat('0.02abc') returns
0.02. Express also parses ?feePct=1&feePct=2 into an array, and
feePct as string then coerces to '1,2', which parseFloat reads as
1. Both inputs pass validation instead of failing.
The pair-fee comparison at Line 487 blocks most of these cases today, so
the impact is limited. A strict check keeps the contract clear.
🛡️ Proposed stricter parse
if (feePct === undefined) {
return { ok: false, error: "Must provide 'feePct' query parameter" };
}
- const parsed = parseFloat(feePct as string);
- if (Number.isNaN(parsed) || parsed < 0) {
+ if (typeof feePct !== 'string' || !/^\d+(\.\d+)?$/.test(feePct)) {
+ return { ok: false, error: 'feePct must be a number >= 0' };
+ }
+ const parsed = Number(feePct);
+ if (!Number.isFinite(parsed) || parsed < 0) {
return { ok: false, error: 'feePct must be a number >= 0' };
}────────────────────────────────────────────────────────────────────────
minor [Maintainability & Code Quality] → ]8;;vscode://file//work/apps/alp-dex/test/quotes.test.ts:224apps/alp-dex/test/quotes.test.ts:224-225]8;; Fix the derivation in the comment. The comment reads floor(1e101e7/20010000). The price leg is 10000 atoms, so the numerator is 1e4 1e7 = 1e11. 1e11 / 20010000 = 4997.5, which floors to the asserted 4997. The stated 1e10 does not produce that result. 📝 Proposed correction - // CP exact-in 10000 on 20M/10M → floor(1e10*1e7/20010000) = 4997 + // CP exact-in 10000 on 2e7/1e7 → floor(1e4*1e7/20010000) = 4997
────────────────────────────────────────
Review complete
3 findings ✔
Major 1
Minor 2
8 files reviewed:
- apps/alp-dex/README.md
- apps/alp-dex/SPEC.md
- apps/alp-dex/index.ts
- apps/alp-dex/src/app.ts
- apps/alp-dex/src/pricing/templates.ts
- apps/alp-dex/src/routes/quotes.ts
- apps/alp-dex/test/app.test.ts
- apps/alp-dex/test/quotes.test.ts
────────────────────────────────────────
Print all AI prompts: coderabbit review --show-prompts
Address CodeRabbit: typed ClientError for 400/500, strict feePct parse, fix test comment math. Also SPEC.md citations and exact string rates (drop roundTo6Decimals).
Build Bitcoin ABC Diffs / Diff Testing (ai-review) passed.
CodeRabbit Review
Diff : committed changes only
Compare : HEAD → master
Directory : work
────────────────────────────────────────
(\(\
(• .•) Optimism is an occupational hazard of programming; feedback is the treatment. - Kent Beck
────────────────────────────────────────────────────────────────────────
major [Stability & Availability]
→ ]8;;vscode://file//work/apps/alp-dex/src/routes/quotes.ts:148apps/alp-dex/src/routes/quotes.ts:148-150]8;;
Add a timeout and a short cache to the per-request LP sync.
Every quote route calls syncLp, so each unauthenticated HTTP request
triggers two Chronik round trips. The SPEC defers rate limiting to deploy
ops, so this endpoint set is currently open. Two consequences follow:
1. A caller can amplify one cheap HTTP request into two upstream Chronik
calls. A burst of requests saturates the Chronik client and the event
loop.
2. seller.sync() has no timeout. If Chronik stalls, the request never
completes and the connection is held open.
Add a deadline around the sync, and reuse a recent sync result within a
short TTL. Quote freshness of a few hundred milliseconds is acceptable
because settle revalidates the price leg against live reserves.
🛡️ Sketch: TTL cache plus deadline
const SYNC_TTL_MS = 2_000;
const SYNC_TIMEOUT_MS = 10_000;
let lastSyncMs = 0;
let inFlight: Promise<void> | null = null;
const withTimeout = async (p: Promise<unknown>): Promise<void> => {
let timer: NodeJS.Timeout;
const deadline = new Promise<never>((_, reject) => {
timer = setTimeout(
() => reject(new Error('Chronik sync timed out')),
SYNC_TIMEOUT_MS,
);
});
try {
await Promise.race([p, deadline]);
} finally {
clearTimeout(timer!);
}
};
const syncLp = async (seller: Wallet, slush: Wallet): Promise<void> => {
if (Date.now() - lastSyncMs < SYNC_TTL_MS) {
return;
}
if (inFlight === null) {
inFlight = withTimeout(
Promise.all([seller.sync(), slush.sync()]),
).finally(() => {
lastSyncMs = Date.now();
inFlight = null;
});
}
await inFlight;
};
Note that the cache and the in-flight de-duplication must live per router
instance, not in module scope, so tests that build several apps stay
isolated.────────────────────────────────────────────────────────────────────────
minor [Functional Correctness]
→ ]8;;vscode://file//work/apps/alp-dex/src/routes/quotes.ts:461apps/alp-dex/src/routes/quotes.ts:461-473]8;;
Treat an empty from or to value as invalid instead of absent.
The checks use truthiness. ?from=&to=1 passes, because the empty from
is falsy, and the request silently becomes an exact-out quote. The same
request with ?from=1&to= becomes exact-in. A client that builds the
query string from an empty input field then receives a quote for the wrong
direction.
Test the presence of each key rather than its truthiness.
🛡️ Proposed fix
- const { from, to, feePct } = req.query;
- if (!from && !to) {
+ const { from, to, feePct } = req.query;
+ const hasFrom = from !== undefined;
+ const hasTo = to !== undefined;
+ if (!hasFrom && !hasTo) {
res.status(400).json({
error: "Must provide either 'from' or 'to' query parameter",
});
return;
}
- if (from && to) {
+ if (hasFrom && hasTo) {
res.status(400).json({
error: "Cannot provide both 'from' and 'to' query parameters",
});
return;
}
The later branch at Line 507 must then switch on hasFrom instead of
from.────────────────────────────────────────
Review complete
2 findings ✔
Major 1
Minor 1
11 files reviewed:
- apps/alp-dex/README.md
- apps/alp-dex/SPEC.md
- apps/alp-dex/index.ts
- apps/alp-dex/src/app.ts
- apps/alp-dex/src/methods/errors.ts
- apps/alp-dex/src/pricing/cp.ts
- apps/alp-dex/src/pricing/templates.ts
- apps/alp-dex/src/routes/quotes.ts
- apps/alp-dex/test/app.test.ts
- apps/alp-dex/test/pricing.test.ts
... and 1 more file
────────────────────────────────────────
Print all AI prompts: coderabbit review --show-prompts
Address CodeRabbit: drop per-request Chronik sync from quote routes; reject empty from/to query keys as present.
Tail of the build log:
/work /work/abc-ci-builds/ai-review Build ai-review failed with exit code 1
Build Bitcoin ABC Diffs / Diff Testing (ai-review) passed.
CodeRabbit Review
Diff : committed changes only
Compare : HEAD → master
Directory : work
────────────────────────────────────────
(\(\
(• .•) Use tracer bullets to find the target. Tracer bullets let you home in on your target by trying things and seeing how close they land.
────────────────────────────────────────
Review complete
No findings ✔
11 files reviewed:
- apps/alp-dex/README.md
- apps/alp-dex/SPEC.md
- apps/alp-dex/index.ts
- apps/alp-dex/src/app.ts
- apps/alp-dex/src/methods/errors.ts
- apps/alp-dex/src/pricing/cp.ts
- apps/alp-dex/src/pricing/templates.ts
- apps/alp-dex/src/routes/quotes.ts
- apps/alp-dex/test/app.test.ts
- apps/alp-dex/test/pricing.test.ts
... and 1 more file
────────────────────────────────────────
| apps/alp-dex/src/app.ts | ||
|---|---|---|
| 36 ↗ | (On Diff #60849) | Why do you need this ? |
| 46–47 ↗ | (On Diff #60849) | |
| apps/alp-dex/src/methods/errors.ts | ||
| 31 ↗ | (On Diff #60849) | I'm not sure I understand the benefit of this class that adds nothing but a type ? |
| apps/alp-dex/src/pricing/templates.ts | ||
| 39 ↗ | (On Diff #60849) | |
| 106 ↗ | (On Diff #60849) | fee can't be 100% ? The range should be [0, 1) |
| apps/alp-dex/src/routes/quotes.ts | ||
| 64 ↗ | (On Diff #60849) | I don't think this works for all cases. You likely want to run some regex but also parse as number and check for zero after that. e.g. string "00" is zero but you won't catch it |
| 82 ↗ | (On Diff #60849) | You did it there, which is much better |
| 89 ↗ | (On Diff #60849) | Isn't it an epsilon constant for js ? |
| 103 ↗ | (On Diff #60849) | I see the ClientError... why don't you make it an HttpError and assign the error code directly instead? This would make the code much easier to read rather than obfuscating the return code behind a pseudo type. You can also have more fine grained codes and not only 2 |
| 149 ↗ | (On Diff #60849) | This would become useless if you get rid of ClientError |
| 158 ↗ | (On Diff #60849) | |
| 159–160 ↗ | (On Diff #60849) | Please stop documenting what the code doesn't do! |
Address Fabien review:
- Drop OPTIONS 204 short-circuit; trim createApp / createQuoteRouter JSDocs (no roadmap-step / negative Chronik docs)
- Rename ClientError → HttpError with status on the error
- feePct range [0, 1); reject qty "00" via Number(); FEE_PCT_EPS for pair match
- platformFee comment: drop roadmap step 11 cite
| apps/alp-dex/src/app.ts | ||
|---|---|---|
| 36 ↗ | (On Diff #60849) | not needed |
| apps/alp-dex/src/methods/errors.ts | ||
| 31 ↗ | (On Diff #60849) | modified so it has a code as well It is prob a bit overengineered for an undeployed server but the idea is client errors -- stuff like the client used an invalid param -- should be distinguishable from server errors |
| apps/alp-dex/src/pricing/templates.ts | ||
| 106 ↗ | (On Diff #60849) | Done. We could tighten further ... Realistically most swap platforms only get above 1% for extremely volatile pairs. But keeping it an open setting based on math limitations is fine. |
Build Bitcoin ABC Diffs / Diff Testing (ai-review) passed.
CodeRabbit Review
Diff : committed changes only
Compare : HEAD → master
Directory : work
────────────────────────────────────────
(\(\
(• .•) Don't use manual procedures. A shell script or batch file will execute the same instructions, in the same order, time after time.
────────────────────────────────────────────────────────────────────────
minor [Functional Correctness] → ]8;;vscode://file//work/apps/alp-dex/src/routes/quotes.ts:157apps/alp-dex/src/routes/quotes.ts:157-164]8;; Restrict the blanket 400 mapping to expected validation failures. quoteMath converts every thrown Error into `HttpError(400, error.message)`. Two consequences follow. A genuine server fault inside the pricing path returns 400, so clients treat a server bug as bad input and do not retry. The internal error.message is also copied into the response body, which contradicts the stated design in src/methods/errors.ts: "Unexpected failures stay plain Error / unknown → 500, no body leak". Consider a dedicated validation error type thrown by the pricing helpers, and let anything else fall through to sendQuoteError as a 500.
────────────────────────────────────────
Review complete
1 finding ✔
Minor 1
11 files reviewed:
- apps/alp-dex/README.md
- apps/alp-dex/SPEC.md
- apps/alp-dex/index.ts
- apps/alp-dex/src/app.ts
- apps/alp-dex/src/methods/errors.ts
- apps/alp-dex/src/pricing/cp.ts
- apps/alp-dex/src/pricing/templates.ts
- apps/alp-dex/src/routes/quotes.ts
- apps/alp-dex/test/app.test.ts
- apps/alp-dex/test/pricing.test.ts
... and 1 more file
────────────────────────────────────────
Print all AI prompts: coderabbit review --show-prompts
Address CodeRabbit: drop quoteMath blanket 400 wrap.
ValidationError extends HttpError(400); pricing/atoms/tokenId throw it
explicitly so unexpected Errors stay 500 without leaking messages.
Build Bitcoin ABC Diffs / Diff Testing (ai-review) passed.
CodeRabbit Review
Diff : committed changes only
Compare : HEAD → master
Directory : work
────────────────────────────────────────
(\(\
(• .•) Race conditions: you *caught* one. Unfortunately you released three.
────────────────────────────────────────────────────────────────────────
major [Functional Correctness] → ]8;;vscode://file//work/apps/alp-dex/src/pricing/templates.ts:98apps/alp-dex/src/pricing/templates.ts:98-124]8;; Preserve the requested exact-in total. priceLegAtoms + feeAtoms can be less than totalFromAtoms because both calculations floor. For example, 100 atoms at a 1% fee produces 99 price-leg atoms and 0 fee atoms. exactInTemplate states that qty is the total payment. Make the emitted outputs sum exactly to qty. Define and test the rounding policy for the remainder.
────────────────────────────────────────
Review complete
1 finding ✔
Major 1
16 files reviewed:
- apps/alp-dex/README.md
- apps/alp-dex/SPEC.md
- apps/alp-dex/index.ts
- apps/alp-dex/src/app.ts
- apps/alp-dex/src/config/tradedConfig.ts
- apps/alp-dex/src/methods/atoms.ts
- apps/alp-dex/src/methods/errors.ts
- apps/alp-dex/src/methods/tokenId.ts
- apps/alp-dex/src/pricing/cp.ts
- apps/alp-dex/src/pricing/quotes.ts
... and 6 more files
────────────────────────────────────────
Print all AI prompts: coderabbit review --show-prompts