Log every settle outcome (client IP, pair, qty, postage, failures). Optional Telegram HTML ops messages when telegram is in config.json.
Details
- Reviewers
Fabien - Group Reviewers
Restricted Project - Commits
- rABC5835ff2edacb: [alp-dex] Add settle logs and optional Telegram ops
- 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
────────────────────────────────────────
(\(\
(• .•) Your types are so loose they're in an open relationship.
────────────────────────────────────────────────────────────────────────
major [Security & Privacy] → ]8;;vscode://file//work/apps/alp-dex/schema.sql:10apps/alp-dex/schema.sql:10-18]8;; Define a retention policy for client_ip and taker_address. The table stores a client IP address and a taker address for every settle attempt, with no expiry. An IP address is personal data under GDPR and CCPA. The schema keeps these rows indefinitely, and idx_swaps_client_ip is absent but idx_swaps_taker_address makes per-user lookup easy. Decide the retention window and enforce it. Options: store a truncated or hashed IP, or add a scheduled delete on created_at. Document the choice in SPEC.md.
────────────────────────────────────────────────────────────────────────
minor [Data Integrity & Integration] → ]8;;vscode://file//work/apps/alp-dex/schema.sql:19apps/alp-dex/schema.sql:19]8;; Make created_at NOT NULL. created_at has a default but stays nullable. An explicit NULL in an insert produces an audit row with no timestamp, and idx_swaps_created_at then cannot order it. Every other audit column is NOT NULL. 🐛 Proposed fix - created_at TIMESTAMPTZ DEFAULT NOW(), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
────────────────────────────────────────────────────────────────────────
major [Stability & Availability] → ]8;;vscode://file//work/apps/alp-dex/scripts/slushToSizedSellerUtxos.ts:89apps/alp-dex/scripts/slushToSizedSellerUtxos.ts:89-99]8;; Cap the default batch at the ALP policy limit. When countArg is absent, numUnits can equal all maxUnits. alpSend() accepts up to 127 entries, but the current 223-byte OP_RETURN policy permits at most 29 outputs for one ALP section. Cap the omitted-count path at ALP_POLICY_MAX_OUTPUTS (29), and tell the operator to rerun for the remainder. Reject an explicit count above the limit instead of silently truncating it. Use a lower cap when the transaction contains additional eMPP sections.
────────────────────────────────────────────────────────────────────────
major [Functional Correctness] → ]8;;vscode://file//work/apps/alp-dex/scripts/_opsShared.ts:58apps/alp-dex/scripts/_opsShared.ts:58-75]8;; Do not add case normalization. Reject an invalid-only filter. assertTokenId already trims and lowercases valid mixed-case IDs. However, when all arguments are invalid, resolveTokenIdFilter returns null, which callers treat as no filter. Report invalid arguments and distinguish this case from an omitted filter.
────────────────────────────────────────────────────────────────────────
minor [Functional Correctness]
→ ]8;;vscode://file//work/apps/alp-dex/src/ops/telegramMessages.ts:147apps/alp-dex/src/ops/telegramMessages.ts:147-152]8;;
Derive the reported From amount from parsedSwap.atomsFrom.
Both builders reconstruct the sold amount as `outputs[0].atoms +
feeInFromAtoms. This depends on outputs[0]` being the slush leg of the
from-token. It also ignores platformFeeInFromAtoms, which is part of the
same field set on ParsedPartiallySignedSwap.
getInvalidSwapMessage and getSwapFailedMessage already use
parsedSwap.atomsFrom for the same line. Use atomsFrom here too. The
reported amount then stays correct if the output order changes or a
platform-fee output appears, and all four messages report one consistent
number.
🐛 Proposed fix (apply in both builders)
- const qtyTokenSoldToSlush = parsedSwap.outputs[0]?.atoms || 0n;
const qtyTokenSoldToFee = parsedSwap.feeInFromAtoms;
const qtyTokenBoughtToBuyer = parsedSwap.atomsTo;
const userAddress = extractUserAddress(parsedSwap);
- const totalFrom = qtyTokenSoldToSlush + qtyTokenSoldToFee;
+ const totalFrom = parsedSwap.atomsFrom;
Also applies to: 195-201────────────────────────────────────────────────────────────────────────
major [Security & Privacy]
→ ]8;;vscode://file//work/apps/alp-dex/src/routes/settle.ts:114apps/alp-dex/src/routes/settle.ts:114-132]8;;
client_ip is forgeable because the first x-forwarded-for hop is
trusted unconditionally.
clientIpFromRequest reads x-forwarded-for and returns the first hop
before it considers req.ip. Any client can set that header. The
persisted client_ip audit column then holds attacker-chosen data, so it
cannot support abuse investigation or rate-limit forensics.
Express already resolves this correctly through the trust proxy setting,
which createApp in src/app.ts does not configure. Set trust proxy to
the actual proxy topology, then read req.ip only.
🔒️ Proposed fix
In src/routes/settle.ts:
/**
- * Client IP: first `x-forwarded-for` hop, then Express `req.ip`.
+ * Client IP as resolved by Express. Requires `trust proxy` to match the
+ * real proxy topology; otherwise the value is the direct peer address.
*/
export const clientIpFromRequest = (req: Request): string => {
- const forwarded = req.headers['x-forwarded-for'];
- const raw =
- typeof forwarded === 'string'
- ? forwarded
- : Array.isArray(forwarded)
- ? forwarded[0]
- : undefined;
- if (raw !== undefined && raw.trim() !== '') {
- const first = raw.split(',')[0]!.trim();
- if (first !== '') {
- return first;
- }
- }
return req.ip ?? req.socket.remoteAddress ?? 'unknown';
};
In src/app.ts, set the hop count that matches the deployment:
// Number of reverse proxies in front of this app.
app.set('trust proxy', 1);
Note that test/settle.test.ts at Line 175 asserts `clientIp ===
'203.0.113.9' from a spoofable X-Forwarded-For` header. Update that test
together with the fix.────────────────────────────────────────────────────────────────────────
critical [Stability & Availability]
→ ]8;;vscode://file//work/apps/alp-dex/src/routes/settle.ts:573apps/alp-dex/src/routes/settle.ts:573-579]8;;
A throw inside recordOutcome turns a successful settle into a 500 and
duplicates the audit row.
recordOutcome is awaited at Line 573, inside the try block, and before
res.status(200).json(...). The function guards insertSwap with its own
try/catch, but the rest is unguarded:
- sendOps is typed as (message: string) => Promise. A non-async
implementation can throw synchronously. void sendOps(message).catch(...)
at Line 297 does not catch that throw.
- The message builders and tradedTokens.get calls can also throw on
unexpected data.
Any such throw rejects recordOutcome. Control moves to the catch at
Line 580, which calls recordOutcome a second time. The result is two
audit rows and an HTTP 500 with Failed to complete swap transaction,
even though the transaction was broadcast and txid is known. The taker
then sees a failure for a settled swap.
Move the success recording out of the try block, or wrap it so it cannot
reject.
🐛 Proposed fix
- await recordOutcome(true, true, 'success');
-
- res.status(200).json({
- success: true,
- txid,
- postagePaidSats: postagePaidSats.toString(),
- });
+ res.status(200).json({
+ success: true,
+ txid,
+ postagePaidSats: postagePaidSats.toString(),
+ });
+
+ // Audit + ops must never turn a broadcast swap into an error.
+ await recordOutcome(true, true, 'success').catch(
+ (recordError: unknown) => {
+ console.error(
+ 'Failed to record settle outcome:',
+ recordError,
+ );
+ },
+ );
Apply the same .catch guard to the three recordOutcome calls in the
catch block at Lines 585-594. A rejection there currently propagates out
of the handler and leaves the request without a response.────────────────────────────────────────────────────────────────────────
major [Security & Privacy] → ]8;;vscode://file//work/apps/alp-dex/src/ops/telegram.ts:11apps/alp-dex/src/ops/telegram.ts:11-31]8;; Add an application-level timeout to the Telegram request. If api.telegram.org stalls, each fire-and-forget call can remain pending and accumulate across settles. Pass signal: AbortSignal.timeout(10_000) when the app targets Node.js 16.14.0+ or 17.3.0+.
────────────────────────────────────────
Review complete
8 findings ✔
Critical 1
Major 5
Minor 2
27 files reviewed:
- apps/alp-dex/README.md
- apps/alp-dex/SPEC.md
- apps/alp-dex/config.sample.json
- apps/alp-dex/index.ts
- apps/alp-dex/package.json
- apps/alp-dex/schema.sql
- apps/alp-dex/scripts/_opsShared.ts
- apps/alp-dex/scripts/sellerXecToSlush.ts
- apps/alp-dex/scripts/slushToPostage.ts
- apps/alp-dex/scripts/slushToSizedSellerUtxos.ts
... and 17 more files
────────────────────────────────────────
Print all AI prompts: coderabbit review --show-prompts
Drop required Postgres: successful fills are on-chain; log client IP and failed settle events to stdout. Optional Telegram and ops scripts unchanged.
Build Bitcoin ABC Diffs / Diff Testing (ai-review) passed.
CodeRabbit Review
Diff : committed changes only
Compare : HEAD → master
Directory : work
────────────────────────────────────────
(\(\
(• .•) Veni, Vidi, Codici Fixi. I came, I saw, I fixed the code.
────────────────────────────────────────────────────────────────────────
minor [Functional Correctness] → ]8;;vscode://file//work/apps/alp-dex/scripts/slushToPostage.ts:47apps/alp-dex/scripts/slushToPostage.ts:47-57]8;; Reject partially numeric counts. parseInt accepts values such as 2abc and 2.9, then sends two UTXOs. Require a canonical positive safe integer before applying MAX_POSTAGE_UTXOS.
────────────────────────────────────────────────────────────────────────
minor [Functional Correctness] → ]8;;vscode://file//work/apps/alp-dex/scripts/_opsShared.ts:61apps/alp-dex/scripts/_opsShared.ts:61-74]8;; Reject invalid token filters. A non-empty invalid argument returns null. The summary commands then display every token instead of the requested token. Throw for each non-empty argument that is not a token ID.
────────────────────────────────────────────────────────────────────────
major [Stability & Availability] → ]8;;vscode://file//work/apps/alp-dex/scripts/slushToSizedSellerUtxos.ts:32apps/alp-dex/scripts/slushToSizedSellerUtxos.ts:32-42]8;; Bound numUnits before building inventory. parseInt accepts partial values. Number(maxUnits) can round bigint values above the safe-integer range. With no count, the script also forwards every fundable unit into one action. This can select the wrong count or build a transaction that cannot be constructed or broadcast. Require a bounded safe integer and batch remaining units. Also applies to: 89-105
────────────────────────────────────────────────────────────────────────
minor [Functional Correctness]
→ ]8;;vscode://file//work/apps/alp-dex/scripts/summarizeSellerWallet.ts:125apps/alp-dex/scripts/summarizeSellerWallet.ts:125-128]8;;
Label this as postage capacity.
This value counts postage stamps only. It does not account for exact-size
seller token UTXOs, which also limit settles. Rename Swap capacity to
Postage capacity.
Proposed fix
- console.log('Swap capacity:');
+ console.log('Postage capacity:');────────────────────────────────────────────────────────────────────────
minor [Functional Correctness]
→ ]8;;vscode://file//work/apps/alp-dex/scripts/_opsShared.ts:48apps/alp-dex/scripts/_opsShared.ts:48-50]8;;
Format sats with bigint arithmetic.
Number(sats) loses precision above Number.MAX_SAFE_INTEGER. This can
display an incorrect XEC balance in recovery commands. Split sats into
whole and fractional bigint parts instead.
Proposed fix
export const formatXec = (sats: bigint): string =>
- `${(Number(sats) / 100).toFixed(2)}`;
+ `${sats / 100n}.${(sats % 100n).toString().padStart(2, '0')}`;────────────────────────────────────────────────────────────────────────
major [Security & Privacy] → ]8;;vscode://file//work/apps/alp-dex/src/routes/settle.ts:194apps/alp-dex/src/routes/settle.ts:194-228]8;; Define a retention and redaction policy for clientIp plus takerAddress. Each audit line pairs a client IP address with an on-chain wallet address. Together these link a network identity to a persistent financial identity. Both are personal data under GDPR and CCPA. The record also runs for failed and invalid requests, so it captures probing traffic from users who never transacted. The code correctly logs only serializedTxHex.length and never the full transaction. Apply comparable care to the identity fields. Options: - Truncate or hash clientIp before logging. - Set a log retention window at the collector. - Document the lawful basis and retention period in SPEC.md.
────────────────────────────────────────────────────────────────────────
major [Security & Privacy]
→ ]8;;vscode://file//work/apps/alp-dex/src/ops/telegramMessages.ts:44apps/alp-dex/src/ops/telegramMessages.ts:44-45]8;;
Escape tokenId in the token explorer href.
previewToken interpolates tokenId into the href attribute with no
escaping. The label argument is escaped by tokenLabelHtml, but
tokenId is not.
An unvalidated tokenId reaches this function. In src/routes/settle.ts,
fromTokenId and toTokenId are initialized from req.params (lines
175-176) and are only replaced with canonical values after
assertConfiguredPair succeeds (lines 298-299). If assertConfiguredPair
throws for an unknown pair, recordOutcome runs with the raw path
segments and passes them to getSwapFailedMessage, which calls
tokenLabelHtml(fromTokenId, ...).
A path segment containing " or `
🔒️ Proposed fix
const previewToken = (tokenId: string, label: string): string =>
- `<a href="${ECASH_EXPLORER_BASE_URL}/token/${tokenId}">${label}</a>`;
+ `<a href="${ECASH_EXPLORER_BASE_URL}/token/${encodeURIComponent(tokenId)}">${label}</a>`;
An alternative fix is to call assertTokenId on the route params before
recordOutcome can observe them.────────────────────────────────────────────────────────────────────────
major [Stability & Availability] → ]8;;vscode://file//work/apps/alp-dex/src/ops/telegram.ts:16apps/alp-dex/src/ops/telegram.ts:16-24]8;; Bound the Telegram request duration. Node’s fetch has no overall timeout. Add `signal: AbortSignal.timeout(10_000)` to prevent stalled requests from remaining pending for an extended period. Catch the resulting rejection if sendOps remains fire-and-forget.
────────────────────────────────────────────────────────────────────────
major [Security & Privacy] → ]8;;vscode://file//work/apps/alp-dex/src/routes/settle.ts:109apps/alp-dex/src/routes/settle.ts:109-127]8;; Use Express’s resolved client IP for audit records. clientIpFromRequest trusts the first X-Forwarded-For entry before checking req.ip. Unless the ingress proxy sanitizes this header, callers can control the recorded clientIp and bypass Express’s right-to-left proxy trust evaluation. Return `req.ip ?? req.socket.remoteAddress ?? 'unknown', configure trust proxy` for the deployment topology, and update forwarded-IP tests accordingly.
────────────────────────────────────────────────────────────────────────
major [Security & Privacy] → ]8;;vscode://file//work/apps/alp-dex/SPEC.md:229apps/alp-dex/SPEC.md:229-230]8;; Use a trusted proxy boundary for the client IP. When alp-dex accepts direct traffic, record the connection peer and ignore x-forwarded-for. When a reverse proxy is used, trust only its explicit addresses before deriving the first untrusted client address. A direct client can forge x-forwarded-for, which makes the audit client IP unreliable.
────────────────────────────────────────
Review complete
10 findings ✔
Major 6
Minor 4
21 files reviewed:
- apps/alp-dex/README.md
- apps/alp-dex/SPEC.md
- apps/alp-dex/index.ts
- apps/alp-dex/package.json
- apps/alp-dex/scripts/_opsShared.ts
- apps/alp-dex/scripts/sellerXecToSlush.ts
- apps/alp-dex/scripts/slushToPostage.ts
- apps/alp-dex/scripts/slushToSizedSellerUtxos.ts
- apps/alp-dex/scripts/summarizeSellerWallet.ts
- apps/alp-dex/scripts/summarizeSlushWallet.ts
... and 11 more files
────────────────────────────────────────
Print all AI prompts: coderabbit review --show-prompts
Drop unused Postgres/platform-fee audit docs; describe ops scripts and always-on settle logs.
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/scripts/slushToPostage.ts:47apps/alp-dex/scripts/slushToPostage.ts:47-57]8;;
Reject partially parsed counts.
parseInt accepts values such as 2.5, 5abc, and 1e3. The script
then creates a different number of postage UTXOs than the operator
supplied.
Validate the complete argument and require a safe positive integer before
broadcasting.
Proposed fix
const countArg = process.argv[2];
- const requestedCount =
- countArg !== undefined ? parseInt(countArg, 10) : null;
- if (
- requestedCount !== null &&
- (Number.isNaN(requestedCount) || requestedCount <= 0)
- ) {
- throw new Error(
- `Invalid count: ${countArg}. Must be a positive integer`,
- );
- }
+ const requestedCount = countArg === undefined ? null : Number(countArg);
+ if (
+ requestedCount !== null &&
+ (!Number.isSafeInteger(requestedCount) || requestedCount <= 0)
+ ) {
+ throw new Error(
+ `Invalid count: ${countArg}. Must be a positive integer`,
+ );
+ }────────────────────────────────────────────────────────────────────────
minor [Functional Correctness]
→ ]8;;vscode://file//work/apps/alp-dex/scripts/slushToSizedSellerUtxos.ts:32apps/alp-dex/scripts/slushToSizedSellerUtxos.ts:32-42]8;;
Reject partially parsed counts.
parseInt accepts values such as 2.5, 5abc, and 1e3. The script can
therefore create a different number of seller inventory UTXOs than the
operator requested.
Validate the complete argument and require a safe positive integer before
broadcasting.
Proposed fix
const tokenId = parseCliTokenId(argv[0]);
const countArg = argv[1];
- const requestedCount =
- countArg !== undefined ? parseInt(countArg, 10) : null;
- if (
- requestedCount !== null &&
- (Number.isNaN(requestedCount) || requestedCount <= 0)
- ) {
+ const requestedCount = countArg === undefined ? null : Number(countArg);
+ if (
+ requestedCount !== null &&
+ (!Number.isSafeInteger(requestedCount) || requestedCount <= 0)
+ ) {
throw new Error(
`Invalid count: ${countArg}. Must be a positive integer`,
);────────────────────────────────────────────────────────────────────────
minor [Functional Correctness]
→ ]8;;vscode://file//work/apps/alp-dex/src/routes/settle.ts:375apps/alp-dex/src/routes/settle.ts:375-381]8;;
Remove the duplicate currentRate assignment.
Line 380 sets currentRate before the queue, and Line 410 computes the
same expression from the same inputs inside the queue. swap.atomsTo and
priceLegAtoms do not change between the two statements. Keep one
assignment. Line 380 also guards priceLegAtoms > 0n, and Line 410 does
not, so Line 410 can write Infinity or NaN into currentRate and into
the audit record.
♻️ Proposed change
const quote = quoteExactIn(priceLegAtoms, reserves, feePct);
const expectedToAtoms = quote.amountOut;
- currentRate = Number(swap.atomsTo) / Number(priceLegAtoms);
Also applies to: 408-411────────────────────────────────────────────────────────────────────────
major [Stability & Availability]
→ ]8;;vscode://file//work/apps/alp-dex/src/ops/telegram.ts:11apps/alp-dex/src/ops/telegram.ts:11-31]8;;
Add a timeout to the Telegram request.
fetch has no default timeout in Node. If api.telegram.org stalls, this
promise stays pending and holds the request body and socket for the
process lifetime. Callers use fire-and-forget, so nothing else bounds the
call.
Use AbortSignal.timeout to bound the call.
⏱️ Proposed fix
export const sendTelegramOps = async (
telegram: TelegramConfig,
html: string,
+ timeoutMs = 10_000,
): Promise<void> => {
const url = `https://api.telegram.org/bot${telegram.botToken}/sendMessage`;
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
chat_id: telegram.opsChat,
text: html,
parse_mode: 'HTML',
}),
+ signal: AbortSignal.timeout(timeoutMs),
});────────────────────────────────────────
Review complete
4 findings ✔
Major 1
Minor 3
21 files reviewed:
- apps/alp-dex/README.md
- apps/alp-dex/SPEC.md
- apps/alp-dex/index.ts
- apps/alp-dex/package.json
- apps/alp-dex/scripts/_opsShared.ts
- apps/alp-dex/scripts/sellerXecToSlush.ts
- apps/alp-dex/scripts/slushToPostage.ts
- apps/alp-dex/scripts/slushToSizedSellerUtxos.ts
- apps/alp-dex/scripts/summarizeSellerWallet.ts
- apps/alp-dex/scripts/summarizeSlushWallet.ts
... and 11 more files
────────────────────────────────────────
Print all AI prompts: coderabbit review --show-prompts
Drop ops CLIs; maintainInventory already balances slush and mints postage. Diff is settle logs + optional Telegram.
Build Bitcoin ABC Diffs / Diff Testing (ai-review) passed.
CodeRabbit Review
Diff : committed changes only
Compare : HEAD → master
Directory : work
────────────────────────────────────────
(\(\
(• .•) 99 little bugs in the code... I filed 100.
────────────────────────────────────────────────────────────────────────
minor [Maintainability & Code Quality] → ]8;;vscode://file//work/apps/alp-dex/README.md:22apps/alp-dex/README.md:22-29]8;; Correct the stream claim for failed settles. logSwapOutcome writes invalid, broadcast-failed, and failed records with console.error, so they go to stderr, not stdout. Operators who capture only stdout lose every failure line. SPEC.md Line 224 states the same claim. 📝 Proposed doc fix -Every settle (`200` / `400` / `500`) writes a stdout line: client IP, pair, -taker, qty, postage, rate, txid, and the error on failures. +Every settle (`200` / `400` / `500`) writes a structured log line: client IP, +pair, taker, qty, postage, rate, txid, and the error on failures. Successes go +to stdout; failures go to stderr.
────────────────────────────────────────────────────────────────────────
minor [Functional Correctness]
→ ]8;;vscode://file//work/apps/alp-dex/src/routes/settle.ts:408apps/alp-dex/src/routes/settle.ts:408-410]8;;
Remove the unguarded currentRate recompute.
Line 380 assigns currentRate only when priceLegAtoms > 0n. Line 410
repeats the division without that guard. If priceLegAtoms is 0n, the
division yields Infinity or NaN. That value then reaches the audit
record serverExchangeRate and the Telegram rate line through
toFixed(6), which renders Infinity or NaN. The value is also
identical to Line 380 when the guard passes, so the recompute adds no
information.
🐛 Proposed fix
const quote = quoteExactIn(priceLegAtoms, reserves, feePct);
const expectedToAtoms = quote.amountOut;
- currentRate = Number(swap.atomsTo) / Number(priceLegAtoms);────────────────────────────────────────────────────────────────────────
minor [Security & Privacy]
→ ]8;;vscode://file//work/apps/alp-dex/src/routes/settle.ts:112apps/alp-dex/src/routes/settle.ts:112-127]8;;
Do not trust x-forwarded-for unconditionally.
Any client can set x-forwarded-for. The audit record clientIp
therefore accepts an attacker-supplied value, even when the node runs
without a reverse proxy. This weakens the log for abuse triage.
Configure Express trust proxy in createApp for the deployment
topology, then read req.ip only. Express then resolves the correct hop
and ignores forged hops from untrusted peers.
🔒 Proposed direction
export const clientIpFromRequest = (req: Request): string => {
- const forwarded = req.headers['x-forwarded-for'];
- const raw =
- typeof forwarded === 'string'
- ? forwarded
- : Array.isArray(forwarded)
- ? forwarded[0]
- : undefined;
- if (raw !== undefined && raw.trim() !== '') {
- const first = raw.split(',')[0]!.trim();
- if (first !== '') {
- return first;
- }
- }
return req.ip ?? req.socket.remoteAddress ?? 'unknown';
};
createApp then needs app.set('trust proxy', ) for the nginx deployment
described in the roadmap.────────────────────────────────────────────────────────────────────────
major [Stability & Availability] → ]8;;vscode://file//work/apps/alp-dex/src/ops/telegram.ts:11apps/alp-dex/src/ops/telegram.ts:11-31]8;; Add an application-level timeout to the Telegram request. The settle route starts sendOps without awaiting it. During a Telegram outage, repeated settles can accumulate pending requests. Use AbortSignal.timeout(timeoutMs) with a 10-second default. Node >=20 supports both global fetch and AbortSignal.timeout. Preserve the existing error propagation for the caller's catch.
────────────────────────────────────────
Review complete
4 findings ✔
Major 1
Minor 3
13 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/ops/telegram.ts
- apps/alp-dex/src/ops/telegramMessages.ts
- apps/alp-dex/src/routes/settle.ts
- apps/alp-dex/src/settle/audit.ts
- apps/alp-dex/test/audit.test.ts
... and 3 more files
────────────────────────────────────────
Print all AI prompts: coderabbit review --show-prompts
Trust Express req.ip, Telegram fetch timeout, settle log cannot fail a broadcast 200; retitle/summary to logs + optional Telegram only.
Build Bitcoin ABC Diffs / Diff Testing (ai-review) passed.
CodeRabbit Review
Diff : committed changes only
Compare : HEAD → master
Directory : work
────────────────────────────────────────
(\(\
(• .•) Iterate the schedule with the code. Use experience you gain as you implement to refine the project time scales.
────────────────────────────────────────────────────────────────────────
minor [Functional Correctness]
→ ]8;;vscode://file//work/apps/alp-dex/src/routes/settle.ts:362apps/alp-dex/src/routes/settle.ts:362-368]8;;
Convert the rate to human units before display and audit.
Lines 366-368 compute currentRate as an atoms ratio. formatRateLine
prints it as "1 === rate " with human token labels, and
SwapRecord.serverExchangeRate stores the same value. If fromDecimals
differs from toDecimals, the printed and logged rate is wrong by
10^(fromDecimals-toDecimals). Both test tokens use 4 decimals, so the
current tests do not detect this.
Keep the atoms ratio for validatePartiallySignedTx and derive a separate
display rate.
🐛 Proposed fix
if (priceLegAtoms > 0n) {
currentRate = Number(swap.atomsTo) / Number(priceLegAtoms);
}
+ // Display/audit rate in human units: the atoms ratio is only
+ // comparable when both tokens share the same decimals.
+ const fromDec = tradedTokens.get(fromTokenId)?.decimals ?? 0;
+ const toDec = tradedTokens.get(toTokenId)?.decimals ?? 0;
+ displayRate = currentRate * 10 ** (fromDec - toDec);
Then pass displayRate to getSwapSuccessfulMessage,
getInvalidSwapMessage, and SwapRecord.serverExchangeRate.
Also applies to: 203-203, 222-231────────────────────────────────────────────────────────────────────────
minor [Functional Correctness]
→ ]8;;vscode://file//work/apps/alp-dex/src/routes/settle.ts:232apps/alp-dex/src/routes/settle.ts:232-264]8;;
Send an ops message when parsedSwap is undefined.
If validation fails before parsePartiallySignedSwap runs (missing
serializedTxHex, bad hex, tokenId mismatch), message stays undefined
and no Telegram message is sent. SPEC.md line 227 states that ops messages
fire after the log for every settle. getSwapFailedMessage already
accepts parsedSwap: null, so the fallback is available.
♻️ Proposed change
- } else if (outcome === 'failed') {
+ } else {
message = getSwapFailedMessage({
parsedSwap: parsedSwap ?? null,
errorMsg: errorMsg ?? 'Unknown error',
Guard the success branch so a success without parsedSwap does not fall
through to the failure text.────────────────────────────────────────
Review complete
2 findings ✔
Minor 2
13 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/ops/telegram.ts
- apps/alp-dex/src/ops/telegramMessages.ts
- apps/alp-dex/src/routes/settle.ts
- apps/alp-dex/src/settle/audit.ts
- apps/alp-dex/test/audit.test.ts
... and 3 more files
────────────────────────────────────────
Print all AI prompts: coderabbit review --show-prompts
Build Bitcoin ABC Diffs / Diff Testing (ai-review) passed.
CodeRabbit Review
Diff : committed changes only
Compare : HEAD → master
Directory : work
────────────────────────────────────────
(\(\
(• .•) There is nothing quite so useless as doing with great efficiency something that should not be done at all. - Peter Drucker
────────────────────────────────────────────────────────────────────────
major [Security & Privacy]
→ ]8;;vscode://file//work/apps/alp-dex/src/ops/telegramMessages.ts:13apps/alp-dex/src/ops/telegramMessages.ts:13-14]8;;
Escape quotes and encode URL path segments.
escapeHtml does not escape ". The three preview helpers interpolate
values directly into href="...".
One of these values is attacker-controlled. In settle.ts lines 166-167,
fromTokenId and toTokenId start as raw req.params values. If
assertConfiguredPair throws at line 283, the reassignment at line 289
never runs, and recordOutcome passes the raw path segments to
getSwapFailedMessage (line 261). A request to
/api/v1/swap/aa"target/bb then closes the attribute and injects
attributes into the anchor.
Telegram HTML supports ``. The result is either an attacker-chosen link in
the operator ops chat or a rejected sendMessage call that drops the
alert.
Escape " in escapeHtml and encode the URL segment separately from the
label.
🔒 Proposed fix
const escapeHtml = (s: string): string =>
- s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
+ s
+ .replace(/&/g, '&')
+ .replace(/</g, '<')
+ .replace(/>/g, '>')
+ .replace(/"/g, '"');
+
+const explorerHref = (kind: string, value: string): string =>
+ `${ECASH_EXPLORER_BASE_URL}/${kind}/${encodeURIComponent(value)}`;
const previewAddress = (address: string): string =>
- `<a href="${ECASH_EXPLORER_BASE_URL}/address/${escapeHtml(address)}">${escapeHtml(previewAddressLabel(address))}</a>`;
+ `<a href="${explorerHref('address', address)}">${escapeHtml(previewAddressLabel(address))}</a>`;
const previewTxid = (txid: string, label: string): string =>
- `<a href="${ECASH_EXPLORER_BASE_URL}/tx/${escapeHtml(txid)}">${escapeHtml(label)}</a>`;
+ `<a href="${explorerHref('tx', txid)}">${escapeHtml(label)}</a>`;
const previewToken = (tokenId: string, label: string): string =>
- `<a href="${ECASH_EXPLORER_BASE_URL}/token/${escapeHtml(tokenId)}">${label}</a>`;
+ `<a href="${explorerHref('token', tokenId)}">${label}</a>`;
Also applies to: 38-45────────────────────────────────────────
Review complete
1 finding ✔
Major 1
13 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/ops/telegram.ts
- apps/alp-dex/src/ops/telegramMessages.ts
- apps/alp-dex/src/routes/settle.ts
- apps/alp-dex/src/settle/audit.ts
- apps/alp-dex/test/audit.test.ts
... and 3 more files
────────────────────────────────────────
Print all AI prompts: coderabbit review --show-prompts
In general telegram escape chars is a valid point but in this server tokenId will always be a 64-char hex string.
I debated having an optional db here but imo just logging with optional tg msg is enough for ops support, and db tracking, in addition to being out of the ethos for DeFi, is overkill for a system w here every tx is recorded onchain.
AI accident that it didn't use grammy. I think because this diff initially used a database, then I decided that was overkill. For the "only use tg notifications", cursor just did this API method since the app only uses a simple send.
If it doesn't want to use the dep ... eh, ok I guess. One less dep. It would be easy to implement with AI if and when some new method needs it.
Though grammy is the monorepo standard, already maintained, and certainly more extensible. So I can see both sides.
grammy is a better option mostly because it is maintained so it will follow any API change and we don't have to support this on our end. Since it's already everywhere in the repo I don't consider it's a big win to drop the dependency
Build Bitcoin ABC Diffs / Diff Testing (ai-review) passed.
CodeRabbit Review
Diff : committed changes only
Compare : HEAD → master
Directory : work
────────────────────────────────────────
(\(\
(• .•) Never ask an AI its Energy Star rating.
────────────────────────────────────────────────────────────────────────
major [Stability & Availability]
→ ]8;;vscode://file//work/apps/alp-dex/src/routes/settle.ts:272apps/alp-dex/src/routes/settle.ts:272-279]8;;
Throttle ops messages for failed settles.
POST /api/v1/swap/:from/:to is unauthenticated and has no rate limit.
Every rejected request reaches recordOutcome, and every outcome triggers
one sendOps call. A client that loops malformed bodies generates one
Telegram sendMessage per request. The result is Telegram 429 responses,
a flooded ops chat that hides real alerts, and unbounded concurrent
outbound fetches from the request path.
Bound the failure notifications. Send ops messages for success and
server-side failures only, or add a per-interval cap for validation
failures.
♻️ Example cap for validation-failure ops messages
+// Module scope: cap ops messages for client-triggered validation failures.
+const OPS_INVALID_WINDOW_MS = 60_000;
+const OPS_INVALID_MAX_PER_WINDOW = 5;
+let opsInvalidWindowStart = 0;
+let opsInvalidSent = 0;
+const allowInvalidOps = (): boolean => {
+ const now = Date.now();
+ if (now - opsInvalidWindowStart > OPS_INVALID_WINDOW_MS) {
+ opsInvalidWindowStart = now;
+ opsInvalidSent = 0;
+ }
+ opsInvalidSent += 1;
+ return opsInvalidSent <= OPS_INVALID_MAX_PER_WINDOW;
+};
- if (message !== undefined) {
+ if (outcome === 'invalid' && !allowInvalidOps()) {
+ return;
+ }
+ if (message !== undefined) {
void sendOps(message).catch((tgError: unknown) => {
Also applies to: 569-589────────────────────────────────────────
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/package.json
- apps/alp-dex/src/app.ts
- apps/alp-dex/src/config/tradedConfig.ts
- apps/alp-dex/src/ops/telegram.ts
- apps/alp-dex/src/ops/telegramMessages.ts
- apps/alp-dex/src/routes/settle.ts
- apps/alp-dex/src/settle/audit.ts
... and 6 more files
────────────────────────────────────────
Print all AI prompts: coderabbit review --show-prompts
Serialize Telegram ops on a FIFO queue; honor 429 retry_after with backoff instead of dropping invalid-settle alerts.
Tail of the build log:
/work /work/abc-ci-builds/ai-review Connecting to CodeRabbit... 0s elapsed ✗ Review error Review failed: Unknown error Build ai-review failed with exit code 1
Tail of the build log:
/work /work/abc-ci-builds/ai-review Connecting to CodeRabbit... 0s elapsed ✗ Review error Review failed: Failed to start review. Please try again. Build ai-review failed with exit code 1