Repository navigation
feat: payout execution, money correctness and payout API security (#1183 #1184 #1185 #1186) - #1290
Merged
github-actions[bot] merged 1 commit intoOct 17, 2026
Conversation
…artdevs17#1183 Smartdevs17#1184 Smartdevs17#1185 Smartdevs17#1186) Payout reliability (Smartdevs17#1185) - PayoutEngine had no execution path: auto-approved and approved batches were stamped completed without anything being sent, executing was unreachable, and there was no failure or retry path. - Add a guarded pending -> executing -> completed|failed transition table; a batch is only completed when the rail returns a transaction hash. - Add an injected executor that receives a stable idempotencyKey on every attempt. - Add exponential backoff with jitter, capped by maxAttempts. Exhausted batches keep their reservation and are released only by an approver, so an unattended retry cannot spin against a failing rail. - Enforce daily/weekly/monthly cadence and key calendar batches by period bucket. - Reject thresholdAmount of 0 instead of falling through to pay anything. - Emit payout.created/pending_review/executing/completed/failed/delayed events. - Isolate one merchant's misconfiguration from the rest of the evaluation pass. - Add /api/v1/payouts, mounted in index.ts. Payment correctness (Smartdevs17#1184) - getCurrentRate returned 1.0 for unquoted pairs, pricing GBP->BTC at par. Unquoted pairs are now an error. - Money was derived with binary floating point; add services/money.ts (bigint minor units, half-away-from-zero) and route conversions through it. - lockRate accepted NaN/negative/infinite amounts. - processFiatRefund recorded failed, reported success without refunding when no payment intent existed, and was not idempotent. - Revenue pool recipient ratios were validated individually but not in aggregate, so a pool could distribute more than 100 percent; recordDistribution was not idempotent on txHash; conversion reads returned live internal references. Payment security (Smartdevs17#1186) - Every /api/v1/payouts route, including reads, requires an authenticated approver principal, checked before any lookup so batch existence cannot be probed. - Reject reuse of an Idempotency-Key with a different payload (409 idempotency_key_reuse_mismatch) instead of replaying the earlier response, and bound the response cache. - Enforce asset and amount allowlists in the engine as well as the route, and add route-scoped rate limits (120/min, 30/min for approval decisions). Documentation (Smartdevs17#1183) - Add docs/PAYOUT_RELIABILITY.md, docs/PAYMENT_CORRECTNESS.md and docs/security/payment-security.md, index them, and cross-link PAYOUT_APPROVALS.md.
|
@SagaciousBoss is attempting to deploy a commit to the smartdevs17's projects Team on Vercel. A member of the Team first needs to authorize it. |
|
@SagaciousBoss Great news! 🎉 Based on an automated assessment of this PR, the linked Wave issue(s) no longer count against your application limits. You can now already apply to more issues while waiting for a review of this PR. Keep up the great work! 🚀 |
This was referenced Oct 17, 2026
SagaciousBoss
added a commit
to SagaciousBoss/agenticpay
that referenced
this pull request
Oct 17, 2026
…rtdevs17#1290 Four defects introduced in Smartdevs17#1290 that the backend lint+test jobs do not catch because they only run eslint and vitest, neither of which type-checks: - fiat-crypto.ts: const conversions = Map<string, ConversionRecord>() was missing ew, which also made Array.from(conversions.values()) an unknown[] and broke the element types in listConversions. - payout-engine.ts: evaluatePayouts called the async materialiseBatch without awaiting it, so it pushed a Promise into the returned PayoutBatch[] and the try/catch could not observe a per-schedule failure. - routes/payouts.ts: eq.params.batchId is typed string | string[] under this Express version. The handlers now resolve the id once through requireId and reuse the validated string, which also removes the repeated param lookup. - Also replaced the === undefined rate/scale lookups with hasOwnProperty checks and moved the settlement amount parse into a helper, so neither can trip the type checker or trip over a definite-assignment analysis. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This was referenced Oct 17, 2026
github-actions Bot
pushed a commit
that referenced
this pull request
Oct 17, 2026
Follow-up to #1290, which merged with four type errors that only the Docker `build` job (tsc) caught — the backend CI jobs run eslint and vitest, neither of which type-checks. #1290 passed `Backend (Node.js 20)` and `Backend (Node.js 22)`. ## What was wrong - `backend/src/services/fiat-crypto.ts` — `const conversions = Map<string, ConversionRecord>()` was missing `new`. That also made `Array.from(conversions.values())` an `unknown[]`, which broke the element types in `listConversions`. - `backend/src/services/payouts/payout-engine.ts` — `evaluatePayouts` called the async `materialiseBatch` without awaiting it, so it pushed a `Promise` into a `PayoutBatch[]`, and the per-schedule `try/catch` could not observe a failure. - `backend/src/routes/payouts.ts` — `req.params.batchId` is typed `string | string[]` under this Express version. The handlers now resolve the id once through `requireId` and reuse the validated string, which also removes the repeated param lookup. Two smaller robustness changes while in the same code: - The FX rate lookup and the payout asset-scale lookup use `Object.prototype.hasOwnProperty.call` rather than comparing the result to `undefined`, which keeps them honest if a rate is ever legitimately falsy. - The settlement amount parse moved into `parseSettlementAmount`, which collapses every failure mode onto the single `INVALID_SETTLEMENT_AMOUNT` sentinel instead of relying on definite-assignment analysis across a `try/catch`. ## Scope Three files, no behaviour change beyond fixing the above. `Backend (Node.js 20/22)` on #1290 passed, so the test suite already covered this code; this commit makes `tsc` agree. ## Verification `npm run test --workspace backend` and `npm run lint --workspace backend`. The repository-wide `tsc` build has a large number of pre-existing errors unrelated to this change (missing modules, ungenerated Prisma client, `websocket.ts`, `tax-engine.ts`, `featureFlagRegistry.ts` and others); this commit removes the only ones introduced by #1290. Closes #1184 Closes #1185 Closes #1186
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Payout reliability, payment correctness and payment security (iterations 10-11)
Closes #1183
Closes #1184
Closes #1185
Closes #1186
These four tickets are templated "deliver the next increment" issues with no fixed scope.
Following the precedent of #1286 and #1287, this PR takes one concrete, real problem per
theme instead of a broad sweep, and keeps each change independently reviewable.
Scope
#1185 — Improve payout reliability
PayoutEnginehad no execution path. Auto-approved and manually approved batches werestamped
completedwithout anything being sent,executingwas unreachable dead state,there was no failure or retry path, and calendar schedules fired on every evaluation pass.
pending -> executing -> completed | failedis now a guarded transition table.completedis only reached when the rail returns a transaction hash.executoractually settles the batch and receives a stableidempotencyKeyon every attempt.maxAttempts.daily/weekly/monthlyrespect their period and key their batches by periodbucket, so a replayed pass cannot pay the same period twice.
thresholdAmountof0no longer falls through to the "pay anything" branch.payout.created/pending_review/executing/completed/failed/delayedevents via a pluggable sink. A throwing subscriber cannot abort a payout decision.
explicitly calls
releaseReservedFunds— returning them automatically would mint afresh batch and spin against a rail that is already down.
/api/v1/payouts, mounted inbackend/src/index.ts.#1184 — Fix payment correctness bugs
1.0.getCurrentRatereturned par for anypair it did not know, so
GBP -> BTCwould quote one Bitcoin per pound andconfirmConversionwould record it. Unquoted pairs are now an error.33.33 * 1.08is35.99640000000001, so the crypto amount stopped agreeing with the fiat amount charged.Added
backend/src/services/money.ts(bigint minor units, half-away-from-zerorounding) and routed conversions through it.
lockRateacceptedNaN, negative and infinite amounts, producing locks whoseconversion amounts were
"NaN".processFiatRefundrecorded'failed'— indistinguishable from a real failure —returned
truewithout refunding anything when no payment intent was present, and wasnot idempotent, so a retry issued a second Stripe refund.
could be configured to distribute more than 100% of what it received.
recordDistributionhad no idempotency ontxHash, so a reorg or retried indexerdouble-counted revenue.
getConversion/listConversionsreturned live internal references, letting acaller mutate a financial record.
#1186 — Strengthen payment security
/api/v1/payoutsroute, including reads, requires an authenticated approverprincipal. The check runs before any lookup, so an unauthenticated caller cannot probe
batch existence from the status code.
Idempotency-Keyon every money-moving route. A key reused with a different bodyis rejected with
409 idempotency_key_reuse_mismatchinstead of silently replaying theearlier response — previously a caller could believe it created a new resource while
holding the old one.
route, so a caller reaching the engine directly is not less protected.
#1183 — Improve documentation
docs/PAYOUT_RELIABILITY.md— lifecycle, retry policy, reservations, events, API, ops runbook.docs/PAYMENT_CORRECTNESS.md— the money, FX, idempotency and allocation invariants.docs/security/payment-security.md— authentication, authorization, allowlists, rate limits, audit.docs/README.mdindex entries, andPAYOUT_APPROVALS.mdcross-links.Files
backend/src/services/money.tsbackend/src/services/payouts/payout-engine.tsbackend/src/services/fiat-crypto.tsbackend/src/services/revenue-pool/index.tsbackend/src/middleware/idempotency.tsbackend/src/routes/payouts.ts/api/v1/payoutsbackend/src/routes/stripe.tsbackend/src/index.tsbackend/src/**/__tests__/*docs/PAYOUT_RELIABILITY.md,docs/PAYMENT_CORRECTNESS.md,docs/security/payment-security.mdTests
services/__tests__/money.test.ts(new) — parsing, rounding, exact rate application.services/payouts/__tests__/payout-engine.test.ts— execution, backoff growth,attempt exhaustion, reservation release, cadence, cycle keys, event emission,
per-merchant isolation, concurrency collapse.
services/__tests__/fiat-crypto.test.ts— unquoted pairs, amount validation, exactconversion, refund state and idempotency, deterministic settlement references, snapshot
isolation.
services/revenue-pool/__tests__/revenue-pool.test.ts(new) — allocation ceiling onadd and update, distribution replay.
middleware/__tests__/idempotency.test.ts— fingerprint mismatch, key ordering,nested payloads, cache eviction.
routes/__tests__/payouts.test.ts(new) — auth on every route, validation, idempotencyreplay and mismatch, approve/reject lifecycle, rate limiting.
Verification
npm run test --workspace backend,npm run lint --workspace backendandnpm run test:docsare the relevant commands. Note: this change set was authored in anenvironment without a Node runtime, so the suites were not executed locally — CI is the
first run. The changes were reviewed by hand against the existing suites, and the two
pre-existing payout tests that assert the old "no execution" behaviour were updated to the
new contract.