Compare commits

..

95 Commits

Author SHA1 Message Date
48cd35970f docs: cross-link Scribase/Toolgate ecosystem (Rithub discoverability pass, 2026-11-16)
All checks were successful
Render keep-warm pinger / ping (map[name:settlekit-api path:/health]) (push) Successful in 2s
Render keep-warm pinger / ping (map[name:settlekit-checkout path:/]) (push) Successful in 3s
Render keep-warm pinger / ping (map[name:settlekit-dashboard path:/]) (push) Successful in 2s
Render keep-warm pinger / ping (map[name:settlekit-web path:/]) (push) Successful in 3s
2026-11-16 14:35:29 +00:00
9b696d5335 fix(worldisflat): remove 'indie' wording from pitch deck persona slide
All checks were successful
Render keep-warm pinger / ping (map[name:settlekit-api path:/health]) (push) Successful in 2m26s
Render keep-warm pinger / ping (map[name:settlekit-checkout path:/]) (push) Successful in 56s
Render keep-warm pinger / ping (map[name:settlekit-dashboard path:/]) (push) Successful in 34s
Render keep-warm pinger / ping (map[name:settlekit-web path:/]) (push) Successful in 36s
Judge pass on the World is Flat submission assets found the deck's "who has
this problem" slide used "Indie API/tool builders" — violates the standing
portfolio rule against "indie"/"indie hacker" audience wording. Reworded to
"Solo founders & small API/tool teams" (matches the rule's target audience:
founders, small teams, developers). Re-exported PDF/PPTX from the fixed
markdown; re-rendered and visually checked the slide, no overflow/wrapping.

Everything else in the deck/video/packet checked clean this pass: all 4
raw GitHub asset URLs verified HTTP 200, ffprobe confirms 66.7s/1920x1080/
h264+aac, ebur128 confirms -14.4 LUFS integrated / -1.9 dBTP true peak
(matches claimed values), all 14 slides + ~20 video frames visually
reviewed with no blank/cut/illegible content, and every factual claim
(mainnet chain id 4663, $wif contract decimals/symbol, testnet tx status,
checkout HTTP 200, API down) re-verified live via direct RPC/curl.

The one real unresolved gap (not fixable without owner action): no real
mainnet $wif-moving transaction exists yet, which is worldisflat.fun's own
rule 3 and judge check txs_valid's pass condition — already correctly
flagged as the blocking gate in plans/submission-packets/worldisflat-settlekit.md.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-11 01:11:50 +03:00
a1482ee535 docs(worldisflat): add pitch deck + narrated demo video for submission
Pitch deck: Marp markdown (docs/worldisflat/PITCH-DECK.md) exported to
.pptx and .pdf, 14 slides (problem, who has it, solution, live proof
screenshots, architecture, $wif integration + honest gap, rule-by-rule
fit mapping, honest $0-revenue traction, roadmap, team/links). Every
screenshot is a real frame pulled from the existing demo capture; every
live claim (checkout 200, API down, $wif mainnet chain id/symbol/decimals,
testnet tx success) re-verified live via curl/eth_call before writing.

Demo video: upgraded the existing silent 65s capture with real narration
(Deepgram Aura-2 TTS, round-trip QC'd word-for-word against its own
transcript) and burned-in top-band captions driven by the narration's
own word-level timings, muxed over the original real screen-capture
footage (no new/AI-generated visuals). Mastered to -14.4 LUFS
integrated / -1.9 dBTP true peak (ebur128-verified). 66.7s, 1920x1080.

No mainnet $wif tx run (owner-gated, unchanged); Render API still shown
as down, never as live.
2026-11-11 00:59:12 +03:00
64c74c7446 fix(checkout): restore checkout build after robinhoodWif registry key
robinhoodWif (18-decimal $wif) is a chain-registry/facilitator asset, not a
PaymentNetwork, so onchain-billing now skips non-PaymentNetwork chains and the
checkout EVM helpers carry the narrowed PaymentNetwork & EvmChainKey type.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-10 18:18:27 +03:00
6a63c8d75f docs(worldisflat): record real demo video for World is Flat submission
Adds a 65s, 1920x1080, silent demo video built entirely from real capture
(headless-browser screenshots + a real macOS screencapture of a terminal
session, composed with ffmpeg only) — no AI-generated footage. Honestly
shows the live checkout, a real checkout-session error (Render DB outage),
the public repo's chain table, a real SIMULATE-mode $wif mainnet proof
(chain id, decimals, symbol, gas estimate), the already-proven testnet
settlement tx, and an explicit caption that no mainnet $wif send has been
executed. Surfaces a real gap found while building it: $wif is not yet
selectable in the hosted checkout UI's network picker (packages/common's
PaymentNetwork enum was never extended for it). Also fixes the SIMULATE
log line to print symbol=WIF, and adds scripts/wif-demo-addendum-capture.sh
for recording a real addendum clip once the owner runs the LIVE mainnet
proof.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-10 18:00:10 +03:00
4a63e6bbdb docs(worldisflat): repoint README live-deployment table off dead Render checkout link
settlekit-checkout.onrender.com and settlekit-api.onrender.com both confirmed
timing out live (000, 20s and 90s+) due to the known DATABASE_URL issue --
README's own "Live deployment" table was still handing a judge that dead
checkout URL as the primary link. Lead with the working
settlekit-checkout.vercel.app instead, label both dead Render routes
"currently down" for transparency.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-10 17:33:52 +03:00
d82a1b448b feat(robinhood): add real $wif mainnet support + mainnet proof script + fix API boot hang
World is Flat hackathon eligibility requires using $wif onchain on Robinhood
Chain; the existing integration only proved testnet Mock-USDC. Adds a real
robinhoodWif registry entry (18-decimal $wif, contract and chain id verified
live via eth_call), a Permit2 facilitator asset entry, and a ready-to-run
LIVE=1-gated mainnet settlement proof script (scripts/wif-mainnet-proof.ts)
with a safe default SIMULATE mode (no funds, no key) smoke-tested against
the live chain.

Also diagnoses and partially fixes settlekit-api.onrender.com timing out:
neither the migration client nor the app's DB connection set a
connect_timeout, so a stale DATABASE_URL hung boot indefinitely, and the
Dockerfile CMD's `&&` meant a migration failure blocked the server from even
starting. Adds a bounded default timeout and decouples server start from
migration success so failures are fast and visible instead of silent.

packages/chains + packages/x402-facilitator: 194/194 tests pass (registry
invariants updated for the two intentional exceptions: $wif=18 decimals,
robinhoodWif is mainnet-only).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-10 17:16:08 +03:00
14e6ca6744 docs(worldisflat): commit the real tx-hash proof update (was uncommitted since 2026-11-07)
SUBMISSION.md had already been edited in place with the real confirmed tx
(0x54a46bc4...f0809, block 149738928, status success on Robinhood testnet)
but the edit was never committed, leaving the public repo without this
evidence. No content change — just persisting what was already verified.
2026-11-10 03:03:23 +03:00
d5d1bf5bfd feat(robinhood): add live testnet e2e settlement script + World is Flat submission doc
Owner-authorized second carve-out to SettleKit's DISCONTINUED status
(2026-10-27), scoped to the World is Flat hackathon (worldisflat.fun/build,
10,000 USDG, Robinhood Chain). Robinhood Chain chain-config, EVM verifier,
and x402-facilitator wiring already existed from the 2026-09-29/30
multichain wave (015899f) and needed no architecture changes — confirmed by
running packages/chains + packages/x402-facilitator's 194 tests green.

Adds scripts/robinhood-testnet-e2e.ts: a real LIVE=1-gated script (same
pattern as operator-arc-e2e.ts / solana-devnet-e2e.ts) that sends a live
ERC-20 transfer on Robinhood Chain testnet (46630) and verifies it through
the actual createEvmVerifier. Smoke-tested against the live RPC: real
assertChainId() succeeds (confirms 46630), then fails cleanly needing a
funded PAYER_PRIVATE_KEY.

docs/worldisflat/SUBMISSION.md documents what's proven vs not: the official
testnet faucet is behind real bot-detection (Vercel checkpoint, confirmed
via both curl and a real headless-Chromium session) and third-party faucets
require a wallet-extension connect — both owner-only. The hackathon's own
submission form requires sign-in (Twitter/X or email), also owner-only.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-07 02:15:09 +03:00
dc88a1f91f fix(solana): payer binding was never enforced on Solana payment verification
The EVM and Zcash on-chain verifiers both enforce the session's declared
`payer` and `notBefore` bindings (packages/chains/src/evm-verifier.ts,
settlement.ts). The Solana verifier (packages/solana/src/x402-verifier.ts,
verify.ts) read neither field, even though payment-verification.ts's
sessionCheck() passes both to every network's verifier identically.

Concretely: a checkout session created with a declared payerAddress (the
pre-authorized-wallet / recurring on-chain-billing flow in
apps/api/src/routes/onchain-billing.ts) accepted a Solana payment of the
right amount to the right address from ANY wallet, not just the declared
payer - the exact binding EVM/Zcash already enforce.

Add payer + notBefore to VerifySplTransferParams/evaluateSplTransfer and
wire them through createSolanaPaymentVerifier, matching the EVM verifier's
semantics (fail closed, including when a tx has no on-chain block time).
The route-provider "routedFill" path (no Solana Pay reference) already has
its own independent notBefore check in
apps/api/src/config/verifier-registry.ts's verifyRoutedSolanaFill, which
bypasses this adapter and is unaffected.

28 solana-package tests pass (8 new), plus full chains (211) and api (231)
suites green; tsc --noEmit clean on both packages.
2026-10-26 22:42:47 +03:00
7ad4ec44c0 fix(sdk-go): VerifyEntitlement decoded the wrong field — always "not allowed"
VerifyEntitlementResult.Granted had json tag "granted", but the real API
(apps/api/src/routes/entitlements.ts -> packages/entitlements's
EntitlementService.verify / ServiceVerifyResult) has only ever returned
"allowed". encoding/json leaves unmatched fields at their zero value, so
Granted silently decoded to false for every real response — any Go backend
gating paid access via this SDK denied every real, fully-paid customer, with
no error ever raised. Same bug shape as the already-fixed Python x402
verifier (a27d0051): an SDK's only production path silently rejecting
everything real.

Rename Granted -> Allowed (json:"allowed"), add the Entitlement and Value
fields the API actually returns, and give Raw a real UnmarshalJSON instead of
a json:"-" tag that silently excluded it from ever being populated despite the
doc comment's "preserved in Raw" claim. Add Email support to
VerifyEntitlementInput/ListEntitlementsOptions, matching the API's own
"check by the buyer's checkout email instead of a customer id" capability,
which the Go SDK had no way to express. Add the first regression tests for
this file (sdks/go had none): one that would not even compile against the old
field names, proving this isn't a cosmetic rename.

Also fix a second real blocker for any Go developer trying to use this SDK at
all: go.mod's module path (github.com/settlekit/settlekit-go) and every
README/docs reference to it pointed at a GitHub org that does not exist
(confirmed 404 on github.com and the Go module proxy) — `go get` of the
documented path fails for everyone. Changed the module path to this
repository's real path (github.com/caelum0x/settlekit/sdks/go) and updated
sdks/go/README.md, docs/WEBHOOKS.md, docs/RELEASING-SDKS.md to match.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-26 17:47:07 +03:00
5c592ddb3e fix(web): point footer 'Open source' link at the real repo
The homepage/footer's GitHub link was hardcoded to
https://github.com/settlekit/settlekit, which 404s (that org/repo
doesn't exist). The real public repo is caelum0x/settlekit (confirmed
public via the API). Every visitor clicking "Open source · self-host
or use hosted cloud" has been hitting a 404 since this was added.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-25 03:40:34 +03:00
83c4149ee6 feat: add IndexNow key + submission script for settlekit-web
First IndexNow coverage for this product -- no key existed before.
Submits against the real live settlekit-web.onrender.com domain (see
app/robots.ts's comment for why, and the prior commit for the
settlekit.dev domain-mismatch finding).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-25 03:36:36 +03:00
3c4479a60a feat(web): add robots.txt + sitemap.xml to settlekit-web
Both were a genuine 404 on the live site (checked via curl against
settlekit-web.onrender.com, the real current deployment) -- the Next app
had no app/robots.ts or app/sitemap.ts at all. Also found while checking
this: settlekit.dev (the domain hardcoded as metadataBase in layout.tsx,
and referenced in every og:image/canonical tag) is not actually serving
this app -- it 200s with a different, stale title ("SettleKit - Settlement
Engine for Payment Processors", Last-Modified Aug 28) on an account this
environment's Cloudflare token has no zone access to. That DNS/deployment
cutover is a real, confirmed owner-only blocker (same shape as the
previously-flagged Render env-var cutover in plans/settlekit.md), not
something fixed here.

Resolves SITE_URL from RENDER_EXTERNAL_URL (set automatically by Render)
so robots.txt/sitemap.xml are correct on the actual live onrender.com URL
right now, and will self-correct once settlekit.dev is cut over.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-25 03:32:43 +03:00
e5d8894192 docs(deploy): flag settlekit-db free-tier expiry (2026-10-30) with a one-command migration path
Render's free Postgres plan backing settlekit-api/checkout expires soon and
was buried in a one-line table note. Document the real impact (service
downtime, not data loss — only testnet demo rows exist today), the two
owner-only fixes (upgrade plan or move to Neon), and add scripts/migrate-db.sh
so moving the data over is a single command once a target DB exists.
2026-10-24 21:39:41 +03:00
a27d00519c fix(sdk-python): x402 api-mode verifier called a route that was never registered
X402Verifier("api") — the only production-safe x402 verification mode, since
"accept" trusts any proof blindly — POSTed to /v1/x402/verify. That route is
never mounted in apps/api (only /v1/paid and /v1/x402/{networks,research,...}
exist). Every call 404'd and was swallowed by `except SettleKitError: return
False`, so every real payment proof verified via the SDK's documented
production path was silently rejected, forever.

Rewire _verify_via_api to POST /v1/payments/observe, the endpoint that
actually does what the docstring promised: independently re-verify the
txHash on-chain (recipient, asset, amount) and record a confirmed payment
credited to the caller's org, idempotent on txHash.

Add the Python SDK's first tests (sdks/python/tests/ did not exist despite
pytest being declared as a dev dependency): one asserts the real endpoint and
body shape are used (fails against the pre-fix code), one asserts a non-2xx
response is treated as a failed verification.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-20 17:49:08 +03:00
5be25bbceb fix(worker): complete the checkout session and grant entitlements when the worker confirms a payment
The claimTxHash flow is designed so the worker's payment-confirm job can
finish confirming a payment even after the buyer closes the tab (an agent
that never polls hits the same path). But the job only flipped the payment
to "confirmed" and emitted the webhook — it never completed the checkout
session or created an entitlement, both of which only happened in the
buyer-driven confirmOnce/fulfillOnce flow and the API's /payments/:id/confirm
route.

Result: a payment the worker confirms settles on-chain and fires the
seller's webhook, but the session stays "open" forever, so the success/
receipt page 409s "not paid yet" indefinitely and no entitlement is ever
created — the GitHub/Discord retry jobs have nothing to retry since they
only act on entitlements that already exist.

Add WorkerStore.saveCheckoutSession (in-memory + Postgres) and complete the
session + grant a payment entitlement per line item right after the worker
confirms a payment, guarded against double-granting.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-18 00:14:20 +03:00
4e9e39e79d ci: add Render keep-warm pinger for rollback services
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-15 17:31:45 +03:00
61afc2c827 Merge branch 'feat/tameion-arc' 2026-10-12 12:49:42 +03:00
a2e15ddc51 feat(web): lead with the merchant pain point: accept USDC payments with no card fees
Hero, title and meta now name what merchants search for (accept USDC payments,
no card fees, no chargebacks) and the signup button says what it does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 06:40:49 +03:00
534e0e418f fix: create guest customer row before claiming payment
payments.customer_id has an FK to customers; guest checkouts used a
synthetic cus_<session> id that was never inserted, so every live
on-chain confirmation failed with 23503 and the status route 502'd.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 19:56:15 +03:00
c34e895977 docs(readme): hackathon demo videos, current Render deployment, honest status, Arc mainnet deploy
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 19:03:55 +03:00
21660a73a1 fix(ui): replace the emoji bell with an SVG icon; readable checkout alerts on the light theme
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 17:59:56 +03:00
6922d273ff docs: record the live Tameion operator console service
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 17:48:54 +03:00
ccda758d3b fix(worker): sign webhook retries with the job clock; add MIT license
The rotation grace check used the wall clock while the job used ctx.now(),
so the retry test started failing once its fixed grace date passed.
The repo already declared MIT in package.json and contract SPDX headers;
add the LICENSE file so GitHub shows it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 17:38:21 +03:00
a9cc50524c feat(contracts): one-command Arc mainnet deploy and verify for OperatorVault and escrow
Adds DeployArcMainnet.s.sol and deploy-arc-mainnet.sh. The script checks the
chain id (5042) and USDC, simulates, prints the cost in USDC, asks for
confirmation, then verifies on Sourcify and Blockscout. Also adds the
bounty runbook. SettleKitCctpHook is excluded: it is not called by CCTP V2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 17:33:07 +03:00
d68a5b25ce docs: record the live Render deployment of main (testnet mode)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 20:05:50 +03:00
894d315a24 fix(api): stop returning raw internal error messages in production
Unhandled errors echoed the driver message to the caller, including SQL and
bound parameters. In production the caller now gets a generic message and
the detail is logged server-side with the request id.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 19:57:39 +03:00
45fced409c fix(api): store a quick product before its price
prices.product_id is a foreign key in Postgres, so saving the price first
made POST /v1/merchant/products fail with a 500 on the live database. The
in-memory repositories never enforced the key; the new test does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 19:57:39 +03:00
dea78f6eeb test: pin checkout test clock and cover x402_nonces in schema test
Checkout fixtures are dated 2026-09-29 but expiry reads the wall clock, so
24 tests started failing once the real date passed the checkout window.
The schema test predated the x402_nonces table, which is keyed by the
claimed authorization instead of id.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 19:36:07 +03:00
3efb74f6c5 fix(deploy): set CI=true in API and worker images so the prod install runs without a TTY
Render builds failed at the prod-deps stage with
ERR_PNPM_ABORTED_REMOVE_MODULES_DIR_NO_TTY.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 19:36:07 +03:00
817a7f9766 docs: Circle grant update, verifiable claims only (no testnet deploy yet)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 18:42:27 +03:00
b2f9e31fa5 fix: close org takeover at registration and harden fee statements and invoice bindings
- POST /v1/auth/register: a merchant always gets a fresh organization; a
  caller-supplied organizationId let anyone join an existing seller's org and
  receive a platform:admin key (tenant takeover, present on main too).
- Customer (portal) sessions carry the seller's org id; they are now refused
  on the management API instead of being treated as the org owner.
- Fee statements: issuance is serialized per merchant+period in-process and a
  duplicate raced in by another instance is voided before sending; a draft
  left by an interrupted run is sent on the next run. Overlapping runs
  previously issued (and emailed) several statements for one month.
- Invoices: SettleKit-owned metadata keys (pay token, session bindings,
  settlement facts, fee-statement markers) are stripped from API input, and a
  payment from another organization never settles an invoice.
- Scope map: /v1/merchant/refunds/* needs payments:write (was reports:write).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 07:08:31 +03:00
8eb0f49d27 docs: record parity build status per gap
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 06:44:07 +03:00
29de477e0f feat: Spanish hosted checkout via packages/localization (G14, part 2)
packages/localization gains the hosted checkout catalog (English source,
complete Spanish), a q-weighted Accept-Language picker limited to en/es
and a placeholder formatter. The checkout app (now depending on
@settlekit/localization) localizes the checkout, payment link, invoice
and success pages plus the order summary, promo, tax and start
components; ?lang=en|es or an sk_lang cookie override the browser
language and <html lang> follows. English output is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 06:42:02 +03:00
c724bf1700 feat: conversion, per-link, churn and LTV metrics (G14, part 1)
GET /v1/analytics/metrics computes, from live sessions, payments,
subscriptions and catalog: checkout conversion, per-payment-link opened /
paid / conversion / revenue, repeat customers, average revenue per
customer, subscription churn, ARPU and an estimated lifetime value, with
exact bigint money. Checkout repositories gain listCreatedSince
(in-memory and Postgres). The dashboard Analytics page shows the new
cards and a payment-link table.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 06:37:57 +03:00
35563d758d chore: prepare SDK releases at 0.1.0 with a publish workflow (G13)
@settlekit/common, @settlekit/sdk and @settlekit/react move to 0.1.0 with
publish metadata (description, MIT licence, repository, public access,
LICENSE and README in the tarball; verified with npm pack --dry-run).
.github/workflows/release-sdks.yml publishes npm, PyPI (trusted
publishing) and crates.io on an sdk-v* tag or as a manual dry run.
docs/RELEASING-SDKS.md lists the owner-only registry setup. Nothing is
published from here. The Python, Go and Rust webhook verifiers already
accept rotated secrets (G8).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 06:34:16 +03:00
1d92fa23f2 feat: branded hosted storefront per merchant (G12)
Merchants can publish a store (slug, title, tagline, https logo, accent
colour, search description, optional custom domain) through settings or
the dashboard. The checkout app serves it at /store/<slug> with SEO and
Open Graph metadata, listing active products (invoice products hidden)
that each open their payment link, and a middleware rewrites '/' on a
merchant's custom domain to its store when CHECKOUT_PRIMARY_HOSTS is set.
Slugs and domains are unique; public data at /v1/public/stores. Carts of
several products stay out of scope because hosted checkout fulfils one
product per session.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 06:32:06 +03:00
132efd87b3 feat: cash-out hand-off to off-ramp partners (G11)
GET /v1/merchant/offramp builds sell links for Transak, MoonPay (signed
server-side with the secret key) and Ramp with the amount, network and
the merchant's own receiving wallet prefilled. SettleKit takes no
custody; partners appear only once the owner configures their keys
(TRANSAK_API_KEY, MOONPAY_PUBLISHABLE_KEY/MOONPAY_SECRET_KEY,
RAMP_HOST_API_KEY). The dashboard Balances page gets a Cash out action per
mainnet network.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 06:24:40 +03:00
6ba53b7a92 feat: refund to payer with prepared transfers verified onchain (G10)
Refunds no longer depend on a pasted hash alone. POST
/v1/merchant/payments/:id/refund/prepare creates a pending refund and
returns the exact transfer back to the buyer: ERC-20 transfer calldata,
token, chain id and an EIP-681 link on EVM networks, or a Solana Pay
transfer request with a unique reference. The destination is the wallet
that paid when known, else the merchant enters it (validated per chain).
POST /v1/merchant/refunds/:id/confirm verifies the signed transfer
onchain with the payment verifiers (destination, amount, time, Solana
reference, one refund per tx) and only then settles: access revoked,
payment refunded once fully refunded, refund.succeeded with source
wallet. Pending refunds can be canceled. Dashboard refund form gets a
'Send from my wallet' mode (browser wallet or mobile link, auto-verify).
apps/refund-protocol stays unwired.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 06:21:27 +03:00
c14d0ab735 feat: team roles with invitations and enforced API key scopes (G9)
Security fix plus team access. Before this change any valid API key,
including access keys the delivery system hands to BUYERS, authenticated
as the merchant on the whole management API, and GET /v1/api-keys listed
every organization's keys. Now only platform keys (issued at sign-up or
via POST /v1/api-keys/platform, marked with the platform product id) can
call the API, and each request needs its resource scope
(<resource>:read|write, write implies read; platform:admin or * for
full access), answered with 403 and details.requiredScope otherwise.
Keys cannot mint broader keys, customer keys cannot carry management
scopes, key listing is tenant-scoped and keys can be revoked by id.

Dashboard sessions get team roles (owner, admin, developer, support,
viewer) mapped to scopes. /v1/team manages members and email
invitations (packages/invitations, token hash only, 7-day expiry);
/v1/auth/invitations/accept joins the org and creates the account. The
last owner is protected and only owners grant owner. Dashboard: Team
page, invite accept page, and an API keys page that creates restricted
keys and shows the secret once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 06:09:06 +03:00
40f90f1c5a feat: webhook event log with resend, test events, secret rotation and auto-disable (G8)
Every seller webhook delivery now keeps an attempt log (status code,
error, time, next retry) in the worker queue (Postgres) or in memory.
New routes: GET /v1/webhooks/deliveries(/:id), POST
/v1/webhooks/events/:id/resend, POST /v1/webhooks/endpoints/:id/test
(signed webhook.test event), rotate-secret with a 0-168h grace window
(both secrets sign as two v1 values, verified by @settlekit/webhooks, the
TS/Python/Go/Rust SDKs and the WooCommerce plugin), and disable/enable.
The worker retries on a 1m..6h exponential schedule instead of every tick,
signs with the live endpoint secret, skips disabled endpoints and
auto-disables one after 100 failed attempts in a row
(WEBHOOK_DISABLE_AFTER_FAILURES). Outbound requests get a 10s timeout.
The dashboard Webhooks page shows the event log with Resend and endpoint
actions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 05:34:39 +03:00
330d111510 feat: fiat pricing with live ECB rates locked per checkout (G7)
Prices can now be set in EUR, GBP and other ECB reference currencies
(displayCurrency + displayAmount, or currency on quick products). Each
checkout converts them to USDC at the live rate from a frankfurter
service (MIT, FX_RATES_URL), rounded half-up to the cent with exact
bigint math, and locks the quote on the session (fxQuote) until it
expires, so onchain verification expects exactly the quoted USDC. Promo,
tax, receipts and the hosted checkout lines use the locked rate; the
payment link page shows the fiat price and today's USDC amount. Missing
or implausible rates fail closed (503); fiat subscriptions and mixed
fiat currencies are refused. Dashboard product form gets a currency
picker.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 05:13:37 +03:00
91c637a470 feat: WooCommerce gateway ported from the BTCPay Greenfield plugin (G6, part 2)
plugins/woocommerce/settlekit-for-woocommerce charges WooCommerce orders
in USDC: checkout creates a SettleKit payment request for the order total
(no email, return to the order received page) and redirects to the hosted
pay page, reusing an open payment when the buyer comes back. The signed
invoice.paid webhook (?wc-api=settlekit) completes the order after
checking invoice id and amount, and the thank-you page double-checks the
status. Structure ported from btcpayserver/woocommerce-greenfield-plugin
(MIT, 371ebfc) with LICENSE and NOTICE kept. A standalone PHP suite runs
under plain PHP CLI and from vitest, including a cross-check of the PHP
signature verifier against @settlekit/webhooks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 04:55:31 +03:00
f1647a5a81 feat: embeddable checkout overlay (embed.js) with allow-listed success callback (G6, part 1)
apps/checkout/public/embed.js opens a payment link, checkout or invoice
from the same checkout origin in an overlay iframe on any site; links
marked data-settlekit-checkout bind automatically, SettleKit.open() is
available from code, and there is an open-in-new-tab fallback for
wallets that block iframes. The success page posts settlekit:success
only to a site the seller listed under Settings > Embedding
(org embedOrigins, validated https origins), and embed.js only accepts
messages from its checkout frame. Payment requests gain sendEmail and
successUrl so store plugins can redirect buyers and bring them back.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 04:52:19 +03:00
22c3208b60 feat: merchant accounting exports with Xero and QuickBooks imports (G5)
New tenant-scoped /v1/exports routes: payments, refunds, invoices and
payouts CSVs, a full USDC ledger, and bank statement files that Xero
(DD/MM/YYYY statement import) and QuickBooks Online (three-column bank
upload) import directly, with optional date ranges. packages/exports
gains a formula-injection guard (opt-in, admin unchanged) and the
accounting formatters. The dashboard Payments page links every export
through a session-authenticated download route.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 04:35:58 +03:00
a4d0f3f5cb feat: tax at checkout and tax-grade receipts (G4)
Sellers can turn on checkout tax in settings (label, own country and tax
ID, legal name, per-country rates, default rate, EU reverse charge).
Sessions add tax on top of the net price after any promo, so onchain
verification expects the tax-inclusive total. Buyers set billing country
and VAT ID via the API (billingCountry, vatId) or on the hosted checkout
until a payment is recorded; EU cross-border B2B with a VAT ID of the
right shape is zero-rated. Settled checkouts get a PDF receipt (pdfkit)
with the seller's tax ID, buyer country / VAT ID, tax rate and the
settlement transaction, linked from the success page, the receipt email
and the customer portal. packages/tax calculateTax is now used at
checkout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 04:30:53 +03:00
4e97fcc409 feat: promo codes at checkout (G3)
Coupons now reach checkout. POST /v1/checkout-sessions takes an optional
couponCode, payment links accept ?promo=CODE (a refused code falls back to
full price with a notice), and the hosted checkout gets a promo field
while the session is open and unpaid. The discounted total becomes the
session amount before network bindings, so onchain verification expects
the discounted amount and a locked Zcash quote is re-priced. Codes are
tenant-scoped, product-scoped codes discount only their products, and
free-trial or 100% codes are refused. The redemption is counted once
after the payment confirms (API confirm and hosted checkout).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 04:09:54 +03:00
e0caf4bace feat: monthly platform fee statements with plan limits after grace (G1)
SettleKit's advertised per-payment fee was never collected because buyers
pay merchants' wallets directly. When PLATFORM_BILLING_ORG_ID is set, the
API now issues each merchant a monthly statement (confirmed payments x the
fee schedule) as an invoice from SettleKit's own org, paid through the
hosted checkout on the G2 payable-invoice path. Totals below the minimum
carry forward, test accounts are skipped, runs are idempotent and happen
automatically every six hours (or via POST /v1/billing/statements/run).
A statement unpaid past due + grace restricts new products to the free
plan limit from packages/pricing (402 with the pay link). Merchants see
accrued fees, statements and a Pay button on the Balances page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 03:50:08 +03:00
466c662ac3 feat: payable invoices and payment requests (G2)
Invoices can now be paid onchain. POST /v1/invoices/:id/send issues the
invoice, binds a public pay page (/i/<token> on the hosted checkout),
opens a checkout session for the invoice total on the merchant's
networks and emails the link. POST /v1/invoices/requests sends an
ad-hoc amount + memo to an email. The invoice turns paid only when a
confirmed onchain payment exists for one of its sessions (on read in the
API and in the new worker invoice-settle job) and emits invoice.paid.
Invoice and receipt PDFs render with pdfkit (MIT). Voiding cancels open
sessions. Dashboard gets a request-a-payment form, send buttons, pay
links and PDF downloads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 03:35:06 +03:00
d04b79d5d9 docs: parity audit vs stablecoin checkout competitors
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 02:30:20 +03:00
b02118086c docs: add SettleKit Operator (Arc) section to README
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 22:43:48 +03:00
2b2c8b471d chore: merge Tameion operator into main alongside multi-chain SettleKit
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 22:43:33 +03:00
9ac5202d60 docs: draft Circle grant update
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 22:32:20 +03:00
b16aead3bf docs: Colosseum submission pack (submission, pitch, demo, launch checklist)
Adds docs/colosseum/SUBMISSION.md (chain matrix with honest labels,
architecture, OSS composed, security model, 1% fee, GTM, traction template
and pre-existing code disclosure with in-window stats against
pre-colosseum-baseline), PITCH-SCRIPT.md, DEMO-SCRIPT.md and
LAUNCH-CHECKLIST.md, and leads the README with the multi-chain product.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 21:52:58 +03:00
33baad09af fix(checkout): show buyers a plain message when subscription options cannot load
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 21:46:24 +03:00
def5b16ede chore(deploy): Colosseum Render blueprint for api, worker, checkout, dashboard and web
- render.yaml deploys the five buyer/seller services on Node 22 with every
  env var the new surfaces read (chains, routing, HyperCore, Zcash, x402/MPP,
  onchain billing, service token, Discord, fee); Node builds install only the
  app and its workspace deps (pnpm --filter <app>...). Free plans everywhere
  except the worker (Render has no free background workers: starter).
- API/worker Dockerfiles install filtered; the API runs migrations on boot
  because preDeployCommand is paid-only.
- worker boots without GitHub App / Resend / Discord credentials: those
  deliveries stay pending and emails are skipped with a warning.
- .env.example documents the service token, manage-link secret and Discord OAuth.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 21:43:12 +03:00
61ce1686ff feat(web): SaaS integration guide at /docs/integrate, with email-based entitlement checks
- /docs/integrate: payment link, embeddable button, server-opened sessions
  with a return URL, Node webhook signature verification with the event list
  and a sample payload, and checking access through the entitlement API.
- api: /v1/entitlements and /v1/entitlements/verify accept the buyer's email
  and are scoped to the caller's organization.
- checkout: confirmed buyers are recorded as customers (email, GitHub,
  Discord, wallet) so sellers can check access by email; receipts and
  subscriptions offer "Continue to <seller>" when the link carried a successUrl.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 21:39:36 +03:00
fd29a1de73 fix(dashboard): webhook endpoints register against the API and show their signing secret
The page posted to a route the API does not have and read fields it does not
return. It now creates /v1/webhooks/endpoints with the chosen events
(default: payment.confirmed, subscription.charged, subscription.canceled,
refund.succeeded) and reveals each endpoint's signing secret for verification.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 21:35:22 +03:00
995083b651 feat(dashboard): onchain subscriptions page and refunds that send funds
- Subscriptions: every buyer subscription with plan, network and collection
  method, status, next charge, last charge (explorer link), dunning state and
  cancel at period end / now; active count, MRR and dunning totals. Falls back
  to the core list when onchain billing is off.
- Payment detail: Refund payment sends the funds on-chain through
  POST /v1/onchain-billing/refunds (operator wallet per network, Base escrow
  via the escrow) and shows the refund transaction link; when the operator is
  not configured for the network it offers "I refunded manually" to record
  the tx hash. Refund rows link to the explorer.
- Refunds ledger links each refund to its payment instead of creating
  unsent pending refunds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 21:35:22 +03:00
bcccfb0bf7 feat(discord): real paid-role delivery with Connect Discord at checkout
- checkout: buyers connect Discord (OAuth2 identify + guilds.join) in the
  delivery-fields step; the callback saves their user id on the session and
  joins them to the product's server. After payment the bot adds the role via
  PUT /guilds/{guild}/members/{user}/roles/{role}; the grant is recorded for
  access-sync revocation. Without DISCORD_BOT_TOKEN the buyer sees
  "pending setup" instead of a fake success.
- worker: discord-delivery-retry grants pending Discord entitlements once the
  bot is configured (backoff per entitlement); DISCORD_BOT_TOKEN is optional.
- api: a configured bot delivers roles even before GitHub is set up;
  checkout subscriptions pass the buyer's Discord / GitHub ids so subscription
  delivery reaches the right accounts.
- dashboard: product settings explain server / role ids and link the bot invite.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 21:31:32 +03:00
ae448fe158 feat(checkout): subscribe to recurring products with onchain billing
Recurring checkouts (/c and /l links) offer Subscribe on the session's network:
smart-wallet spend permission, Permit2 capped allowance, Solana SPL delegate or
renewal invoices by email (HyperCore / Zcash). The page states the per-period
price, total cap and expiry before signing; the buyer's wallet (EIP-6963 /
Wallet Standard) sends prerequisite calls and signs the server-built grant,
and the API activates it, charges the first period and delivers access.
Buyers get a signed /s/<token> manage page with status, next charge, charges
with explorer links, cancel and an on-chain revoke. All billing calls go
server-side through /v1/onchain-billing with the service token.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 21:24:52 +03:00
667e330109 feat(api): operator refunds that send funds, subscription read model, checkout service token
- POST /v1/onchain-billing/refunds records the refund tx hash, marks full
  refunds, revokes access and emits refund.succeeded; GET /refunds/route tells
  the dashboard whether the operator can send the refund on that network
- subscription list/detail read model: next charge, cap, grant expiry,
  dunning state, charges with explorer links; cancel mirrors the core
  subscription and emits subscription.canceled
- manual refunds emit refund.succeeded; payment detail refunds carry explorer links
- SETTLEKIT_SERVICE_TOKEN + X-SettleKit-Organization lets the hosted checkout
  call /v1/onchain-billing server-side for the session's seller (scoped to that prefix)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 21:19:13 +03:00
9691cf7c48 feat(webhooks): signed seller webhooks for payments and subscription charges
Shared outbox in @settlekit/persistence writes one idempotent webhook_events
row per (org, type, business key) and queues a worker_webhook_jobs delivery per
subscribed endpoint; the worker signs and retries them (capped attempts).
payment.confirmed is emitted from checkout, worker confirmations, API confirms
and agent payments; subscription.charged (+ payment.confirmed) from every
collected onchain period. In-memory API mode delivers in-process.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 21:19:12 +03:00
39b29903b2 fix(pricing): default platform fee to 1% with no fixed fee to match the landing page
DEFAULT_FEE_SCHEDULE in packages/platform-billing is the single source of truth;
.env.example documents how the API and web env mirror it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 21:11:28 +03:00
2a8d6f16d5 fix(api): scope refunds, disputes, dunning, invoices, license keys, coupons and entitlement lists to the caller's org
Coupons gain an organizationId (column + migration 0010); legacy rows with no
owner stay hidden from every tenant.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 21:09:48 +03:00
7647d733b1 fix(api): enforce tenant ownership on single-resource routes
Payments (GET/confirm/fail/refund), checkout sessions (GET/cancel/expire/
collect-fields) and every other route loading a record by opaque id now
require the record to belong to the authenticated org, answering 404 (never
403) on mismatch so ids in other tenants cannot be probed. Creation paths
that reference another resource (payment->session, checkout->price,
subscription->product/price, refund/dispute->payment, dunning->subscription)
apply the same guard, and escrow tasks are scoped to the caller's org
instead of a client-supplied organizationId.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 21:08:55 +03:00
95c6e6f003 chore: merge agent payments, onchain billing and x402 facilitator into colosseum branch
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 21:07:16 +03:00
9dade882f4 chore: document checkout URL, fee and proof-exclusion env for the new surfaces
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 21:01:06 +03:00
454973716f fix(api): default unconfigured Solana/HyperCore labels to the deployment's chain env
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 21:00:47 +03:00
ee1b528bfa feat(web): stablecoins-on-every-chain landing and live /proof page
Landing: no-merchant-of-record headline, founder story, eight-chain grid
with honest labels (Robinhood USDG, Tempo USDC.e bridged, Zcash
transparent ZEC), how it works, agent payments (x402, MPP), simple
pricing from one config constant, CTA into sign-up and guided setup.
/proof lists confirmed payments from the public API with explorer links,
per-network totals, labelled agent purchases and testnet separated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 20:52:59 +03:00
7245d08879 feat(dashboard): guided onboarding, multi-chain payments, products with payment links, balances
- /onboarding: business name, accepted networks and receiving addresses
  (one EVM address for every EVM chain, Solana, HyperCore, Zcash t-address)
  validated per chain, first product, shareable link + embed button
- Payments list (network, asset, route, buyer, explorer link, filters) and
  detail with created/paid/verified/delivered timeline and refund recording
- Products create/edit with USD price, delivery type, per-network toggles,
  pause/re-open; customers with spend and access; live on-chain balances
- Settings: networks and addresses, webhooks, API keys; short sidebar

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 20:50:21 +03:00
19fa1aa9cb feat(checkout): reusable payment links and seller-hosted delivery links
/l/<slug> shows the product and opens a fresh checkout session per visit
(client-side, so link unfurlers never create sessions). File and plain
access products reveal the seller's https link after payment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 20:37:41 +03:00
547ec1ba71 feat(api): merchant workspace, reusable payment links and public proof
- /v1/merchant: networks + receiving addresses validated per chain and
  stored on the org, enriched payments with timeline, refunds that revoke
  access, one-step products with payment links, customers with
  entitlements, live on-chain balances per network
- /v1/public: payment-link summary, fresh checkout session per visit,
  proof of confirmed payments across sellers (test orgs excluded)
- self-serve orgs get their organizations/merchants rows on first save

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 20:37:40 +03:00
3546736841 docs: correct OperatorVault forge test count in TAMEION.md
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 17:25:02 +03:00
eb57108fa9 docs: add TAMEION.md with pitch, architecture, run guide and disclosure
Also defaults the console's CHECKOUT_URL to the checkout app's dev port.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 17:22:39 +03:00
43c331ad20 chore: add Tameion Render blueprint and operator env documentation
render.tameion.yaml provisions db, api, worker and operator-console with
every operator variable documented (secrets as sync: false, the console's
key sourced from the API bootstrap key); .env.example gains the operator
and console variables.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 17:21:25 +03:00
1d87abc9d2 feat: add operator console pages, escalation review and public proof
Owner pages (overview balances and spend vs caps, decisions with tool trace
and Verify on Arc, escalation approve/reject, bills with manual or invoice
intake, policy on-chain vs off-chain drift) behind a server-side owner
session; public /proof with live metrics and Arcscan links, and /connect
onboarding for external teams. The operator API key stays on the server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 17:19:42 +03:00
19291a5d0b feat: add operator console server logic with API client, owner auth and proof formatting
New @settlekit/operator-console (Next.js 14) scaffold and its server-side
libraries: typed operator API client (key sent only on private routes,
envelope/error mapping), HMAC-signed owner session tokens with constant-time
password check, proof view model with per-decision anchored status, policy
drift rows, decision paging, bill form validation, attempt limiter, and the
connect-your-business onboarding over the existing API. Tests include an
onboarding run against the real API app.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 17:19:41 +03:00
b110508926 feat: expose operator vault state for the console
Adds buildOperatorState (bucket balances, held total, today's UTC-day spend
vs caps, pending escalations) and OperatorRuntime.state(), read from the
vault executor (on-chain reads when OperatorVault is configured), served at
GET /v1/operator/state for the operator org.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 16:59:41 +03:00
2134532ba3 fix: drop Solana from the Tameion branch while keeping fail-closed confirmation
The cherry-picked fail-closed payment fixes imported @settlekit/solana, which
does not exist on this branch, breaking tsc -b and the api/worker suites.
Solana verification, env and session references are removed; arc/base/
ethereum keep the per-network verifier registry and the worker keeps
payTo-bound verification. A solana network is now rejected as unsupported
(400 on checkout/observe, unsupported in the worker). Also adds the missing
packages/circle project reference to the api, points the api/worker test
scripts at the root vitest config, and removes the operator's
vitest.apps.config.ts workaround.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 16:55:28 +03:00
0a86d7af03 fix: harden operator against double execution and payee swaps
- Events and escalation resolutions are claimed atomically in the store
  (operator_claims, INSERT ... ON CONFLICT DO NOTHING) before any money
  moves, so concurrent API/worker processes cannot execute twice; claims
  are released only when nothing was executed.
- x402 purchases pin the policy-approved payee and price: the settler
  refuses a re-read challenge that names another payTo or a higher price.
- A broadcast vault transaction whose receipt is unavailable or reverted
  is recorded as failed with its txHash (VaultTxError) for reconciliation.
- verifyDecision never reports a decision that moved money as valid
  without checking its DecisionAnchored logs on Arc.
- The worker's shared runtime reads the current run's clock and logger.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 16:40:43 +03:00
b7d674bbc2 feat: add live Arc e2e script for the operator
scripts/operator-arc-e2e.ts (refuses without LIVE=1) deploys OperatorVault
from the Foundry artifact when no vault is given, sets caps and allowlist as
the owner, pays the vault from a customer wallet, lets the operator allocate
the sale, pays a small bill, escalates a larger one in the vault, has the
owner approve it on-chain, then verifies every decision's chain, commitment
and DecisionAnchored log and prints the proof. Adds reusable arc-live
helpers (deploy, USDC transfer, balance, signer address).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 16:27:02 +03:00
1e20ece9df feat: add operator tick job to the worker
Each run expires stale escalations (vault-held ones on-chain, bills closed
as rejected), turns confirmed Arc payments into the operator vault without
a decision into revenue.received (payer read from the USDC transfer), raises
bill.due for open bills inside the due window, and emits one tick per UTC
day. Event ids are deterministic so nothing is decided twice. The API and
worker only run the operator with OPERATOR_VAULT_ADDRESS set or an explicit
OPERATOR_SIMULATION=1; otherwise the job no-ops and the routes answer 503.

Registered with one export in jobs/index.ts and one scheduler entry in
runtime.ts (the scheduler lists jobs explicitly).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 16:23:29 +03:00
2a4864dd49 feat: add operator API routes and public proof endpoints
/v1/operator (API key or dashboard session, scoped to the vault's org):
POST /events (caller org forced, duplicate event ids replay the recorded
decision, single-flight per event), GET /decisions[/:id], POST|GET /bills,
GET /escalations, owner-only POST /escalations/:id/approve|reject, GET and
owner-only PUT /policy which refuses drift from on-chain caps and allowlist.
/v1/public/operator: GET /proof (cached aggregates, demo org excluded) and
GET /verify/:id. Mounted with one route line in app.ts ahead of the v1
API-key group. Escalated bills close when the owner resolves them.

App-level operator tests run through vitest.apps.config.ts because the api
and worker tsconfigs reference packages/solana, absent on this branch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 16:15:22 +03:00
bb5daed488 feat: add operator proof, verification, policy admin and runtime
computeProof aggregates the hash-chained logs (orgs, counterparties, USDC
in/out, outcomes incl. blocked by policy and blocked on-chain, latency,
model cost, Arcscan anchors) and always excludes the demo org.
verifyDecision recomputes the chain prefix and the pre-execution commitment
and checks each transaction receipt on Arc for DecisionAnchored from the
vault. PolicyAdmin parses USDC policy bodies and refuses caps or allowlist
entries that drift from the vault. createOperatorRuntime assembles store,
DCW or viem vault executors (or a clearly labelled local simulation),
Claude or heuristic engine, screening, x402, alerts and bill intake from env.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 16:01:08 +03:00
341b977c28 feat: add AP bill intake and escalation notifications
BillIntake accepts manual bills or raw invoice text; Claude extracts vendor,
amount, due date and wallet through a single record_invoice tool, and the
wallet must appear verbatim in the invoice. Payees missing from the policy
allowlist are escalated at intake with their own decision record; due bills
go straight to the operator. Escalation notifications go to email via
@settlekit/notifications and to a Discord webhook (mentions disabled) behind
an AlertChannel interface; channel failures never block an escalation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 15:53:29 +03:00
fee0101b44 feat: add OperatorVault executor over Circle DCW and viem
VaultExecutor reads the vault through viem, simulates every write as the
signer so vault reverts surface as VaultError codes without spending gas,
then sends through a VaultTransport: Circle developer-controlled wallet
contract execution (buildContractExecutionRequest via createContractExecution,
pollTransaction to COMPLETE, deterministic idempotency keys) on ARC-TESTNET,
or a viem private-key signer when DCW cannot target the chain. pay() reads
the Escalated log for vault escalation ids. Includes per-request Circle
entity-secret ciphertext (RSA-OAEP SHA-256) and Arc viem client factories.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 15:47:56 +03:00
8c1d704a96 feat: add Claude operator agent, tools and decision service
OperatorAgent drives the Anthropic SDK tool runner (betaZodTool) over read
tools (treasury state, open bills, counterparty risk, payment history, x402
quotes) and policy-checked action tools that require rationale,
alternatives and confidence. claude-sonnet-5 handles revenue and ticks,
claude-opus-5-5 bills, refunds and disputes; at most 12 iterations, with
HeuristicOperator fallback when no key is set or the API fails.

OperatorService turns each event into one hash-chained DecisionRecord with
the tool trace, verdict, usage cost and outcome. The vault anchors a
pre-execution commitment hash of the reasoning; owner approvals, rejections
and 72h expiries are recorded as decisions too. Invoice and customer text
is passed as escaped untrusted data.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 15:41:33 +03:00
f30aef513d feat: add operator heuristic engine, executors, escalations and stores
Deterministic HeuristicOperator for revenue, bills, refunds, disputes and
ticks with rationale, alternatives and confidence. LocalExecutor simulates
OperatorVault independently for parity tests; executeProposal routes
proposals and holds off-chain escalations. 72h escalation queue, and
in-memory plus self-creating Postgres jsonb stores (doc projection) that
reject decision-chain forks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 15:17:34 +03:00
858a1a1485 feat: add @settlekit/operator policy, allocation and decision log
OperatorPolicy.evaluate mirrors OperatorVault check order (deny reasons map
1:1 to vault errors), reuses @settlekit/treasury for allowlist and UTC-day
window, and adds stricter off-chain gates (risk, compliance, min float,
x402 budget). Exact bigint revenue split, validated operator events, and a
sha256 hash-chained decision log with tamper detection.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 15:17:30 +03:00
4c1742c20b feat: add OperatorVault contract with caps, escalation and yield hooks
Owner/operator roles, USDC buckets, allowlist + per-tx + UTC daily caps,
TAX lock, owner approve/reject/expire escalations, USYC adapter hooks,
pause kill switch and DecisionAnchored on every mutation. 21 forge tests
including a reentrant-token CEI check, plus DeployOperator script.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 15:02:00 +03:00
e646e1286d docs: add Tameion operator plan
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 14:56:08 +03:00
b2c4a50da0 fix: verify worker payment confirmations against the session payTo per network
The payment-confirm job verified every pending payment on Arc with
to = the USDC contract address instead of the merchant's payTo, so a
transfer to anyone could confirm. It now loads the payment's checkout
session (new WorkerStore.getCheckoutSession, in-memory + Pg) and routes
by network: Arc via the Arc client against session.payToAddress, Solana
via @settlekit/solana (base58 signature, session paymentReference, no
0x check). Networks the worker cannot verify (base/ethereum, or solana
without SOLANA_CLUSTER) stay pending — fail closed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 14:55:35 +03:00
0dad9a9170 fix: fail closed on payment confirmation without an on-chain verifier
Security: POST /v1/payments/:id/confirm only verified Arc payments; any
other network confirmed with an arbitrary txHash and granted
entitlements. The API now keeps a per-network verifier registry
(ctx.verifiers: arc via the existing Arc client, base via the generic
EVM client + BASE_RPC_URL + Base USDC, solana via @settlekit/solana)
and confirm/observe reject any network without one.

- a transaction hash settles at most one payment (409 on reuse, also
  on record); EVM hashes are normalized to lowercase
- checkout sessions accept network solana, require a base58 payTo and
  get a fresh Solana Pay paymentReference the tx must include
- observe validates hash/address formats per network (base58 vs 0x)
- compliance screening maps solana to Circle's SOL chain
- env: SOLANA_CLUSTER, SOLANA_RPC_URL, SOLANA_USDC_MINT, BASE_RPC_URL,
  BASE_MIN_CONFIRMATIONS

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 14:55:35 +03:00
499 changed files with 38802 additions and 1694 deletions

View File

@ -151,8 +151,15 @@ GITHUB_WEBHOOK_SECRET=replace_with_github_webhook_secret
# --- Discord (community / role access delivery) -------------------------------
# Bot token used to add/remove Discord roles on purchase.
# Bot token used to add/remove Discord roles on purchase (API, worker, checkout).
# Unset = Discord purchases show "pending setup"; roles are granted once set.
DISCORD_BOT_TOKEN=replace_with_discord_bot_token
# Checkout "Connect Discord" (OAuth2 identify + guilds.join). Register the
# redirect <CHECKOUT_PUBLIC_URL>/api/discord/callback in the Discord portal.
# DISCORD_CLIENT_ID=
# DISCORD_CLIENT_SECRET=
# Dashboard: shows the "add the bot to your server" link.
# NEXT_PUBLIC_DISCORD_CLIENT_ID=
# --- Email (transactional, via Resend) ----------------------------------------
@ -186,6 +193,37 @@ WEBHOOK_SIGNING_SECRET=replace_with_webhook_signing_secret
# Public base URL of the SettleKit API, read by the browser-facing Next apps.
NEXT_PUBLIC_API_URL=http://localhost:8787
# Dashboard: hosted checkout base URL; payment links are <url>/l/<slug>.
NEXT_PUBLIC_CHECKOUT_URL=http://localhost:3000
# --- Platform fee (single source of truth) --------------------------------------
# Default: 1% per successful payment, no fixed fee. Defined once as
# DEFAULT_FEE_SCHEDULE in packages/platform-billing/src/fees.ts ({ bps: 100,
# fixed: "0" }). The API uses it unless PLATFORM_FEE_BPS / PLATFORM_FEE_FIXED
# are set; the landing/pricing pages (apps/web) default to the same values via
# NEXT_PUBLIC_PLATFORM_FEE_*. To change the fee, change the constant and set
# all four variables to the new values so the page matches what is charged.
# PLATFORM_FEE_BPS=100
# PLATFORM_FEE_FIXED=0
#
# --- Platform fee statements (SettleKit's own revenue) ---------------------------
# Buyers pay merchants' wallets directly, so the fee above is billed monthly: a
# statement invoice from SettleKit's own organization, paid through SettleKit's
# own checkout. Off (and nothing enforced) until PLATFORM_BILLING_ORG_ID is set.
# That org must finish payment setup (receiving wallets) in the dashboard.
# PLATFORM_BILLING_ORG_ID=org_settlekit
# PLATFORM_BILLING_DUE_DAYS=14 # due N days after the month ends
# PLATFORM_BILLING_GRACE_DAYS=14 # then free-plan product limits apply
# PLATFORM_BILLING_MIN_USD=1 # smaller totals roll into next month
# PLATFORM_BILLING_AUTORUN=1 # 0 = only POST /v1/billing/statements/run
#
# Public URL of the hosted checkout (invoice pay pages /i/<token>, receipt PDF
# links in receipt emails; API and worker). Falls back to NEXT_PUBLIC_CHECKOUT_URL.
# CHECKOUT_PUBLIC_URL=https://pay.example.com
NEXT_PUBLIC_PLATFORM_FEE_BPS=100
NEXT_PUBLIC_PLATFORM_FEE_FIXED=0
# API: extra organization ids hidden from the public /proof page (demo/test
# sellers; the bootstrap org and orgs flagged testAccount are always hidden).
# PROOF_EXCLUDED_ORGS=org_demo1,org_demo2
# =============================================================================
# Everything below is OPTIONAL for local dev — the API boots with none of it
@ -287,6 +325,14 @@ X402_PAY_TO=0x0000000000000000000000000000000000000000
# ONCHAIN_BILLING_OPERATOR_PRIVATE_KEY=0x... # EVM operator (pull spender, escrow operator, refund sender)
# ONCHAIN_BILLING_SOLANA_SECRET= # Solana SPL delegate + refund sender
# ONCHAIN_BILLING_CHECKOUT_URL=https://pay.example.com # renewal-invoice links
# ONCHAIN_BILLING_NETWORKS=base,arbitrum,solana,hypercore,zcash # default: every enabled network
# ONCHAIN_BILLING_ESCROW=off # disable Base commerce-payments escrow
# The hosted checkout calls /v1/onchain-billing server-side with this token
# (same value on the API and the checkout; 32+ chars, e.g. openssl rand -hex 32).
# Accepted ONLY under /v1/onchain-billing, with X-SettleKit-Organization.
# SETTLEKIT_SERVICE_TOKEN=
# Checkout: signs buyer "manage subscription" links (/s/<token>).
# CHECKOUT_MANAGE_SECRET=
# HYPERCORE_ENABLED=true # also enables HyperCore refunds (operator usdSend)
# HYPERCORE_REFUND_PRIVATE_KEY=0x... # optional: HyperCore refund account (default: operator key)
@ -403,3 +449,97 @@ SETTLEKIT_API_KEY=sk_replace_with_api_key
# SETTLEKIT_PAY_TO=0xYourMerchantWalletAddress
# SETTLEKIT_NETWORK=base
# SETTLEKIT_VERIFY_MODE=accept
# =============================================================================
# Autonomous operator (Tameion, Arc testnet) — packages/operator, apps/api
# /v1/operator/*, worker operator tick, apps/operator-console.
# The operator runs only with OPERATOR_VAULT_ADDRESS (real OperatorVault) or
# OPERATOR_SIMULATION=1 (labelled simulation, no chain).
# =============================================================================
# Org the operator acts for (defaults to the API's default org).
# OPERATOR_ORG_ID=org_your_business
# Deployed OperatorVault (contracts/script/DeployOperator.s.sol).
# OPERATOR_VAULT_ADDRESS=0xYourOperatorVault
# OPERATOR_SIMULATION=1
# Operator signer: Circle DCW address (needs CIRCLE_API_KEY + CIRCLE_ENTITY_SECRET)
# or a raw key; OPERATOR_SIGNER=viem forces the key when both are set.
# OPERATOR_WALLET_ADDRESS=0xAgentDcwAddress
# OPERATOR_PRIVATE_KEY=0x...
# OPERATOR_SIGNER=viem
# Owner signer for approve / reject / expire / caps / allowlist transactions.
# OWNER_WALLET_ADDRESS=0xOwnerDcwAddress
# OWNER_PRIVATE_KEY=0x...
# 32-byte hex entity secret registered with Circle (DCW contract execution).
# CIRCLE_ENTITY_SECRET=replace_with_registered_entity_secret_hex
# CIRCLE_W3S_BASE_URL=https://api.circle.com
# Arc testnet overrides (defaults: rpc.testnet.arc.network, chain 5042002, native USDC).
# ARC_RPC_URL=https://rpc.testnet.arc.network
# ARC_USDC_ADDRESS=0x3600000000000000000000000000000000000000
# ARC_EXPLORER_URL=https://testnet.arcscan.app
# Claude decision engine (deterministic heuristic engine when unset).
# ANTHROPIC_API_KEY=sk-ant-replace
# OPERATOR_MODEL_ROUTINE=claude-sonnet-5
# OPERATOR_MODEL_CRITICAL=claude-opus-5-5
# Default policy; caps must equal the vault's (PUT /v1/operator/policy refuses drift).
# OPERATOR_SPLIT_OPERATING_BPS=7000
# OPERATOR_SPLIT_YIELD_BPS=2000
# OPERATOR_SPLIT_REFUND_BPS=1000
# OPERATOR_TAX_RATE_BPS=2500
# OPERATOR_PER_TX_CAP_USDC=1000
# OPERATOR_DAILY_CAP_USDC=1500
# OPERATOR_ESCALATE_ABOVE_USDC=500
# OPERATOR_MIN_FLOAT_USDC=0
# OPERATOR_YIELD_TARGET_USDC=0
# OPERATOR_MAX_X402_PER_DAY=20
# OPERATOR_ALLOWLIST=0xVendorA,0xVendorB
# API key ids (besides the bootstrap key and dashboard sessions) that may
# approve/reject escalations and change policy.
# OPERATOR_OWNER_KEY_IDS=key_abc123
# x402 purchases from a Circle wallet (all four required).
# OPERATOR_X402_WALLET_ID=wallet-id
# ARC_USDC_TOKEN_ID=circle-token-id-for-arc-usdc
# OPERATOR_X402_ALLOWED_HOSTS=api.example.com
# Escalation alerts (email via RESEND_API_KEY above, and/or Discord).
# OPERATOR_ALERT_EMAIL=owner@example.com
# OPERATOR_ALERT_FROM=SettleKit Operator <operator@settlekit.dev>
# OPERATOR_DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/...
# OPERATOR_CONSOLE_URL=http://localhost:3009
# --- apps/operator-console (server-side only; never NEXT_PUBLIC_) -------------
# OPERATOR_API_URL=http://localhost:8787
# Owner-capable API key (API_BOOTSTRAP_KEY or an id in OPERATOR_OWNER_KEY_IDS).
# OPERATOR_CONSOLE_API_KEY=replace_with_owner_api_key
# CONSOLE_OWNER_PASSWORD=replace_with_a_long_password
# At least 32 characters; login is disabled otherwise.
# CONSOLE_SESSION_SECRET=replace_with_32_plus_random_characters
# CHECKOUT_URL=http://localhost:3000
# --- Fiat pricing (products priced in EUR, GBP, ...) --------------------------
# Live ECB reference rates from a frankfurter service (lineofflight/frankfurter,
# MIT). Self-host it (docker image) and point FX_RATES_URL at it, or leave the
# public instance. Checkout fails closed when no valid rate is available.
# FX_RATES_URL=https://api.frankfurter.dev/v1
# FX_RATES_TTL_SECONDS=600
# --- Team invitations ----------------------------------------------------------
# Dashboard public URL used in invitation emails (/invite/<token>).
# DASHBOARD_PUBLIC_URL=https://dashboard.example.com
#
# --- Webhook delivery ------------------------------------------------------------
# Disable an endpoint after this many failed attempts in a row (worker).
# WEBHOOK_DISABLE_AFTER_FAILURES=100
# --- Cash out to a bank (off-ramp hand-off, no custody) -----------------------
# The dashboard Balances page opens a partner's sell flow with the amount,
# network and the merchant's own wallet prefilled. A partner shows only when
# its public key is set. Open the partner accounts first.
# TRANSAK_API_KEY=
# TRANSAK_ENV=staging # sandbox; omit for production
# MOONPAY_PUBLISHABLE_KEY=
# MOONPAY_SECRET_KEY= # signs sell URLs (server-side only)
# RAMP_HOST_API_KEY=
# --- Hosted storefront custom domains (apps/checkout) ------------------------
# This checkout's own hosts; "/" on any other host shows that domain's store.
# CHECKOUT_PRIMARY_HOSTS=pay.example.com,localhost

82
.github/workflows/release-sdks.yml vendored Normal file
View File

@ -0,0 +1,82 @@
# Publish the SettleKit SDKs when a tag like sdk-v0.1.0 is pushed.
#
# Needs repository secrets set by the owner:
# NPM_TOKEN npm automation token with publish rights on @settlekit
# CARGO_REGISTRY_TOKEN crates.io API token
# PyPI uses trusted publishing (configure the "settlekit" project on PyPI to
# trust this workflow); no token is stored.
# Go: the module path is github.com/settlekit/settlekit-go, so the Go SDK is
# released by mirroring sdks/go to that repository and tagging it there.
name: release-sdks
on:
push:
tags: ["sdk-v*"]
workflow_dispatch:
inputs:
dry_run:
description: "Build and pack without publishing"
type: boolean
default: true
permissions:
contents: read
jobs:
npm:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: pnpm
registry-url: https://registry.npmjs.org
- run: pnpm install --frozen-lockfile
- run: pnpm --filter @settlekit/common --filter @settlekit/sdk --filter @settlekit/react build
- run: pnpm vitest run packages/common packages/sdk packages/webhooks
- name: Publish (common first, then sdk and react)
if: ${{ github.event_name == 'push' || !inputs.dry_run }}
run: |
pnpm --filter @settlekit/common publish --access public --no-git-checks
pnpm --filter @settlekit/sdk --filter @settlekit/react publish --access public --no-git-checks
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Pack (dry run)
if: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run }}
run: pnpm --filter @settlekit/sdk --filter @settlekit/react --filter @settlekit/common pack
pypi:
runs-on: ubuntu-latest
permissions:
id-token: write
defaults:
run:
working-directory: sdks/python
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- run: python -m pip install build
- run: python -m build
- uses: pypa/gh-action-pypi-publish@release/v1
if: ${{ github.event_name == 'push' || !inputs.dry_run }}
with:
packages-dir: sdks/python/dist
crates:
runs-on: ubuntu-latest
defaults:
run:
working-directory: sdks/rust
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- run: cargo test
- run: cargo publish --dry-run
- run: cargo publish
if: ${{ github.event_name == 'push' || !inputs.dry_run }}
env:
CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}

37
.github/workflows/render-keepwarm.yml vendored Normal file
View File

@ -0,0 +1,37 @@
name: Render keep-warm pinger
# Keeps the free-tier Render rollback services warm so a rollback from the
# box-hosted api/checkout doesn't eat a 33-37s cold start on the first
# request. Pure keep-alive ping, no secrets, no deploy action.
# See plans/settlekit.md "Render pinger" task.
on:
schedule:
- cron: "*/20 * * * *"
workflow_dispatch: {}
jobs:
ping:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
service:
- { name: settlekit-web, path: / }
- { name: settlekit-api, path: /health }
- { name: settlekit-checkout, path: / }
- { name: settlekit-dashboard, path: / }
steps:
- name: Ping ${{ matrix.service.name }}
run: |
url="https://${{ matrix.service.name }}.onrender.com${{ matrix.service.path }}"
echo "Pinging $url"
code=$(curl -s -o /dev/null -w "%{http_code}" --max-time 45 --retry 2 --retry-delay 5 "$url" || echo "000")
echo "HTTP $code"
# Any response (even 404/401) proves the instance is awake; only a
# hard connection failure (000) is worth flagging, and even that
# should not fail the whole workflow - this is best-effort warmth,
# not an uptime monitor.
if [ "$code" = "000" ]; then
echo "::warning::$url did not respond (service may be sleeping, suspended, or renamed)"
fi

21
LICENSE Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 caelum0x
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

137
README.md
View File

@ -1,23 +1,64 @@
# SettleKit
> **SettleKit lets developers sell private repos, SaaS, APIs, templates, and AI tools in USDC — and automatically delivers access after payment.**
> **Get paid in stablecoins on any chain, by people or AI agents, and deliver access automatically.**
SettleKit is an open-source Commerce OS for software. Connect GitHub, create a
product, set a USDC price, and share your checkout link. SettleKit handles
payment verification, **access delivery**, subscriptions, license keys,
webhooks, and customer portals.
SettleKit is an open-source payment link and checkout for software sellers:
founders, small teams, app studios, and API or tool builders. Create a product,
set a USD price, share one link. Buyers pay on the chain they already use;
SettleKit verifies the transfer on-chain, fail closed, and delivers access the
moment it confirms: GitHub repo invites, license keys, API keys, Discord roles,
SaaS plans, files, and signed webhooks to your backend.
Sell private GitHub repos, SaaS subscriptions, API access, AI agent tools,
templates, datasets, license keys, and digital downloads — settled in USDC on
Arc, with automatic access delivery the moment a payment confirms.
| Network | Asset | Label |
| --- | --- | --- |
| Solana | USDC | Solana Pay + x402 agent payments |
| Ethereum, Base, Arbitrum | USDC | wallet checkout + x402 agent payments |
| Hyperliquid | USDC on HyperEVM, or `usdSend` to HyperCore | two separate balances |
| Robinhood Chain | USDG (Paxos), or $wif | no native USDC on mainnet; $wif is Permit2-only (experimental) |
| Tempo | USDC.e | bridged; MPP agent payments |
| Zcash | ZEC at a locked USD quote | transparent only, mainnet only |
- **Pay with any token** from another chain (Relay, LI.FI fallback); access is granted only after the destination transfer is verified.
- **AI agents buy directly** over x402 v2 (Solana, EVM chains) and MPP (Tempo) and get the product in the response.
- **Onchain subscriptions** (Permit2, Base spend permissions and commerce-payments escrow, SPL delegate, renewal invoices) and **refunds that send funds**.
- **Public proof**: every confirmed payment is listed at `/proof` with explorer links, mainnet and testnet kept apart.
- **1% per payment**, no fixed or monthly fee (`DEFAULT_FEE_SCHEDULE` in `packages/platform-billing`). Open source and self-hostable.
```text
Create product → Set price → Buyer pays → Access delivered
Create product -> Share link -> Buyer pays on any chain (or an agent pays) -> Verified on-chain -> Access delivered
```
### Colosseum Crypto World's Fair
SettleKit is entered in the Colosseum Crypto World's Fair (Sep 14 to Oct 12, 2026).
Work done in the window is `git diff pre-colosseum-baseline..HEAD` on
`feat/solana-colosseum`; everything up to tag `pre-colosseum-baseline`
(`7c6f6ce`, 2026-06-22) pre-exists and is disclosed.
| Doc | What's inside |
| --- | --- |
| [docs/colosseum/SUBMISSION.md](./docs/colosseum/SUBMISSION.md) | Problem, solution, chain matrix with honest labels, architecture, OSS composed, security model, business model, GTM, traction template, disclosure with in-window stats |
| [docs/colosseum/PITCH-SCRIPT.md](./docs/colosseum/PITCH-SCRIPT.md) | 2 to 3 minute pitch video script |
| [docs/colosseum/DEMO-SCRIPT.md](./docs/colosseum/DEMO-SCRIPT.md) | Demo video click path and required setup |
| [docs/colosseum/LAUNCH-CHECKLIST.md](./docs/colosseum/LAUNCH-CHECKLIST.md) | Owner steps to go live: Render, env, keys, first mainnet payment per chain |
### SettleKit Operator (Arc)
An autonomous business operator on Arc, built for the Tameion Agents Hackathon
(Canteen x Circle). Checkout revenue lands in an on-chain `OperatorVault`
(`contracts/src/OperatorVault.sol`), and a Claude agent allocates it, pays
vendors and handles refunds within on-chain caps. Anything outside those caps
is escalated to the owner, and every decision is hash-chained and anchored on
Arc. The code lives in `packages/operator`, `apps/operator-console`,
`/v1/operator/*` in `apps/api`, and the worker's operator tick. It is a no-op
unless `OPERATOR_VAULT_ADDRESS` or `OPERATOR_SIMULATION=1` is set.
See [TAMEION.md](./TAMEION.md) for the pitch, architecture, run guide and
disclosure, and [docs/tameion/](./docs/tameion/) for the plan.
---
## Demo
## Demo (pre-hackathon, Arc USDC)
<p align="center">
<a href="https://github.com/caelum0x/settlekit/releases/download/demo-2026-06-22/settlekit-demo.mp4">
@ -31,22 +72,69 @@ Create product → Set price → Buyer pays → Access delivered
---
## Hackathon demos (October 2026)
| Video | Length | For |
| --- | --- | --- |
| [settlekit-colosseum.mp4](https://github.com/caelum0x/settlekit/releases/download/hackathon-2026-10/settlekit-colosseum.mp4) | 2:18 | Colosseum Crypto World's Fair (Solana checkout, x402 agent payments) |
| [settlekit-tameion.mp4](https://github.com/caelum0x/settlekit/releases/download/hackathon-2026-10/settlekit-tameion.mp4) | 2:22 | Tameion Agents Hackathon (Arc operator, OperatorVault) |
Both were recorded on 2026-10-07 against the live deployment below, in testnet mode.
---
## Live deployment
SettleKit is live — API on Render, frontends on Vercel:
SettleKit runs on Render's free plan in **testnet mode**. Every service auto-deploys from `main`:
| Surface | URL |
| --- | --- |
| Marketing site | https://settlekit-web.vercel.app |
| Merchant dashboard | https://dashboard-neon-beta-80.vercel.app |
| Marketplace | https://settlekit-marketplace.vercel.app |
| Checkout | https://settlekit-checkout.vercel.app |
| Docs | https://settlekit-docs.vercel.app |
| API | https://settlekit-zym1.onrender.com |
| Marketing site, public proof, integration docs | https://settlekit-web.onrender.com (`/proof`, `/docs/integrate`) |
| API | https://settlekit-api.onrender.com (`/health`) — **currently down** (see note below) |
| Checkout (demo $1 link) | https://settlekit-checkout.vercel.app — **use this, not** the Render URL below |
| Checkout (Render, currently down) | https://settlekit-checkout.onrender.com/l/pro-templates-demo-417bacd7 |
| Merchant dashboard | https://settlekit-dashboard.onrender.com |
| Operator console (Arc) | https://settlekit-operator.onrender.com/proof |
> The API runs on Render's free tier and sleeps when idle, so the first request
> after a pause can take ~60s to wake. Frontends read the API URL from
> `NEXT_PUBLIC_API_URL`. Full setup in [docs/DEPLOYMENT.md](./docs/DEPLOYMENT.md).
> Free instances sleep when idle, so the first request after a pause takes
> about 40 to 80 seconds. **As of 2026-11-10, `settlekit-api.onrender.com` and
> `settlekit-checkout.onrender.com`'s checkout route time out entirely (not just a
> cold-start delay — confirmed with 20s+ and 90s+ live requests) because the API's
> `DATABASE_URL` has been unreachable since the free Render Postgres expired
> 2026-10-30; a code fix (bounded connect timeout, decoupled boot) shipped but the
> Render dashboard DB step itself is still outstanding.** Use
> `https://settlekit-checkout.vercel.app` and `https://settlekit-web.vercel.app`
> for a working checkout/marketing demo in the meantime — both return HTTP 200
> live. The demo checkout accepts Solana devnet USDC and Base, Arbitrum and
> Ethereum testnet USDC. The operator console shows "operator not configured"
> until a vault is attached (see [TAMEION.md](./TAMEION.md)). Full setup is in
> [docs/DEPLOYMENT.md](./docs/DEPLOYMENT.md).
### Status and traction (as of 2026-10-07)
These are the real numbers, so the hackathon submissions use them too.
| | |
| --- | --- |
| Tests | 2,152 vitest passing (3 skipped); 48 Foundry tests, 21 of them on `OperatorVault`; 181 operator-stack tests |
| Solana | A live checkout session returns a devnet Solana Pay URL with a server-built transaction |
| Arc | `OperatorVault` deploys and its caps and allowlist apply on an Arc testnet fork; the full USDC path runs on Arc testnet itself |
| Users and revenue | 0 mainnet payments, 0 external users, no revenue yet |
| Repo | 0 stars, 261 clones in the last 14 days |
### Arc mainnet (chain 5042)
`contracts/script/deploy-arc-mainnet.sh` deploys `OperatorVault` and
`SettleKitEscrow` to Arc mainnet and verifies them on Sourcify and Blockscout
in one command. It is not deployed yet. The expected cost is about 0.06 USDC.
```bash
cast wallet import settlekit-deployer --interactive # once; fund it with ~1 USDC on Arc
contracts/script/deploy-arc-mainnet.sh --account settlekit-deployer
```
`SettleKitCctpHook` must **not** be deployed to mainnet: under CCTP V2, funds
minted to it would be stuck. See [docs/tameion/MAINNET-BOUNTY.md](./docs/tameion/MAINNET-BOUNTY.md).
---
@ -232,10 +320,15 @@ closed per network. Full matrix with finality notes:
| Solana | USDC | mainnet, devnet | |
| Base, Ethereum, Arbitrum, HyperEVM | USDC | mainnet, testnet | |
| Robinhood Chain | USDG (mainnet), Mock USDC (testnet) | mainnet, testnet | no native USDC |
| Robinhood Chain ($wif) | $wif, 18 decimals | mainnet only | experimental, Permit2-only — see `docs/worldisflat/SUBMISSION.md` |
| Tempo | USDC.e (mainnet), pathUSD (testnet) | mainnet, testnet | bridged |
| Arc | USDC | testnet only | testnet |
| Zcash | ZEC at a locked USD quote | mainnet only | transparent, not shielded |
**World is Flat hackathon** (Robinhood Chain, $wif): full writeup, real on-chain proofs and an
honest demo video at [docs/worldisflat/SUBMISSION.md](./docs/worldisflat/SUBMISSION.md) —
[docs/worldisflat/media/settlekit-wif-demo.mp4](./docs/worldisflat/media/settlekit-wif-demo.mp4).
---
## Architecture overview
@ -323,4 +416,8 @@ repo conventions (ESM `.js` import suffixes, immutability, the
## License
Open source — self-host or use the hosted cloud.
## More from this account
- [Scribase](https://scribase.com) — hosted Postgres, one backend instead of stitching together Supabase + Neon + Clerk + Resend
- [Toolgate](https://toolgate.scribase.com) — one key for agent tools, pay only for what you call
- All repos: [git.ereboslab.com/caelum0x](https://git.ereboslab.com/caelum0x)

141
TAMEION.md Normal file
View File

@ -0,0 +1,141 @@
# SettleKit Operator: an autonomous business operator on Arc
Entry for the Tameion Agents Hackathon (Canteen x Circle, Arc). Branch `feat/tameion-arc`.
## Pitch
**RFB 4, Autonomous Business Operator (headline).** A small business sells in USDC on Arc through SettleKit checkout. The money lands in an `OperatorVault`, and a Claude agent runs the back office from there: it allocates every sale across operating float, tax reserve, yield sleeve and refund reserve, pays vendors and contractors, buys x402 services and handles refunds. Anything above a threshold, to an unknown payee, or flagged by screening goes to the human owner. Every decision is hash-chained and anchored on Arc, so anyone can check what the agent decided, why, and that the reasoning existed before the money moved.
- **RFB 2, AP/AR (workflow):** revenue in from checkout (AR), bills out (AP) through manual entry or pasted invoice text that Claude extracts. Unknown payees are escalated, never auto-paid.
- **RFB 1, Treasury (workflow):** policy-driven allocation, tax reserve the agent cannot spend, a minimum float, and a yield sleeve with a USYC adapter hook.
- **RFB 5, Screening:** every counterparty is screened with Circle's Compliance Engine plus `@settlekit/risk` rules on payment history. A screening outage is treated as unknown, not clean.
## How it works
```
checkout (Arc USDC) --> OperatorVault <-- agent (Circle DCW) --- Claude + tools
| |
on-chain caps off-chain policy
allowlist, TAX lock risk + compliance
Pending escalations <-- owner approve/reject (console)
|
DecisionAnchored(decisionHash) --> public /proof + /verify
```
### Three layers of policy
1. **Off-chain evaluate (agent side).** `packages/operator/src/policy.ts` `evaluate()` runs before any action: allowlist, per-payment and daily caps, bucket balance, TAX lock, minimum float, x402 daily budget, risk and compliance. Deny reasons are ordered exactly like the vault's checks, so the off-chain verdict predicts the on-chain revert. The off-chain policy may be stricter than the vault, never looser; `PUT /v1/operator/policy` refuses any drift from on-chain caps or allowlist.
2. **On-chain vault (Arc).** `contracts/src/OperatorVault.sol` enforces caps, the UTC-day spend window, the payee allowlist and the TAX lock no matter what the agent proposes. Payments above `escalateAbove` become `Pending` escalations that only the owner can approve (which executes) or reject. `pause()` is a kill switch.
3. **Human escalation.** Pending items reach the owner by email or Discord and in the console. They auto-expire after 72h and are recorded as rejected, with the reason logged.
### Hash-chained decision log
Each `DecisionRecord` (event, model, inputs digest, tool trace, policy verdict, rationale, alternatives considered, confidence, outcome, tx hashes, usage and cost, latency) is sha256-hashed over canonical JSON together with `prevHash`. Before execution the agent computes a **commitment hash** of its reasoning, and the vault emits `DecisionAnchored(decisionHash, action)` on every mutation. `GET /v1/public/operator/verify/:id` recomputes the chain and reads the anchor from the Arc receipt.
## Circle tools used
| Tool | Where |
| --- | --- |
| **USDC on Arc** (testnet, chain 5042002) | Checkout settlement, vault accounting, all agent payments (`packages/arc`, `OperatorVault`) |
| **Developer-Controlled Wallets, contract execution** | The agent's signer: vault calls go through Circle DCW `contractExecution` + transaction polling (`packages/operator/src/vault-transport.ts`, `packages/circle-wallets`). A viem signer is the fallback. |
| **Compliance Engine address screening** | Counterparty screening before payouts and refunds (`packages/operator/src/screening.ts`, `packages/compliance`) |
| **USYC (yield)** | `sweepToYield` / `redeemFromYield` through an owner-set `IYieldAdapter`. This is a hook: no adapter is deployed, and without one the vault reverts `YieldDisabled`. |
| **x402 via Circle wallets** | `buy_x402_service` settles from a Circle wallet (`@settlekit/x402-client`), within a daily budget |
| Paymaster | Not used by the operator. On Arc, gas is paid in USDC. |
## Repository map (Tameion delta)
- `contracts/src/OperatorVault.sol`, `contracts/test/OperatorVault.t.sol` (21 forge tests), `contracts/script/DeployOperator.s.sol`
- `packages/operator` (`@settlekit/operator`): policy, allocation, decision log, Claude agent and tools, heuristic engine, vault executor over Circle DCW or viem, escalations, bills, notifier, proof, verify, state, Pg and in-memory stores
- `apps/api/src/routes/operator.ts`: `/v1/operator/{events,decisions,bills,escalations,state,policy}` and public `/v1/public/operator/{proof,verify/:id}`
- `apps/worker/src/jobs/operator-tick-job.ts`: confirmed vault payments become `revenue.received`, due bills become `bill.due`, a daily `tick` runs, and stale escalations expire
- `apps/operator-console` (`@settlekit/operator-console`): owner console, public `/proof`, `/connect` onboarding
- `scripts/operator-arc-e2e.ts`: live Arc testnet end-to-end run
- `render.tameion.yaml`: Render blueprint (db, api, worker, console)
## Run locally
Use filtered installs only; never install the whole monorepo.
```bash
pnpm install --filter "@settlekit/api..." --filter "@settlekit/worker..." --filter @settlekit/operator-console
npx tsc -b packages/operator apps/api apps/worker
# API in labelled simulation (no chain), bootstrap key = owner
cd apps/api && API_BOOTSTRAP_KEY=dev-owner-key OPERATOR_SIMULATION=1 \
OPERATOR_ALLOWLIST=0xYourVendor node dist/server.js # :8787
# Console
cd apps/operator-console && OPERATOR_API_URL=http://localhost:8787 \
OPERATOR_CONSOLE_API_KEY=dev-owner-key CONSOLE_OWNER_PASSWORD=choose-one \
CONSOLE_SESSION_SECRET=$(openssl rand -hex 32) pnpm dev # :3009
```
For real on-chain operation, deploy the vault and set `OPERATOR_VAULT_ADDRESS` plus a signer (see `.env.example`, "Autonomous operator"):
```bash
cd contracts && OPERATOR_VAULT_OWNER=0xOwner OPERATOR_VAULT_OPERATOR=0xAgentDcw \
forge script script/DeployOperator.s.sol --rpc-url https://rpc.testnet.arc.network \
--private-key $DEPLOYER_KEY --broadcast
```
### Tests
```bash
cd contracts && forge test # OperatorVault and existing contracts
npx vitest run packages/operator # operator core
npx vitest run apps/api apps/worker # full API + worker suites
npx vitest run apps/operator-console # console logic + onboarding against the real API app
cd apps/operator-console && npx next build && rm -rf .next
```
### Live end-to-end on Arc testnet
`scripts/operator-arc-e2e.ts` runs a sale, allocation, a paid bill, an escalated bill, owner approval, and verification of every decision against `DecisionAnchored`. It moves testnet USDC, so it refuses to run without `LIVE=1`:
```bash
cd contracts && forge build && cd ..
LIVE=1 OWNER_PRIVATE_KEY=0x.. PAYER_PRIVATE_KEY=0x.. VENDOR_ADDRESS=0x.. \
OPERATOR_WALLET_ADDRESS=0x.. CIRCLE_API_KEY=.. CIRCLE_ENTITY_SECRET=.. \
ANTHROPIC_API_KEY=.. apps/api/node_modules/.bin/tsx scripts/operator-arc-e2e.ts
```
## Demo script (under 3 minutes)
1. **0:00 Problem (15s).** A small team gets paid in USDC but still does treasury, AP and refunds by hand.
2. **0:15 Sale (30s).** Open an Arc checkout link from `/connect` and pay with testnet USDC. The worker turns the confirmed payment into `revenue.received`, and the agent allocates it. Show the decision in `/decisions/[id]` with rationale, alternatives, policy verdict and tool trace.
3. **0:45 AP (30s).** Paste an invoice into `/bills`. Claude extracts it, and the allowlisted vendor is paid inside the caps. Open the Arcscan link.
4. **1:15 Guard rails (40s).** Add a bill above `escalateAbove`: the vault holds it as `Pending`. Add one to an unknown wallet: it is escalated off-chain. Approve one and reject the other in `/escalations`. Show `/policy` with on-chain vs off-chain values and the drift indicator.
5. **1:55 Proof (40s).** On the public `/proof` page, show orgs, counterparties, USDC in and out, outcomes including blocked by policy and blocked on-chain, median latency and cost per decision. Click "Verify on Arc" on a decision and show the `DecisionAnchored` event on Arcscan.
6. **2:35 Close (20s).** Circle tools used, what is next (USYC adapter, more teams), and the repo link.
## Traction (fill in before submission)
All figures are on Arc testnet and taken from `/proof`, which excludes the `demo` org.
| Metric | Value | Source |
| --- | --- | --- |
| External teams onboarded via `/connect` | _TBD_ | distinct orgs on /proof |
| Distinct counterparties | _TBD_ | /proof |
| USDC in / out (testnet) | _TBD_ | /proof |
| Decisions (executed / escalated / blocked by policy / blocked on-chain) | _TBD_ | /proof |
| Median decision latency | _TBD_ | /proof |
| Claude cost per decision | _TBD_ | /proof |
| Real vendor bills mirrored on testnet | _TBD_ | labelled "testnet mirror of real invoice" |
| Team quotes / feedback | _TBD_ | |
## Open-source components (all permissive)
Next.js (MIT), React (MIT), Hono (MIT), viem (MIT), zod (MIT), @anthropic-ai/sdk (MIT), Vitest (MIT), Foundry/forge tooling (MIT/Apache-2.0). The Solidity contracts have no third-party dependencies.
## Disclosure
- **Baseline.** Tag `pre-tameion-baseline` = `7c6f6ce` (2026-06-22), the state of SettleKit after the earlier Lepton entry. Only the delta counts for this hackathon:
```bash
git diff --stat pre-tameion-baseline..feat/tameion-arc
```
- **Not claimed as new (dependencies from the Lepton entry and earlier):** `packages/agent`, `packages/x402-client`, `packages/citation-toll`, `packages/streaming`, `packages/agent-economy`; contracts `LeptonStreamSettlement`, `RecursiveSplitDistributor`, `AgentReputationBond`; `apps/arc-fintech` (vendored Circle starter); and the existing SettleKit commerce stack (checkout, payments, treasury, risk, compliance, circle-wallets packages).
- **Shared security fixes.** Fail-closed payment confirmation (the API rejects confirmations on any network without an on-chain verifier; one tx hash can settle only one payment) and worker `payTo` verification were cherry-picked from the Colosseum (Solana) branch and are also part of that entry. On this branch the Solana parts are removed: a `solana` network is rejected as unsupported. They are disclosed as shared fixes, not Tameion features.
- **No Solana.** This entry does not include `packages/solana` or a Solana checkout.

View File

@ -187,6 +187,7 @@ const KNOWN_EVENT_TYPES = new Set<WebhookEventType>([
"entitlement.revoked",
"delivery.succeeded",
"delivery.failed",
"invoice.paid",
]);
function asEventType(value: string): WebhookEventType {

View File

@ -2,19 +2,22 @@
# Multi-stage build for the SettleKit API (@settlekit/api).
# Build context is the monorepo root: `docker build -f apps/api/Dockerfile .`
# ---- Base: Node 20 + pnpm via Corepack -------------------------------------
# ---- Base: Node 22 + pnpm via Corepack -------------------------------------
FROM node:22-alpine AS base
ENV PNPM_HOME=/pnpm
ENV PATH=$PNPM_HOME:$PATH
# Non-interactive build: lets the prod-deps `pnpm install --prod` purge the
# modules dir without a TTY prompt (ERR_PNPM_ABORTED_REMOVE_MODULES_DIR_NO_TTY).
ENV CI=true
RUN corepack enable
WORKDIR /app
# ---- Dependencies: install the full workspace (frozen) ---------------------
# ---- Dependencies: install only the api and its workspace deps (frozen) ----
FROM base AS deps
COPY package.json pnpm-workspace.yaml pnpm-lock.yaml tsconfig.base.json ./
COPY packages ./packages
COPY apps ./apps
RUN pnpm install --frozen-lockfile
RUN pnpm install --frozen-lockfile --filter settlekit --filter "@settlekit/api..."
# ---- Build: compile package deps + the api via tsc project references ------
FROM deps AS build
@ -44,4 +47,15 @@ COPY --from=prod-deps /app/apps/api/node_modules ./apps/api/node_modules
WORKDIR /app/apps/api
EXPOSE 8787
CMD ["node", "dist/server.js"]
# Apply pending migrations (idempotent), then serve. Render's preDeployCommand
# is paid-plan only, so the free API migrates on boot.
#
# The migration step is `||`, not `&&`: found 2026-11-10 that a stale/
# unreachable DATABASE_URL made migration hang (now bounded by
# packages/database's DEFAULT_CONNECT_TIMEOUT_SECONDS) and, with the old
# `&&` chain, a migration failure meant the server was never even attempted
# — one bad DB env var took down the whole container, including endpoints
# that don't need the database. Now the server always starts and reports
# its own real DB-connectivity error (fast, bounded, visible in logs)
# instead of the whole boot silently never finishing.
CMD ["sh", "-c", "if [ -n \"$DATABASE_URL\" ]; then node /app/packages/database/dist/cli.js || echo '[migrate] failed or timed out — starting the server anyway so non-DB endpoints still serve'; fi; exec node dist/server.js"]

View File

@ -46,22 +46,26 @@
"@settlekit/dunning": "workspace:*",
"@settlekit/entitlements": "workspace:*",
"@settlekit/escrow": "workspace:*",
"@settlekit/exports": "workspace:*",
"@settlekit/file-delivery": "workspace:*",
"@settlekit/gateway": "workspace:*",
"@settlekit/github": "workspace:*",
"@settlekit/hyperliquid": "workspace:*",
"@settlekit/invitations": "workspace:*",
"@settlekit/invoices": "workspace:*",
"@settlekit/license-keys": "workspace:*",
"@settlekit/marketplace-core": "workspace:*",
"@settlekit/notifications": "workspace:*",
"@settlekit/onchain": "workspace:*",
"@settlekit/onchain-billing": "workspace:*",
"@settlekit/operator": "workspace:*",
"@settlekit/oss-fund": "workspace:*",
"@settlekit/paymaster": "workspace:*",
"@settlekit/payments": "workspace:*",
"@settlekit/payouts": "workspace:*",
"@settlekit/persistence": "workspace:*",
"@settlekit/platform-billing": "workspace:*",
"@settlekit/pricing": "workspace:*",
"@settlekit/product-catalog": "workspace:*",
"@settlekit/rate-limits": "workspace:*",
"@settlekit/refunds": "workspace:*",

View File

@ -30,7 +30,9 @@ import {
} from "@settlekit/common";
import { DeliveryRunner, type DeliveryContext } from "@settlekit/delivery";
import { confirmPayment, recordPendingPayment } from "@settlekit/payments";
import { paymentConfirmedWebhook } from "@settlekit/persistence";
import type { AppContext } from "../context.js";
import { emitWebhook } from "../webhooks/outbox.js";
import { assertTxHashUnused, requireTxHash } from "../routes/payment-verification.js";
import { deliveryActionsFor } from "./delivery-action.js";
@ -196,6 +198,10 @@ export async function fulfilAgentPurchase(ctx: AppContext, input: AgentPurchaseI
...(input.price.creditsGranted !== undefined ? { creditsRemaining: input.price.creditsGranted } : {}),
});
const delivery = await runDelivery(ctx, input, payment, entitlement);
await emitWebhook(
ctx.webhookOutbox,
paymentConfirmedWebhook(payment, { productIds: [input.product.id], ...(customer.email ? { customerEmail: customer.email } : {}) }),
);
return {
payment,
entitlement,

View File

@ -0,0 +1,139 @@
/**
* Growth metrics for the merchant dashboard: checkout conversion, per-link
* performance, subscription churn and customer lifetime value. Pure: callers
* pass the org's sessions, payments, subscriptions and catalog. Money is exact
* (bigint base units); rates are fractions rounded to 4 decimals.
*/
import { fromBaseUnits, toBaseUnits, type CheckoutSession, type Payment, type Price, type Product, type Subscription } from "@settlekit/common";
export interface LinkStats {
productId: string;
name: string;
slug: string | null;
opened: number;
paid: number;
conversion: number;
revenue: string;
}
export interface GrowthMetrics {
windowDays: number;
checkouts: { opened: number; paid: number; conversion: number };
links: LinkStats[];
revenue: { window: string; allTime: string };
customers: { paying: number; repeat: number; repeatRate: number };
/** Average all-time revenue per paying customer. */
averageRevenuePerCustomer: string;
subscriptions: {
active: number;
churned: number;
churnRate: number;
/** Average monthly revenue per active subscription. */
arpu: string;
/** arpu / monthly churn, null while no subscription has churned. */
estimatedLifetimeValue: string | null;
};
}
const DAY_MS = 86_400_000;
function rate(part: number, whole: number): number {
return whole === 0 ? 0 : Math.round((part / whole) * 10_000) / 10_000;
}
function sum(payments: readonly Payment[]): bigint {
return payments.reduce((acc, p) => acc + toBaseUnits(p.amount.amount), 0n);
}
export interface MetricsInput {
sessions: readonly CheckoutSession[];
/** Confirmed (and refunded) payments of the org, all time. */
payments: readonly Payment[];
subscriptions: readonly Subscription[];
products: readonly Product[];
prices: readonly Price[];
now: Date;
days: number;
}
export function computeGrowthMetrics(input: MetricsInput): GrowthMetrics {
const start = input.now.getTime() - input.days * DAY_MS;
const confirmed = input.payments.filter((p) => p.status === "confirmed");
const inWindow = confirmed.filter((p) => Date.parse(p.confirmedAt ?? p.createdAt) >= start);
const paidSessionIds = new Set(confirmed.map((p) => p.checkoutSessionId));
const sessions = input.sessions.filter((s) => Date.parse(s.createdAt) >= start && s.invoiceId === undefined);
const paidSessions = sessions.filter((s) => s.status === "completed" || paidSessionIds.has(s.id));
// Per payment link (first line's product).
const byProduct = new Map<string, { opened: number; paid: number; revenue: bigint }>();
const revenueBySession = new Map<string, bigint>();
for (const p of confirmed) revenueBySession.set(p.checkoutSessionId, (revenueBySession.get(p.checkoutSessionId) ?? 0n) + toBaseUnits(p.amount.amount));
for (const s of sessions) {
const productId = s.lineItems[0]?.productId;
if (!productId) continue;
const row = byProduct.get(productId) ?? { opened: 0, paid: 0, revenue: 0n };
row.opened += 1;
if (s.status === "completed" || paidSessionIds.has(s.id)) {
row.paid += 1;
row.revenue += revenueBySession.get(s.id) ?? 0n;
}
byProduct.set(productId, row);
}
const productsById = new Map(input.products.map((p) => [p.id, p]));
const links: LinkStats[] = [...byProduct.entries()]
.map(([productId, row]) => {
const product = productsById.get(productId);
const slug = product?.metadata.paymentLinkSlug;
return {
productId,
name: product?.name ?? productId,
slug: typeof slug === "string" ? slug : null,
opened: row.opened,
paid: row.paid,
conversion: rate(row.paid, row.opened),
revenue: fromBaseUnits(row.revenue),
};
})
.sort((a, b) => b.opened - a.opened);
// Customers.
const perCustomer = new Map<string, number>();
for (const p of confirmed) perCustomer.set(p.customerId, (perCustomer.get(p.customerId) ?? 0) + 1);
const paying = perCustomer.size;
const repeat = [...perCustomer.values()].filter((n) => n >= 2).length;
const allTime = sum(confirmed);
// Subscriptions: churn over the window, ARPU and a simple LTV estimate.
const pricesById = new Map(input.prices.map((p) => [p.id, p]));
const active = input.subscriptions.filter((s) => s.status === "active" || s.status === "past_due" || s.status === "in_grace");
const churned = input.subscriptions.filter(
(s) => (s.status === "canceled" || s.status === "expired") && Date.parse(s.currentPeriodEnd) >= start && Date.parse(s.currentPeriodEnd) <= input.now.getTime(),
);
let mrr = 0n;
for (const s of active) {
const price = pricesById.get(s.priceId);
if (!price) continue;
const base = toBaseUnits(price.amount);
mrr += price.interval === "yearly" ? base / 12n : base;
}
const churnRate = rate(churned.length, active.length + churned.length);
const arpu = active.length === 0 ? 0n : mrr / BigInt(active.length);
const monthlyChurn = churnRate === 0 ? 0 : Math.min(1, (churnRate * 30) / input.days);
const ltv = monthlyChurn === 0 ? null : fromBaseUnits(BigInt(Math.round(Number(arpu) / monthlyChurn)));
return {
windowDays: input.days,
checkouts: { opened: sessions.length, paid: paidSessions.length, conversion: rate(paidSessions.length, sessions.length) },
links,
revenue: { window: fromBaseUnits(sum(inWindow)), allTime: fromBaseUnits(allTime) },
customers: { paying, repeat, repeatRate: rate(repeat, paying) },
averageRevenuePerCustomer: paying === 0 ? "0" : fromBaseUnits(allTime / BigInt(paying)),
subscriptions: {
active: active.length,
churned: churned.length,
churnRate,
arpu: fromBaseUnits(arpu),
estimatedLifetimeValue: ltv,
},
};
}

View File

@ -45,6 +45,9 @@ import { x402Routes } from "./routes/x402.js";
import { escrowRoutes } from "./routes/escrow.js";
import { couponRoutes } from "./routes/coupons.js";
import { invoiceRoutes } from "./routes/invoices.js";
import { billingRoutes } from "./routes/billing.js";
import { exportRoutes } from "./routes/exports.js";
import { teamRoutes } from "./routes/team.js";
import { refundRoutes } from "./routes/refunds.js";
import { dunningRoutes } from "./routes/dunning.js";
import { disputeRoutes } from "./routes/disputes.js";
@ -61,9 +64,12 @@ import { onchainEscrowRoutes } from "./routes/onchain-escrow.js";
import { authRoutes } from "./routes/auth.js";
import { leptonRoutes } from "./routes/lepton.js";
import { fundRoutes } from "./routes/fund.js";
import { merchantRoutes } from "./routes/merchant.js";
import { publicRoutes } from "./routes/public.js";
import { x402AgentRoutes } from "./routes/x402-agent.js";
import { mppTempoRoutes } from "./routes/mpp-tempo.js";
import { onchainBillingRoutes } from "./routes/onchain-billing.js";
import { operatorRoutes } from "./routes/operator.js";
/** Build the full SettleKit API app. Pass a context to share/isolate state. */
export function createApp(ctx: AppContext): Hono<AppEnv> {
@ -134,6 +140,11 @@ export function createApp(ctx: AppContext): Hono<AppEnv> {
// signature (verified in the handler), not an API key. Mounted outside the
// v1 api-key guard. POST /v1/circle/webhooks.
app.route("/v1/circle", circleWebhookRoutes());
app.route("/", operatorRoutes()); // /v1/operator/* (own API-key guard) + /v1/public/operator/*
// Payment links + public proof are PUBLIC: buyers open checkout sessions
// from a seller's link, visitors read settled on-chain payments.
app.route("/v1/public", publicRoutes());
// Everything else under /v1 requires a valid Bearer API key.
const v1 = new Hono<AppEnv>();
@ -186,8 +197,13 @@ export function createApp(ctx: AppContext): Hono<AppEnv> {
// ---- Onboarding (merchant activation funnel) ---------------------------
v1.route("/onboarding", onboardingRoutes());
// ---- Merchant workspace (dashboard onboarding, payments, payouts) -------
v1.route("/merchant", merchantRoutes());
// ---- Organization settings ---------------------------------------------
v1.route("/settings", settingsRoutes());
// Team members, roles and invitations.
v1.route("/team", teamRoutes());
// ---- Escrow (plan §26) -------------------------------------------------
v1.route("/escrow", escrowRoutes());
@ -195,6 +211,10 @@ export function createApp(ctx: AppContext): Hono<AppEnv> {
// ---- Commerce engines: coupons + invoices ------------------------------
v1.route("/coupons", couponRoutes());
v1.route("/invoices", invoiceRoutes());
// SettleKit's own fee statements for this merchant (platform revenue).
v1.route("/billing", billingRoutes());
// Accounting exports (CSV, Xero / QuickBooks bank statement imports).
v1.route("/exports", exportRoutes());
// ---- Commerce engines: refunds, dunning, disputes, payouts -------------
v1.route("/refunds", refundRoutes());

View File

@ -43,6 +43,7 @@ import {
export type { PaymentVerifiers, ZcashRuntime } from "./verifier-registry.js";
import {
buildDiscordClient,
createDeliveryClients,
type DeliveryGrantSink,
} from "../wiring/delivery-clients.js";
@ -180,11 +181,15 @@ export function buildIntegrations(
: {}),
});
} else {
deliveryClients = createInMemoryDeliveryClients({
const inMemory = createInMemoryDeliveryClients({
licenseTokenSecret: config.licenseTokenSecret,
fileDelivery: config.fileDelivery,
...sharedStores,
});
// A configured Discord bot grants real roles even before GitHub is set up.
deliveryClients = config.discord
? { ...inMemory, discord: buildDiscordClient({ discordApi, grants: options.grantSink ?? createInMemoryGrantSink() }) }
: inMemory;
}
const arcClient = config.arc

View File

@ -170,6 +170,9 @@ import type { DeliveryGrantSink } from "./wiring/delivery-clients.js";
import { loadAgentPayments, type AgentPaymentsRuntime } from "./agent-payments/config.js";
import type { OnchainBillingRuntime } from "@settlekit/onchain-billing";
import { buildApiOnchainBilling } from "./onchain-billing/runtime.js";
import { createWebhookJobStore, createWebhookOutbox } from "./webhooks/outbox.js";
import { createFrankfurterSource, type FxRateSource } from "./fx/rates.js";
import type { WebhookJobStore, WebhookOutbox } from "@settlekit/persistence";
/** The fully-wired set of services + stores shared across requests. */
export interface AppContext {
@ -194,6 +197,10 @@ export interface AppContext {
readonly deliveryClients: DeliveryClients;
readonly webhookEndpoints: EntityStore<WebhookEndpoint>;
readonly webhookEvents: EntityStore<WebhookEvent>;
/** Signed seller webhooks (payment / subscription / refund events). */
readonly webhookOutbox: WebhookOutbox;
/** Per-endpoint delivery log (attempts, retries, resends). */
readonly webhookJobs: WebhookJobStore;
// Access / key services.
readonly apiKeys: ApiKeyService;
@ -300,6 +307,8 @@ export interface AppContext {
readonly agentPayments: AgentPaymentsRuntime | null;
/** Onchain subscriptions, Base escrow and per-network refunds; null when unconfigured. */
readonly onchainBilling: OnchainBillingRuntime | null;
/** Live FX rates for fiat-priced products (frankfurter, ECB rates). */
readonly fxRates: FxRateSource;
}
/** Pick the Postgres implementation when `db` is set, else the in-memory one. */
@ -411,6 +420,10 @@ export async function createContext(): Promise<AppContext> {
...(process.env.MERCHANT_WEBSITE ? { website: process.env.MERCHANT_WEBSITE } : {}),
};
const webhookEndpointStore = pick<EntityStore<WebhookEndpoint>>(db, (d) => new PgWebhookEndpointStore(d), () => new InMemoryEntityStore<WebhookEndpoint>());
const webhookEventStore = pick<EntityStore<WebhookEvent>>(db, (d) => new PgWebhookEventStore(d), () => new InMemoryEntityStore<WebhookEvent>());
const webhookJobs = createWebhookJobStore(db);
const base: Omit<AppContext, "onchainBilling"> = {
db,
persistent: db !== null,
@ -427,8 +440,10 @@ export async function createContext(): Promise<AppContext> {
deliveryRuns: pick<EntityStore<DeliveryRun>>(db, (d) => new PgDeliveryRunStore(d), () => new InMemoryEntityStore<DeliveryRun>()),
deliveryRegistry: createDefaultRegistry(),
deliveryClients: integrations.deliveryClients,
webhookEndpoints: pick<EntityStore<WebhookEndpoint>>(db, (d) => new PgWebhookEndpointStore(d), () => new InMemoryEntityStore<WebhookEndpoint>()),
webhookEvents: pick<EntityStore<WebhookEvent>>(db, (d) => new PgWebhookEventStore(d), () => new InMemoryEntityStore<WebhookEvent>()),
webhookEndpoints: webhookEndpointStore,
webhookEvents: webhookEventStore,
webhookJobs,
webhookOutbox: createWebhookOutbox(db, webhookEndpointStore, webhookEventStore, webhookJobs),
apiKeys: new ApiKeyService(apiKeyStore),
licenses: new LicenseService(licenseStore, { tokenSecret: config.licenseTokenSecret }),
@ -557,6 +572,10 @@ export async function createContext(): Promise<AppContext> {
payoutStore,
platformFeeSchedule,
agentPayments: loadAgentPayments(process.env, db ? { nonceStore: new PgX402NonceStore(db) } : {}),
fxRates: createFrankfurterSource({
...(process.env.FX_RATES_URL ? { baseUrl: process.env.FX_RATES_URL } : {}),
...(process.env.FX_RATES_TTL_SECONDS ? { ttlMs: Number(process.env.FX_RATES_TTL_SECONDS) * 1000 } : {}),
}),
};
return { ...base, onchainBilling: await buildApiOnchainBilling(base) };
}
@ -568,5 +587,9 @@ export interface AppEnv {
apiKeyId?: string;
/** Organization the authenticated API key belongs to (tenant scope). */
organizationId?: string;
/** Team role of a dashboard session (absent for API keys). */
teamRole?: string;
/** Scopes the caller holds (API key scopes, or the session role's). */
grantedScopes?: readonly string[];
};
}

77
apps/api/src/fx/rates.ts Normal file
View File

@ -0,0 +1,77 @@
/**
* Live FX rates for fiat-priced products, from a frankfurter service
* (lineofflight/frankfurter, MIT; ECB reference rates). Self-host it and set
* FX_RATES_URL, or use the public instance by default. Rates are cached per
* currency for FX_RATES_TTL_SECONDS (default 600) and sanity-checked; a
* missing or implausible rate fails closed.
*/
import { SettleKitError, formatRate, type FiatCurrency } from "@settlekit/common";
export interface FxRate {
/** USD per 1 unit of the currency. */
rate: string;
/** Publication date (YYYY-MM-DD). */
date: string;
source: string;
}
export interface FxRateSource {
usdPer(currency: FiatCurrency): Promise<FxRate>;
}
export interface FrankfurterOptions {
baseUrl?: string;
ttlMs?: number;
fetch?: typeof fetch;
now?: () => number;
}
const DEFAULT_URL = "https://api.frankfurter.dev/v1";
function unavailable(currency: string, why: string): SettleKitError {
return new SettleKitError({
code: "integration_error",
message: `Prices in ${currency} are temporarily unavailable (${why}). Try again shortly.`,
httpStatus: 503,
retryable: true,
});
}
export function createFrankfurterSource(options: FrankfurterOptions = {}): FxRateSource {
const baseUrl = (options.baseUrl ?? DEFAULT_URL).replace(/\/+$/, "");
const ttlMs = options.ttlMs ?? 600_000;
const doFetch = options.fetch ?? fetch;
const now = options.now ?? Date.now;
const cache = new Map<string, { at: number; value: FxRate }>();
async function fetchLatest(currency: string): Promise<{ date?: unknown; rates?: Record<string, unknown> } | null> {
try {
const res = await doFetch(`${baseUrl}/latest?base=${encodeURIComponent(currency)}&symbols=USD`, {
headers: { accept: "application/json" },
signal: AbortSignal.timeout(5_000),
});
if (!res.ok) throw unavailable(currency, `rate service answered ${res.status}`);
return (await res.json()) as { date?: unknown; rates?: Record<string, unknown> } | null;
} catch (error) {
if (error instanceof SettleKitError) throw error;
throw unavailable(currency, "rate service unreachable");
}
}
return {
async usdPer(currency) {
if (currency === "USD") return { rate: "1", date: new Date(now()).toISOString().slice(0, 10), source: "USDC par" };
const hit = cache.get(currency);
if (hit && now() - hit.at < ttlMs) return hit.value;
const body = await fetchLatest(currency);
const raw = body?.rates?.USD;
const date = typeof body?.date === "string" && /^\d{4}-\d{2}-\d{2}$/.test(body.date) ? body.date : null;
if (typeof raw !== "number" || !(raw > 0.000001 && raw < 1_000_000) || !date) {
throw unavailable(currency, "no valid rate");
}
const value: FxRate = { rate: formatRate(raw), date, source: "ECB via frankfurter" };
cache.set(currency, { at: now(), value });
return value;
},
};
}

View File

@ -0,0 +1,74 @@
/**
* Lock a live FX rate on a checkout session for fiat-priced lines. The line
* prices are converted to USDC before totals, promo and tax are computed,
* so the session amount (what onchain verification expects) is in USDC and
* the quote holds for the session lifetime.
*/
import {
fiatToUsdc,
fromBaseUnits,
toBaseUnits,
isFiatCurrency,
toIso,
validationError,
type FxQuote,
type Price,
} from "@settlekit/common";
import type { PricedLineItem } from "@settlekit/payments";
import type { FxRateSource } from "./rates.js";
export interface FxPricing {
items: PricedLineItem[];
quote?: FxQuote;
}
/** Whether a price is set in a fiat currency other than USD. */
export function isFiatPrice(price: Price): boolean {
return price.displayCurrency !== undefined && price.displayAmount !== undefined && price.displayCurrency !== "USD";
}
/**
* Convert fiat-priced lines to USDC at one live rate. All fiat lines of a
* session must share a currency (USDC-priced lines are left as they are).
*/
export async function lockFx(
rates: FxRateSource,
items: readonly PricedLineItem[],
expiresAt: string,
now: Date = new Date(),
): Promise<FxPricing> {
const fiat = items.filter((i) => isFiatPrice(i.price));
if (fiat.length === 0) return { items: [...items] };
const currencies = new Set(fiat.map((i) => i.price.displayCurrency!));
if (currencies.size > 1) throw validationError("items priced in different currencies cannot share one checkout");
const currency = [...currencies][0]!;
if (!isFiatCurrency(currency)) throw validationError(`unsupported price currency: ${currency}`);
const { rate, date, source } = await rates.usdPer(currency);
let fiatTotal = 0n;
let usdcTotal = 0n;
const converted = items.map((item) => {
if (!isFiatPrice(item.price)) return item;
const unit = fiatToUsdc(item.price.displayAmount!, rate);
const qty = BigInt(item.lineItem.quantity);
fiatTotal += toBaseUnits(item.price.displayAmount!) * qty;
usdcTotal += toBaseUnits(unit) * qty;
return { ...item, price: { ...item.price, amount: unit } };
});
const quote: FxQuote = {
currency,
amount: fromBaseUnits(fiatTotal),
rate,
usdcAmount: fromBaseUnits(usdcTotal),
source,
rateDate: date,
lockedAt: toIso(now),
expiresAt,
};
return { items: converted, quote };
}
/** Attach the locked quote to a drafted session (valid until it expires). */
export function withFx<T extends { expiresAt: string }>(session: T, quote: FxQuote | undefined): T & { fxQuote?: FxQuote } {
return quote ? { ...session, fxQuote: { ...quote, expiresAt: session.expiresAt } } : session;
}

View File

@ -47,9 +47,18 @@ export function error(c: Context, err: unknown): Response {
err.httpStatus as ContentfulStatusCode,
);
}
const message = err instanceof Error ? err.message : "Unexpected error";
const detail = err instanceof Error ? err.message : "Unexpected error";
if (process.env.NODE_ENV !== "production") {
return c.json<ErrorEnvelope>({ error: { code: "internal_error", message: detail } }, 500);
}
// Production: never echo internals (SQL, parameters, stack) to the caller.
// The detail goes to the server log, keyed by the request id.
const requestId = c.res.headers.get("x-request-id") ?? c.req.header("x-request-id") ?? null;
process.stderr.write(
`${JSON.stringify({ ts: new Date().toISOString(), app: "api", level: "error", msg: "unhandled error", method: c.req.method, path: c.req.path, requestId, error: detail })}\n`,
);
return c.json<ErrorEnvelope>(
{ error: { code: "internal_error", message } },
{ error: { code: "internal_error", message: "Something went wrong on our side. Please try again." } },
500,
);
}

View File

@ -0,0 +1,156 @@
/**
* Live on-chain balances of the merchant's receiving addresses.
*
* SettleKit never holds merchant funds: buyers pay straight into the
* merchant's own wallets. "Payouts" is therefore a read of what already sits
* in those wallets, per network, straight from each chain:
* - EVM chains: ERC-20 `balanceOf` on the registry stablecoin via JSON-RPC.
* - Solana: USDC token accounts owned by the address.
* - HyperCore: withdrawable USDC in the Hyperliquid account.
* - Zcash: transparent address balance from Blockchair (mainnet only).
* Each read is independent and time-boxed; a failing RPC yields an error row
* rather than failing the page.
*/
import type { PaymentNetwork } from "@settlekit/common";
import { getEvmChain, type EvmChainKey } from "@settlekit/chains";
import { apiConfig, balanceEndpoints, networkInfo } from "./network-catalog.js";
export interface NetworkBalance {
network: PaymentNetwork;
address: string;
asset: string;
/** Decimal string in whole units (e.g. "12.50"), null when unreadable. */
balance: string | null;
env: "mainnet" | "testnet";
error?: string;
addressUrl: string | null;
}
const TIMEOUT_MS = 8_000;
const BALANCE_OF = "0x70a08231";
async function postJson(url: string, body: unknown, headers: Record<string, string> = {}): Promise<unknown> {
const res = await fetch(url, {
method: "POST",
headers: { "content-type": "application/json", ...headers },
body: JSON.stringify(body),
signal: AbortSignal.timeout(TIMEOUT_MS),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
/** Format integer base units as a decimal string with `decimals` places. */
export function formatUnits(raw: bigint, decimals: number): string {
const negative = raw < 0n;
const abs = negative ? -raw : raw;
const base = 10n ** BigInt(decimals);
const whole = abs / base;
const fraction = (abs % base).toString().padStart(decimals, "0").replace(/0+$/, "");
const shown = fraction.length > 0 ? `${whole}.${fraction}` : `${whole}`;
return negative ? `-${shown}` : shown;
}
async function evmBalance(key: EvmChainKey, address: string): Promise<string> {
const cfg = apiConfig();
const runtime = cfg.evm.enabled[key];
const spec = runtime?.spec ?? getEvmChain(key, cfg.evm.env);
if (!spec) throw new Error("chain not in registry");
const rpcUrl = runtime?.rpcUrl ?? spec.defaultRpcUrl;
const token = runtime?.tokenAddress ?? spec.token.address;
const data = `${BALANCE_OF}${address.toLowerCase().replace(/^0x/, "").padStart(64, "0")}`;
const body = (await postJson(rpcUrl, {
jsonrpc: "2.0",
id: 1,
method: "eth_call",
params: [{ to: token, data }, "latest"],
})) as { result?: string; error?: { message?: string } };
if (!body.result) throw new Error(body.error?.message ?? "empty eth_call result");
return formatUnits(BigInt(body.result === "0x" ? "0x0" : body.result), spec.token.decimals);
}
async function solanaBalance(address: string): Promise<string> {
const { rpcUrl, mint } = balanceEndpoints().solana;
const body = (await postJson(rpcUrl, {
jsonrpc: "2.0",
id: 1,
method: "getTokenAccountsByOwner",
params: [address, { mint }, { encoding: "jsonParsed" }],
})) as {
result?: { value?: { account?: { data?: { parsed?: { info?: { tokenAmount?: { amount?: string } } } } } }[] };
error?: { message?: string };
};
if (!body.result) throw new Error(body.error?.message ?? "empty RPC result");
const total = (body.result.value ?? []).reduce((sum, entry) => {
const amount = entry.account?.data?.parsed?.info?.tokenAmount?.amount;
return sum + (amount && /^\d+$/.test(amount) ? BigInt(amount) : 0n);
}, 0n);
return formatUnits(total, 6);
}
async function hyperCoreBalance(address: string): Promise<string> {
const { apiUrl } = balanceEndpoints().hypercore;
const body = (await postJson(`${apiUrl}/info`, { type: "clearinghouseState", user: address })) as {
withdrawable?: string;
};
if (typeof body.withdrawable !== "string") throw new Error("no withdrawable balance in response");
return body.withdrawable;
}
async function zcashBalance(address: string): Promise<string> {
const { explorerUrl, network, apiKey } = balanceEndpoints().zcash;
if (network !== "mainnet") throw new Error("Zcash balance reads are mainnet only");
const url = `${explorerUrl.replace(/\/+$/, "")}/dashboards/address/${encodeURIComponent(address)}${apiKey ? `?key=${encodeURIComponent(apiKey)}` : ""}`;
const res = await fetch(url, { signal: AbortSignal.timeout(TIMEOUT_MS) });
if (!res.ok) throw new Error(`explorer HTTP ${res.status}`);
const body = (await res.json()) as { data?: Record<string, { address?: { balance?: number | string } }> };
const balance = body.data?.[address]?.address?.balance;
if (balance === undefined) throw new Error("address not found in explorer response");
return formatUnits(BigInt(String(balance)), 8);
}
function addressUrl(network: PaymentNetwork, address: string, env: "mainnet" | "testnet"): string | null {
switch (network) {
case "solana":
return `https://solscan.io/account/${address}${env === "testnet" ? "?cluster=devnet" : ""}`;
case "hypercore":
return `https://app.hyperliquid${env === "testnet" ? "-testnet" : ""}.xyz/explorer/address/${address}`;
case "zcash":
return env === "mainnet" ? `https://blockchair.com/zcash/address/${address}` : null;
default: {
const spec = getEvmChain(network as EvmChainKey, env);
const tx = spec?.explorerTx("0x");
return tx ? tx.replace(/\/tx\/0x$/, `/address/${address}`) : null;
}
}
}
async function readOne(network: PaymentNetwork, address: string): Promise<string> {
switch (network) {
case "solana":
return solanaBalance(address);
case "hypercore":
return hyperCoreBalance(address);
case "zcash":
return zcashBalance(address);
default:
return evmBalance(network as EvmChainKey, address);
}
}
/** Read every accepted network's balance in parallel. */
export async function readBalances(payToByNetwork: Partial<Record<PaymentNetwork, string>>): Promise<NetworkBalance[]> {
const entries = Object.entries(payToByNetwork) as [PaymentNetwork, string][];
return Promise.all(
entries.map(async ([network, address]): Promise<NetworkBalance> => {
const info = networkInfo(network);
const env = info?.env ?? "mainnet";
const base = { network, address, asset: info?.asset ?? "USDC", env, addressUrl: addressUrl(network, address, env) };
try {
return { ...base, balance: await readOne(network, address) };
} catch (err) {
return { ...base, balance: null, error: err instanceof Error ? err.message : "balance read failed" };
}
}),
);
}

View File

@ -0,0 +1,95 @@
/**
* Merchant customer list: everyone who paid (from payments + the checkout
* fields they filled in) merged with explicitly created customers, each with
* lifetime spend and the entitlements (access) they hold.
*/
import type { Entitlement } from "@settlekit/common";
import type { AppContext } from "../context.js";
import { buildPaymentViews } from "./payment-views.js";
export interface CustomerView {
id: string;
email: string | null;
githubUsername: string | null;
discordUserId: string | null;
wallet: string | null;
payments: number;
spentUsd: string;
firstSeen: string;
lastPaid: string | null;
networks: string[];
entitlements: Pick<Entitlement, "id" | "productId" | "entitlementType" | "status" | "createdAt" | "expiresAt">[];
}
function addUsd(a: string, b: string): string {
const cents = (v: string): bigint => {
const [w = "0", f = ""] = v.split(".");
return BigInt(w) * 100n + BigInt((f + "00").slice(0, 2));
};
const t = cents(a) + cents(b);
return `${t / 100n}.${(t % 100n).toString().padStart(2, "0")}`;
}
export async function listCustomers(ctx: AppContext, organizationId: string): Promise<CustomerView[]> {
const payments = await ctx.payments.listByOrganization(organizationId);
const views = await buildPaymentViews(ctx, payments);
const stored = await ctx.customers.list((c) => c.organizationId === organizationId);
const byId = new Map<string, CustomerView>();
for (const c of stored) {
byId.set(c.id, {
id: c.id,
email: c.email || null,
githubUsername: c.githubUsername ?? null,
discordUserId: c.discordUserId ?? null,
wallet: c.walletAddress ?? null,
payments: 0,
spentUsd: "0.00",
firstSeen: c.createdAt,
lastPaid: null,
networks: [],
entitlements: [],
});
}
for (const v of views) {
const prev = byId.get(v.buyer.customerId);
const paid = v.status === "confirmed";
const next: CustomerView = {
id: v.buyer.customerId,
email: prev?.email ?? v.buyer.email,
githubUsername: prev?.githubUsername ?? v.buyer.githubUsername,
discordUserId: prev?.discordUserId ?? v.buyer.discordUserId,
wallet: prev?.wallet ?? v.buyer.wallet,
payments: (prev?.payments ?? 0) + (paid ? 1 : 0),
spentUsd: paid ? addUsd(prev?.spentUsd ?? "0.00", v.amountUsd) : prev?.spentUsd ?? "0.00",
firstSeen: prev && prev.firstSeen < v.createdAt ? prev.firstSeen : v.createdAt,
lastPaid:
paid && (!prev?.lastPaid || (v.confirmedAt ?? v.createdAt) > prev.lastPaid)
? v.confirmedAt ?? v.createdAt
: prev?.lastPaid ?? null,
networks: [...new Set([...(prev?.networks ?? []), v.networkName])],
entitlements: [],
};
byId.set(next.id, next);
}
const withAccess = await Promise.all(
[...byId.values()].map(async (c) => {
const ents = (await ctx.entitlementRepo.listByCustomer(c.id)).filter((e) => e.organizationId === organizationId);
return {
...c,
entitlements: ents.map(({ id, productId, entitlementType, status, createdAt, expiresAt }) => ({
id,
productId,
entitlementType,
status,
createdAt,
...(expiresAt !== undefined ? { expiresAt } : {}),
})),
};
}),
);
return withAccess
.filter((c) => c.payments > 0 || c.entitlements.length > 0 || stored.some((s) => s.id === c.id))
.sort((a, b) => (b.lastPaid ?? b.firstSeen).localeCompare(a.lastPaid ?? a.firstSeen));
}

View File

@ -0,0 +1,348 @@
/**
* Payable invoices and payment requests.
*
* `send` issues the invoice, binds an unguessable public token (the client's
* pay page at `<checkout>/i/<token>`), opens a checkout session for the
* invoice total on the merchant's networks, and emails the link. The session
* is a normal checkout session (same on-chain verification, same Solana Pay
* reference / Zcash quote bindings), bought against a hidden per-invoice
* product so the hosted checkout renders and settles it unchanged.
*
* The invoice is marked paid only when a CONFIRMED payment exists for one of
* its sessions ({@link reconcileInvoiceWithPayments}), which the API runs on
* read and the worker's invoice-settle job runs on a schedule.
*/
import {
generateId,
generateSecret,
notFound,
validationError,
type CheckoutSession,
type Payment,
type Price,
type Product,
} from "@settlekit/common";
import { cancelSession, createCheckoutSession, isSessionExpired } from "@settlekit/payments";
import {
checkoutSessionIdsOf,
finalizeInvoice,
latestCheckoutSessionId,
payTokenOf,
reconcileInvoice,
unpayableReason,
withCheckoutSession,
withPayToken,
withPayerEmail,
PAYER_EMAIL_KEY,
type Invoice,
type InvoiceSettlement,
type Merchant,
} from "@settlekit/invoices";
import { emitWebhookSafely, invoicePaidWebhook } from "@settlekit/persistence";
import type { AppContext } from "../context.js";
import { bindSession, payableNetworks, saveBoundSession } from "./payment-links.js";
import { merchantIdFor } from "./products.js";
/** Product metadata marker for the hidden per-invoice product. */
export const INVOICE_PRODUCT_KIND = "invoice";
/** Whether a catalog product is the hidden product behind an invoice. */
export function isInvoiceProduct(product: Product): boolean {
return product.metadata.kind === INVOICE_PRODUCT_KIND;
}
/** Public base URL of the hosted checkout (pay pages live there). */
export function checkoutBaseUrl(env: NodeJS.ProcessEnv = process.env): string {
const url = env.CHECKOUT_PUBLIC_URL ?? env.NEXT_PUBLIC_CHECKOUT_URL ?? "http://localhost:3000";
return url.replace(/\/+$/, "");
}
/** The public pay page URL for a pay token. */
export function payUrlFor(token: string, env: NodeJS.ProcessEnv = process.env): string {
return `${checkoutBaseUrl(env)}/i/${encodeURIComponent(token)}`;
}
function describe(invoice: Invoice): string {
const lines = invoice.lineItems.map((l) => (l.quantity > 1 ? `${l.quantity} x ${l.description}` : l.description));
const text = lines.join(", ");
return text.length > 280 ? `${text.slice(0, 277)}...` : text || `Invoice ${invoice.number}`;
}
/**
* The hidden product + price a checkout session for this invoice buys. It is
* archived (never listed or sold through a link) and delivers by email only.
*/
async function ensureInvoiceProduct(ctx: AppContext, invoice: Invoice): Promise<{ product: Product; price: Price }> {
const [existing] = await ctx.products.list((p) => isInvoiceProduct(p) && p.metadata.invoiceId === invoice.id);
const now = new Date().toISOString();
const product =
existing ??
(await ctx.products.save({
id: generateId("product"),
merchantId: merchantIdFor(invoice.organizationId),
organizationId: invoice.organizationId,
name: `Invoice ${invoice.number}`,
description: describe(invoice),
type: "consulting_slot",
status: "archived",
deliveryMode: "email",
metadata: { kind: INVOICE_PRODUCT_KIND, invoiceId: invoice.id, template: "invoice_paid" },
createdAt: now,
updatedAt: now,
}));
const prices = await ctx.prices.list((p) => p.productId === product.id && p.active);
const matching = prices.find((p) => p.amount === invoice.total.amount && p.currency === invoice.currency);
if (matching) return { product, price: matching };
for (const stale of prices) await ctx.prices.save({ ...stale, active: false });
const price = await ctx.prices.save({
id: generateId("price"),
productId: product.id,
amount: invoice.total.amount,
currency: invoice.currency,
interval: "one_time",
usageBased: false,
active: true,
createdAt: now,
});
return { product, price };
}
function isStillPayable(session: CheckoutSession | null): session is CheckoutSession {
return session !== null && session.status === "open" && !isSessionExpired(session);
}
/**
* The open checkout session for an invoice: the latest one while it is still
* payable, else a fresh one (recorded on the invoice). Returns the updated
* invoice with the session.
*/
export async function openInvoiceSession(
ctx: AppContext,
invoice: Invoice,
): Promise<{ invoice: Invoice; session: CheckoutSession }> {
const reason = unpayableReason(invoice);
if (reason) throw validationError(reason, { invoiceId: invoice.id, status: invoice.status });
const latestId = latestCheckoutSessionId(invoice);
const latest = latestId ? await ctx.checkouts.findById(latestId) : null;
if (isStillPayable(latest) && latest.organizationId === invoice.organizationId && latest.invoiceId === invoice.id) {
return { invoice, session: latest };
}
const { accepted, payTo } = await payableNetworks(ctx, invoice.organizationId);
if (accepted.length === 0) {
throw validationError("Add a receiving wallet in payment settings before sending invoices", {
invoiceId: invoice.id,
});
}
const { product, price } = await ensureInvoiceProduct(ctx, invoice);
const network = accepted[0]!;
const payToByNetwork = Object.fromEntries(accepted.map((n) => [n, payTo[n]!]));
const payerEmail = invoice.metadata[PAYER_EMAIL_KEY];
const draft = createCheckoutSession({
organizationId: invoice.organizationId,
merchantId: merchantIdFor(invoice.organizationId),
customerId: invoice.customerId,
items: [{ lineItem: { productId: product.id, priceId: price.id, quantity: 1 }, price }],
payToAddress: payToByNetwork[network]!,
network,
ttlDays: 1,
...(payerEmail ? { collectedFields: { email: payerEmail } } : {}),
...(invoice.metadata.successUrl ? { successUrl: invoice.metadata.successUrl } : {}),
});
const session = await saveBoundSession(
ctx,
await bindSession(ctx, { ...draft, acceptedNetworks: accepted, payToByNetwork, invoiceId: invoice.id }),
);
const updated = await ctx.invoices.save(withCheckoutSession(invoice, session.id));
return { invoice: updated, session };
}
/** The confirmed payment for a checkout session, as invoice settlement facts. */
export async function confirmedSettlement(
ctx: AppContext,
sessionId: string,
): Promise<InvoiceSettlement | undefined> {
const payments = await ctx.payments.findByCheckoutSessionId(sessionId);
const confirmed = payments.find((p: Payment) => p.status === "confirmed");
if (!confirmed) return undefined;
return {
paymentId: confirmed.id,
checkoutSessionId: sessionId,
amount: confirmed.amount.amount,
network: confirmed.network,
organizationId: confirmed.organizationId,
...(confirmed.txHash ? { txHash: confirmed.txHash } : {}),
...(confirmed.confirmedAt ? { confirmedAt: confirmed.confirmedAt } : {}),
};
}
/** Settle an open invoice if one of its sessions has a confirmed payment. */
export async function reconcileInvoiceWithPayments(ctx: AppContext, invoice: Invoice): Promise<Invoice> {
if (invoice.status !== "open" || checkoutSessionIdsOf(invoice).length === 0) return invoice;
const settled = await reconcileInvoice(invoice, (id) => confirmedSettlement(ctx, id));
if (!settled) return invoice;
const saved = await ctx.invoices.save(settled);
await emitWebhookSafely(ctx.webhookOutbox, invoicePaidWebhook(saved));
return saved;
}
export interface SendInvoiceResult {
invoice: Invoice;
payUrl: string;
checkoutSessionId: string;
emailedTo: string | null;
/** Why no email went out (no address, email not configured, send error). */
emailSkipped?: string;
}
function esc(value: string): string {
return value
.replaceAll("&", "&amp;")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll('"', "&quot;");
}
/** Plain, accessible invoice email: amount, due date and one pay button. */
export function invoiceEmail(invoice: Invoice, merchantName: string, payUrl: string): { subject: string; html: string; text: string } {
const amount = `${invoice.total.amount} ${invoice.total.currency}`;
const due = invoice.dueAt ? ` due ${invoice.dueAt.slice(0, 10)}` : "";
const subject = `Invoice ${invoice.number} from ${merchantName}`;
const text = [
`${merchantName} sent you invoice ${invoice.number} for ${amount}${due}.`,
"",
...invoice.lineItems.map((l) => `- ${l.quantity} x ${l.description}: ${l.unitAmount.amount} ${l.unitAmount.currency}`),
"",
`Pay online in USDC: ${payUrl}`,
].join("\n");
const html = `<!doctype html><html><body style="font-family:system-ui,sans-serif;color:#111;max-width:560px;margin:auto;padding:24px">
<p>${esc(merchantName)} sent you invoice <strong>${esc(invoice.number)}</strong> for <strong>${esc(amount)}</strong>${esc(due)}.</p>
<ul>${invoice.lineItems.map((l) => `<li>${l.quantity} x ${esc(l.description)}: ${esc(`${l.unitAmount.amount} ${l.unitAmount.currency}`)}</li>`).join("")}</ul>
<p><a href="${esc(payUrl)}" style="display:inline-block;padding:12px 20px;background:#111;color:#fff;border-radius:8px;text-decoration:none">Pay invoice</a></p>
<p style="color:#555;font-size:13px">Or open ${esc(payUrl)}</p>
</body></html>`;
return { subject, html, text };
}
/**
* Issue (finalize a draft), bind the pay token, open the checkout session and
* email the pay link. Idempotent: re-sending keeps the same link.
*/
export async function sendInvoice(
ctx: AppContext,
invoice: Invoice,
options: { payerEmail?: string; env?: NodeJS.ProcessEnv; skipEmail?: boolean } = {},
): Promise<SendInvoiceResult> {
let current = invoice.status === "draft" ? finalizeInvoice(invoice) : invoice;
const reason = unpayableReason(current);
if (reason) throw validationError(reason, { invoiceId: invoice.id, status: current.status });
const customer = await ctx.customers.findById(current.customerId);
const payerEmail = options.payerEmail ?? current.metadata[PAYER_EMAIL_KEY] ?? customer?.email ?? undefined;
current = withPayToken(current, generateSecret(24));
if (payerEmail) current = withPayerEmail(current, payerEmail);
current = await ctx.invoices.save(current);
const opened = await openInvoiceSession(ctx, current);
const token = payTokenOf(opened.invoice)!;
const payUrl = payUrlFor(token, options.env);
const base = { invoice: opened.invoice, payUrl, checkoutSessionId: opened.session.id };
if (options.skipEmail) return { ...base, emailedTo: null, emailSkipped: "not requested" };
if (!payerEmail) return { ...base, emailedTo: null, emailSkipped: "no payer email on the invoice or customer" };
if (!ctx.email) return { ...base, emailedTo: null, emailSkipped: "email is not configured (RESEND_API_KEY)" };
const { merchantName } = await payableNetworks(ctx, current.organizationId);
const message = invoiceEmail(opened.invoice, merchantName, payUrl);
try {
await ctx.email.send({
to: payerEmail,
...message,
tags: [
{ name: "type", value: "invoice" },
{ name: "invoice_id", value: opened.invoice.id },
],
});
return { ...base, emailedTo: payerEmail };
} catch (error) {
return { ...base, emailedTo: null, emailSkipped: error instanceof Error ? error.message : "email send failed" };
}
}
/** Load an invoice by its public pay token (404 when unknown). */
export async function invoiceByToken(ctx: AppContext, token: string): Promise<Invoice> {
const invoice = await ctx.invoices.findByPayToken(token);
if (!invoice) throw notFound("This invoice link does not exist");
return reconcileInvoiceWithPayments(ctx, invoice);
}
/** Buyer-safe view of an invoice for the public pay page. */
export interface PublicInvoiceView {
number: string;
status: Invoice["status"];
merchantName: string;
currency: string;
lineItems: { description: string; quantity: number; unitAmount: string }[];
subtotal: string;
discount: string | null;
tax: string | null;
total: string;
issuedAt: string | null;
dueAt: string | null;
paidAt: string | null;
paidTxHash: string | null;
paidNetwork: string | null;
payable: boolean;
unpayableReason: string | null;
}
export async function publicInvoiceView(ctx: AppContext, invoice: Invoice): Promise<PublicInvoiceView> {
const { merchantName } = await payableNetworks(ctx, invoice.organizationId);
const reason = unpayableReason(invoice);
return {
number: invoice.number,
status: invoice.status,
merchantName,
currency: invoice.currency,
lineItems: invoice.lineItems.map((l) => ({
description: l.description,
quantity: l.quantity,
unitAmount: l.unitAmount.amount,
})),
subtotal: invoice.subtotal.amount,
discount: invoice.discount?.amount ?? null,
tax: invoice.tax?.amount ?? null,
total: invoice.total.amount,
issuedAt: invoice.issuedAt ?? null,
dueAt: invoice.dueAt ?? null,
paidAt: invoice.paidAt ?? null,
paidTxHash: invoice.metadata.paidTxHash ?? null,
paidNetwork: invoice.metadata.paidNetwork ?? null,
payable: reason === null,
unpayableReason: reason,
};
}
/** Seller identity printed on an org's invoice and receipt PDFs. */
export async function invoiceMerchant(ctx: AppContext, organizationId: string): Promise<Merchant> {
const settings = await ctx.orgSettings.get(organizationId);
return {
name: settings.orgName,
...(settings.supportEmail ? { email: settings.supportEmail } : {}),
};
}
/**
* Cancel every still-open checkout session of an invoice (after a void), so
* a client holding an old link can no longer pay it.
*/
export async function closeInvoiceSessions(ctx: AppContext, invoice: Invoice): Promise<number> {
let closed = 0;
for (const id of checkoutSessionIdsOf(invoice)) {
const session = await ctx.checkouts.findById(id);
if (session?.status !== "open") continue;
await ctx.checkouts.save(cancelSession(session));
closed += 1;
}
return closed;
}

View File

@ -0,0 +1,164 @@
/**
* The networks a merchant can accept, as this deployment actually runs them.
*
* One row per payable network with the stablecoin a buyer sends, whether the
* deployment runs it on mainnet or testnet, whether it can verify payments on
* it at all (networks without a verifier fail closed), which address a
* merchant pastes for it, and how to link a transaction. Honest labels come
* from the chain registry: Robinhood Chain settles USDG, Tempo settles bridged
* USDC.e, Zcash settles transparent ZEC.
*/
import type { PaymentNetwork } from "@settlekit/common";
import { getEvmChain, type ChainEnv, type EvmChainKey } from "@settlekit/chains";
import { SOLANA_CLUSTERS, USDC_MINT_DEVNET, USDC_MINT_MAINNET } from "@settlekit/solana";
import { hyperCoreTxUrl, defaultHyperliquidApiUrl } from "@settlekit/hyperliquid";
import { zcashExplorerTxUrl } from "@settlekit/zcash";
import { loadConfig, type ApiConfig } from "../config/env.js";
/** Which receiving address a network uses. EVM chains share one address. */
export type AddressGroup = "evm" | "solana" | "hypercore" | "zcash";
export interface NetworkInfo {
network: PaymentNetwork;
name: string;
/** Asset the merchant receives, e.g. USDC, USDG, USDC.e, ZEC. */
asset: string;
env: ChainEnv;
/** Whether this deployment can verify payments on the network. */
enabled: boolean;
addressGroup: AddressGroup;
/** Honest disclosure shown next to the chain. */
note?: string;
}
/** Networks offered to merchants, in display order (Arc is out of scope). */
export const MERCHANT_NETWORKS: readonly PaymentNetwork[] = [
"solana",
"base",
"ethereum",
"arbitrum",
"robinhood",
"hyperevm",
"hypercore",
"tempo",
"zcash",
];
const EVM_NAMES: Record<string, string> = {
ethereum: "Ethereum",
base: "Base",
arbitrum: "Arbitrum",
robinhood: "Robinhood Chain",
hyperevm: "HyperEVM",
tempo: "Tempo",
};
let cachedConfig: ApiConfig | null = null;
/** The API config (loaded once; boot already validated it). */
export function apiConfig(): ApiConfig {
cachedConfig ??= loadConfig();
return cachedConfig;
}
function evmRow(key: EvmChainKey, cfg: ApiConfig): NetworkInfo {
const runtime = cfg.evm.enabled[key];
const env: ChainEnv = runtime?.spec.env ?? cfg.evm.env;
const spec = runtime?.spec ?? getEvmChain(key, env);
const asset = spec?.token.symbol ?? "USDC";
const notes: string[] = [];
if (key === "robinhood") notes.push(env === "mainnet" ? "Settles USDG (Paxos Global Dollar); no native USDC on Robinhood Chain" : "Testnet Mock USDC");
if (key === "tempo") notes.push(env === "mainnet" ? "Settles USDC.e, bridged via Stargate" : "Testnet pathUSD / AlphaUSD");
return {
network: key as PaymentNetwork,
name: EVM_NAMES[key] ?? key,
asset,
env,
enabled: runtime !== undefined,
addressGroup: "evm",
...(notes.length > 0 ? { note: notes.join("; ") } : {}),
};
}
/** Every merchant network with its live deployment status. */
export function networkCatalog(cfg: ApiConfig = apiConfig()): NetworkInfo[] {
return MERCHANT_NETWORKS.map((network): NetworkInfo => {
switch (network) {
case "solana":
return {
network,
name: "Solana",
asset: "USDC",
env: cfg.solana ? (cfg.solana.cluster === "devnet" ? "testnet" : "mainnet") : cfg.evm.env,
enabled: cfg.solana !== null,
addressGroup: "solana",
};
case "hypercore":
return {
network,
name: "Hyperliquid (HyperCore)",
asset: "USDC",
env: cfg.hypercore?.network ?? cfg.evm.env,
enabled: cfg.hypercore !== null,
addressGroup: "hypercore",
note: "Paid with usdSend into your Hyperliquid account balance",
};
case "zcash":
return {
network,
name: "Zcash",
asset: "ZEC",
env: cfg.zcash?.network ?? "mainnet",
enabled: cfg.zcash !== null,
addressGroup: "zcash",
note: "Transparent ZEC at a locked USD quote; payments are visible on-chain",
};
default:
return evmRow(network as EvmChainKey, cfg);
}
});
}
/** Catalog row for one network. */
export function networkInfo(network: PaymentNetwork, cfg: ApiConfig = apiConfig()): NetworkInfo | undefined {
return networkCatalog(cfg).find((row) => row.network === network);
}
/** Block-explorer link for a transaction, matched to the deployment's env. */
export function explorerTxUrl(network: PaymentNetwork, txHash: string, cfg: ApiConfig = apiConfig()): string | null {
if (!txHash) return null;
switch (network) {
case "solana": {
const cluster = cfg.solana?.cluster ?? (cfg.evm.env === "testnet" ? "devnet" : "mainnet");
return `https://solscan.io/tx/${txHash}${SOLANA_CLUSTERS[cluster].explorerClusterParam}`;
}
case "hypercore":
return hyperCoreTxUrl(txHash, cfg.hypercore?.network ?? cfg.evm.env);
case "zcash":
return zcashExplorerTxUrl(cfg.zcash?.network ?? "mainnet", txHash);
default: {
const key = network as EvmChainKey;
const spec = cfg.evm.enabled[key]?.spec ?? getEvmChain(key, cfg.evm.env);
return spec?.explorerTx(txHash) ?? null;
}
}
}
/** RPC / API endpoints used to read merchant balances. */
export function balanceEndpoints(cfg: ApiConfig = apiConfig()) {
const solanaCluster = cfg.solana?.cluster ?? (cfg.evm.env === "testnet" ? "devnet" : "mainnet");
return {
solana: {
rpcUrl: cfg.solana?.rpcUrl ?? SOLANA_CLUSTERS[solanaCluster].rpcUrl,
mint: cfg.solana?.usdcMint ?? (solanaCluster === "mainnet" ? USDC_MINT_MAINNET : USDC_MINT_DEVNET),
},
hypercore: {
apiUrl: cfg.hypercore?.apiUrl ?? defaultHyperliquidApiUrl(cfg.hypercore?.network ?? cfg.evm.env),
},
zcash: {
explorerUrl: cfg.zcash?.explorerUrl ?? "https://api.blockchair.com/zcash",
network: cfg.zcash?.network ?? "mainnet",
apiKey: cfg.zcash?.apiKey,
},
};
}

View File

@ -0,0 +1,185 @@
/**
* Reusable payment links.
*
* A product's link (`/l/<slug>` on the checkout app) is permanent; every
* visit asks the API for a FRESH checkout session bound to the merchant's
* current networks + receiving addresses, so one link can be shared forever
* while each buyer still gets their own single-use session (own Solana Pay
* reference, own Zcash quote, own payer binding).
*/
import { fiatToUsdc, isFiatCurrency, notFound, validationError, type CheckoutSession, type PaymentNetwork, type Product } from "@settlekit/common";
import { createCheckoutSession } from "@settlekit/payments";
import type { AppContext } from "../context.js";
import { withNetworkBindings } from "../routes/checkout-sessions.js";
import { saveZcashSession } from "../routes/zcash-quote.js";
import { payToFor } from "../routes/payment-verification.js";
import { loadProfile } from "./profile.js";
import { applyPromo } from "./session-promo.js";
import { lockFx, withFx } from "../fx/session-fx.js";
import { withSessionTax } from "@settlekit/persistence";
import { networkCatalog } from "./network-catalog.js";
import { activePrice, findBySlug, merchantIdFor } from "./products.js";
/** Public, non-sensitive summary of a payment link. */
export interface PaymentLinkSummary {
slug: string;
productId: string;
name: string;
description: string;
merchantName: string;
priceUsd: string;
/** Set when the price is in a fiat currency (settles in USDC at checkout). */
displayCurrency?: string;
displayAmount?: string;
interval: string;
networks: { network: PaymentNetwork; name: string; asset: string; env: string }[];
}
interface ResolvedLink {
product: Product;
priceId: string;
priceUsd: string;
displayCurrency?: string;
displayAmount?: string;
interval: string;
merchantName: string;
accepted: PaymentNetwork[];
payTo: Partial<Record<PaymentNetwork, string>>;
}
/**
* Networks an org can be paid on right now, in checkout order: the merchant's
* accepted networks that have a receiving address, optionally narrowed to a
* product's list, with networks this deployment can verify first.
*/
export async function payableNetworks(
ctx: AppContext,
organizationId: string,
productNetworks: readonly PaymentNetwork[] | null = null,
): Promise<{ merchantName: string; accepted: PaymentNetwork[]; payTo: Partial<Record<PaymentNetwork, string>> }> {
const profile = await loadProfile(ctx, organizationId);
const enabled = new Set(networkCatalog().filter((n) => n.enabled).map((n) => n.network));
const accepted = profile.acceptedNetworks
.filter((n) => profile.payToByNetwork[n] !== undefined)
.filter((n) => productNetworks === null || productNetworks.includes(n))
// Networks this deployment can verify come first (the default network).
.sort((a, b) => Number(enabled.has(b)) - Number(enabled.has(a)));
return { merchantName: profile.orgName, accepted, payTo: profile.payToByNetwork };
}
async function resolveLink(ctx: AppContext, slug: string): Promise<ResolvedLink> {
const product = await findBySlug(ctx, slug);
if (!product || product.status !== "active") throw notFound("This payment link is not active");
const price = await activePrice(ctx, product.id);
if (!price) throw notFound("This payment link has no price yet");
const productNetworks = Array.isArray(product.metadata.acceptedNetworks)
? (product.metadata.acceptedNetworks as PaymentNetwork[])
: null;
const { merchantName, accepted, payTo } = await payableNetworks(ctx, product.organizationId, productNetworks);
if (accepted.length === 0) throw notFound("The seller has not finished setting up payments");
return {
product,
priceId: price.id,
priceUsd: price.amount,
...(price.displayCurrency && price.displayAmount
? { displayCurrency: price.displayCurrency, displayAmount: price.displayAmount }
: {}),
interval: price.interval,
merchantName,
accepted,
payTo,
};
}
export async function linkSummary(ctx: AppContext, slug: string): Promise<PaymentLinkSummary> {
const resolved = await resolveLink(ctx, slug);
// Fiat prices show today's USDC amount (the stored one is only a reference).
const link =
resolved.displayCurrency && resolved.displayAmount && isFiatCurrency(resolved.displayCurrency)
? await ctx.fxRates
.usdPer(resolved.displayCurrency)
.then(({ rate }) => ({ ...resolved, priceUsd: fiatToUsdc(resolved.displayAmount!, rate) }))
.catch(() => resolved)
: resolved;
const catalog = networkCatalog();
return {
slug,
productId: link.product.id,
name: link.product.name,
description: link.product.description,
merchantName: link.merchantName,
priceUsd: link.priceUsd,
...(link.displayCurrency ? { displayCurrency: link.displayCurrency, displayAmount: link.displayAmount } : {}),
interval: link.interval,
networks: link.accepted.flatMap((n) => {
const row = catalog.find((r) => r.network === n);
return row ? [{ network: n, name: row.name, asset: row.asset, env: row.env }] : [];
}),
};
}
/** Attach network bindings, dropping Zcash when its quote is unavailable. */
export async function bindSession(ctx: AppContext, draft: CheckoutSession): Promise<CheckoutSession> {
try {
return await withNetworkBindings(ctx, draft);
} catch (err) {
// A ZEC price outage must not take the whole link down: drop Zcash
// for this session and keep every other network payable.
const accepted = draft.acceptedNetworks ?? [draft.network];
if (!accepted.includes("zcash") || accepted.length === 1) throw err;
const rest: PaymentNetwork[] = accepted.filter((n) => n !== "zcash");
const payTo: Partial<Record<PaymentNetwork, string>> = Object.fromEntries(
Object.entries(draft.payToByNetwork ?? {}).filter(([n]) => n !== "zcash"),
);
const network: PaymentNetwork = rest.includes(draft.network) ? draft.network : rest[0]!;
return withNetworkBindings(ctx, {
...draft,
network,
payToAddress: payTo[network] ?? draft.payToAddress,
acceptedNetworks: rest,
payToByNetwork: payTo,
});
}
}
/** Open a fresh checkout session for a payment link visit. */
export async function openLinkSession(
ctx: AppContext,
slug: string,
options: { successUrl?: string; cancelUrl?: string; promo?: string } = {},
): Promise<CheckoutSession> {
const link = await resolveLink(ctx, slug);
const price = await ctx.prices.findById(link.priceId);
if (!price) throw validationError("price vanished");
const network = link.accepted[0]!;
const payToByNetwork = Object.fromEntries(link.accepted.map((n) => [n, link.payTo[n]!])) as Partial<
Record<PaymentNetwork, string>
>;
const fx = await lockFx(ctx.fxRates, [{ lineItem: { productId: link.product.id, priceId: price.id, quantity: 1 }, price }], "");
const fxPrice = fx.items[0]!.price;
const created = createCheckoutSession({
organizationId: link.product.organizationId,
merchantId: merchantIdFor(link.product.organizationId),
items: fx.items,
payToAddress: payToByNetwork[network]!,
network,
ttlDays: 1,
...(options.successUrl ? { successUrl: options.successUrl } : {}),
...(options.cancelUrl ? { cancelUrl: options.cancelUrl } : {}),
});
const draft = withFx(created, fx.quote);
const discounted = options.promo ? await applyPromo(ctx, draft, options.promo, new Map([[price.id, fxPrice]])) : draft;
// The seller's default rate applies until the buyer sets their country.
const taxed = withSessionTax(discounted, (await ctx.orgSettings.get(link.product.organizationId)).tax);
const session = await bindSession(ctx, { ...taxed, acceptedNetworks: link.accepted, payToByNetwork });
return session.settlementQuote !== undefined
? saveZcashSession(ctx, { ...session, settlementQuote: session.settlementQuote }, payToFor(session, "zcash"))
: ctx.checkouts.save(session);
}
/** Persist a bound session (Zcash sessions reserve their amount tag atomically). */
export function saveBoundSession(ctx: AppContext, session: CheckoutSession): Promise<CheckoutSession> {
return session.settlementQuote !== undefined
? saveZcashSession(ctx, { ...session, settlementQuote: session.settlementQuote }, payToFor(session, "zcash"))
: ctx.checkouts.save(session);
}

View File

@ -0,0 +1,214 @@
/**
* Merchant-facing payment views: a payment joined with the checkout session
* it paid (asset, payer, any-token route, buyer fields), the products it
* bought, and — for the detail view — its timeline, entitlements, delivery
* runs and refunds.
*/
import type {
CheckoutSession,
DeliveryRun,
Entitlement,
Payment,
PaymentNetwork,
Product,
} from "@settlekit/common";
import type { Refund } from "@settlekit/refunds";
import type { AppContext } from "../context.js";
import { explorerTxUrl, networkInfo } from "./network-catalog.js";
/** How the payment arrived. */
export type PaymentSource = "checkout" | "agent_x402" | "agent_mpp" | "direct";
export interface PaymentView {
id: string;
status: Payment["status"];
network: PaymentNetwork;
networkName: string;
env: "mainnet" | "testnet";
asset: string;
/** Invoiced USD amount. */
amountUsd: string;
/** What actually moved on-chain when it differs from USD (Zcash). */
settled?: { amount: string; asset: string };
txHash: string | null;
explorerUrl: string | null;
source: PaymentSource;
createdAt: string;
confirmedAt: string | null;
buyer: {
customerId: string;
email: string | null;
githubUsername: string | null;
discordUserId: string | null;
wallet: string | null;
};
products: { id: string; name: string }[];
routedFrom: {
provider: string;
originChainId: number;
originToken: string;
originTxHash: string | null;
state: string;
} | null;
}
export interface TimelineStep {
key: "created" | "paid" | "verified" | "delivered" | "refunded";
label: string;
at: string | null;
done: boolean;
detail?: string;
}
export interface PaymentDetail extends PaymentView {
sessionId: string | null;
timeline: TimelineStep[];
entitlements: Entitlement[];
deliveryRuns: DeliveryRun[];
refunds: (Refund & { explorerUrl: string | null })[];
}
/** Classify a payment by the session id convention of each rail. */
export function paymentSource(payment: Payment): PaymentSource {
const id = payment.checkoutSessionId;
if (id.startsWith("x402:")) return "agent_x402";
if (id.startsWith("mpp:")) return "agent_mpp";
if (id.startsWith("direct:")) return "direct";
return "checkout";
}
function zecAmount(session: CheckoutSession | null): PaymentView["settled"] {
const quote = session?.settlementQuote;
if (!quote) return undefined;
const zats = BigInt(quote.amountBase);
const whole = zats / 100_000_000n;
const frac = (zats % 100_000_000n).toString().padStart(8, "0").replace(/0+$/, "");
return { amount: frac ? `${whole}.${frac}` : `${whole}`, asset: "ZEC" };
}
/** Build views for many payments, loading each session/product once. */
export async function buildPaymentViews(ctx: AppContext, payments: readonly Payment[]): Promise<PaymentView[]> {
const productCache = new Map<string, Promise<Product | null>>();
const product = (id: string): Promise<Product | null> => {
let hit = productCache.get(id);
if (!hit) {
hit = ctx.products.findById(id);
productCache.set(id, hit);
}
return hit;
};
return Promise.all(
payments.map(async (payment) => {
const session = paymentSource(payment) === "checkout" ? await ctx.checkouts.findById(payment.checkoutSessionId) : null;
return toView(payment, session, product);
}),
);
}
async function toView(
payment: Payment,
session: CheckoutSession | null,
product: (id: string) => Promise<Product | null>,
): Promise<PaymentView> {
const info = networkInfo(payment.network);
const fields = session?.collectedFields ?? {};
const productIds = [...new Set((session?.lineItems ?? []).flatMap((li) => (li.productId ? [li.productId] : [])))];
const products = (await Promise.all(productIds.map(product))).flatMap((p) => (p ? [{ id: p.id, name: p.name }] : []));
const route = session?.route;
const settled = payment.network === "zcash" ? zecAmount(session) : undefined;
return {
id: payment.id,
status: payment.status,
network: payment.network,
networkName: info?.name ?? payment.network,
env: info?.env ?? "mainnet",
asset: info?.asset ?? payment.amount.currency,
amountUsd: payment.amount.amount,
...(settled ? { settled } : {}),
txHash: payment.txHash ?? null,
explorerUrl: payment.txHash ? explorerTxUrl(payment.network, payment.txHash) : null,
source: paymentSource(payment),
createdAt: payment.createdAt,
confirmedAt: payment.confirmedAt ?? null,
buyer: {
customerId: payment.customerId,
email: fields.email ?? null,
githubUsername: fields.githubUsername ?? null,
discordUserId: fields.discordUserId ?? null,
wallet: session?.payerAddress ?? route?.originAddress ?? null,
},
products,
routedFrom: route
? {
provider: route.provider,
originChainId: route.originChainId,
originToken: route.originToken,
originTxHash: route.originTxHash ?? null,
state: route.state,
}
: null,
};
}
function deliveredAt(entitlements: Entitlement[], runs: DeliveryRun[]): { at: string | null; detail?: string } {
const finished = runs.find((r) => r.status === "succeeded");
if (finished) return { at: finished.completedAt ?? finished.createdAt, detail: "Delivery run succeeded" };
const active = entitlements.find((e) => e.status === "active");
if (active) return { at: active.createdAt, detail: `Access granted (${active.entitlementType.replace(/_/g, " ")})` };
const pending = entitlements.find((e) => e.status === "pending");
if (pending) return { at: null, detail: "Access pending (waiting on the delivery integration)" };
const failed = runs.find((r) => r.status === "failed" || r.status === "partially_failed");
if (failed) return { at: null, detail: "Delivery failed; retry from Delivery runs" };
return { at: null };
}
/** The full detail view for one (already ownership-checked) payment. */
export async function buildPaymentDetail(ctx: AppContext, payment: Payment): Promise<PaymentDetail> {
const [view] = await buildPaymentViews(ctx, [payment]);
const source = paymentSource(payment);
const session = source === "checkout" ? await ctx.checkouts.findById(payment.checkoutSessionId) : null;
const entitlements = (await ctx.entitlementRepo.listByCustomer(payment.customerId)).filter(
(e) => e.grantedBy.type === "payment" && e.grantedBy.id === payment.id && e.organizationId === payment.organizationId,
);
const deliveryRuns = await ctx.deliveryRuns.list((r) => r.paymentId === payment.id && r.organizationId === payment.organizationId);
const refunds = await ctx.refunds.listByPayment(payment.id);
const delivered = deliveredAt(entitlements, deliveryRuns);
const refunded = refunds.find((r) => r.status === "succeeded");
const verified = payment.status === "confirmed" || payment.status === "refunded";
const timeline: TimelineStep[] = [
{ key: "created", label: "Checkout created", at: session?.createdAt ?? payment.createdAt, done: true },
{
key: "paid",
label: "Buyer paid",
at: payment.txHash ? payment.createdAt : null,
done: payment.txHash !== undefined,
...(view!.routedFrom ? { detail: `Routed via ${view!.routedFrom.provider} from chain ${view!.routedFrom.originChainId}` } : {}),
},
{
key: "verified",
label: "Verified on-chain",
at: payment.confirmedAt ?? null,
done: verified,
...(verified ? { detail: `${payment.confirmations} confirmation${payment.confirmations === 1 ? "" : "s"}` } : {}),
},
{ key: "delivered", label: "Access delivered", at: delivered.at, done: delivered.at !== null, ...(delivered.detail ? { detail: delivered.detail } : {}) },
];
if (refunded || payment.status === "refunded") {
timeline.push({
key: "refunded",
label: "Refunded",
at: refunded?.updatedAt ?? null,
done: true,
...(refunded?.txHash ? { detail: `Refund tx ${refunded.txHash}` } : {}),
});
}
return {
...view!,
sessionId: session?.id ?? null,
timeline,
entitlements,
deliveryRuns,
refunds: refunds.map((r) => ({ ...r, explorerUrl: r.txHash ? explorerTxUrl(payment.network, r.txHash) : null })),
};
}

View File

@ -0,0 +1,294 @@
/**
* One-step product setup for merchants: name, USD price and how the buyer
* gets access, published immediately with a reusable payment link.
*
* Delivery kinds map onto the catalog's product types + delivery modes the
* checkout already fulfils:
* github_repo -> github_repo_access / github_invite (metadata.repoId "owner/repo")
* license_key -> license_key / license_key
* file -> digital_download / file_download (metadata.fileUrl, revealed after payment)
* discord_role -> discord_access / discord_role (metadata.guildId + roleId)
* access -> saas_plan / saas_entitlement (metadata.accessUrl, optional)
*/
import { randomBytes } from "node:crypto";
import { z } from "zod";
import {
FIAT_CURRENCIES,
fiatToUsdc,
generateId,
type FiatCurrency,
validationError,
type DeliveryMode,
type PaymentNetwork,
type Price,
type Product,
type ProductType,
} from "@settlekit/common";
import { createProductDraft } from "@settlekit/product-catalog";
import type { AppContext } from "../context.js";
import { MERCHANT_NETWORKS } from "./network-catalog.js";
export const DELIVERY_KINDS = ["github_repo", "license_key", "file", "discord_role", "access"] as const;
export type DeliveryKind = (typeof DELIVERY_KINDS)[number];
const KIND_MAP: Record<DeliveryKind, { type: ProductType; deliveryMode: DeliveryMode }> = {
github_repo: { type: "github_repo_access", deliveryMode: "github_invite" },
license_key: { type: "license_key", deliveryMode: "license_key" },
file: { type: "digital_download", deliveryMode: "file_download" },
discord_role: { type: "discord_access", deliveryMode: "discord_role" },
access: { type: "saas_plan", deliveryMode: "saas_entitlement" },
};
const usd = z
.string()
.trim()
.regex(/^\d+(\.\d{1,2})?$/, "price must be a USD amount like 29 or 29.99")
.refine((v) => Number(v) >= 0.5, "minimum price is $0.50")
.refine((v) => Number(v) <= 100_000, "maximum price is $100,000");
const httpsUrl = z.string().trim().url().refine((v) => v.startsWith("https://"), "must be an https:// link");
const networkEnum = z.enum(MERCHANT_NETWORKS as unknown as [PaymentNetwork, ...PaymentNetwork[]]);
export const deliverySchema = z.discriminatedUnion("kind", [
z.object({
kind: z.literal("github_repo"),
repo: z.string().trim().regex(/^[A-Za-z0-9-]+\/[A-Za-z0-9._-]+$/, "use owner/repo, e.g. acme/pro-templates"),
}),
z.object({ kind: z.literal("license_key"), machineLimit: z.number().int().min(1).max(100).default(3) }),
z.object({ kind: z.literal("file"), fileUrl: httpsUrl }),
z.object({
kind: z.literal("discord_role"),
guildId: z.string().trim().regex(/^\d{5,25}$/, "server id is numeric"),
roleId: z.string().trim().regex(/^\d{5,25}$/, "role id is numeric"),
}),
z.object({ kind: z.literal("access"), accessUrl: httpsUrl.optional().or(z.literal("")) }),
]);
export const quickProductSchema = z
.object({
name: z.string().trim().min(1).max(120),
description: z.string().trim().max(2000).default(""),
priceUsd: usd,
/**
* Currency of `priceUsd` (default USD). Any other fiat currency settles in
* USDC at the live rate locked on each checkout.
*/
currency: z.enum(FIAT_CURRENCIES).default("USD"),
interval: z.enum(["one_time", "monthly", "yearly"]).default("one_time"),
delivery: deliverySchema,
/** Subset of the merchant's networks this product accepts (all when omitted). */
acceptedNetworks: z.array(networkEnum).optional(),
})
.refine((body) => body.currency === "USD" || body.interval === "one_time", {
message: "subscriptions are priced in USD for now",
path: ["currency"],
});
export const productPatchSchema = z.object({
name: z.string().trim().min(1).max(120).optional(),
description: z.string().trim().max(2000).optional(),
priceUsd: usd.optional(),
status: z.enum(["active", "archived"]).optional(),
delivery: deliverySchema.optional(),
acceptedNetworks: z.array(networkEnum).nullable().optional(),
});
export type QuickProductInput = z.infer<typeof quickProductSchema>;
export type ProductPatch = z.infer<typeof productPatchSchema>;
export interface MerchantProductView {
id: string;
name: string;
description: string;
status: Product["status"];
priceUsd: string | null;
/** Fiat price when the product is priced in another currency. */
displayCurrency: string | null;
displayAmount: string | null;
priceId: string | null;
interval: Price["interval"] | null;
deliveryKind: DeliveryKind | "other";
delivery: Record<string, unknown>;
acceptedNetworks: PaymentNetwork[] | null;
slug: string | null;
createdAt: string;
}
/** A short, unguessable, URL-safe slug for a payment link. */
export function newSlug(name: string): string {
const stem = name
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 32);
const suffix = randomBytes(4).toString("hex");
return stem ? `${stem}-${suffix}` : suffix;
}
function deliveryMetadata(delivery: QuickProductInput["delivery"]): Record<string, unknown> {
switch (delivery.kind) {
case "github_repo":
return { deliveryKind: "github_repo", repoId: delivery.repo };
case "license_key":
return { deliveryKind: "license_key", machineLimit: delivery.machineLimit };
case "file":
return { deliveryKind: "file", fileUrl: delivery.fileUrl };
case "discord_role":
return { deliveryKind: "discord_role", guildId: delivery.guildId, roleId: delivery.roleId };
case "access":
return { deliveryKind: "access", ...(delivery.accessUrl ? { accessUrl: delivery.accessUrl } : {}), features: { access: true } };
}
}
function kindOf(product: Product): DeliveryKind | "other" {
const kind = product.metadata.deliveryKind;
return typeof kind === "string" && (DELIVERY_KINDS as readonly string[]).includes(kind) ? (kind as DeliveryKind) : "other";
}
function publicDelivery(product: Product): Record<string, unknown> {
const m = product.metadata;
const pick = (k: string): Record<string, unknown> => (m[k] !== undefined ? { [k]: m[k] } : {});
return { ...pick("repoId"), ...pick("machineLimit"), ...pick("fileUrl"), ...pick("guildId"), ...pick("roleId"), ...pick("accessUrl") };
}
function acceptedOf(product: Product): PaymentNetwork[] | null {
const list = product.metadata.acceptedNetworks;
return Array.isArray(list) ? (list.filter((n) => typeof n === "string") as PaymentNetwork[]) : null;
}
export function slugOf(product: Product): string | null {
const slug = product.metadata.paymentLinkSlug;
return typeof slug === "string" && slug.length > 0 ? slug : null;
}
/** The product's current price (newest active). */
export async function activePrice(ctx: AppContext, productId: string): Promise<Price | null> {
const prices = await ctx.prices.list((p) => p.productId === productId && p.active);
return prices.sort((a, b) => b.createdAt.localeCompare(a.createdAt))[0] ?? null;
}
export async function productView(ctx: AppContext, product: Product): Promise<MerchantProductView> {
const price = await activePrice(ctx, product.id);
return {
id: product.id,
name: product.name,
description: product.description,
status: product.status,
priceUsd: price?.amount ?? null,
displayCurrency: price?.displayCurrency ?? null,
displayAmount: price?.displayAmount ?? null,
priceId: price?.id ?? null,
interval: price?.interval ?? null,
deliveryKind: kindOf(product),
delivery: publicDelivery(product),
acceptedNetworks: acceptedOf(product),
slug: slugOf(product),
createdAt: product.createdAt,
};
}
/**
* A price in USD (USDC 1:1) or another fiat currency. A fiat price keeps its
* display amount; `amount` is the USDC value at the current rate (reference).
*/
async function priceIn(
ctx: AppContext,
productId: string,
amount: string,
currency: FiatCurrency,
interval: Price["interval"],
): Promise<Price> {
if (currency === "USD") return newPrice(productId, amount, interval);
const { rate } = await ctx.fxRates.usdPer(currency);
return { ...newPrice(productId, fiatToUsdc(amount, rate), interval), displayCurrency: currency, displayAmount: amount };
}
function newPrice(productId: string, amount: string, interval: Price["interval"]): Price {
return {
id: generateId("price"),
productId,
amount,
currency: "USDC",
interval,
usageBased: false,
active: true,
createdAt: new Date().toISOString(),
};
}
/** Create, price and publish a product with a payment link in one step. */
export async function createQuickProduct(ctx: AppContext, organizationId: string, input: QuickProductInput): Promise<Product> {
const map = KIND_MAP[input.delivery.kind];
const draft = createProductDraft({
merchantId: merchantIdFor(organizationId),
organizationId,
name: input.name,
description: input.description,
template: { type: map.type, deliveryMode: map.deliveryMode, requiredBuyerFields: [] },
metadata: {
...deliveryMetadata(input.delivery),
paymentLinkSlug: newSlug(input.name),
...(input.acceptedNetworks ? { acceptedNetworks: input.acceptedNetworks } : {}),
},
});
// The product row must exist before its price: prices.product_id is a
// foreign key in Postgres. Publish only once the price is in place.
await ctx.products.save(draft);
await ctx.prices.save(await priceIn(ctx, draft.id, input.priceUsd, input.currency, input.interval));
const now = new Date().toISOString();
return ctx.products.save({ ...draft, status: "active", updatedAt: now });
}
/** Apply a merchant edit; a new price supersedes (deactivates) the old one. */
export async function updateProduct(ctx: AppContext, product: Product, patch: ProductPatch): Promise<Product> {
if (patch.priceUsd !== undefined) {
const current = await activePrice(ctx, product.id);
const currency = (current?.displayCurrency ?? "USD") as FiatCurrency;
const unchanged = currency === "USD" ? current?.amount === patch.priceUsd : current?.displayAmount === patch.priceUsd;
if (!unchanged) {
if (current) await ctx.prices.save({ ...current, active: false });
await ctx.prices.save(await priceIn(ctx, product.id, patch.priceUsd, currency, current?.interval ?? "one_time"));
}
}
let metadata: Record<string, unknown> = { ...product.metadata };
let type = product.type;
let deliveryMode = product.deliveryMode;
if (patch.delivery) {
const map = KIND_MAP[patch.delivery.kind];
for (const key of ["repoId", "machineLimit", "fileUrl", "guildId", "roleId", "accessUrl", "features"]) delete metadata[key];
metadata = { ...metadata, ...deliveryMetadata(patch.delivery) };
type = map.type;
deliveryMode = map.deliveryMode;
}
if (patch.acceptedNetworks !== undefined) {
const { acceptedNetworks: _drop, ...rest } = metadata;
void _drop;
metadata = patch.acceptedNetworks === null ? rest : { ...rest, acceptedNetworks: patch.acceptedNetworks };
}
if (!slugOf(product)) metadata = { ...metadata, paymentLinkSlug: newSlug(patch.name ?? product.name) };
if (patch.status === "active" && !(await activePrice(ctx, product.id))) {
throw validationError("set a price before activating the product");
}
return ctx.products.save({
...product,
...(patch.name !== undefined ? { name: patch.name } : {}),
...(patch.description !== undefined ? { description: patch.description } : {}),
...(patch.status !== undefined ? { status: patch.status } : {}),
type,
deliveryMode,
metadata,
updatedAt: new Date().toISOString(),
});
}
/** Stable merchant id for an org (one merchant per self-serve org). */
export function merchantIdFor(organizationId: string): string {
return `mch_${organizationId.replace(/^org(anization)?_/, "")}`;
}
/** Find the product a payment-link slug points at. */
export async function findBySlug(ctx: AppContext, slug: string): Promise<Product | null> {
const [product] = await ctx.products.list((p) => slugOf(p) === slug);
return product ?? null;
}

View File

@ -0,0 +1,163 @@
/**
* The merchant's payment profile: which networks they accept and the address
* that receives funds on each. Stored on the organization's settings so every
* checkout session (API, payment links, dashboard) uses the same destinations.
*
* Merchants paste one address per address group — one EVM address serves
* Ethereum, Base, Arbitrum, Robinhood Chain, HyperEVM and Tempo — and every
* address is validated for its chain before it is saved (funds sent to a
* malformed address are unrecoverable).
*/
import { z } from "zod";
import { isPaymentNetwork, validationError, type PaymentNetwork } from "@settlekit/common";
import { checkPayTo } from "@settlekit/chains";
import type { OrgSettings } from "@settlekit/persistence";
import { merchants } from "@settlekit/database";
import type { AppContext } from "../context.js";
import { MERCHANT_NETWORKS, networkCatalog, apiConfig, type AddressGroup } from "./network-catalog.js";
import { merchantIdFor } from "./products.js";
export interface MerchantAddresses {
evm?: string;
solana?: string;
hypercore?: string;
zcash?: string;
}
export interface MerchantProfile {
organizationId: string;
orgName: string;
supportEmail: string;
acceptedNetworks: PaymentNetwork[];
payToByNetwork: Partial<Record<PaymentNetwork, string>>;
addresses: MerchantAddresses;
onboarded: boolean;
testAccount: boolean;
}
const networkEnum = z.enum(MERCHANT_NETWORKS as unknown as [PaymentNetwork, ...PaymentNetwork[]]);
export const profileInputSchema = z.object({
orgName: z.string().trim().min(1).max(120).optional(),
supportEmail: z.string().trim().email().or(z.literal("")).optional(),
acceptedNetworks: z.array(networkEnum).min(1, "choose at least one network"),
addresses: z.object({
evm: z.string().trim().optional(),
solana: z.string().trim().optional(),
hypercore: z.string().trim().optional(),
zcash: z.string().trim().optional(),
}),
testAccount: z.boolean().optional(),
});
export type ProfileInput = z.infer<typeof profileInputSchema>;
const GROUP_LABEL: Record<AddressGroup, string> = {
evm: "EVM address (0x...)",
solana: "Solana address",
hypercore: "Hyperliquid address (0x...)",
zcash: "Zcash transparent address (t1... / t3...)",
};
function groupOf(network: PaymentNetwork): AddressGroup {
if (network === "solana" || network === "hypercore" || network === "zcash") return network;
return "evm";
}
/** Read a merchant's profile from their org settings. */
export function profileFromSettings(organizationId: string, settings: OrgSettings): MerchantProfile {
const accepted = (settings.acceptedNetworks ?? []).filter(
(n): n is PaymentNetwork => isPaymentNetwork(n) && MERCHANT_NETWORKS.includes(n),
);
const payTo: Partial<Record<PaymentNetwork, string>> = {};
for (const [network, address] of Object.entries(settings.payToByNetwork ?? {})) {
if (isPaymentNetwork(network) && typeof address === "string" && address.length > 0) payTo[network] = address;
}
const addresses: MerchantAddresses = {};
for (const network of MERCHANT_NETWORKS) {
const address = payTo[network];
if (address !== undefined) addresses[groupOf(network)] ??= address;
}
return {
organizationId,
orgName: settings.orgName,
supportEmail: settings.supportEmail,
acceptedNetworks: accepted,
payToByNetwork: payTo,
addresses,
onboarded: accepted.length > 0 && accepted.every((n) => payTo[n] !== undefined),
testAccount: settings.testAccount === true,
};
}
export async function loadProfile(ctx: AppContext, organizationId: string): Promise<MerchantProfile> {
return profileFromSettings(organizationId, await ctx.orgSettings.get(organizationId));
}
/**
* Validate the pasted addresses for every accepted network and derive the
* per-network payTo map. Throws a validation error naming each bad field.
*/
export function resolvePayTo(input: ProfileInput): Partial<Record<PaymentNetwork, string>> {
const zcashNetwork = apiConfig().zcash?.network ?? "mainnet";
const problems: Record<string, string> = {};
const payTo: Partial<Record<PaymentNetwork, string>> = {};
for (const network of new Set(input.acceptedNetworks)) {
const group = groupOf(network);
// HyperCore accounts are 0x addresses; default to the EVM address.
const address = group === "hypercore" ? input.addresses.hypercore || input.addresses.evm : input.addresses[group];
if (!address) {
problems[group] = `${GROUP_LABEL[group]} is required to accept ${network}`;
continue;
}
const check = checkPayTo(network, address, { zcashNetwork });
if (!check.ok) {
problems[group] = `${GROUP_LABEL[group]}: ${check.reason}`;
continue;
}
payTo[network] = address;
}
if (Object.keys(problems).length > 0) {
throw validationError("Some receiving addresses are missing or invalid", { fields: problems });
}
return payTo;
}
/** Validate + persist a merchant's networks and addresses. */
export async function saveProfile(ctx: AppContext, organizationId: string, input: ProfileInput): Promise<MerchantProfile> {
const payToByNetwork = resolvePayTo(input);
const acceptedNetworks = MERCHANT_NETWORKS.filter((n) => payToByNetwork[n] !== undefined);
const current = await ctx.orgSettings.get(organizationId);
const settings = await ctx.orgSettings.update(organizationId, {
...(input.orgName !== undefined ? { orgName: input.orgName } : {}),
...(input.supportEmail !== undefined ? { supportEmail: input.supportEmail } : {}),
...(input.testAccount !== undefined ? { testAccount: input.testAccount } : {}),
acceptedNetworks,
payToByNetwork: payToByNetwork as Record<string, string>,
onboardedAt: current.onboardedAt ?? new Date().toISOString(),
});
await ensureMerchantRow(ctx, organizationId, settings.orgName, settings.supportEmail);
return profileFromSettings(organizationId, settings);
}
/** Catalog rows plus whether the merchant accepts each network. */
export function networksForProfile(profile: MerchantProfile) {
return networkCatalog().map((row) => ({
...row,
accepted: profile.acceptedNetworks.includes(row.network),
payTo: profile.payToByNetwork[row.network] ?? null,
}));
}
/**
* Postgres: keep a merchants row for the org so the hosted checkout shows the
* seller's name (the org row itself is created by the settings store).
*/
async function ensureMerchantRow(ctx: AppContext, organizationId: string, displayName: string, supportEmail: string): Promise<void> {
if (!ctx.db) return;
const values = { displayName, supportEmail: supportEmail || null };
await ctx.db
.insert(merchants)
.values({ id: merchantIdFor(organizationId), organizationId, defaultCurrency: "USDC", status: "active", metadata: {}, ...values })
.onConflictDoUpdate({ target: merchants.id, set: values });
}

View File

@ -0,0 +1,132 @@
/**
* Public proof of settlement: recent confirmed payments across every seller,
* with network, asset, amount, explorer link and time, plus totals per
* network. Agent purchases (x402 / MPP) are labelled. Payments of demo/test
* organizations are excluded (the bootstrap org, orgs flagged `testAccount`,
* and any id in PROOF_EXCLUDED_ORGS). Testnet payments stay visible but are
* labelled testnet — nothing is presented as mainnet volume unless it is.
*
* No buyer or seller identity is exposed: only on-chain facts anyone could
* read from the explorer link.
*/
import type { Payment, PaymentNetwork } from "@settlekit/common";
import { DEFAULT_ORG_ID } from "@settlekit/persistence";
import type { AppContext } from "../context.js";
import { explorerTxUrl, networkInfo } from "./network-catalog.js";
import { paymentSource, type PaymentSource } from "./payment-views.js";
export interface ProofPayment {
network: PaymentNetwork;
networkName: string;
env: "mainnet" | "testnet";
asset: string;
amountUsd: string;
txHash: string;
explorerUrl: string | null;
confirmedAt: string;
source: PaymentSource;
}
export interface ProofTotals {
network: PaymentNetwork;
networkName: string;
env: "mainnet" | "testnet";
asset: string;
count: number;
volumeUsd: string;
}
export interface ProofReport {
generatedAt: string;
payments: ProofPayment[];
totals: ProofTotals[];
mainnet: { count: number; volumeUsd: string };
testnet: { count: number; volumeUsd: string };
agentPurchases: number;
}
const SCAN_LIMIT = 2_000;
const SHOW_LIMIT = 100;
const CACHE_MS = 30_000;
let cache: { at: number; report: ProofReport } | null = null;
function excludedOrgs(): Set<string> {
const extra = (process.env.PROOF_EXCLUDED_ORGS ?? "").split(",").map((s) => s.trim()).filter(Boolean);
return new Set([DEFAULT_ORG_ID, ...extra]);
}
/** Sum decimal USD strings exactly (6 dp, bigint). */
function addUsd(a: string, b: string): string {
const toMicros = (v: string): bigint => {
const [whole = "0", frac = ""] = v.split(".");
return BigInt(whole) * 1_000_000n + BigInt((frac + "000000").slice(0, 6));
};
const total = toMicros(a) + toMicros(b);
const cents = (total % 1_000_000n).toString().padStart(6, "0").slice(0, 2);
return `${total / 1_000_000n}.${cents}`;
}
async function isTestOrg(ctx: AppContext, organizationId: string, memo: Map<string, Promise<boolean>>): Promise<boolean> {
let hit = memo.get(organizationId);
if (!hit) {
hit = ctx.orgSettings.get(organizationId).then((s) => s.testAccount === true);
memo.set(organizationId, hit);
}
return hit;
}
async function confirmedPayments(ctx: AppContext): Promise<Payment[]> {
if (ctx.payments.listRecentConfirmed) return ctx.payments.listRecentConfirmed(SCAN_LIMIT);
return [];
}
export async function buildProof(ctx: AppContext): Promise<ProofReport> {
if (cache && Date.now() - cache.at < CACHE_MS) return cache.report;
const excluded = excludedOrgs();
const memo = new Map<string, Promise<boolean>>();
const rows: ProofPayment[] = [];
for (const payment of await confirmedPayments(ctx)) {
if (!payment.txHash || excluded.has(payment.organizationId)) continue;
if (await isTestOrg(ctx, payment.organizationId, memo)) continue;
const info = networkInfo(payment.network);
rows.push({
network: payment.network,
networkName: info?.name ?? payment.network,
env: info?.env ?? "mainnet",
asset: info?.asset ?? payment.amount.currency,
amountUsd: payment.amount.amount,
txHash: payment.txHash,
explorerUrl: explorerTxUrl(payment.network, payment.txHash),
confirmedAt: payment.confirmedAt ?? payment.createdAt,
source: paymentSource(payment),
});
}
const byKey = new Map<string, ProofTotals>();
const sums = { mainnet: { count: 0, volumeUsd: "0.00" }, testnet: { count: 0, volumeUsd: "0.00" } };
for (const row of rows) {
const key = `${row.network}:${row.env}`;
const prev = byKey.get(key) ?? {
network: row.network,
networkName: row.networkName,
env: row.env,
asset: row.asset,
count: 0,
volumeUsd: "0.00",
};
byKey.set(key, { ...prev, count: prev.count + 1, volumeUsd: addUsd(prev.volumeUsd, row.amountUsd) });
sums[row.env] = { count: sums[row.env].count + 1, volumeUsd: addUsd(sums[row.env].volumeUsd, row.amountUsd) };
}
const report: ProofReport = {
generatedAt: new Date().toISOString(),
payments: rows.slice(0, SHOW_LIMIT),
totals: [...byKey.values()].sort((a, b) => b.count - a.count),
mainnet: sums.mainnet,
testnet: sums.testnet,
agentPurchases: rows.filter((r) => r.source === "agent_x402" || r.source === "agent_mpp").length,
};
cache = { at: Date.now(), report };
return report;
}

View File

@ -0,0 +1,102 @@
/**
* Tax-grade receipts for settled checkouts.
*
* A receipt is rendered from the completed session and its confirmed payment:
* line items at list price, promo discount, tax with its rate and
* jurisdiction (or "reverse charge"), the seller's legal name and tax ID,
* the buyer's billing country and VAT ID, and the settlement transaction.
* Invoice sessions reuse the paid invoice itself. The checkout session id is
* the capability (the same one the hosted checkout's success page uses).
*/
import { addMoney, effectiveUnitAmount, money, multiplyMoney, notFound, type CheckoutSession, type Payment } from "@settlekit/common";
import { renderInvoicePdf, type Invoice, type InvoicePdfOptions } from "@settlekit/invoices";
import type { AppContext } from "../context.js";
import { invoiceMerchant, reconcileInvoiceWithPayments } from "./invoice-payments.js";
function pct(bps: number): string {
return `${(bps / 100).toFixed(2).replace(/\.?0+$/, "")}%`;
}
async function settledSession(ctx: AppContext, sessionId: string): Promise<{ session: CheckoutSession; payment: Payment }> {
const session = await ctx.checkouts.findById(sessionId);
const payments = session ? await ctx.payments.findByCheckoutSessionId(session.id) : [];
const payment = payments.find((p) => p.status === "confirmed" || p.status === "refunded");
if (!session || !payment) throw notFound("No settled payment for this checkout");
return { session, payment };
}
async function receiptDocument(ctx: AppContext, session: CheckoutSession, payment: Payment): Promise<Invoice> {
if (session.invoiceId) {
const found = await ctx.invoices.get(session.invoiceId);
if (found.ok) return reconcileInvoiceWithPayments(ctx, found.value);
}
const lineItems = await Promise.all(
session.lineItems.map(async (line) => {
const price = await ctx.prices.findById(line.priceId);
const product = await ctx.products.findById(price?.productId ?? line.productId ?? "");
return {
description: product?.name ?? "Purchase",
quantity: line.quantity,
unitAmount: money(price ? effectiveUnitAmount(price, session.fxQuote) : "0", price?.currency ?? payment.amount.currency),
};
}),
);
const listed = lineItems.reduce((sum, l) => addMoney(sum, multiplyMoney(l.unitAmount, l.quantity)), money("0"));
const at = payment.confirmedAt ?? payment.createdAt;
return {
id: `rcpt_${payment.id}`,
number: `R-${payment.id.replace(/^[a-z]+_/, "").slice(-10).toUpperCase()}`,
organizationId: session.organizationId,
customerId: payment.customerId,
lineItems,
subtotal: session.discount?.subtotal ?? listed,
...(session.discount ? { discount: session.discount.amountOff } : {}),
...(session.tax ? { tax: session.tax.amount } : {}),
total: payment.amount,
currency: payment.amount.currency,
status: "paid",
issuedAt: at,
paidAt: at,
metadata: {
paidNetwork: payment.network,
...(payment.txHash ? { paidTxHash: payment.txHash } : {}),
},
};
}
/** Render the receipt PDF for a settled checkout session. */
export async function receiptPdf(ctx: AppContext, sessionId: string): Promise<{ pdf: Buffer; filename: string }> {
const { session, payment } = await settledSession(ctx, sessionId);
const doc = await receiptDocument(ctx, session, payment);
const settings = await ctx.orgSettings.get(session.organizationId);
const merchant = await invoiceMerchant(ctx, session.organizationId);
const tax = settings.tax;
const fields = session.collectedFields;
const options: InvoicePdfOptions = {
title: "Receipt",
...(tax
? {
seller: {
...(tax.taxId ? { taxId: tax.taxId } : {}),
...(tax.sellerCountry ? { country: tax.sellerCountry } : {}),
...(tax.addressLines ? { addressLines: tax.addressLines } : {}),
},
}
: {}),
buyer: {
...(fields.name ? { name: fields.name } : {}),
...(fields.email ? { email: fields.email } : {}),
...(session.tax?.country ? { country: session.tax.country } : {}),
...(session.tax?.vatId ? { taxId: session.tax.vatId } : {}),
},
...(session.tax
? {
taxLabel: session.tax.reverseCharge
? `${session.tax.label} 0% (reverse charge: VAT due by the buyer)`
: `${session.tax.label} ${pct(session.tax.rateBps)} (${session.tax.jurisdiction})`,
}
: {}),
};
const pdf = await renderInvoicePdf(doc, { ...merchant, ...(tax?.legalName ? { name: tax.legalName } : {}) }, options);
return { pdf, filename: `${doc.number}.pdf` };
}

View File

@ -0,0 +1,103 @@
/**
* Refund to payer: SettleKit prepares the exact transfer back to the buyer's
* wallet (no custody, SettleKit never signs), the merchant signs it with
* their own wallet, and the refund is marked succeeded only after the
* transfer is verified onchain with the same verifiers that confirm payments.
*
* EVM (Base, Ethereum, Arbitrum, Robinhood, HyperEVM, Tempo): an ERC-20
* transfer (calldata + EIP-681 link for mobile wallets).
* Solana: a Solana Pay transfer request with a unique reference.
*
* HyperCore and Zcash refunds stay record-only (send from the wallet app,
* then record the transaction).
*/
import {
toBaseUnits,
validationError,
type CheckoutSession,
type Payment,
type PaymentNetwork,
} from "@settlekit/common";
import { checkPayTo, getEvmChain, isEvmChainKey } from "@settlekit/chains";
import { USDC_MINT_DEVNET, USDC_MINT_MAINNET, createReference, encodeTransferRequestUrl } from "@settlekit/solana";
import type { AppContext } from "../context.js";
import { apiConfig, networkCatalog } from "./network-catalog.js";
export interface RefundTransferPlan {
network: PaymentNetwork;
to: string;
amount: string;
asset: string;
evm?: { chainId: number; token: string; data: string; eip681: string };
solana?: { url: string; reference: string; mint: string };
}
/** ERC-20 `transfer(address,uint256)` calldata. */
export function erc20TransferData(to: string, amountBase: bigint): string {
const addr = to.toLowerCase().replace(/^0x/, "").padStart(64, "0");
const value = amountBase.toString(16).padStart(64, "0");
return `0xa9059cbb${addr}${value}`;
}
function evmPlan(network: PaymentNetwork, to: string, amount: string): RefundTransferPlan {
if (!isEvmChainKey(network)) throw validationError(`${network} is not an EVM network`);
const cfg = apiConfig();
const env = cfg.evm.enabled[network]?.spec.env ?? cfg.evm.env;
const spec = cfg.evm.enabled[network]?.spec ?? getEvmChain(network, env);
if (!spec) throw validationError(`refunds are not available on ${network} in this deployment`);
const base = toBaseUnits(amount);
return {
network,
to,
amount,
asset: spec.token.symbol,
evm: {
chainId: spec.chainId,
token: spec.token.address,
data: erc20TransferData(to, base),
eip681: `ethereum:${spec.token.address}@${spec.chainId}/transfer?address=${to}&uint256=${base.toString()}`,
},
};
}
function solanaPlan(to: string, amount: string, refundId: string): RefundTransferPlan {
const cluster = apiConfig().solana?.cluster;
const mint = cluster === "devnet" ? USDC_MINT_DEVNET : USDC_MINT_MAINNET;
const reference = createReference();
const url = encodeTransferRequestUrl(
{ recipient: to, amount, splToken: mint, references: [reference], label: "Refund", memo: `refund:${refundId}` },
{ maxDecimals: 6 },
);
return { network: "solana", to, amount, asset: "USDC", solana: { url, reference, mint } };
}
/** Networks with a prepared refund transfer. */
export function supportsWalletRefund(network: PaymentNetwork): boolean {
return network === "solana" || (isEvmChainKey(network) && network !== "arc");
}
/** Build the transfer the merchant signs. */
export function refundPlan(network: PaymentNetwork, to: string, amount: string, refundId: string): RefundTransferPlan {
if (network === "solana") return solanaPlan(to, amount, refundId);
if (supportsWalletRefund(network)) return evmPlan(network, to, amount);
throw validationError(`prepared refunds are not available on ${network}; send it from your wallet and record the transaction`);
}
/** The buyer wallet a payment came from, when SettleKit knows it. */
export async function payerAddressFor(ctx: AppContext, payment: Payment): Promise<string | null> {
const session: CheckoutSession | null = await ctx.checkouts.findById(payment.checkoutSessionId);
if (session?.payerAddress) return session.payerAddress;
const customer = await ctx.customers.findById(payment.customerId);
return customer?.walletAddress ?? null;
}
/** Validate the refund destination for the payment's network. */
export function assertDestination(network: PaymentNetwork, to: string): void {
const check = checkPayTo(network, to);
if (!check.ok) throw validationError(`refund address is not a valid ${network} address: ${check.reason}`, { fields: ["to"] });
}
/** Asset label of the payment's network (USDC, USDG, USDC.e ...). */
export function assetFor(network: PaymentNetwork): string {
return networkCatalog().find((n) => n.network === network)?.asset ?? "USDC";
}

View File

@ -0,0 +1,40 @@
/**
* Apply a promo code to a draft checkout session inside the API (session
* create and payment-link visits). The discount is applied BEFORE network
* bindings, so a locked Zcash quote already reflects the discounted amount.
*/
import { money, multiplyMoney, validationError, type CheckoutSession, type Price } from "@settlekit/common";
import { quoteSessionCoupon, withSessionDiscount, type SessionLine } from "@settlekit/persistence";
import type { AppContext } from "../context.js";
/** Line totals of a draft session from its resolved prices. */
export function linesFor(session: CheckoutSession, prices: ReadonlyMap<string, Price>): SessionLine[] {
return session.lineItems.flatMap((line) => {
const price = prices.get(line.priceId);
if (!price || price.usageBased) return [];
return [
{
...(line.productId !== undefined ? { productId: line.productId } : { productId: price.productId }),
amount: multiplyMoney(money(price.amount, price.currency), line.quantity),
},
];
});
}
/** The draft with the promo applied, or a 400 naming why the code is refused. */
export async function applyPromo(
ctx: AppContext,
draft: CheckoutSession,
code: string,
prices: ReadonlyMap<string, Price>,
): Promise<CheckoutSession> {
const quote = await quoteSessionCoupon({
store: ctx.couponStore,
code,
organizationId: draft.organizationId,
lines: linesFor(draft, prices),
...(draft.customerId !== undefined ? { customerId: draft.customerId } : {}),
});
if (!quote.ok) throw validationError(quote.reason, { fields: { couponCode: quote.reason } });
return withSessionDiscount(draft, quote);
}

View File

@ -0,0 +1,107 @@
/**
* Hosted storefront: one branded page per merchant listing their active
* products, each opening its reusable payment link. Served by the checkout
* app at /store/<slug> (or the merchant's custom domain).
*/
import { SettleKitError, notFound, type Product } from "@settlekit/common";
import type { StoreSettings } from "@settlekit/persistence";
import { z } from "zod";
import type { AppContext } from "../context.js";
import { isInvoiceProduct } from "./invoice-payments.js";
import { activePrice, slugOf } from "./products.js";
import { payableNetworks } from "./payment-links.js";
export const storeSchema = z.object({
enabled: z.boolean(),
slug: z.string().trim().toLowerCase().regex(/^[a-z0-9](?:[a-z0-9-]{1,38}[a-z0-9])$/, "3-40 lowercase letters, digits or dashes"),
title: z.string().trim().max(80).optional(),
tagline: z.string().trim().max(160).optional(),
logoUrl: z.string().trim().url().refine((v) => v.startsWith("https://"), "logo must be an https:// image").optional(),
accentColor: z.string().trim().regex(/^#[0-9a-fA-F]{6}$/, "use a colour like #1e40a2").optional(),
seoDescription: z.string().trim().max(300).optional(),
customDomain: z
.string()
.trim()
.toLowerCase()
.regex(/^(?!-)[a-z0-9-]{1,63}(?:\.[a-z0-9-]{1,63})+$/, "a domain like shop.example.com")
.optional(),
});
const RESERVED = new Set(["admin", "api", "settlekit", "store", "www", "checkout", "pay"]);
/** Validate a store patch (slug unique across merchants). */
export async function validateStore(ctx: AppContext, organizationId: string, input: z.infer<typeof storeSchema>): Promise<StoreSettings> {
if (RESERVED.has(input.slug)) throw new SettleKitError({ code: "validation_error", message: "That store address is reserved" });
const taken = await ctx.orgSettings.findByStore?.({ slug: input.slug });
if (taken && taken.organizationId !== organizationId) {
throw new SettleKitError({ code: "conflict", message: "That store address is taken" });
}
if (input.customDomain) {
const domain = await ctx.orgSettings.findByStore?.({ domain: input.customDomain });
if (domain && domain.organizationId !== organizationId) {
throw new SettleKitError({ code: "conflict", message: "That domain is used by another store" });
}
}
return input;
}
export interface StorefrontProduct {
name: string;
description: string;
slug: string;
priceUsd: string;
displayCurrency: string | null;
displayAmount: string | null;
interval: string;
}
export interface Storefront {
slug: string;
title: string;
tagline: string | null;
logoUrl: string | null;
accentColor: string | null;
seoDescription: string | null;
merchantName: string;
/** Whether buyers can pay right now (the merchant finished payment setup). */
acceptingPayments: boolean;
networks: string[];
products: StorefrontProduct[];
}
/** The public storefront for a slug or custom domain. */
export async function loadStorefront(ctx: AppContext, match: { slug?: string; domain?: string }): Promise<Storefront> {
const found = await ctx.orgSettings.findByStore?.(match);
const store = found?.settings.store;
if (!found || !store?.enabled) throw notFound("This store does not exist");
const products = await ctx.products.list(
(p: Product) => p.organizationId === found.organizationId && p.status === "active" && !isInvoiceProduct(p) && slugOf(p) !== null,
);
const views: StorefrontProduct[] = [];
for (const product of products.sort((a, b) => a.createdAt.localeCompare(b.createdAt))) {
const price = await activePrice(ctx, product.id);
if (!price) continue;
views.push({
name: product.name,
description: product.description,
slug: slugOf(product)!,
priceUsd: price.amount,
displayCurrency: price.displayCurrency ?? null,
displayAmount: price.displayAmount ?? null,
interval: price.interval,
});
}
const { merchantName, accepted } = await payableNetworks(ctx, found.organizationId);
return {
slug: store.slug,
title: store.title || merchantName,
tagline: store.tagline ?? null,
logoUrl: store.logoUrl ?? null,
accentColor: store.accentColor ?? null,
seoDescription: store.seoDescription ?? null,
merchantName,
acceptingPayments: accepted.length > 0,
networks: accepted,
products: views,
};
}

View File

@ -15,24 +15,58 @@
* failure it throws a `unauthorized` {@link SettleKitError} (HTTP 401) which the
* error middleware maps to `{ error }`.
*
* A platform **service token** (`SETTLEKIT_SERVICE_TOKEN`) lets SettleKit's own
* hosted checkout call the onchain-billing API server-side on behalf of the
* checkout session's seller: it must name that seller in
* `X-SettleKit-Organization`, and it is accepted ONLY under
* `/v1/onchain-billing` (subscribe / grant / buyer cancel), never elsewhere.
* It never reaches a browser.
*
* A bootstrap key may be supplied via `API_BOOTSTRAP_KEY` so the very first
* caller can authenticate before any keys exist in the store — handy for local
* dev and for the test client.
*/
import { timingSafeEqual } from "node:crypto";
import type { MiddlewareHandler } from "hono";
import { SettleKitError } from "@settlekit/common";
import { isPlatformKey, isTeamRole, requiredScope, scopesAllow, scopesForRole } from "@settlekit/api-keys";
import { DEFAULT_ORG_ID } from "@settlekit/persistence";
import type { AppEnv } from "../context.js";
const BEARER_RE = /^Bearer\s+(.+)$/i;
const SERVICE_SCOPE = "/v1/onchain-billing/";
const ORG_HEADER = "x-settlekit-organization";
const ORG_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
/** Constant-time string comparison (length leak only). */
function safeEqual(a: string, b: string): boolean {
const left = Buffer.from(a);
const right = Buffer.from(b);
return left.length === right.length && timingSafeEqual(left, right);
}
function unauthorized(message: string): SettleKitError {
return new SettleKitError({ code: "unauthorized", message });
}
/** 403 unless `granted` covers the scope this request needs. */
function assertScope(granted: readonly string[], method: string, path: string, who: string): void {
const scope = requiredScope(method, path);
if (scopesAllow(granted, scope)) return;
throw new SettleKitError({
code: "forbidden",
message: `${who} does not have the ${scope} permission`,
details: { requiredScope: scope },
});
}
/** Require a valid Bearer API key on every request this middleware guards. */
export function authMiddleware(): MiddlewareHandler<AppEnv> {
const bootstrapKey = process.env.API_BOOTSTRAP_KEY;
const serviceToken = process.env.SETTLEKIT_SERVICE_TOKEN?.trim();
if (serviceToken !== undefined && serviceToken.length > 0 && serviceToken.length < 32) {
throw new Error("SETTLEKIT_SERVICE_TOKEN must be at least 32 characters");
}
return async (c, next) => {
const header = c.req.header("authorization");
@ -45,11 +79,23 @@ export function authMiddleware(): MiddlewareHandler<AppEnv> {
}
const plaintext = match[1].trim();
// Hosted-checkout service path: onchain billing only, bound to one seller.
if (serviceToken && safeEqual(plaintext, serviceToken)) {
if (!c.req.path.startsWith(SERVICE_SCOPE)) throw unauthorized("Service token is not valid for this route");
const org = c.req.header(ORG_HEADER)?.trim();
if (!org || !ORG_ID_RE.test(org)) throw unauthorized(`Service token requires the ${ORG_HEADER} header`);
c.set("apiKeyId", "service:checkout");
c.set("organizationId", org);
await next();
return;
}
// Bootstrap path: a configured static key authenticates without the store.
// It operates on the platform default organization.
if (bootstrapKey && plaintext === bootstrapKey) {
c.set("apiKeyId", "bootstrap");
c.set("organizationId", DEFAULT_ORG_ID);
c.set("grantedScopes", ["*"]);
await next();
return;
}
@ -57,6 +103,16 @@ export function authMiddleware(): MiddlewareHandler<AppEnv> {
const ctx = c.get("ctx");
const result = await ctx.apiKeys.verify(plaintext);
if (result.valid && result.apiKey) {
// Keys delivered to BUYERS (product access keys) are not management
// credentials: they must never act as the merchant.
if (!isPlatformKey(result.apiKey)) {
throw new SettleKitError({
code: "forbidden",
message: "This is a customer access key; it cannot call the SettleKit management API",
});
}
assertScope(result.apiKey.scopes, c.req.method, c.req.path, "This API key");
c.set("grantedScopes", result.apiKey.scopes);
// Best-effort usage stamp; never block the request on a usage write failure.
try {
await ctx.apiKeys.recordUsage(plaintext);
@ -76,9 +132,22 @@ export function authMiddleware(): MiddlewareHandler<AppEnv> {
const session = await ctx.auth.authenticateSession(plaintext);
if (session.ok) {
const { account } = session.value;
// Customer (buyer portal) accounts carry their seller's org id but are
// never management credentials.
if (account.type !== "merchant") {
throw new SettleKitError({
code: "forbidden",
message: "Customer accounts cannot call the SettleKit management API",
});
}
if (!account.organizationId) {
throw unauthorized("Session account has no organization");
}
// Team roles: accounts that created the org have no role (owner).
const role = account.role && isTeamRole(account.role) ? account.role : "owner";
assertScope(scopesForRole(role), c.req.method, c.req.path, `Your role (${role})`);
c.set("teamRole", role);
c.set("grantedScopes", scopesForRole(role));
c.set("apiKeyId", `session:${account.id}`);
c.set("organizationId", account.organizationId);
await next();

View File

@ -12,7 +12,13 @@ import {
createAccessHooks,
type OnchainBillingRuntime,
} from "@settlekit/onchain-billing";
import { DEFAULT_MERCHANT_ID, PgOnchainBillingStore } from "@settlekit/persistence";
import {
DEFAULT_MERCHANT_ID,
PgOnchainBillingStore,
emitWebhookSafely,
paymentConfirmedWebhook,
subscriptionChargedWebhook,
} from "@settlekit/persistence";
import { createHyperCoreClient, createHyperCoreUsdSender, loadHyperCoreConfig, type HyperCoreUsdSender } from "@settlekit/hyperliquid";
import type { AppContext } from "../context.js";
import { deliverOnchainSubscription } from "./delivery.js";
@ -40,6 +46,16 @@ export async function buildApiOnchainBilling(
async queueDelivery(delivery) {
await deliverOnchainSubscription(ctx, delivery);
},
async onCharged(sub, charge, period, paymentId) {
await emitWebhookSafely(ctx.webhookOutbox, subscriptionChargedWebhook(sub, charge, period, paymentId));
const payment = paymentId ? await ctx.payments.findById(paymentId) : null;
if (payment) {
await emitWebhookSafely(
ctx.webhookOutbox,
paymentConfirmedWebhook(payment, { productIds: [sub.productId], ...(sub.customerEmail ? { customerEmail: sub.customerEmail } : {}) }),
);
}
},
}, {
onError: (message, meta) => console.warn(`[onchain-billing] ${message}`, meta),
});

View File

@ -0,0 +1,123 @@
/**
* Read models for onchain subscriptions: what the merchant dashboard's
* Subscriptions page and the buyer's manage page render (status, next
* charge, what the buyer authorized, dunning state, charge history with
* explorer links). Never exposes the pending intent's typed data.
*/
import { fromBaseUnits } from "@settlekit/common";
import type { OnchainCharge, OnchainSubscription, OnchainBillingRuntime } from "@settlekit/onchain-billing";
import type { AppContext } from "../context.js";
import { explorerTxUrl, networkInfo } from "../merchant/network-catalog.js";
export interface ChargeView {
id: string;
periodIndex: number;
status: OnchainCharge["status"];
amount: string;
attempt: number;
txHash: string | null;
explorerUrl: string | null;
failureReason: string | null;
invoiceRef: string | null;
updatedAt: string;
}
export interface OnchainSubscriptionView {
id: string;
subscriptionId: string | null;
status: OnchainSubscription["status"];
/** past_due / suspended mean dunning is running or exhausted. */
dunning: "none" | "retrying" | "suspended";
network: OnchainSubscription["network"];
networkName: string;
method: OnchainSubscription["method"];
customerId: string;
customerEmail: string | null;
payer: string;
payTo: string;
productId: string;
productName: string;
priceId: string;
amountPerPeriod: string;
interval: "monthly" | "yearly";
periodsCovered: number;
/** price x periods: the most the buyer's grant allows in total. */
cap: string;
/** When the buyer's grant stops allowing pulls (null before activation). */
grantExpiresAt: string | null;
currentPeriodEnd: string | null;
/** Next scheduled pull / invoice; null when canceled or ending at period end. */
nextChargeAt: string | null;
cancelAtPeriodEnd: boolean;
canceledAt: string | null;
lastChargeError: string | null;
lastCharge: ChargeView | null;
charges: ChargeView[];
createdAt: string;
}
const YEAR_SECONDS = 360 * 86_400;
function at(anchorAt: string | undefined, seconds: number): string | null {
if (!anchorAt) return null;
return new Date(new Date(anchorAt).getTime() + seconds * 1000).toISOString();
}
export function chargeView(charge: OnchainCharge, network: OnchainSubscription["network"]): ChargeView {
return {
id: charge.id,
periodIndex: charge.periodIndex,
status: charge.status,
amount: fromBaseUnits(BigInt(charge.amount)),
attempt: charge.attempt,
txHash: charge.txHash ?? null,
explorerUrl: charge.txHash ? explorerTxUrl(network, charge.txHash) : null,
failureReason: charge.failureReason ?? null,
invoiceRef: charge.invoiceRef ?? null,
updatedAt: charge.updatedAt,
};
}
export async function onchainSubscriptionView(
ctx: AppContext,
runtime: OnchainBillingRuntime,
sub: OnchainSubscription,
): Promise<OnchainSubscriptionView> {
const charges = [...(await runtime.store.listCharges(sub.id))].sort(
(a, b) => a.periodIndex - b.periodIndex || a.attempt - b.attempt,
);
const product = await ctx.products.findById(sub.productId);
const active = sub.status === "active" || sub.status === "past_due";
const paidEnd = sub.paidThrough >= 0 ? at(sub.anchorAt, (sub.paidThrough + 1) * sub.periodSeconds) : null;
const next = active && !sub.cancelAtPeriodEnd ? (paidEnd ?? at(sub.anchorAt, 0)) : null;
const views = charges.map((charge) => chargeView(charge, sub.network));
return {
id: sub.id,
subscriptionId: sub.subscriptionId ?? null,
status: sub.status,
dunning: sub.status === "past_due" ? "retrying" : sub.status === "suspended" ? "suspended" : "none",
network: sub.network,
networkName: networkInfo(sub.network)?.name ?? sub.network,
method: sub.method,
customerId: sub.customerId,
customerEmail: sub.customerEmail ?? null,
payer: sub.payer,
payTo: sub.payTo,
productId: sub.productId,
productName: product?.name ?? sub.productId,
priceId: sub.priceId,
amountPerPeriod: sub.amountDisplay,
interval: sub.periodSeconds >= YEAR_SECONDS ? "yearly" : "monthly",
periodsCovered: sub.periodsCovered,
cap: fromBaseUnits(BigInt(sub.amountPerPeriod) * BigInt(sub.periodsCovered)),
grantExpiresAt: sub.status === "pending_grant" ? null : at(sub.anchorAt, sub.periodsCovered * sub.periodSeconds),
currentPeriodEnd: paidEnd,
nextChargeAt: next,
cancelAtPeriodEnd: sub.cancelAtPeriodEnd,
canceledAt: sub.canceledAt ?? null,
lastChargeError: sub.lastChargeError ?? null,
lastCharge: views.at(-1) ?? null,
charges: views,
createdAt: sub.createdAt,
};
}

View File

@ -0,0 +1,109 @@
/**
* HTTP helpers for the operator routes: domain-error mapping, JSON views
* (bigints as base-unit strings), owner checks and single-flight per event.
*/
import type { Context } from "hono";
import { SettleKitError } from "@settlekit/common";
import {
BillValidationError,
DuplicateEventError,
EscalationStateError,
EventValidationError,
OperatorServiceError,
PolicyDriftError,
PolicyValidationError,
X402Error,
} from "@settlekit/operator";
import type { AppEnv } from "../context.js";
/** Render bigints as base-unit decimal strings so bodies are JSON-safe. */
export function jsonView(value: unknown): unknown {
if (typeof value === "bigint") return value.toString();
if (Array.isArray(value)) return value.map(jsonView);
if (value !== null && typeof value === "object") {
return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, jsonView(v)]));
}
return value;
}
/** Map operator domain errors onto SettleKitError with the right status. */
export function toHttpError(err: unknown): unknown {
if (err instanceof EventValidationError || err instanceof BillValidationError || err instanceof PolicyValidationError) {
return new SettleKitError({ code: "validation_error", message: err.message, httpStatus: 400, details: { issues: [...err.issues] } });
}
if (err instanceof PolicyDriftError) {
return new SettleKitError({ code: "conflict", message: err.message, httpStatus: 409, details: { drift: [...err.issues] } });
}
if (err instanceof DuplicateEventError) {
return new SettleKitError({ code: "conflict", message: err.message, httpStatus: 409 });
}
if (err instanceof EscalationStateError || err instanceof X402Error) {
return new SettleKitError({ code: "conflict", message: err.message, httpStatus: 409 });
}
if (err instanceof OperatorServiceError) {
const notFound = /not found/.test(err.message);
return new SettleKitError({ code: notFound ? "not_found" : "conflict", message: err.message, httpStatus: notFound ? 404 : 409 });
}
return err;
}
export function forbidden(message: string): SettleKitError {
return new SettleKitError({ code: "forbidden", message, httpStatus: 403 });
}
export function notFound(message: string): SettleKitError {
return new SettleKitError({ code: "not_found", message, httpStatus: 404 });
}
/**
* Owner credentials: the bootstrap key, a first-party dashboard session (a
* human), or an API key id listed in OPERATOR_OWNER_KEY_IDS. Programmatic
* agent keys can submit events but never change policy or resolve escalations.
* `apiKeyId` is set only by the auth middleware ("bootstrap" for the env
* bootstrap key, "session:<accountId>" for verified sessions); stored API key
* ids are generated by @settlekit/api-keys and never use either form.
*/
export function isOwner(c: Context<AppEnv>, env: NodeJS.ProcessEnv = process.env): boolean {
const keyId = c.get("apiKeyId");
if (!keyId) return false;
if (keyId === "bootstrap" || keyId.startsWith("session:")) return true;
const owners = (env.OPERATOR_OWNER_KEY_IDS ?? "").split(",").map((s) => s.trim()).filter(Boolean);
return owners.includes(keyId);
}
export function ownerId(c: Context<AppEnv>): string {
return c.get("apiKeyId") ?? "unknown";
}
/** Run at most one handler per key at a time within this process. */
export class SingleFlight {
private inFlight: ReadonlyMap<string, Promise<unknown>> = new Map();
async run<T>(key: string, work: () => Promise<T>): Promise<T> {
const existing = this.inFlight.get(key);
if (existing) return existing as Promise<T>;
const promise = work().finally(() => {
this.inFlight = new Map([...this.inFlight].filter(([k]) => k !== key));
});
this.inFlight = new Map([...this.inFlight, [key, promise]]);
return promise;
}
}
/** Tiny TTL cache for public aggregates. */
export class TtlCache<T> {
private entry: { readonly at: number; readonly value: Promise<T> } | null = null;
constructor(private readonly ttlMs: number, private readonly now: () => number = Date.now) {}
get(load: () => Promise<T>): Promise<T> {
const t = this.now();
if (this.entry && t - this.entry.at < this.ttlMs) return this.entry.value;
const value = load().catch((error: unknown) => {
this.entry = null;
throw error;
});
this.entry = { at: t, value };
return value;
}
}

View File

@ -0,0 +1,29 @@
/**
* Process-wide operator runtime for the API, built lazily from the
* environment on first use (so importing the routes never touches the
* network or database). Disabled unless a vault is configured or
* OPERATOR_SIMULATION=1 is set explicitly.
*/
import { SettleKitError } from "@settlekit/common";
import { createOperatorRuntime, operatorEnabled, type OperatorRuntime } from "@settlekit/operator";
import { DEFAULT_ORG_ID } from "@settlekit/persistence";
let instance: OperatorRuntime | null = null;
function logError(context: string, error: unknown): void {
const message = error instanceof Error ? error.message : String(error);
process.stderr.write(`${JSON.stringify({ level: "error", service: "operator", context, message })}\n`);
}
export function getOperatorRuntime(): OperatorRuntime {
if (instance) return instance;
if (!operatorEnabled(process.env)) {
throw new SettleKitError({
code: "integration_error",
message: "The operator is not configured (set OPERATOR_VAULT_ADDRESS, or OPERATOR_SIMULATION=1 for a local simulation)",
httpStatus: 503,
});
}
instance = createOperatorRuntime(process.env, DEFAULT_ORG_ID, { onError: logError });
return instance;
}

View File

@ -0,0 +1,131 @@
/**
* Cash out to a bank: hand-off links to off-ramp partners.
*
* SettleKit never takes custody: the merchant opens the partner's sell flow
* with the amount, network and their own wallet prefilled, sends USDC from
* their wallet to the partner there, and receives fiat in their bank. A
* partner appears only when the owner configured its public key.
*
* Transak TRANSAK_API_KEY (+ TRANSAK_ENV=staging for the sandbox)
* MoonPay MOONPAY_PUBLISHABLE_KEY + MOONPAY_SECRET_KEY (URL signing)
* Ramp RAMP_HOST_API_KEY
*
* Parameter names follow each partner's published widget docs; check them
* against the partner dashboard when the account is opened.
*/
import { createHmac } from "node:crypto";
import { toBaseUnits, validationError, type PaymentNetwork } from "@settlekit/common";
export interface OfframpLink {
provider: "transak" | "moonpay" | "ramp";
name: string;
url: string;
}
export interface OfframpRequest {
network: PaymentNetwork;
/** USDC amount to sell, decimal string. */
amount: string;
/** The merchant's own wallet on `network` (refunds of failed sells go here). */
wallet: string;
/** Where the partner returns the merchant afterwards. */
returnUrl?: string;
}
/** Networks each partner supports for USDC sells, with its network/asset code. */
const TRANSAK_NETWORK: Partial<Record<PaymentNetwork, string>> = {
ethereum: "ethereum",
base: "base",
arbitrum: "arbitrum",
solana: "solana",
};
const MOONPAY_CURRENCY: Partial<Record<PaymentNetwork, string>> = {
ethereum: "usdc",
base: "usdc_base",
arbitrum: "usdc_arbitrum",
solana: "usdc_sol",
};
const RAMP_ASSET: Partial<Record<PaymentNetwork, string>> = {
ethereum: "ETH_USDC",
base: "BASE_USDC",
arbitrum: "ARBITRUM_USDC",
solana: "SOLANA_USDC",
};
function query(params: Record<string, string>): string {
return Object.entries(params)
.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
.join("&");
}
function transak(req: OfframpRequest, env: NodeJS.ProcessEnv): OfframpLink | null {
const apiKey = env.TRANSAK_API_KEY?.trim();
const network = TRANSAK_NETWORK[req.network];
if (!apiKey || !network) return null;
const base = env.TRANSAK_ENV === "staging" ? "https://global-stg.transak.com" : "https://global.transak.com";
const params: Record<string, string> = {
apiKey,
productsAvailed: "SELL",
cryptoCurrencyCode: "USDC",
network,
cryptoAmount: req.amount,
walletAddress: req.wallet,
...(req.returnUrl ? { redirectURL: req.returnUrl } : {}),
};
return { provider: "transak", name: "Transak", url: `${base}/?${query(params)}` };
}
function moonpay(req: OfframpRequest, env: NodeJS.ProcessEnv): OfframpLink | null {
const apiKey = env.MOONPAY_PUBLISHABLE_KEY?.trim();
const secret = env.MOONPAY_SECRET_KEY?.trim();
const currency = MOONPAY_CURRENCY[req.network];
if (!apiKey || !secret || !currency) return null;
const search = `?${query({
apiKey,
baseCurrencyCode: currency,
baseCurrencyAmount: req.amount,
quoteCurrencyCode: "usd",
refundWalletAddress: req.wallet,
...(req.returnUrl ? { redirectURL: req.returnUrl } : {}),
})}`;
// MoonPay requires URLs carrying wallet addresses to be signed with the secret key.
const signature = createHmac("sha256", secret).update(search).digest("base64");
return { provider: "moonpay", name: "MoonPay", url: `https://sell.moonpay.com/${search}&signature=${encodeURIComponent(signature)}` };
}
function ramp(req: OfframpRequest, env: NodeJS.ProcessEnv): OfframpLink | null {
const hostApiKey = env.RAMP_HOST_API_KEY?.trim();
const asset = RAMP_ASSET[req.network];
if (!hostApiKey || !asset) return null;
const params: Record<string, string> = {
hostApiKey,
hostAppName: "SettleKit",
enabledFlows: "OFFRAMP",
defaultFlow: "OFFRAMP",
swapAsset: asset,
offrampAsset: asset,
swapAmount: toBaseUnits(req.amount).toString(),
userAddress: req.wallet,
...(req.returnUrl ? { finalUrl: req.returnUrl } : {}),
};
return { provider: "ramp", name: "Ramp", url: `https://app.ramp.network/?${query(params)}` };
}
/** Every configured partner that can cash out USDC on `network`. */
export function offrampLinks(req: OfframpRequest, env: NodeJS.ProcessEnv = process.env): OfframpLink[] {
if (!/^\d+(\.\d{1,6})?$/.test(req.amount) || toBaseUnits(req.amount) <= 0n) {
throw validationError("amount must be a positive USDC amount", { fields: ["amount"] });
}
return [transak(req, env), moonpay(req, env), ramp(req, env)].filter((l): l is OfframpLink => l !== null);
}
/** Partners configured at all (for the dashboard to explain what is missing). */
export function configuredOfframps(env: NodeJS.ProcessEnv = process.env): string[] {
return [
env.TRANSAK_API_KEY?.trim() ? "transak" : null,
env.MOONPAY_PUBLISHABLE_KEY?.trim() && env.MOONPAY_SECRET_KEY?.trim() ? "moonpay" : null,
env.RAMP_HOST_API_KEY?.trim() ? "ramp" : null,
].filter((p): p is string => p !== null);
}

View File

@ -0,0 +1,339 @@
/**
* SettleKit's own revenue: monthly platform fee statements.
*
* Buyers pay merchants' wallets directly, so the per-payment fee advertised on
* the pricing page is collected as a monthly statement: confirmed payments in
* the coverage window x the platform fee schedule, issued as an invoice from
* SettleKit's own organization (`PLATFORM_BILLING_ORG_ID`) and paid through
* SettleKit's own checkout (the same payable-invoice path merchants use).
*
* A merchant whose statement stays unpaid past its due date plus the grace
* period is `restricted`: the free plan's product limit (packages/pricing)
* applies until it is paid. Nothing is enforced while platform billing is not
* configured, so local runs and demo deployments behave exactly as before.
*/
import { money, SettleKitError, type Customer } from "@settlekit/common";
import { canCreateProduct, HOSTED_PLAN_LIMITS } from "@settlekit/pricing";
import {
billingStanding,
buildFeeStatement,
isBillingPeriod,
meetsMinimum,
periodBounds,
statementDescription,
type BillingPeriod,
type BillingStanding,
type FeeStatement,
} from "@settlekit/platform-billing";
import { payTokenOf, type Invoice } from "@settlekit/invoices";
import { generateId } from "@settlekit/common";
import type { AppContext } from "../context.js";
import { isInvoiceProduct, payUrlFor, reconcileInvoiceWithPayments, sendInvoice } from "../merchant/invoice-payments.js";
export const FEE_STATEMENT_KIND = "platform_fee";
export interface PlatformBillingConfig {
/** SettleKit's own organization: issues statements and receives fee payments. */
orgId: string;
/** Days after the period end a statement is due. */
dueDays: number;
/** Days after the due date before plan limits apply. */
graceDays: number;
/** Statements below this fee total are not issued (fees carry forward). */
minimum: string;
}
function intEnv(env: NodeJS.ProcessEnv, key: string, fallback: number, min: number, max: number): number {
const raw = env[key];
if (raw === undefined || raw.trim() === "") return fallback;
const n = Number(raw);
if (!Number.isInteger(n) || n < min || n > max) throw new Error(`${key} must be an integer in [${min}, ${max}]`);
return n;
}
/** Platform billing config, or null when `PLATFORM_BILLING_ORG_ID` is unset. */
export function loadPlatformBillingConfig(env: NodeJS.ProcessEnv = process.env): PlatformBillingConfig | null {
const orgId = env.PLATFORM_BILLING_ORG_ID?.trim();
if (!orgId) return null;
const minimum = env.PLATFORM_BILLING_MIN_USD?.trim() || "1";
if (!/^\d+(\.\d{1,6})?$/.test(minimum)) throw new Error("PLATFORM_BILLING_MIN_USD must be a decimal amount");
return {
orgId,
dueDays: intEnv(env, "PLATFORM_BILLING_DUE_DAYS", 14, 0, 90),
graceDays: intEnv(env, "PLATFORM_BILLING_GRACE_DAYS", 14, 0, 180),
minimum,
};
}
/**
* Every non-void fee statement issued to a merchant org, oldest first. Open
* statements are reconciled against their checkout sessions first, so a
* statement paid a moment ago already reads as paid.
*/
export async function statementsFor(ctx: AppContext, cfg: PlatformBillingConfig, merchantOrgId: string): Promise<Invoice[]> {
const all = await ctx.invoices.list();
const mine = all.filter(
(inv) =>
inv.organizationId === cfg.orgId &&
inv.metadata.kind === FEE_STATEMENT_KIND &&
inv.metadata.merchantOrgId === merchantOrgId &&
inv.status !== "void",
);
const current = await Promise.all(mine.map((inv) => reconcileInvoiceWithPayments(ctx, inv)));
return current.sort((a, b) => (a.metadata.coverageEnd ?? "").localeCompare(b.metadata.coverageEnd ?? ""));
}
/** Coverage starts where the last issued statement ended (epoch when none). */
function coverageStartOf(statements: readonly Invoice[]): Date {
const last = statements[statements.length - 1]?.metadata.coverageEnd;
return last ? new Date(last) : new Date(0);
}
/** The platform-org customer that represents a merchant org (created once). */
async function merchantCustomer(ctx: AppContext, cfg: PlatformBillingConfig, merchantOrgId: string): Promise<Customer> {
const [existing] = await ctx.customers.list(
(c) => c.organizationId === cfg.orgId && c.metadata.merchantOrgId === merchantOrgId,
);
const settings = await ctx.orgSettings.get(merchantOrgId);
if (existing) {
if (settings.supportEmail && existing.email !== settings.supportEmail) {
return ctx.customers.save({ ...existing, email: settings.supportEmail, name: settings.orgName });
}
return existing;
}
return ctx.customers.save({
id: generateId("customer"),
organizationId: cfg.orgId,
email: settings.supportEmail,
name: settings.orgName,
metadata: { merchantOrgId, source: "platform_billing" },
createdAt: new Date().toISOString(),
});
}
/** Fees accrued since the last statement (the current, unbilled window). */
export async function accruedFees(
ctx: AppContext,
cfg: PlatformBillingConfig | null,
merchantOrgId: string,
now: Date,
): Promise<FeeStatement> {
const statements = cfg ? await statementsFor(ctx, cfg, merchantOrgId) : [];
const start = coverageStartOf(statements);
return buildFeeStatement({
payments: await ctx.payments.findConfirmedByOrganization(merchantOrgId),
schedule: ctx.platformFeeSchedule,
coverageStart: start,
coverageEnd: new Date(Math.max(now.getTime(), start.getTime() + 1)),
});
}
export type StatementOutcome =
| { status: "issued"; invoice: Invoice; payUrl: string; emailedTo: string | null }
| { status: "exists"; invoice: Invoice }
| { status: "below_minimum"; fees: string };
/**
* Issue a merchant's statement for a closed month. Idempotent per
* (merchant, period); fees below the minimum carry into the next statement.
*/
export async function issueStatement(
ctx: AppContext,
cfg: PlatformBillingConfig,
merchantOrgId: string,
period: BillingPeriod,
now: Date = new Date(),
): Promise<StatementOutcome> {
if (!isBillingPeriod(period)) throw new SettleKitError({ code: "validation_error", message: "period must be YYYY-MM" });
const { end } = periodBounds(period);
if (end.getTime() > now.getTime()) {
throw new SettleKitError({ code: "validation_error", message: `period ${period} has not ended yet` });
}
return serialized(`${merchantOrgId}:${period}`, () => issueStatementOnce(ctx, cfg, merchantOrgId, period, end));
}
/**
* Per-key in-process lock: the scheduler tick and a manual run (or two ticks)
* must never issue the same statement twice.
*/
const statementLocks = new Map<string, Promise<unknown>>();
async function serialized<T>(key: string, work: () => Promise<T>): Promise<T> {
const previous = statementLocks.get(key) ?? Promise.resolve();
const run = previous.catch(() => undefined).then(work);
const tail = run.catch(() => undefined);
statementLocks.set(key, tail);
try {
return await run;
} finally {
if (statementLocks.get(key) === tail) statementLocks.delete(key);
}
}
/**
* The statement that wins when several exist for one period (another API
* instance raced this one): one already sent beats a draft, then the lowest
* id, so every instance agrees on the same winner.
*/
function winningStatement(candidates: readonly Invoice[]): Invoice {
return [...candidates].sort((a, b) => {
const sentA = a.status === "draft" ? 1 : 0;
const sentB = b.status === "draft" ? 1 : 0;
return sentA !== sentB ? sentA - sentB : a.id.localeCompare(b.id);
})[0]!;
}
async function sendStatement(ctx: AppContext, invoice: Invoice, email: string | undefined): Promise<StatementOutcome> {
const sent = await sendInvoice(ctx, invoice, email ? { payerEmail: email } : {});
return { status: "issued", invoice: sent.invoice, payUrl: sent.payUrl, emailedTo: sent.emailedTo };
}
async function issueStatementOnce(
ctx: AppContext,
cfg: PlatformBillingConfig,
merchantOrgId: string,
period: BillingPeriod,
end: Date,
): Promise<StatementOutcome> {
const statements = await statementsFor(ctx, cfg, merchantOrgId);
const existing = statements.find((s) => s.metadata.period === period);
if (existing) {
// A draft left behind by an interrupted run is sent now, not skipped forever.
if (existing.status === "draft") {
const customer = await merchantCustomer(ctx, cfg, merchantOrgId);
return sendStatement(ctx, existing, customer.email ?? undefined);
}
return { status: "exists", invoice: existing };
}
const start = coverageStartOf(statements);
if (start.getTime() >= end.getTime()) return { status: "below_minimum", fees: "0" };
const statement = buildFeeStatement({
payments: await ctx.payments.findConfirmedByOrganization(merchantOrgId),
schedule: ctx.platformFeeSchedule,
coverageStart: start,
coverageEnd: end,
});
if (!meetsMinimum(statement, cfg.minimum)) return { status: "below_minimum", fees: statement.fees.amount };
const customer = await merchantCustomer(ctx, cfg, merchantOrgId);
const created = await ctx.invoices.create({
organizationId: cfg.orgId,
customerId: customer.id,
lineItems: [{ description: statementDescription(statement, period), quantity: 1, unitAmount: money(statement.fees.amount) }],
dueAt: new Date(end.getTime() + cfg.dueDays * 86_400_000).toISOString(),
metadata: {
kind: FEE_STATEMENT_KIND,
merchantOrgId,
period,
coverageStart: statement.coverageStart,
coverageEnd: statement.coverageEnd,
paymentCount: String(statement.paymentCount),
grossVolume: statement.grossVolume.amount,
feeBps: String(statement.schedule.bps),
feeFixed: statement.schedule.fixed,
},
});
if (!created.ok) throw created.error;
// Another instance may have issued the same period meanwhile: keep one.
const forPeriod = (await statementsFor(ctx, cfg, merchantOrgId)).filter((s) => s.metadata.period === period);
const winner = winningStatement(forPeriod.some((s) => s.id === created.value.id) ? forPeriod : [...forPeriod, created.value]);
if (winner.id !== created.value.id) {
const voided = await ctx.invoices.void(created.value.id);
if (!voided.ok) throw voided.error;
return { status: "exists", invoice: winner };
}
return sendStatement(ctx, created.value, customer.email ?? undefined);
}
/** Merchant org ids that sell on this deployment (excluding the platform org). */
async function merchantOrgIds(ctx: AppContext, cfg: PlatformBillingConfig): Promise<string[]> {
const products = await ctx.products.list((p) => !isInvoiceProduct(p));
const ids = new Set(products.map((p) => p.organizationId));
ids.delete(cfg.orgId);
return [...ids].sort();
}
export interface StatementRunResult {
period: BillingPeriod;
results: ({ merchantOrgId: string } & ({ status: StatementOutcome["status"]; invoiceId?: string; fees?: string } | { status: "error"; error: string }))[];
}
/** Issue every merchant's statement for `period` (safe to re-run). */
export async function runStatements(
ctx: AppContext,
cfg: PlatformBillingConfig,
period: BillingPeriod,
now: Date = new Date(),
): Promise<StatementRunResult> {
const results: StatementRunResult["results"] = [];
for (const merchantOrgId of await merchantOrgIds(ctx, cfg)) {
const settings = await ctx.orgSettings.get(merchantOrgId);
if (settings.testAccount === true) continue;
try {
const outcome = await issueStatement(ctx, cfg, merchantOrgId, period, now);
results.push(
outcome.status === "below_minimum"
? { merchantOrgId, status: outcome.status, fees: outcome.fees }
: { merchantOrgId, status: outcome.status, invoiceId: outcome.invoice.id },
);
} catch (error) {
results.push({ merchantOrgId, status: "error", error: error instanceof Error ? error.message : String(error) });
}
}
return { period, results };
}
/** A merchant's standing from their open statements. */
export async function standingFor(
ctx: AppContext,
cfg: PlatformBillingConfig | null,
merchantOrgId: string,
now: Date = new Date(),
): Promise<BillingStanding> {
if (!cfg || merchantOrgId === cfg.orgId) return "good";
const statements = await statementsFor(ctx, cfg, merchantOrgId);
return billingStanding(
statements.map((s) => ({ status: s.status, ...(s.dueAt ? { dueAt: s.dueAt } : {}) })),
now,
cfg.graceDays,
);
}
/** Public-facing summary of one statement for the merchant. */
export function statementView(invoice: Invoice) {
const token = payTokenOf(invoice);
return {
id: invoice.id,
number: invoice.number,
period: invoice.metadata.period ?? null,
status: invoice.status,
total: invoice.total.amount,
currency: invoice.currency,
paymentCount: Number(invoice.metadata.paymentCount ?? "0"),
grossVolume: invoice.metadata.grossVolume ?? "0",
dueAt: invoice.dueAt ?? null,
paidAt: invoice.paidAt ?? null,
payUrl: token ? payUrlFor(token) : null,
};
}
/**
* Plan-limit gate for product creation: a restricted merchant keeps selling
* what they have but can only add products within the free plan's limit.
*/
export async function assertCanCreateProduct(ctx: AppContext, organizationId: string, now: Date = new Date()): Promise<void> {
const cfg = loadPlatformBillingConfig();
if ((await standingFor(ctx, cfg, organizationId, now)) !== "restricted") return;
const active = await ctx.products.list(
(p) => p.organizationId === organizationId && p.status === "active" && !isInvoiceProduct(p),
);
if (canCreateProduct("free", active.length)) return;
const open = (await statementsFor(ctx, cfg!, organizationId)).find((s) => s.status === "open");
const payUrl = open ? statementView(open).payUrl : null;
throw new SettleKitError({
code: "payment_required",
message: `Your SettleKit fee statement is overdue, so your account is limited to ${String(HOSTED_PLAN_LIMITS.free.products)} active products. Pay it to add more${payUrl ? `: ${payUrl}` : "."}`,
httpStatus: 402,
details: { payUrl },
});
}

View File

@ -0,0 +1,48 @@
/**
* Runs the monthly fee statements without an operator click: shortly after
* boot and then every few hours, the API issues the previous month's
* statements (idempotent per merchant and period: runs in one process are
* serialized, and a duplicate raced in by another instance is voided before
* it is sent). Only active when platform billing is
* configured; `PLATFORM_BILLING_AUTORUN=0` turns it off.
*/
import { previousPeriod } from "@settlekit/platform-billing";
import type { AppContext } from "../context.js";
import { loadPlatformBillingConfig, runStatements, type StatementRunResult } from "./fee-statements.js";
export const STATEMENT_TICK_MS = 6 * 60 * 60 * 1000;
const FIRST_TICK_MS = 60 * 1000;
type Log = (message: string, fields?: Record<string, unknown>) => void;
/** One scheduler tick: bill last month if needed. Null when not configured. */
export async function statementTick(ctx: AppContext, now: Date = new Date()): Promise<StatementRunResult | null> {
const cfg = loadPlatformBillingConfig();
if (!cfg) return null;
return runStatements(ctx, cfg, previousPeriod(now), now);
}
/** Start the timer; returns a stop function (no-op when disabled). */
export function startStatementScheduler(ctx: AppContext, log: Log, env: NodeJS.ProcessEnv = process.env): () => void {
if (!loadPlatformBillingConfig(env) || env.PLATFORM_BILLING_AUTORUN === "0") return () => {};
const tick = async (): Promise<void> => {
try {
const result = await statementTick(ctx);
if (!result) return;
const issued = result.results.filter((r) => r.status === "issued").length;
const errors = result.results.filter((r) => r.status === "error");
log("platform fee statements", { period: result.period, issued, errors: errors.length });
for (const e of errors) log("platform fee statement failed", { ...e });
} catch (error) {
log("platform fee statements failed", { error: error instanceof Error ? error.message : String(error) });
}
};
const first = setTimeout(() => void tick(), FIRST_TICK_MS);
const every = setInterval(() => void tick(), STATEMENT_TICK_MS);
first.unref();
every.unref();
return () => {
clearTimeout(first);
clearInterval(every);
};
}

View File

@ -25,6 +25,7 @@ import {
import type { AppEnv, AppContext } from "../context.js";
import { data } from "../http/respond.js";
import { requireOrg } from "../http/tenant.js";
import { computeGrowthMetrics } from "../analytics/metrics.js";
const DAY_MS = 24 * 60 * 60 * 1000;
@ -113,6 +114,34 @@ async function computeSummary(ctx: AppContext, organizationId: string, now: Date
export function analyticsRoutes(): Hono<AppEnv> {
const app = new Hono<AppEnv>();
// Conversion, per-link stats, churn and LTV over a window (default 30 days).
app.get("/metrics", async (c) => {
const ctx = c.get("ctx");
const org = requireOrg(c);
const days = Math.min(Math.max(Number(c.req.query("days") ?? 30) || 30, 1), 365);
const now = new Date();
const since = new Date(now.getTime() - days * DAY_MS);
const [sessions, payments, subscriptions, products, prices] = await Promise.all([
ctx.checkouts.listCreatedSince ? ctx.checkouts.listCreatedSince(since) : Promise.resolve([]),
ctx.payments.listByOrganization(org),
ctx.subscriptions.listByOrganization(org),
ctx.products.list((p) => p.organizationId === org),
ctx.prices.list(),
]);
return data(
c,
computeGrowthMetrics({
sessions: sessions.filter((s) => s.organizationId === org),
payments,
subscriptions,
products,
prices,
now,
days,
}),
);
});
app.get("/summary", async (c) => {
const ctx = c.get("ctx");
// Tenant-scoped: summary for the authenticated organization.

View File

@ -8,6 +8,8 @@
*/
import { Hono } from "hono";
import { z } from "zod";
import { SettleKitError, validationError, type ApiKey } from "@settlekit/common";
import { MANAGEMENT_SCOPES, PLATFORM_ADMIN_SCOPE, PLATFORM_KEY_PRODUCT, WILDCARD_SCOPE, isPlatformKey, scopesAllow } from "@settlekit/api-keys";
import type { AppEnv } from "../context.js";
import { created, data } from "../http/respond.js";
import { parseBody } from "../http/validate.js";
@ -32,17 +34,70 @@ const revokeSchema = z.object({
key: z.string().min(1),
});
const platformSchema = z.object({
/** Management scopes (e.g. payments:read, webhooks:write) or platform:admin. */
scopes: z
.array(z.enum([PLATFORM_ADMIN_SCOPE, ...MANAGEMENT_SCOPES] as [string, ...string[]]))
.min(1),
/** Who or what the key is for (shown in the dashboard). */
label: z.string().trim().min(1).max(60).default("API key"),
env: z.enum(["live", "test"]).default("live"),
});
function keyView(key: ApiKey) {
return { ...key, kind: isPlatformKey(key) ? ("platform" as const) : ("customer" as const) };
}
export function apiKeyRoutes(): Hono<AppEnv> {
const app = new Hono<AppEnv>();
// List all API key records (merchant-wide; never exposes plaintext).
// List the organization's key records (never exposes plaintext).
app.get("/", async (c) => {
return data(c, await c.get("ctx").apiKeys.list());
const org = requireOrg(c);
const keys = (await c.get("ctx").apiKeys.list()).filter((k) => k.organizationId === org);
return data(c, keys.map(keyView));
});
// Issue a platform key with restricted management scopes. A caller can only
// grant scopes it holds itself (no privilege escalation).
app.post("/platform", async (c) => {
const body = await parseBody(c, platformSchema);
const granted = c.get("grantedScopes") ?? [];
const exceeding = body.scopes.filter((s) => !scopesAllow(granted, s));
if (exceeding.length > 0) {
throw new SettleKitError({
code: "forbidden",
message: `You cannot grant scopes you do not hold: ${exceeding.join(", ")}`,
details: { scopes: exceeding },
});
}
const result = await c.get("ctx").apiKeys.issue({
organizationId: requireOrg(c),
customerId: body.label,
productId: PLATFORM_KEY_PRODUCT,
entitlementId: PLATFORM_KEY_PRODUCT,
scopes: body.scopes,
env: body.env,
});
return created(c, { apiKey: keyView(result.apiKey), plaintext: result.plaintext });
});
// Revoke a key of this organization by id.
app.post("/:id/revoke", async (c) => {
return data(c, keyView(await c.get("ctx").apiKeys.revokeById(c.req.param("id"), requireOrg(c))));
});
// Issue a new API key. Returns the one-time plaintext.
app.post("/", async (c) => {
const body = await parseBody(c, issueSchema);
// Customer access keys never carry management scopes (use /platform).
const management = body.scopes.filter((s) => s === WILDCARD_SCOPE || s === PLATFORM_ADMIN_SCOPE || (MANAGEMENT_SCOPES as readonly string[]).includes(s));
if (management.length > 0) {
throw validationError(`customer keys cannot carry management scopes (${management.join(", ")}); use POST /v1/api-keys/platform`, {
fields: ["scopes"],
});
}
const result = await c.get("ctx").apiKeys.issue({
organizationId: requireOrg(c),
customerId: body.customerId,

View File

@ -25,8 +25,11 @@ import { setCookie, deleteCookie } from "hono/cookie";
import { z } from "zod";
import { SettleKitError, generateId } from "@settlekit/common";
import { signCookie } from "@settlekit/auth";
import { PLATFORM_KEY_PRODUCT } from "@settlekit/api-keys";
import type { Account, Session } from "@settlekit/auth";
import type { AppEnv } from "../context.js";
import { isInvitationOpen } from "@settlekit/invitations";
import { hashInviteToken, loadTeam, saveTeam } from "./team.js";
import { created, data } from "../http/respond.js";
import { parseBody, unwrapResult } from "../http/validate.js";
@ -38,7 +41,7 @@ const SESSION_COOKIE = "sk_session";
* are org-scoped admin credentials (not tied to a sold product), so they reuse
* the api-key store with this sentinel + the `platform:admin` scope.
*/
const PLATFORM_SENTINEL = "__platform__";
const PLATFORM_SENTINEL = PLATFORM_KEY_PRODUCT;
const BEARER_RE = /^Bearer\s+(.+)$/i;
@ -78,6 +81,13 @@ const walletLinkSchema = z.object({
signature: z.string().regex(/^0x[0-9a-fA-F]{130}$/, "signature must be a 65-byte 0x-hex ECDSA signature"),
});
const acceptInviteSchema = z.object({
token: z.string().regex(/^[A-Za-z0-9_-]{1,64}\.[A-Za-z0-9_-]{16,64}$/, "invalid invitation link"),
/** Required when no account exists yet for the invited email. */
password: z.string().min(8).optional(),
displayName: z.string().trim().min(1).max(120).optional(),
});
const updateAccountSchema = z.object({
displayName: z.string().min(1).max(120).optional(),
});
@ -121,9 +131,11 @@ export function authRoutes(): Hono<AppEnv> {
// A new merchant gets its own organization (its tenant boundary). Customers
// join an explicitly-provided org. The org id is attached to the account so
// the merchant's platform key — and every scoped read/write — is isolated.
// A merchant ALWAYS gets a fresh org: a caller-supplied id would let anyone
// join (and receive an admin key for) an existing seller's organization.
// Teammates join through signed invitations instead.
const organizationId =
body.organizationId ??
(body.type === "merchant" ? generateId("organization") : undefined);
body.type === "merchant" ? generateId("organization") : body.organizationId;
const account: Account = unwrapResult(
await ctx.auth.registerWithPassword({
@ -277,6 +289,62 @@ export function authRoutes(): Hono<AppEnv> {
});
// POST /logout -> revoke the session token (idempotent) and clear the cookie.
// POST /invitations/accept -> join the inviting organization with the
// invited role. The emailed token proves control of the address. A new
// person sets a password here; an existing account without an org joins
// and signs in as usual.
app.post("/invitations/accept", async (c) => {
const ctx = c.get("ctx");
const body = await parseBody(c, acceptInviteSchema);
const organizationId = body.token.slice(0, body.token.indexOf("."));
const team = await loadTeam(ctx, organizationId);
const hash = hashInviteToken(body.token);
const invitation = team.invitations.find((inv) => inv.tokenHash === hash);
if (!invitation || !isInvitationOpen(invitation)) {
throw new SettleKitError({ code: "not_found", message: "This invitation is invalid or has expired" });
}
let account = await ctx.auth.findAccountByEmail(invitation.email);
let sessionToken: string | undefined;
if (account) {
if (account.organizationId && account.organizationId !== organizationId) {
throw new SettleKitError({ code: "conflict", message: "This email already belongs to another SettleKit organization" });
}
account = unwrapResult(await ctx.auth.assignOrganization(account.id, organizationId, invitation.role));
} else {
if (!body.password) {
throw new SettleKitError({ code: "validation_error", message: "Choose a password (8+ characters) to create your account" });
}
const registered = unwrapResult(
await ctx.auth.registerWithPassword({
type: "merchant",
email: invitation.email,
password: body.password,
organizationId,
...(body.displayName ? { displayName: body.displayName } : {}),
}),
);
account = unwrapResult(await ctx.auth.assignOrganization(registered.id, organizationId, invitation.role));
const login = unwrapResult(await ctx.auth.loginWithPassword({ email: invitation.email, password: body.password }));
setSessionCookie(c, login.session);
sessionToken = login.session.token;
}
const now = new Date().toISOString();
await saveTeam(ctx, organizationId, {
members: [
...team.members.filter((m) => m.accountId !== account!.id),
{ accountId: account.id, email: account.email, role: invitation.role, joinedAt: now },
],
invitations: team.invitations.map((inv) => (inv.id === invitation.id ? { ...inv, status: "accepted" as const } : inv)),
});
return data(c, {
account,
role: invitation.role,
...(sessionToken ? { sessionToken } : { requiresLogin: true }),
});
});
app.post("/logout", async (c) => {
const token = requireBearer(c.req.header("authorization"));
unwrapResult(await c.get("ctx").auth.logout(token));

View File

@ -0,0 +1,67 @@
/**
* Platform billing routes: what a merchant owes SettleKit.
*
* GET /v1/billing/fees schedule, standing, accrued (unbilled) fees, statements
* POST /v1/billing/statements/run issue every merchant's statement for a closed month
* (platform operator only: the platform org or bootstrap key)
*/
import { Hono } from "hono";
import { z } from "zod";
import { SettleKitError } from "@settlekit/common";
import { previousPeriod } from "@settlekit/platform-billing";
import type { AppEnv } from "../context.js";
import { data } from "../http/respond.js";
import { parseBody } from "../http/validate.js";
import { requireOrg } from "../http/tenant.js";
import {
accruedFees,
loadPlatformBillingConfig,
runStatements,
standingFor,
statementView,
statementsFor,
} from "../platform/fee-statements.js";
const runSchema = z.object({
period: z.string().regex(/^\d{4}-(0[1-9]|1[0-2])$/, "period must be YYYY-MM").optional(),
});
export function billingRoutes(): Hono<AppEnv> {
const app = new Hono<AppEnv>();
app.get("/fees", async (c) => {
const ctx = c.get("ctx");
const org = requireOrg(c);
const cfg = loadPlatformBillingConfig();
const now = new Date();
const accrued = await accruedFees(ctx, cfg, org, now);
const statements = cfg ? await statementsFor(ctx, cfg, org) : [];
return data(c, {
configured: cfg !== null,
schedule: ctx.platformFeeSchedule,
standing: await standingFor(ctx, cfg, org, now),
graceDays: cfg?.graceDays ?? null,
accrued: {
since: accrued.coverageStart,
paymentCount: accrued.paymentCount,
grossVolume: accrued.grossVolume.amount,
fees: accrued.fees.amount,
},
statements: statements.map(statementView).reverse(),
});
});
app.post("/statements/run", async (c) => {
const ctx = c.get("ctx");
const cfg = loadPlatformBillingConfig();
if (!cfg) {
throw new SettleKitError({ code: "validation_error", message: "platform billing is not configured (set PLATFORM_BILLING_ORG_ID)" });
}
const isOperator = c.get("apiKeyId") === "bootstrap" || requireOrg(c) === cfg.orgId;
if (!isOperator) throw new SettleKitError({ code: "forbidden", message: "only the platform operator can run statements" });
const body = await parseBody(c, runSchema);
return data(c, await runStatements(ctx, cfg, body.period ?? previousPeriod(new Date())));
});
return app;
}

View File

@ -25,6 +25,9 @@ import { parseBody } from "../http/validate.js";
import { requireOrg, requireOwned } from "../http/tenant.js";
import { payToFor } from "./payment-verification.js";
import { lockZcashQuoteFor, saveZcashSession } from "./zcash-quote.js";
import { applyPromo } from "../merchant/session-promo.js";
import { lockFx, withFx } from "../fx/session-fx.js";
import { withSessionTax } from "@settlekit/persistence";
const NETWORKS = PAYMENT_NETWORKS as unknown as readonly [PaymentNetwork, ...PaymentNetwork[]];
@ -54,6 +57,12 @@ const createSchema = z
cancelUrl: z.string().url().optional(),
collectedFields: z.record(z.string()).optional(),
ttlDays: z.number().int().positive().optional(),
/** Optional promo code; the session amount becomes the discounted total. */
couponCode: z.string().trim().min(1).max(64).optional(),
/** Buyer billing country (ISO alpha-2) for the seller's tax rate. */
billingCountry: z.string().trim().length(2).optional(),
/** Buyer VAT ID (EU B2B reverse charge when the seller enables it). */
vatId: z.string().trim().min(4).max(20).optional(),
})
.superRefine((body, ctx) => {
// Every payable network needs a valid destination for ITS chain: funds
@ -89,7 +98,7 @@ const createSchema = z
* payable (the paying tx must include it) and a locked ZEC quote when Zcash
* is payable (the buyer owes exactly that many zatoshis).
*/
async function withNetworkBindings(ctx: AppContext, session: CheckoutSession): Promise<CheckoutSession> {
export async function withNetworkBindings(ctx: AppContext, session: CheckoutSession): Promise<CheckoutSession> {
const accepted = session.acceptedNetworks ?? [session.network];
const withReference = accepted.includes("solana") ? { ...session, paymentReference: createReference() } : session;
if (!accepted.includes("zcash")) return withReference;
@ -141,11 +150,13 @@ export function checkoutRoutes(): Hono<AppEnv> {
}),
);
// Fiat-priced lines settle in USDC at a live rate locked on the session.
const fx = await lockFx(ctx.fxRates, priced, "");
const draft = createCheckoutSession({
organizationId: org,
merchantId: body.merchantId,
...(body.customerId !== undefined ? { customerId: body.customerId } : {}),
items: priced,
items: fx.items,
payToAddress: body.payToAddress,
network: body.network as PaymentNetwork,
...(body.successUrl !== undefined ? { successUrl: body.successUrl } : {}),
@ -153,8 +164,16 @@ export function checkoutRoutes(): Hono<AppEnv> {
...(body.collectedFields !== undefined ? { collectedFields: body.collectedFields } : {}),
...(body.ttlDays !== undefined ? { ttlDays: body.ttlDays } : {}),
});
const discounted =
body.couponCode !== undefined
? await applyPromo(ctx, withFx(draft, fx.quote), body.couponCode, new Map(fx.items.map((p) => [p.price.id, p.price])))
: withFx(draft, fx.quote);
const taxed = withSessionTax(discounted, (await ctx.orgSettings.get(org)).tax, {
...(body.billingCountry !== undefined ? { country: body.billingCountry } : {}),
...(body.vatId !== undefined ? { vatId: body.vatId } : {}),
});
const session = await withNetworkBindings(ctx, {
...draft,
...taxed,
...(body.acceptedNetworks !== undefined ? { acceptedNetworks: body.acceptedNetworks } : {}),
...(body.payToByNetwork !== undefined ? { payToByNetwork: body.payToByNetwork } : {}),
...(body.requireMemo === true ? { requireMemo: true } : {}),

View File

@ -12,16 +12,28 @@ import { notFound, type Entitlement } from "@settlekit/common";
import type { AppEnv } from "../context.js";
import { data } from "../http/respond.js";
import { parseBody, validate } from "../http/validate.js";
import { requireOwned, scopeToOrg } from "../http/tenant.js";
import { requireOrg, requireOwned, scopeToOrg } from "../http/tenant.js";
const verifySchema = z
.object({
customerId: z.string().min(1),
customerId: z.string().min(1).optional(),
/** Check by the buyer's checkout email instead of a customer id. */
email: z.string().email().optional(),
productId: z.string().optional(),
feature: z.string().optional(),
requiredCredits: z.number().int().positive().optional(),
})
.strict();
.strict()
.refine((b) => b.customerId !== undefined || b.email !== undefined, { message: "customerId or email is required" });
/** Customer ids of the caller's org to check: the given id, or every customer with the email. */
async function customerIdsFor(c: Context<AppEnv>, input: { customerId?: string | undefined; email?: string | undefined }): Promise<string[]> {
if (input.customerId) return [input.customerId];
const org = requireOrg(c);
const email = (input.email ?? "").toLowerCase();
const matches = await c.get("ctx").customers.list((cu) => cu.organizationId === org && cu.email.toLowerCase() === email);
return matches.map((cu) => cu.id);
}
const spendSchema = z.object({
customerId: z.string().min(1),
@ -40,20 +52,30 @@ export function entitlementRoutes(): Hono<AppEnv> {
app.get("/", async (c) => {
const ctx = c.get("ctx");
const customerId = c.req.query("customerId");
if (!customerId) throw notFound("customerId query param is required");
const email = c.req.query("email");
if (!customerId && !email) throw notFound("customerId or email query param is required");
const activeOnly = c.req.query("activeOnly") === "true";
const productId = c.req.query("productId");
const list = await ctx.entitlementRepo.listByCustomer(customerId, {
activeOnly,
...(productId !== undefined ? { productId } : {}),
});
return data(c, scopeToOrg(c, list));
const lists = await Promise.all(
(await customerIdsFor(c, { customerId, email })).map((id) =>
ctx.entitlementRepo.listByCustomer(id, { activeOnly, ...(productId !== undefined ? { productId } : {}) }),
),
);
return data(c, scopeToOrg(c, lists.flat()));
});
// Verify access (feature / credits / product).
// Verify access (feature / credits / product), scoped to the caller's org.
app.post("/verify", async (c) => {
const body = await parseBody(c, verifySchema);
const result = await c.get("ctx").entitlements.verify(body);
const org = requireOrg(c);
const { customerId: _id, email: _email, ...check } = body;
let result: { allowed: boolean; reason?: string } = { allowed: false, reason: "no_active_entitlement" };
for (const id of await customerIdsFor(c, body)) {
const attempt = await c.get("ctx").entitlements.verify({ ...check, customerId: id });
const owned = !attempt.entitlement || attempt.entitlement.organizationId === org;
if (attempt.allowed && owned) return data(c, attempt);
if (owned) result = attempt;
}
return data(c, result);
});

View File

@ -0,0 +1,262 @@
/**
* Merchant accounting exports (CSV), tenant-scoped.
*
* GET /v1/exports/payments.csv confirmed + refunded payments
* GET /v1/exports/refunds.csv refunds
* GET /v1/exports/invoices.csv invoices and payment requests
* GET /v1/exports/payouts.csv payouts
* GET /v1/exports/ledger.csv every wallet movement, all fields
* GET /v1/exports/xero.csv Xero bank statement import
* GET /v1/exports/quickbooks.csv QuickBooks Online bank upload
*
* Optional `?from=YYYY-MM-DD&to=YYYY-MM-DD` (to is exclusive). Every text
* cell is guarded against spreadsheet formula injection.
*/
import { Hono, type Context } from "hono";
import { validationError, type Payment } from "@settlekit/common";
import {
inRange,
ledgerCsv,
quickBooksStatementCsv,
toCsv,
xeroStatementCsv,
type LedgerEntry,
} from "@settlekit/exports";
import type { AppContext, AppEnv } from "../context.js";
import { ownedPaymentIds, requireOrg, scopeToOrg } from "../http/tenant.js";
import { reconcileInvoiceWithPayments } from "../merchant/invoice-payments.js";
const GUARD = { guardFormulas: true } as const;
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
function range(c: Context<AppEnv>): { from?: Date; to?: Date } {
const parse = (key: "from" | "to"): Date | undefined => {
const raw = c.req.query(key);
if (raw === undefined || raw === "") return undefined;
if (!DATE_RE.test(raw) || Number.isNaN(new Date(`${raw}T00:00:00Z`).getTime())) {
throw validationError(`${key} must be a date like 2026-09-01`, { fields: [key] });
}
return new Date(`${raw}T00:00:00Z`);
};
const from = parse("from");
const to = parse("to");
return { ...(from ? { from } : {}), ...(to ? { to } : {}) };
}
function within(iso: string | undefined, r: { from?: Date; to?: Date }): boolean {
if (!iso) return r.from === undefined && r.to === undefined;
const t = new Date(iso).getTime();
return (r.from === undefined || t >= r.from.getTime()) && (r.to === undefined || t < r.to.getTime());
}
function csv(c: Context<AppEnv>, name: string, body: string): Response {
const org = requireOrg(c).replace(/[^A-Za-z0-9_-]/g, "");
return c.body(body, 200, {
"content-type": "text/csv; charset=utf-8",
"content-disposition": `attachment; filename="settlekit-${org}-${name}.csv"`,
"cache-control": "private, no-store",
});
}
/** Buyer label for a payment: customer email when known, else the id. */
async function payeeFor(ctx: AppContext, customerId: string, cache: Map<string, string>): Promise<string> {
const known = cache.get(customerId);
if (known !== undefined) return known;
const customer = await ctx.customers.findById(customerId);
const label = customer?.email || customerId;
cache.set(customerId, label);
return label;
}
async function productNames(ctx: AppContext, payment: Payment): Promise<string> {
const session = await ctx.checkouts.findById(payment.checkoutSessionId);
if (!session) return "Payment";
const names = await Promise.all(
session.lineItems.map(async (l) => (l.productId ? (await ctx.products.findById(l.productId))?.name : undefined)),
);
return names.filter(Boolean).join(", ") || "Payment";
}
/** Every USDC movement of the org: payments in, refunds out. */
async function ledger(c: Context<AppEnv>): Promise<LedgerEntry[]> {
const ctx = c.get("ctx");
const org = requireOrg(c);
const payments = (await ctx.payments.listByOrganization(org)).filter(
(p) => p.status === "confirmed" || p.status === "refunded",
);
const cache = new Map<string, string>();
const byId = new Map(payments.map((p) => [p.id, p]));
const entries: LedgerEntry[] = [];
for (const p of payments) {
entries.push({
date: p.confirmedAt ?? p.createdAt,
amount: p.amount.amount,
currency: p.amount.currency,
payee: await payeeFor(ctx, p.customerId, cache),
description: await productNames(ctx, p),
reference: p.id,
network: p.network,
txHash: p.txHash ?? "",
kind: "payment",
});
}
const refunds = (await ctx.refundStore.listAll()).filter((r) => byId.has(r.paymentId) && r.status === "succeeded");
for (const r of refunds) {
const payment = byId.get(r.paymentId)!;
entries.push({
date: r.updatedAt,
amount: `-${r.amount.amount}`,
currency: r.amount.currency,
payee: await payeeFor(ctx, r.customerId, cache),
description: `Refund (${r.reason})`,
reference: r.id,
network: payment.network,
txHash: r.txHash ?? "",
kind: "refund",
});
}
return entries;
}
export function exportRoutes(): Hono<AppEnv> {
const app = new Hono<AppEnv>();
app.get("/payments.csv", async (c) => {
const ctx = c.get("ctx");
const r = range(c);
const cache = new Map<string, string>();
const payments = (await ctx.payments.listByOrganization(requireOrg(c)))
.filter((p) => within(p.confirmedAt ?? p.createdAt, r))
.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
const rows = await Promise.all(
payments.map(async (p) => ({ p, payee: await payeeFor(ctx, p.customerId, cache), items: await productNames(ctx, p) })),
);
return csv(
c,
"payments",
toCsv(
rows,
[
{ header: "id", value: (x) => x.p.id },
{ header: "created_at", value: (x) => x.p.createdAt },
{ header: "confirmed_at", value: (x) => x.p.confirmedAt ?? "" },
{ header: "status", value: (x) => x.p.status },
{ header: "amount", value: (x) => x.p.amount.amount },
{ header: "currency", value: (x) => x.p.amount.currency },
{ header: "network", value: (x) => x.p.network },
{ header: "tx_hash", value: (x) => x.p.txHash ?? "" },
{ header: "customer", value: (x) => x.payee },
{ header: "items", value: (x) => x.items },
{ header: "checkout_session_id", value: (x) => x.p.checkoutSessionId },
],
GUARD,
),
);
});
app.get("/refunds.csv", async (c) => {
const ctx = c.get("ctx");
const r = range(c);
const owned = await ownedPaymentIds(c);
const refunds = (await ctx.refundStore.listAll())
.filter((x) => owned.has(x.paymentId) && within(x.createdAt, r))
.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
return csv(
c,
"refunds",
toCsv(
refunds,
[
{ header: "id", value: (x) => x.id },
{ header: "payment_id", value: (x) => x.paymentId },
{ header: "created_at", value: (x) => x.createdAt },
{ header: "status", value: (x) => x.status },
{ header: "amount", value: (x) => x.amount.amount },
{ header: "currency", value: (x) => x.amount.currency },
{ header: "reason", value: (x) => x.reason },
{ header: "tx_hash", value: (x) => x.txHash ?? "" },
],
GUARD,
),
);
});
app.get("/invoices.csv", async (c) => {
const ctx = c.get("ctx");
const r = range(c);
const invoices = await Promise.all(
scopeToOrg(c, await ctx.invoices.list())
.filter((i) => within(i.issuedAt ?? i.paidAt ?? i.dueAt, r))
.map((i) => reconcileInvoiceWithPayments(ctx, i)),
);
const cache = new Map<string, string>();
const rows = await Promise.all(invoices.map(async (i) => ({ i, payee: await payeeFor(ctx, i.customerId, cache) })));
return csv(
c,
"invoices",
toCsv(
rows.sort((a, b) => a.i.number.localeCompare(b.i.number)),
[
{ header: "number", value: (x) => x.i.number },
{ header: "id", value: (x) => x.i.id },
{ header: "kind", value: (x) => x.i.metadata.kind ?? "invoice" },
{ header: "status", value: (x) => x.i.status },
{ header: "customer", value: (x) => x.payee },
{ header: "issued_at", value: (x) => x.i.issuedAt ?? "" },
{ header: "due_at", value: (x) => x.i.dueAt ?? "" },
{ header: "paid_at", value: (x) => x.i.paidAt ?? "" },
{ header: "subtotal", value: (x) => x.i.subtotal.amount },
{ header: "discount", value: (x) => x.i.discount?.amount ?? "0" },
{ header: "tax", value: (x) => x.i.tax?.amount ?? "0" },
{ header: "total", value: (x) => x.i.total.amount },
{ header: "currency", value: (x) => x.i.currency },
{ header: "paid_tx_hash", value: (x) => x.i.metadata.paidTxHash ?? "" },
],
GUARD,
),
);
});
app.get("/payouts.csv", async (c) => {
const ctx = c.get("ctx");
const r = range(c);
const payouts = (await ctx.payoutStore.listByOrganization(requireOrg(c)))
.filter((p) => within(p.createdAt, r))
.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
return csv(
c,
"payouts",
toCsv(
payouts,
[
{ header: "id", value: (x) => x.id },
{ header: "created_at", value: (x) => x.createdAt },
{ header: "status", value: (x) => x.status },
{ header: "amount", value: (x) => x.amount.amount },
{ header: "currency", value: (x) => x.amount.currency },
{ header: "network", value: (x) => x.network },
{ header: "wallet", value: (x) => x.walletAddress },
{ header: "tx_hash", value: (x) => x.txHash ?? "" },
],
GUARD,
),
);
});
app.get("/ledger.csv", async (c) => {
const r = range(c);
return csv(c, "ledger", ledgerCsv(inRange(await ledger(c), r.from, r.to)));
});
app.get("/xero.csv", async (c) => {
const r = range(c);
return csv(c, "xero-bank-statement", xeroStatementCsv(inRange(await ledger(c), r.from, r.to)));
});
app.get("/quickbooks.csv", async (c) => {
const r = range(c);
return csv(c, "quickbooks-bank-upload", quickBooksStatementCsv(inRange(await ledger(c), r.from, r.to)));
});
return app;
}

View File

@ -9,16 +9,31 @@
* POST /v1/invoices/:id/finalize draft -> open
* POST /v1/invoices/:id/pay open -> paid
* POST /v1/invoices/:id/void draft|open -> void
* POST /v1/invoices/:id/send issue + pay link + email (payable onchain)
* GET /v1/invoices/:id.pdf invoice (or receipt, once paid) PDF
* POST /v1/invoices/requests ad-hoc payment request (amount + memo), sent
*
* Reads reconcile an open, sent invoice against its checkout sessions, so the
* status flips to paid as soon as a confirmed payment exists.
*/
import { Hono, type Context } from "hono";
import { z } from "zod";
import { money } from "@settlekit/common";
import { generateId, money, validationError } from "@settlekit/common";
import { renderInvoicePdf } from "@settlekit/invoices";
import type { Invoice, InvoiceLineItem } from "@settlekit/invoices";
import type { AppEnv } from "../context.js";
import { created, data } from "../http/respond.js";
import { parseBody } from "../http/validate.js";
import { unwrapResult } from "../http/internal.js";
import { requireOrg, requireOwned, scopeToOrg } from "../http/tenant.js";
import {
closeInvoiceSessions,
invoiceMerchant,
payUrlFor,
reconcileInvoiceWithPayments,
sendInvoice,
} from "../merchant/invoice-payments.js";
import { payTokenOf, withoutReservedMetadata } from "@settlekit/invoices";
const amount = z.string().regex(/^\d+(\.\d+)?$/);
@ -45,6 +60,23 @@ const createSchema = z.object({
metadata: z.record(z.string()).optional(),
});
const sendSchema = z.object({
payerEmail: z.string().trim().email().optional(),
});
const requestSchema = z.object({
amount: amount.refine((v) => Number(v) > 0, "amount must be greater than zero"),
description: z.string().trim().min(1).max(280),
payerEmail: z.string().trim().email().optional(),
customerId: z.string().min(1).optional(),
dueAt: z.string().datetime().optional(),
metadata: z.record(z.string()).optional(),
/** Email the pay link to payerEmail (default true). Plugins that redirect set false. */
sendEmail: z.boolean().optional(),
/** Where the hosted checkout returns the payer after paying (https). */
successUrl: z.string().url().refine((v) => v.startsWith("https://") || v.startsWith("http://localhost"), "successUrl must be https").optional(),
});
function toLineItem(input: z.infer<typeof lineItemSchema>): InvoiceLineItem {
return { description: input.description, quantity: input.quantity, unitAmount: money(input.unitAmount) };
}
@ -52,7 +84,25 @@ function toLineItem(input: z.infer<typeof lineItemSchema>): InvoiceLineItem {
/** Load an invoice by id, requiring it belongs to the caller's org (else 404). */
async function ownedInvoice(c: Context<AppEnv>, id: string): Promise<Invoice> {
const found = await c.get("ctx").invoices.get(id);
return requireOwned(c, found.ok ? found.value : undefined, "invoice", id);
const owned = requireOwned(c, found.ok ? found.value : undefined, "invoice", id);
return reconcileInvoiceWithPayments(c.get("ctx"), owned);
}
/** The org customer for a payer email, created on first request. */
async function customerForEmail(c: Context<AppEnv>, email: string): Promise<string> {
const ctx = c.get("ctx");
const org = requireOrg(c);
const lower = email.toLowerCase();
const [existing] = await ctx.customers.list((cu) => cu.organizationId === org && cu.email.toLowerCase() === lower);
if (existing) return existing.id;
const customer = await ctx.customers.save({
id: generateId("customer"),
organizationId: org,
email,
metadata: { source: "payment_request" },
createdAt: new Date().toISOString(),
});
return customer.id;
}
export function invoiceRoutes(): Hono<AppEnv> {
@ -76,16 +126,61 @@ export function invoiceRoutes(): Hono<AppEnv> {
}
: {}),
...(body.dueAt !== undefined ? { dueAt: body.dueAt } : {}),
...(body.metadata !== undefined ? { metadata: body.metadata } : {}),
...(body.metadata !== undefined ? { metadata: withoutReservedMetadata(body.metadata) } : {}),
}),
);
return created(c, invoice);
});
// Ad-hoc payment request: one line, sent immediately. Registered before
// `/:id` routes so "requests" is never read as an invoice id.
app.post("/requests", async (c) => {
const ctx = c.get("ctx");
const body = await parseBody(c, requestSchema);
if (!body.customerId && !body.payerEmail) {
throw validationError("payerEmail or customerId is required", { fields: ["payerEmail", "customerId"] });
}
if (body.customerId) {
const customer = await ctx.customers.findById(body.customerId);
requireOwned(c, customer, "customer", body.customerId);
}
const customerId = body.customerId ?? (await customerForEmail(c, body.payerEmail!));
const invoice = unwrapResult(
await ctx.invoices.create({
organizationId: requireOrg(c),
customerId,
lineItems: [{ description: body.description, quantity: 1, unitAmount: money(body.amount) }],
...(body.dueAt !== undefined ? { dueAt: body.dueAt } : {}),
metadata: {
...withoutReservedMetadata(body.metadata),
kind: "payment_request",
...(body.successUrl ? { successUrl: body.successUrl } : {}),
},
}),
);
const sent = await sendInvoice(ctx, invoice, {
...(body.payerEmail ? { payerEmail: body.payerEmail } : {}),
...(body.sendEmail === false ? { skipEmail: true } : {}),
});
return created(c, sent);
});
app.get("/", async (c) => {
const ctx = c.get("ctx");
const customerId = c.req.query("customerId");
const invoices = await c.get("ctx").invoices.list(customerId ?? undefined);
return data(c, scopeToOrg(c, invoices));
const invoices = scopeToOrg(c, await ctx.invoices.list(customerId ?? undefined));
return data(c, await Promise.all(invoices.map((inv) => reconcileInvoiceWithPayments(ctx, inv))));
});
app.get("/:id{.+\\.pdf}", async (c) => {
const ctx = c.get("ctx");
const invoice = await ownedInvoice(c, c.req.param("id").replace(/\.pdf$/, ""));
const token = payTokenOf(invoice);
const pdf = await renderInvoicePdf(invoice, await invoiceMerchant(ctx, invoice.organizationId), token ? { payUrl: payUrlFor(token) } : {});
return c.body(new Uint8Array(pdf), 200, {
"content-type": "application/pdf",
"content-disposition": `inline; filename="${invoice.number}.pdf"`,
});
});
// `:id.html` must be matched before the bare `:id` route below.
@ -111,9 +206,20 @@ export function invoiceRoutes(): Hono<AppEnv> {
return data(c, invoice);
});
app.post("/:id/send", async (c) => {
const invoice = await ownedInvoice(c, c.req.param("id"));
const raw = await c.req.json().catch(() => ({}));
const body = sendSchema.safeParse(raw);
if (!body.success) throw validationError("payerEmail must be an email address", { fields: ["payerEmail"] });
const sent = await sendInvoice(c.get("ctx"), invoice, body.data.payerEmail ? { payerEmail: body.data.payerEmail } : {});
return data(c, sent);
});
app.post("/:id/void", async (c) => {
const ctx = c.get("ctx");
const { id } = await ownedInvoice(c, c.req.param("id"));
const invoice = unwrapResult(await c.get("ctx").invoices.void(id));
const invoice = unwrapResult(await ctx.invoices.void(id));
await closeInvoiceSessions(ctx, invoice);
return data(c, invoice);
});

View File

@ -0,0 +1,316 @@
/**
* Merchant workspace routes (dashboard). Every read and write is scoped to
* the authenticated organization.
*
* GET /v1/merchant/profile networks + receiving addresses
* POST /v1/merchant/profile save networks + addresses (validated per chain)
* GET /v1/merchant/networks networks this deployment runs (env, asset, enabled)
* GET /v1/merchant/overview onboarding state + headline numbers
* GET /v1/merchant/payments enriched payments (all networks)
* GET /v1/merchant/payments/:id payment detail + timeline
* POST /v1/merchant/payments/:id/refund record a refund sent manually (+ optionally revoke access)
* GET /v1/merchant/products products with price + payment link
* POST /v1/merchant/products create + price + publish in one step
* PATCH /v1/merchant/products/:id edit name / price / delivery / networks / status
* GET /v1/merchant/customers buyers with spend + entitlements
* GET /v1/merchant/balances live on-chain balances of receiving addresses
*/
import { Hono, type Context } from "hono";
import { z } from "zod";
import { conflict, isPaymentNetwork, notFound, toBaseUnits, validationError, type Payment, type Product } from "@settlekit/common";
import { isValidTxHash } from "@settlekit/chains";
import { refundPayment } from "@settlekit/payments";
import type { AppContext, AppEnv } from "../context.js";
import { created, data } from "../http/respond.js";
import { parseBody } from "../http/validate.js";
import { unwrapResult } from "../http/internal.js";
import { requireOrg, requireOwned, requireOwnedPayment } from "../http/tenant.js";
import { loadProfile, networksForProfile, profileInputSchema, saveProfile } from "../merchant/profile.js";
import { networkCatalog } from "../merchant/network-catalog.js";
import { buildPaymentDetail, buildPaymentViews } from "../merchant/payment-views.js";
import {
createQuickProduct,
productPatchSchema,
productView,
quickProductSchema,
updateProduct,
} from "../merchant/products.js";
import { listCustomers } from "../merchant/customers.js";
import { readBalances } from "../merchant/balances.js";
import { refundSucceededWebhook } from "@settlekit/persistence";
import { emitWebhook } from "../webhooks/outbox.js";
import { isInvoiceProduct } from "../merchant/invoice-payments.js";
import { configuredOfframps, offrampLinks } from "../payouts/offramp.js";
import { assertDestination, payerAddressFor, refundPlan, supportsWalletRefund } from "../merchant/refund-to-payer.js";
import { assertTxHashUnused, requireTxHash, verifyOnChainOrThrow } from "./payment-verification.js";
import type { Refund } from "@settlekit/refunds";
import { assertCanCreateProduct } from "../platform/fee-statements.js";
const refundSchema = z.object({
reason: z.enum(["duplicate", "fraudulent", "customer_request", "delivery_failed"]).default("customer_request"),
/** Partial refund amount in USD; defaults to the full payment. */
amountUsd: z.string().regex(/^\d+(\.\d{1,6})?$/).optional(),
/** Transaction that sent the funds back from the merchant's wallet. */
txHash: z.string().trim().min(1).optional(),
revokeAccess: z.boolean().default(true),
});
const prepareRefundSchema = z.object({
reason: z.enum(["duplicate", "fraudulent", "customer_request", "delivery_failed"]).default("customer_request"),
/** Partial refund amount; defaults to what is still refundable. */
amountUsd: z.string().regex(/^\d+(\.\d{1,6})?$/).optional(),
/** Buyer wallet; defaults to the wallet that paid when known. */
to: z.string().trim().min(1).optional(),
});
const confirmRefundSchema = z.object({
txHash: z.string().trim().min(1),
revokeAccess: z.boolean().default(true),
});
/**
* Mark a refund succeeded: full refunds flip the payment to refunded, access
* granted by the payment is revoked (unless told not to) and the seller's
* refund.succeeded webhook is queued.
*/
async function settleRefund(
ctx: AppContext,
payment: Payment,
pending: Refund,
options: { txHash?: string; revokeAccess: boolean; source: "manual" | "wallet" },
): Promise<Refund> {
const settled = unwrapResult(await ctx.refunds.markSucceeded(pending.id));
const refund = options.txHash ? await ctx.refundStore.save({ ...settled, txHash: options.txHash }) : settled;
const amount = refund.amount.amount;
const priorOthers = (await ctx.refunds.listByPayment(payment.id)).filter((r) => r.id !== refund.id && r.status === "succeeded");
const refundedTotal = priorOthers.reduce((sum, r) => sum + toBaseUnits(r.amount.amount), toBaseUnits(amount));
if (refundedTotal >= toBaseUnits(payment.amount.amount)) await ctx.payments.save(refundPayment(payment));
if (options.revokeAccess) {
const granted = (await ctx.entitlementRepo.listByCustomer(payment.customerId)).filter(
(e) => e.grantedBy.type === "payment" && e.grantedBy.id === payment.id && e.status !== "revoked",
);
for (const e of granted) await ctx.entitlements.revoke(e.id, `refunded (${refund.reason})`);
}
await emitWebhook(
ctx.webhookOutbox,
refundSucceededWebhook({
refundId: refund.id,
payment,
amount,
reason: refund.reason,
txHash: options.txHash ?? null,
source: options.source,
}),
);
return refund;
}
async function ownedProduct(c: Context<AppEnv>, id: string): Promise<Product> {
return requireOwned(c, await c.get("ctx").products.findById(id), "product", id);
}
export function merchantRoutes(): Hono<AppEnv> {
const app = new Hono<AppEnv>();
app.get("/profile", async (c) => {
const profile = await loadProfile(c.get("ctx"), requireOrg(c));
return data(c, { profile, networks: networksForProfile(profile) });
});
app.post("/profile", async (c) => {
const body = await parseBody(c, profileInputSchema);
const profile = await saveProfile(c.get("ctx"), requireOrg(c), body);
return data(c, { profile, networks: networksForProfile(profile) });
});
app.get("/networks", (c) => data(c, networkCatalog()));
app.get("/overview", async (c) => {
const ctx = c.get("ctx");
const org = requireOrg(c);
const [profile, payments, products] = await Promise.all([
loadProfile(ctx, org),
ctx.payments.listByOrganization(org),
ctx.products.list((p) => p.organizationId === org && !isInvoiceProduct(p)),
]);
const confirmed = payments.filter((p) => p.status === "confirmed");
const byNetwork: Record<string, { count: number; volumeUsd: number }> = {};
for (const p of confirmed) {
const prev = byNetwork[p.network] ?? { count: 0, volumeUsd: 0 };
byNetwork[p.network] = { count: prev.count + 1, volumeUsd: prev.volumeUsd + Number(p.amount.amount) };
}
const firstProduct = products.find((p) => p.status === "active");
return data(c, {
onboarded: profile.onboarded,
acceptedNetworks: profile.acceptedNetworks,
productCount: products.length,
firstProduct: firstProduct ? await productView(ctx, firstProduct) : null,
paymentCount: confirmed.length,
volumeUsd: confirmed.reduce((sum, p) => sum + Number(p.amount.amount), 0).toFixed(2),
byNetwork,
});
});
app.get("/payments", async (c) => {
const ctx = c.get("ctx");
const status = c.req.query("status");
const network = c.req.query("network");
const all = await ctx.payments.listByOrganization(requireOrg(c));
const filtered = all
.filter((p) => !status || p.status === status)
.filter((p) => !network || p.network === network)
.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
return data(c, await buildPaymentViews(ctx, filtered));
});
app.get("/payments/:id", async (c) => {
const payment = await requireOwnedPayment(c, c.req.param("id"));
return data(c, await buildPaymentDetail(c.get("ctx"), payment));
});
app.post("/payments/:id/refund", async (c) => {
const ctx = c.get("ctx");
const payment = await requireOwnedPayment(c, c.req.param("id"));
const body = await parseBody(c, refundSchema);
if (payment.status !== "confirmed") throw conflict(`only confirmed payments can be refunded (payment is ${payment.status})`);
if (body.txHash !== undefined && !isValidTxHash(payment.network, body.txHash)) {
throw validationError(`refund transaction hash is not a valid ${payment.network} transaction id`);
}
const amount = body.amountUsd ?? payment.amount.amount;
const pending = unwrapResult(
await ctx.refunds.create({ payment, customerId: payment.customerId, amount, reason: body.reason }),
);
const refund = await settleRefund(ctx, payment, pending, {
...(body.txHash ? { txHash: body.txHash } : {}),
revokeAccess: body.revokeAccess,
source: "manual",
});
const updated = await ctx.payments.findById(payment.id);
return data(c, { refund, payment: await buildPaymentDetail(ctx, updated ?? payment) });
});
// Refund to payer, step 1: prepare the exact transfer back to the buyer's
// wallet for the merchant to sign (SettleKit never holds or signs funds).
app.post("/payments/:id/refund/prepare", async (c) => {
const ctx = c.get("ctx");
const payment = await requireOwnedPayment(c, c.req.param("id"));
const body = await parseBody(c, prepareRefundSchema);
if (payment.status !== "confirmed") throw conflict(`only confirmed payments can be refunded (payment is ${payment.status})`);
if (!supportsWalletRefund(payment.network)) {
throw validationError(`prepared refunds are not available on ${payment.network}; send it from your wallet and record the transaction`);
}
const to = body.to ?? (await payerAddressFor(ctx, payment));
if (!to) throw validationError("SettleKit does not know the buyer's wallet for this payment; enter the address to refund", { fields: ["to"] });
assertDestination(payment.network, to);
const amount = body.amountUsd ?? (await ctx.refunds.remainingRefundable(payment)).amount;
const pending = unwrapResult(
await ctx.refunds.create({ payment, customerId: payment.customerId, amount, reason: body.reason }),
);
const plan = refundPlan(payment.network, to, pending.amount.amount, pending.id);
const refund = await ctx.refundStore.save({
...pending,
destination: to,
network: payment.network,
source: "wallet",
...(plan.solana ? { reference: plan.solana.reference } : {}),
});
return created(c, { refund, plan });
});
// Refund to payer, step 2: verify the signed transfer onchain, then settle.
app.post("/refunds/:id/confirm", async (c) => {
const ctx = c.get("ctx");
const body = await parseBody(c, confirmRefundSchema);
const refund = await ctx.refundStore.findById(c.req.param("id"));
const payment = refund ? await ctx.payments.findById(refund.paymentId) : null;
requireOwned(c, payment, "refund", c.req.param("id"));
if (!refund || !payment) throw notFound("refund not found");
if (refund.status === "succeeded") return data(c, { refund, payment: await buildPaymentDetail(ctx, payment) });
if (refund.status !== "pending" || !refund.destination) throw conflict(`this refund is ${refund.status} and cannot be confirmed`);
const txHash = requireTxHash(payment.network, body.txHash);
await assertTxHashUnused(ctx, txHash);
const reused = (await ctx.refundStore.listAll()).find((r) => r.id !== refund.id && r.txHash === txHash);
if (reused) throw conflict("this transaction already settled another refund", { refundId: reused.id });
await verifyOnChainOrThrow(ctx, {
network: payment.network,
txHash,
amount: refund.amount.amount,
asset: refund.amount.currency,
payTo: refund.destination,
resource: `refund:${refund.id}`,
notBefore: refund.createdAt,
...(refund.reference ? { reference: refund.reference } : {}),
});
const settled = await settleRefund(ctx, payment, refund, { txHash, revokeAccess: body.revokeAccess, source: "wallet" });
const updated = await ctx.payments.findById(payment.id);
return data(c, { refund: settled, payment: await buildPaymentDetail(ctx, updated ?? payment) });
});
app.post("/refunds/:id/cancel", async (c) => {
const ctx = c.get("ctx");
const refund = await ctx.refundStore.findById(c.req.param("id"));
const payment = refund ? await ctx.payments.findById(refund.paymentId) : null;
requireOwned(c, payment, "refund", c.req.param("id"));
if (!refund) throw notFound("refund not found");
if (refund.status !== "pending") throw conflict(`this refund is ${refund.status}`);
return data(c, unwrapResult(await ctx.refunds.markFailed(refund.id, "canceled by the merchant")));
});
app.get("/products", async (c) => {
const ctx = c.get("ctx");
const org = requireOrg(c);
const products = await ctx.products.list((p) => p.organizationId === org && !isInvoiceProduct(p));
const views = await Promise.all(products.map((p) => productView(ctx, p)));
return data(c, views.sort((a, b) => b.createdAt.localeCompare(a.createdAt)));
});
app.post("/products", async (c) => {
const ctx = c.get("ctx");
const body = await parseBody(c, quickProductSchema);
await assertCanCreateProduct(ctx, requireOrg(c));
const product = await createQuickProduct(ctx, requireOrg(c), body);
return created(c, await productView(ctx, product));
});
app.get("/products/:id", async (c) => {
return data(c, await productView(c.get("ctx"), await ownedProduct(c, c.req.param("id"))));
});
app.patch("/products/:id", async (c) => {
const ctx = c.get("ctx");
const product = await ownedProduct(c, c.req.param("id"));
const body = await parseBody(c, productPatchSchema);
if (body.status === "active" && product.status !== "active") await assertCanCreateProduct(ctx, product.organizationId);
return data(c, await productView(ctx, await updateProduct(ctx, product, body)));
});
app.get("/customers", async (c) => {
return data(c, await listCustomers(c.get("ctx"), requireOrg(c)));
});
app.get("/balances", async (c) => {
const profile = await loadProfile(c.get("ctx"), requireOrg(c));
return data(c, await readBalances(profile.payToByNetwork));
});
// Cash out to a bank: partner sell links prefilled with the merchant's own
// wallet (no custody). Empty when no partner key is configured.
app.get("/offramp", async (c) => {
const profile = await loadProfile(c.get("ctx"), requireOrg(c));
const network = c.req.query("network") ?? "";
const amount = c.req.query("amount") ?? "";
if (!isPaymentNetwork(network)) throw validationError("network is required", { fields: ["network"] });
const wallet = profile.payToByNetwork[network];
if (!wallet) throw validationError(`you have no receiving wallet on ${network}`, { fields: ["network"] });
const returnUrl = process.env.DASHBOARD_PUBLIC_URL ? `${process.env.DASHBOARD_PUBLIC_URL.replace(/\/+$/, "")}/payouts` : undefined;
return data(c, {
network,
amount,
wallet,
configured: configuredOfframps(),
links: offrampLinks({ network, amount, wallet, ...(returnUrl ? { returnUrl } : {}) }),
});
});
return app;
}

View File

@ -16,6 +16,7 @@ import { Hono } from "hono";
import type { AppEnv, AppContext } from "../context.js";
import { data } from "../http/respond.js";
import { requireOrg } from "../http/tenant.js";
import { isInvoiceProduct } from "../merchant/invoice-payments.js";
/** A single activation step, with where to go to complete it. */
export interface OnboardingStep {
@ -42,7 +43,7 @@ async function computeOnboarding(
ctx: AppContext,
organizationId: string,
): Promise<OnboardingStatus> {
const products = await ctx.products.list((p) => p.organizationId === organizationId);
const products = await ctx.products.list((p) => p.organizationId === organizationId && !isInvoiceProduct(p));
const productIds = new Set(products.map((p) => p.id));
const [prices, confirmedPayments, payouts] = await Promise.all([

View File

@ -3,8 +3,8 @@
*
* GET /v1/onchain-billing/networks billable networks + methods
* POST /v1/onchain-billing/subscriptions create intent -> what the buyer signs/sends
* GET /v1/onchain-billing/subscriptions?customerId= list (org-scoped)
* GET /v1/onchain-billing/subscriptions/:id one subscription + its charges
* GET /v1/onchain-billing/subscriptions?customerId=&view=1 list (org-scoped; view=1 -> dashboard read model)
* GET /v1/onchain-billing/subscriptions/:id one subscription + its charges + read model
* POST /v1/onchain-billing/subscriptions/:id/grant submit the signed grant; charges period 0
* POST /v1/onchain-billing/subscriptions/:id/charge charge the due period now (idempotent)
* POST /v1/onchain-billing/subscriptions/:id/cancel cancel (at period end by default) + revoke actions
@ -13,7 +13,8 @@
* POST /v1/onchain-billing/escrow/:id/authorize submit the payer signature
* POST /v1/onchain-billing/escrow/:id/capture|void operator actions
* GET /v1/onchain-billing/escrow/:id/reclaim payer calldata after authorization expiry
* POST /v1/onchain-billing/refunds owner refund, dispatched per network
* GET /v1/onchain-billing/refunds/route?paymentId= can the operator send this refund automatically?
* POST /v1/onchain-billing/refunds owner refund, dispatched per network (sends funds)
*/
import { Hono, type Context } from "hono";
import { z } from "zod";
@ -25,10 +26,12 @@ import {
notFound,
toBaseUnits,
validationError,
type Customer,
type Payment,
} from "@settlekit/common";
import { checkPayTo, type Hex } from "@settlekit/chains";
import { completeSession, createCheckoutSession } from "@settlekit/payments";
import { completeSession, createCheckoutSession, refundPayment } from "@settlekit/payments";
import { refundSucceededWebhook, subscriptionCanceledWebhook } from "@settlekit/persistence";
import {
BILLING_METHODS,
ChargeDeclinedError,
@ -44,6 +47,9 @@ import { created, data } from "../http/respond.js";
import { parseBody } from "../http/validate.js";
import { ownedSubscription as ownedCoreSubscription, requireOrg, requireOwned, requireOwnedPayment } from "../http/tenant.js";
import { unwrapResult } from "../http/internal.js";
import { explorerTxUrl } from "../merchant/network-catalog.js";
import { onchainSubscriptionView } from "../onchain-billing/views.js";
import { emitWebhook } from "../webhooks/outbox.js";
const BILLING_NETWORKS = ["solana", "base", "arc", "ethereum", "arbitrum", "robinhood", "hyperevm", "tempo", "zcash", "hypercore"] as const;
const amount = z.string().regex(/^\d+(\.\d{1,6})?$/, "decimal amount with up to 6 decimals");
@ -60,6 +66,13 @@ const createSchema = z.object({
periods: z.number().int().min(1).max(120).optional(),
/** Link to an existing core subscription (else one is created on first charge). */
subscriptionId: z.string().min(1).optional(),
/** Delivery identities collected at checkout (GitHub invite, Discord role). */
buyer: z
.object({
githubUsername: z.string().trim().min(1).max(39).optional(),
discordUserId: z.string().regex(/^\d{15,21}$/).optional(),
})
.optional(),
});
const grantSchema = z.object({
@ -67,7 +80,11 @@ const grantSchema = z.object({
approveSignature: z.string().min(32).optional(),
});
const cancelSchema = z.object({ atPeriodEnd: z.boolean().optional() });
const cancelSchema = z.object({
atPeriodEnd: z.boolean().optional(),
/** Who asked: the seller (dashboard / API) or the buyer (hosted manage page). */
by: z.enum(["merchant", "buyer"]).optional(),
});
const escrowSchema = z.object({
payer: z.string().regex(/^0x[0-9a-fA-F]{40}$/),
@ -90,6 +107,8 @@ const refundSchema = z
reason: z.enum(["duplicate", "fraudulent", "customer_request", "delivery_failed"]),
/** Recipient for payments not made through onchain billing. */
to: z.string().min(1).optional(),
/** Revoke the access the payment granted (default true). */
revokeAccess: z.boolean().optional(),
})
.refine((b) => b.paymentId !== undefined || b.escrowPaymentId !== undefined, { message: "paymentId or escrowPaymentId is required" });
@ -191,6 +210,7 @@ export function onchainBillingRoutes(): Hono<AppEnv> {
await assertCustomerNotForeign(c, body.customerId);
if (body.subscriptionId) await ownedCoreSubscription(c, body.subscriptionId);
const organizationId = requireOrg(c);
await upsertBuyer(ctx, organizationId, body);
const checkoutSessionId = await recordSession(ctx, {
organizationId,
customerId: body.customerId,
@ -223,14 +243,24 @@ export function onchainBillingRoutes(): Hono<AppEnv> {
});
app.get("/subscriptions", async (c) => {
const runtime = billing(c);
const customerId = c.req.query("customerId");
const list = await billing(c).subscriptions.list({ organizationId: requireOrg(c), ...(customerId ? { customerId } : {}) });
return data(c, list);
const list = await runtime.subscriptions.list({ organizationId: requireOrg(c), ...(customerId ? { customerId } : {}) });
if (c.req.query("view") !== "1") return data(c, list);
const views = await Promise.all(
list.filter((s) => s.status !== "pending_grant").map((s) => onchainSubscriptionView(c.get("ctx"), runtime, s)),
);
return data(c, views.sort((a, b) => b.createdAt.localeCompare(a.createdAt)));
});
app.get("/subscriptions/:id", async (c) => {
const runtime = billing(c);
const sub = await ownedSubscription(c, c.req.param("id"));
return data(c, { subscription: sub, charges: await billing(c).store.listCharges(sub.id) });
return data(c, {
subscription: sub,
charges: await runtime.store.listCharges(sub.id),
view: await onchainSubscriptionView(c.get("ctx"), runtime, sub),
});
});
app.post("/subscriptions/:id/grant", async (c) => {
@ -261,10 +291,15 @@ export function onchainBillingRoutes(): Hono<AppEnv> {
});
app.post("/subscriptions/:id/cancel", async (c) => {
const ctx = c.get("ctx");
const runtime = billing(c);
const sub = await ownedSubscription(c, c.req.param("id"));
const body = await parseBody(c, cancelSchema);
const result = await guard(() => billing(c).subscriptions.cancel(sub.id, body.atPeriodEnd ?? true));
return data(c, jsonSafe(result));
const atPeriodEnd = body.atPeriodEnd ?? true;
const result = await guard(() => runtime.subscriptions.cancel(sub.id, atPeriodEnd));
await markCoreCanceled(ctx, result.subscription.subscriptionId, atPeriodEnd);
await emitWebhook(ctx.webhookOutbox, subscriptionCanceledWebhook(result.subscription, atPeriodEnd, body.by ?? "merchant"));
return data(c, { ...(jsonSafe(result) as object), view: await onchainSubscriptionView(ctx, runtime, result.subscription) });
});
app.post("/escrow", async (c) => {
@ -349,11 +384,35 @@ export function onchainBillingRoutes(): Hono<AppEnv> {
return data(c, await guard(() => (runtime.escrow as NonNullable<typeof runtime.escrow>).reclaimCall(record.id)));
});
app.get("/refunds/route", async (c) => {
const runtime = billing(c);
const paymentId = c.req.query("paymentId");
if (!paymentId) throw validationError("paymentId query param is required");
const payment = await requireOwnedPayment(c, paymentId);
const escrow = paymentId.startsWith("pay_esc_");
const route = runtime.refunds.routeFor(payment.network, escrow);
const known = await knownPayer(c, payment.id);
return data(c, {
paymentId,
network: payment.network,
route,
automated: route !== null,
/** The payer's wallet when onchain billing recorded it; otherwise the seller supplies `to`. */
to: known,
needsRecipient: route !== null && !escrow && known === null,
operator: runtime.operatorAddress,
reason: route === null ? `The SettleKit operator wallet is not configured to send refunds on ${payment.network}.` : null,
});
});
app.post("/refunds", async (c) => {
const ctx = c.get("ctx");
const runtime = billing(c);
const body = await parseBody(c, refundSchema);
const target = await resolveRefundTarget(c, body);
if (target.payment.status !== "confirmed") {
throw validationError(`only confirmed payments can be refunded (payment is ${target.payment.status})`);
}
const refund = unwrapResult(
await ctx.refunds.create({ payment: target.payment, customerId: target.payment.customerId, amount: body.amount, reason: body.reason }),
);
@ -367,8 +426,24 @@ export function onchainBillingRoutes(): Hono<AppEnv> {
...(target.escrowPaymentId ? { escrowPaymentId: target.escrowPaymentId } : {}),
}),
);
const succeeded = unwrapResult(await ctx.refunds.markSucceeded(refund.id));
return created(c, { refund: succeeded, execution });
const marked = unwrapResult(await ctx.refunds.markSucceeded(refund.id));
const succeeded = await ctx.refundStore.save({ ...marked, txHash: execution.txHash });
await settleRefund(ctx, target.payment, body.amount, body.reason, body.revokeAccess ?? true);
await emitWebhook(
ctx.webhookOutbox,
refundSucceededWebhook({
refundId: succeeded.id,
payment: target.payment,
amount: body.amount,
reason: body.reason,
txHash: execution.txHash,
source: execution.route === "escrow_refund" ? "escrow" : "operator",
}),
);
return created(c, {
refund: succeeded,
execution: { ...execution, explorerUrl: explorerTxUrl(target.network, execution.txHash) },
});
} catch (error) {
const reason = error instanceof Error ? error.message : "refund failed";
await ctx.refunds.markFailed(refund.id, reason);
@ -447,8 +522,68 @@ async function resolveRefundTarget(
if (!sub) throw notFound("onchain charge for payment not found", { id: payment.id });
return { payment, network: sub.network, to: sub.payer };
}
if (!body.to) throw validationError("`to` (the payer's address) is required for payments made outside onchain billing");
const check = checkPayTo(payment.network, body.to);
const session = await ctx.checkouts.findById(payment.checkoutSessionId);
const to = body.to ?? session?.payerAddress;
if (!to) throw validationError("`to` (the payer's address) is required: this payment did not record the buyer's wallet");
const check = checkPayTo(payment.network, to);
if (!check.ok) throw validationError(`to ${check.reason}`);
return { payment, network: payment.network, to: body.to };
return { payment, network: payment.network, to };
}
/** Mirror an onchain cancel onto the linked core subscription. */
async function markCoreCanceled(ctx: AppContext, subscriptionId: string | undefined, atPeriodEnd: boolean): Promise<void> {
if (!subscriptionId) return;
const core = await ctx.subscriptions.findById(subscriptionId);
if (!core || core.status === "canceled") return;
await ctx.subscriptions.save(atPeriodEnd ? { ...core, cancelAtPeriodEnd: true } : { ...core, status: "canceled", cancelAtPeriodEnd: true });
}
/** The payer wallet onchain billing knows for a payment (subscription pulls / escrow). */
async function knownPayer(c: Context<AppEnv>, paymentId: string): Promise<string | null> {
const runtime = billing(c);
if (paymentId.startsWith("pay_esc_")) {
const record = await runtime.store.getEscrowPayment(paymentId.slice("pay_".length));
return record ? paymentInfoFromJson(record.paymentInfo).payer : null;
}
const chargeId = chargeIdForPayment(paymentId);
if (!chargeId) {
const payment = await c.get("ctx").payments.findById(paymentId);
const session = payment ? await c.get("ctx").checkouts.findById(payment.checkoutSessionId) : null;
return session?.payerAddress ?? null;
}
const charge = await runtime.store.getChargeById(chargeId);
const sub = charge ? await runtime.store.getSubscription(charge.onchainSubscriptionId) : undefined;
return sub?.payer || null;
}
/** After funds moved: mark a full refund on the payment and revoke its access. */
async function settleRefund(ctx: AppContext, payment: Payment, amount: string, reason: string, revokeAccess: boolean): Promise<void> {
if (money(amount).amount === money(payment.amount.amount).amount) await ctx.payments.save(refundPayment(payment));
if (!revokeAccess) return;
const granted = (await ctx.entitlementRepo.listByCustomer(payment.customerId)).filter(
(e) => e.grantedBy.type === "payment" && e.grantedBy.id === payment.id && e.status !== "revoked",
);
for (const e of granted) await ctx.entitlements.revoke(e.id, `refunded (${reason})`);
}
/** Create / refresh the buyer's customer record so delivery knows their email, GitHub and Discord ids. */
async function upsertBuyer(
ctx: AppContext,
organizationId: string,
body: { customerId: string; email?: string | undefined; payer?: string | undefined; buyer?: { githubUsername?: string | undefined; discordUserId?: string | undefined } | undefined },
): Promise<void> {
const existing = await ctx.customers.findById(body.customerId);
const email = body.email ?? existing?.email;
if (!email) return;
const identities = {
...(body.buyer?.githubUsername ? { githubUsername: body.buyer.githubUsername } : {}),
...(body.buyer?.discordUserId ? { discordUserId: body.buyer.discordUserId } : {}),
...(body.payer && !existing?.walletAddress ? { walletAddress: body.payer } : {}),
};
if (existing && Object.keys(identities).length === 0 && existing.email === email) return;
await ctx.customers.save({
...(existing ?? { id: body.customerId, organizationId, metadata: {}, createdAt: new Date().toISOString() }),
email,
...identities,
} satisfies Customer);
}

View File

@ -0,0 +1,202 @@
/**
* Autonomous operator routes (SettleKit Operator on Arc).
*
* Authenticated (Bearer API key or dashboard session), scoped to the org the
* operator vault is configured for:
* POST /v1/operator/events handle a business event
* GET /v1/operator/decisions hash-chained decision log
* GET /v1/operator/decisions/:id one decision
* POST /v1/operator/bills AP intake (manual or invoice text)
* GET /v1/operator/bills bills (?status=)
* GET /v1/operator/escalations escalations (?status=)
* POST /v1/operator/escalations/:id/approve owner only
* POST /v1/operator/escalations/:id/reject owner only
* GET /v1/operator/state vault buckets, spend vs caps, pending escalations
* GET /v1/operator/policy policy + on-chain drift
* PUT /v1/operator/policy owner only; refuses drift
*
* Public (no key):
* GET /v1/public/operator/proof live aggregates (demo org excluded)
* GET /v1/public/operator/verify/:id recompute chain + check Arc anchor
*/
import { Hono, type Context, type MiddlewareHandler } from "hono";
import { z } from "zod";
import {
findDecisionByEventRef,
parseOperatorEvent,
policyView,
type Bill,
type EscalationStatus,
type OperatorProof,
type OperatorRuntime,
} from "@settlekit/operator";
import type { AppEnv } from "../context.js";
import { authMiddleware } from "../middleware/auth.js";
import { created, data } from "../http/respond.js";
import { parseBody, validate } from "../http/validate.js";
import { requireOrg } from "../http/tenant.js";
import { getOperatorRuntime } from "../operator/runtime.js";
import { SingleFlight, TtlCache, forbidden, isOwner, jsonView, notFound, ownerId, toHttpError } from "../operator/http.js";
export interface OperatorRouteOptions {
readonly runtime?: () => OperatorRuntime;
readonly auth?: MiddlewareHandler<AppEnv>;
readonly proofTtlMs?: number;
}
const listSchema = z.object({
afterSeq: z.coerce.number().int().min(-1).optional(),
limit: z.coerce.number().int().min(1).max(500).optional(),
});
const billSchema = z.union([
z.object({ invoiceText: z.string().min(1).max(50_000) }),
z.object({
payee: z.string(),
amountUsdc: z.string(),
dueAt: z.string(),
description: z.string(),
vendor: z.string().max(200).optional(),
}),
]);
const billStatus = z.object({ status: z.enum(["open", "paid", "escalated", "rejected"]).optional() });
const escalationStatus = z.object({ status: z.enum(["pending", "approved", "rejected", "expired"]).optional() });
const rejectSchema = z.object({ reason: z.string().min(1).max(1000) });
async function guarded<T>(work: () => Promise<T>): Promise<T> {
try {
return await work();
} catch (err) {
throw toHttpError(err);
}
}
function privateRoutes(runtime: () => OperatorRuntime): Hono<AppEnv> {
const app = new Hono<AppEnv>();
const flight = new SingleFlight();
/** The operator acts for exactly one org: the one its vault belongs to. */
const org = (c: Context<AppEnv>): string => {
const orgId = requireOrg(c);
if (orgId !== runtime().config.orgId) throw forbidden("The operator is not enabled for this organization");
return orgId;
};
const owner = (c: Context<AppEnv>): void => {
if (!isOwner(c)) throw forbidden("Only the organization owner can do this");
};
app.post("/events", async (c) => {
const orgId = org(c);
const raw = (await c.req.json().catch(() => null)) as Record<string, unknown> | null;
return guarded(async () => {
const event = parseOperatorEvent(raw && typeof raw === "object" ? { ...raw, orgId } : raw);
const rt = runtime();
const decision = await flight.run(`${orgId}:${event.id}`, async () => {
const existing = await findDecisionByEventRef(rt.store, orgId, event.id);
return existing ? { record: existing, replay: true } : { record: await rt.service.handle(event), replay: false };
});
return decision.replay ? data(c, jsonView(decision.record)) : created(c, jsonView(decision.record));
});
});
app.get("/decisions", async (c) => {
const orgId = org(c);
const q = validate(listSchema, c.req.query());
const records = await runtime().store.listDecisions(orgId, { afterSeq: q.afterSeq ?? -1, limit: q.limit ?? 100 });
return data(c, jsonView(records));
});
app.get("/decisions/:id", async (c) => {
const record = await runtime().store.getDecision(org(c), c.req.param("id"));
if (!record) throw notFound("Decision not found");
return data(c, jsonView(record));
});
app.post("/bills", async (c) => {
const orgId = org(c);
const body = await parseBody(c, billSchema);
return guarded(async () => {
const intake = runtime().intake;
const result = "invoiceText" in body ? await intake.fromInvoiceText(orgId, body.invoiceText) : await intake.manual(orgId, body);
return created(c, jsonView(result));
});
});
app.get("/bills", async (c) => {
const q = validate(billStatus, c.req.query());
const bills: readonly Bill[] = await runtime().store.listBills(org(c), q.status);
return data(c, jsonView(bills));
});
app.get("/escalations", async (c) => {
const q = validate(escalationStatus, c.req.query());
return data(c, jsonView(await runtime().store.listEscalations(org(c), q.status as EscalationStatus | undefined)));
});
app.post("/escalations/:id/approve", async (c) => {
const orgId = org(c);
owner(c);
const id = c.req.param("id");
return guarded(async () => data(c, jsonView(await flight.run(`esc:${id}`, () => runtime().service.approve(orgId, id, ownerId(c))))));
});
app.post("/escalations/:id/reject", async (c) => {
const orgId = org(c);
owner(c);
const body = await parseBody(c, rejectSchema);
const id = c.req.param("id");
return guarded(async () => data(c, jsonView(await flight.run(`esc:${id}`, () => runtime().service.reject(orgId, id, ownerId(c), body.reason)))));
});
app.get("/state", async (c) => {
const orgId = org(c);
const rt = runtime();
const state = await guarded(() => rt.state());
return data(c, { ...state, orgId, executor: rt.executorKind, vault: rt.config.vault?.address ?? null, explorerUrl: rt.config.explorerUrl });
});
app.get("/policy", async (c) => {
const rt = runtime();
const policy = await rt.policy.get(org(c));
return data(c, { policy: policyView(policy), drift: await rt.policy.drift(policy), executor: rt.executorKind, engine: rt.engineName, vault: rt.config.vault?.address ?? null });
});
app.put("/policy", async (c) => {
const orgId = org(c);
owner(c);
const body = (await c.req.json().catch(() => null)) as unknown;
return guarded(async () => data(c, { policy: policyView(await runtime().policy.put(orgId, body)) }));
});
return app;
}
function publicRoutes(runtime: () => OperatorRuntime, ttlMs: number): Hono<AppEnv> {
const app = new Hono<AppEnv>();
const cache = new TtlCache<OperatorProof>(ttlMs);
app.get("/proof", async (c) => {
const rt = runtime();
const proof = await cache.get(() => rt.proof());
return data(c, { ...proof, network: "arc-testnet", executor: rt.executorKind, vault: rt.config.vault?.address ?? null });
});
app.get("/verify/:id", async (c) => {
const result = await runtime().verify(c.req.param("id"));
if (!result) throw notFound("Decision not found");
return data(c, jsonView(result));
});
return app;
}
/** Mount at "/" (outside the v1 API-key group): serves both prefixes. */
export function operatorRoutes(options: OperatorRouteOptions = {}): Hono<AppEnv> {
const runtime = options.runtime ?? getOperatorRuntime;
const app = new Hono<AppEnv>();
app.route("/v1/public/operator", publicRoutes(runtime, options.proofTtlMs ?? 30_000));
const operator = new Hono<AppEnv>();
operator.use("*", options.auth ?? authMiddleware());
operator.route("/", privateRoutes(runtime));
app.route("/v1/operator", operator);
return app;
}

View File

@ -21,7 +21,9 @@ import {
refundPayment,
} from "@settlekit/payments";
import { completeSession } from "@settlekit/payments";
import { paymentConfirmedWebhook, redeemSessionCoupon } from "@settlekit/persistence";
import type { AppEnv, AppContext } from "../context.js";
import { emitWebhook } from "../webhooks/outbox.js";
import { created, data } from "../http/respond.js";
import { parseBody } from "../http/validate.js";
import { requireOrg, requireOwned, requireOwnedPayment } from "../http/tenant.js";
@ -168,10 +170,20 @@ export function paymentRoutes(): Hono<AppEnv> {
// Complete the session (idempotent) and grant entitlements for each product.
if (session.status === "open") {
await ctx.checkouts.save(completeSession(session));
const completed = completeSession(session);
// Count the promo redemption once, now that the discounted price is paid.
const redeemed = await redeemSessionCoupon(ctx.couponStore, completed, savedPayment.customerId);
await ctx.checkouts.save(redeemed ?? completed);
}
const entitlements = await grantEntitlements(ctx, savedPayment.id);
await emitWebhook(
ctx.webhookOutbox,
paymentConfirmedWebhook(savedPayment, {
...(session.collectedFields.email ? { customerEmail: session.collectedFields.email } : {}),
productIds: session.lineItems.flatMap((line) => (line.productId ? [line.productId] : [])),
}),
);
return data(c, { payment: savedPayment, entitlements });
});
@ -248,6 +260,7 @@ export function paymentRoutes(): Hono<AppEnv> {
// The on-chain verifier already enforced confirmations; mark confirmed.
const settled = confirmPayment(pending, txHash, Math.max(body.confirmations, 1), 1);
const saved = await ctx.payments.save(settled);
await emitWebhook(ctx.webhookOutbox, paymentConfirmedWebhook(saved));
return created(c, { payment: saved, deduped: false });
});

View File

@ -7,12 +7,14 @@
*/
import { Hono, type Context } from "hono";
import { z } from "zod";
import { generateId, type Price, type Product } from "@settlekit/common";
import { FIAT_CURRENCIES, fiatToUsdc, generateId, type Price, type Product } from "@settlekit/common";
import { createProductDraft, publishProduct } from "@settlekit/product-catalog";
import type { AppEnv } from "../context.js";
import { created, data } from "../http/respond.js";
import { parseBody } from "../http/validate.js";
import { requireOrg, requireOwned } from "../http/tenant.js";
import { isInvoiceProduct } from "../merchant/invoice-payments.js";
import { assertCanCreateProduct } from "../platform/fee-statements.js";
const PRODUCT_TYPES = [
"saas_plan",
@ -59,14 +61,34 @@ const createProductSchema = z.object({
metadata: z.record(z.unknown()).default({}),
});
const createPriceSchema = z.object({
amount: z.string().regex(/^\d+(\.\d+)?$/, "amount must be a decimal string"),
currency: z.literal("USDC").default("USDC"),
interval: z.enum(["one_time", "monthly", "yearly"]).default("one_time"),
usageBased: z.boolean().default(false),
unitAmount: z.string().regex(/^\d+(\.\d+)?$/).optional(),
creditsGranted: z.number().int().positive().optional(),
});
const createPriceSchema = z
.object({
/** USDC amount; optional when the price is set in a fiat currency. */
amount: z.string().regex(/^\d+(\.\d+)?$/, "amount must be a decimal string").optional(),
currency: z.literal("USDC").default("USDC"),
interval: z.enum(["one_time", "monthly", "yearly"]).default("one_time"),
usageBased: z.boolean().default(false),
unitAmount: z.string().regex(/^\d+(\.\d+)?$/).optional(),
creditsGranted: z.number().int().positive().optional(),
/** Price in a fiat currency; settles in USDC at the live rate per checkout. */
displayCurrency: z.enum(FIAT_CURRENCIES).optional(),
displayAmount: z.string().regex(/^\d+(\.\d{1,2})?$/, "displayAmount must be like 29 or 29.99").optional(),
})
.superRefine((body, ctx) => {
const fiat = body.displayCurrency !== undefined || body.displayAmount !== undefined;
if (fiat && (body.displayCurrency === undefined || body.displayAmount === undefined)) {
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["displayAmount"], message: "set displayCurrency and displayAmount together" });
}
if (!fiat && body.amount === undefined) {
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["amount"], message: "amount is required" });
}
if (fiat && body.interval !== "one_time") {
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["displayCurrency"], message: "subscriptions are priced in USD for now" });
}
if (fiat && body.usageBased) {
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["usageBased"], message: "usage prices are set in USDC" });
}
});
/** Load a product by id, requiring it belongs to the caller's org (else 404). */
async function ownedProduct(c: Context<AppEnv>, id: string): Promise<Product> {
@ -101,7 +123,7 @@ export function productRoutes(): Hono<AppEnv> {
app.get("/", async (c) => {
// Tenant-scoped: only the authenticated organization's products.
const org = requireOrg(c);
const products = await c.get("ctx").products.list((p) => p.organizationId === org);
const products = await c.get("ctx").products.list((p) => p.organizationId === org && !isInvoiceProduct(p));
return data(c, products);
});
@ -115,6 +137,7 @@ export function productRoutes(): Hono<AppEnv> {
const ctx = c.get("ctx");
const id = c.req.param("id");
const product = await ownedProduct(c, id);
if (product.status !== "active") await assertCanCreateProduct(ctx, product.organizationId);
const prices = await ctx.prices.list((p) => p.productId === id);
const published = publishProduct(product, prices);
return data(c, await ctx.products.save(published));
@ -127,10 +150,16 @@ export function productRoutes(): Hono<AppEnv> {
await ownedProduct(c, productId);
const body = await parseBody(c, createPriceSchema);
const fiat = body.displayCurrency !== undefined && body.displayAmount !== undefined;
// USDC reference value at creation; each checkout re-converts at the live rate.
const amount = fiat
? fiatToUsdc(body.displayAmount!, (await ctx.fxRates.usdPer(body.displayCurrency!)).rate)
: body.amount!;
const price: Price = {
id: generateId("price"),
productId,
amount: body.amount,
amount,
...(fiat ? { displayCurrency: body.displayCurrency!, displayAmount: body.displayAmount! } : {}),
currency: body.currency,
interval: body.interval,
usageBased: body.usageBased,

View File

@ -0,0 +1,121 @@
/**
* Public (unauthenticated) routes: buyers and visitors, no API key.
*
* GET /v1/public/networks networks this deployment runs
* GET /v1/public/links/:slug payment-link summary (product, price, networks)
* POST /v1/public/links/:slug/sessions open a fresh checkout session for one visit
* GET /v1/public/proof recent confirmed payments + totals per network
*
* Only non-sensitive data leaves these routes: no buyer identity, no seller
* account data beyond the display name on their own payment link.
*/
import { Hono } from "hono";
import { z } from "zod";
import type { AppEnv } from "../context.js";
import { created, data } from "../http/respond.js";
import { validate } from "../http/validate.js";
import { networkCatalog } from "../merchant/network-catalog.js";
import { linkSummary, openLinkSession } from "../merchant/payment-links.js";
import { buildProof } from "../merchant/proof.js";
import {
invoiceByToken,
invoiceMerchant,
openInvoiceSession,
payUrlFor,
publicInvoiceView,
} from "../merchant/invoice-payments.js";
import { renderInvoicePdf } from "@settlekit/invoices";
import { receiptPdf } from "../merchant/receipts.js";
import { loadStorefront } from "../merchant/storefront.js";
const tokenSchema = z.string().regex(/^[A-Za-z0-9_-]{16,128}$/, "invalid invoice link");
const sessionIdSchema = z.string().regex(/^[A-Za-z0-9_-]{8,100}$/, "invalid checkout session");
const storeSlugSchema = z.string().regex(/^[a-z0-9-]{3,40}$/, "invalid store");
const domainSchema = z.string().regex(/^[a-z0-9.-]{3,253}$/, "invalid domain");
const slugSchema = z.string().regex(/^[a-z0-9-]{4,64}$/, "invalid payment link");
const sessionSchema = z.object({
successUrl: z.string().url().optional(),
cancelUrl: z.string().url().optional(),
/** Promo code from the link (`/l/<slug>?promo=CODE`). */
promo: z.string().trim().min(1).max(64).optional(),
});
export function publicRoutes(): Hono<AppEnv> {
const app = new Hono<AppEnv>();
app.get("/networks", (c) => data(c, networkCatalog()));
app.get("/links/:slug", async (c) => {
const slug = validate(slugSchema, c.req.param("slug"));
return data(c, await linkSummary(c.get("ctx"), slug));
});
app.post("/links/:slug/sessions", async (c) => {
const slug = validate(slugSchema, c.req.param("slug"));
const raw = await c.req.json().catch(() => ({}));
const body = validate(sessionSchema, raw);
const session = await openLinkSession(c.get("ctx"), slug, body);
return created(c, { sessionId: session.id, expiresAt: session.expiresAt });
});
// Invoices + payment requests: the pay token IS the capability (unguessable,
// 24 random bytes); an unknown token answers 404, a malformed one 400.
app.get("/invoices/:token", async (c) => {
const token = validate(tokenSchema, c.req.param("token"));
const ctx = c.get("ctx");
return data(c, await publicInvoiceView(ctx, await invoiceByToken(ctx, token)));
});
app.post("/invoices/:token/sessions", async (c) => {
const token = validate(tokenSchema, c.req.param("token"));
const ctx = c.get("ctx");
const { session } = await openInvoiceSession(ctx, await invoiceByToken(ctx, token));
return created(c, { sessionId: session.id, expiresAt: session.expiresAt });
});
app.get("/invoices/:token/pdf", async (c) => {
const token = validate(tokenSchema, c.req.param("token"));
const ctx = c.get("ctx");
const invoice = await invoiceByToken(ctx, token);
const pdf = await renderInvoicePdf(invoice, await invoiceMerchant(ctx, invoice.organizationId), {
payUrl: payUrlFor(token),
});
return c.body(new Uint8Array(pdf), 200, {
"content-type": "application/pdf",
"content-disposition": `inline; filename="${invoice.number}.pdf"`,
"cache-control": "private, no-store",
});
});
// Receipt for a settled checkout; the checkout session id is the capability.
app.get("/receipts/:sessionId/pdf", async (c) => {
const sessionId = validate(sessionIdSchema, c.req.param("sessionId"));
const { pdf, filename } = await receiptPdf(c.get("ctx"), sessionId);
return c.body(new Uint8Array(pdf), 200, {
"content-type": "application/pdf",
"content-disposition": `inline; filename="${filename}"`,
"cache-control": "private, no-store",
});
});
// Hosted storefronts: by slug, or by the custom domain the host routes.
app.get("/stores/:slug", async (c) => {
const slug = validate(storeSlugSchema, c.req.param("slug"));
c.header("cache-control", "public, max-age=30");
return data(c, await loadStorefront(c.get("ctx"), { slug }));
});
app.get("/stores/by-domain/:domain", async (c) => {
const domain = validate(domainSchema, c.req.param("domain").toLowerCase());
c.header("cache-control", "public, max-age=30");
return data(c, await loadStorefront(c.get("ctx"), { domain }));
});
app.get("/proof", async (c) => {
c.header("cache-control", "public, max-age=30");
return data(c, await buildProof(c.get("ctx")));
});
return app;
}

View File

@ -9,7 +9,10 @@
*/
import { Hono } from "hono";
import { z } from "zod";
import { validationError } from "@settlekit/common";
import { normalizeTaxSettings } from "@settlekit/persistence";
import type { AppEnv } from "../context.js";
import { storeSchema, validateStore } from "../merchant/storefront.js";
import { data } from "../http/respond.js";
import { parseBody } from "../http/validate.js";
import { requireOrg } from "../http/tenant.js";
@ -21,6 +24,32 @@ const patchSchema = z.object({
payoutCurrency: z.string().min(1).optional(),
webhookSecret: z.string().optional(),
defaultRail: z.enum(["arc", "circle", "x402"]).optional(),
/** Exact origins allowed to embed the checkout (embed.js success callback). */
embedOrigins: z
.array(
z
.string()
.trim()
.regex(/^https:\/\/[a-z0-9.-]+(:\d{2,5})?$|^http:\/\/localhost(:\d{2,5})?$/i, "origins look like https://shop.example.com"),
)
.max(20)
.optional(),
/** Hosted storefront (/store/<slug>). */
store: storeSchema.optional(),
/** Checkout tax + seller tax identity printed on receipts. */
tax: z
.object({
enabled: z.boolean(),
label: z.string().max(40).default("Tax"),
sellerCountry: z.string().max(2).optional(),
taxId: z.string().max(64).optional(),
legalName: z.string().max(200).optional(),
addressLines: z.array(z.string().max(200)).max(6).optional(),
defaultRateBps: z.number().int().min(0).max(10_000).default(0),
rates: z.record(z.string(), z.number().int().min(0).max(10_000)).default({}),
reverseCharge: z.boolean().default(false),
})
.optional(),
});
export function settingsRoutes(): Hono<AppEnv> {
@ -35,8 +64,21 @@ export function settingsRoutes(): Hono<AppEnv> {
app.post("/", async (c) => {
const body = await parseBody(c, patchSchema);
// Drop any client-supplied organizationId; the tenant is the authenticated org.
const { organizationId, ...patch } = body;
const { organizationId, tax, embedOrigins, store, ...raw } = body;
const rest = {
...raw,
...(store !== undefined ? { store: await validateStore(c.get("ctx"), requireOrg(c), store) } : {}),
...(embedOrigins !== undefined ? { embedOrigins: [...new Set(embedOrigins.map((o) => o.toLowerCase()))] } : {}),
};
void organizationId;
let patch: typeof rest & { tax?: ReturnType<typeof normalizeTaxSettings> } = rest;
if (tax !== undefined) {
try {
patch = { ...rest, tax: normalizeTaxSettings(tax) };
} catch (error) {
throw validationError(error instanceof Error ? error.message : "invalid tax settings", { fields: ["tax"] });
}
}
const settings = await c.get("ctx").orgSettings.update(requireOrg(c), patch);
return data(c, settings);
});

209
apps/api/src/routes/team.ts Normal file
View File

@ -0,0 +1,209 @@
/**
* Team: members with roles and email invitations.
*
* GET /v1/team members + invitations
* POST /v1/team/invitations invite by email with a role
* POST /v1/team/invitations/:id/revoke revoke a pending invitation
* PATCH /v1/team/members/:accountId change a member's role
* DELETE /v1/team/members/:accountId remove a member
*
* Roles map to management scopes (see @settlekit/api-keys scopesForRole):
* owner and admin have full access, developer builds (products, checkout,
* webhooks, API keys), support handles customers and payments, viewer reads.
* Only an owner can grant or change the owner role, and the last owner cannot
* be removed or demoted. Invitations are accepted at
* POST /v1/auth/invitations/accept (the emailed link).
*/
import { createHash } from "node:crypto";
import { Hono, type Context } from "hono";
import { z } from "zod";
import { SettleKitError, conflict, generateSecret, notFound, validationError } from "@settlekit/common";
import { TEAM_ROLES } from "@settlekit/api-keys";
import { createInvitation, isInvitationOpen, revokeInvitation, type InvitationRole } from "@settlekit/invitations";
import type { TeamInvitation, TeamMember, TeamSettings } from "@settlekit/persistence";
import type { AppContext, AppEnv } from "../context.js";
import { created, data } from "../http/respond.js";
import { parseBody } from "../http/validate.js";
import { requireOrg } from "../http/tenant.js";
const roleEnum = z.enum(TEAM_ROLES);
const inviteSchema = z.object({ email: z.string().trim().email(), role: roleEnum });
const roleSchema = z.object({ role: roleEnum });
export function hashInviteToken(token: string): string {
return createHash("sha256").update(token).digest("hex");
}
/** Invite tokens carry the org id so acceptance can find the invitation. */
export function inviteToken(organizationId: string): string {
return `${organizationId}.${generateSecret(24)}`;
}
export function dashboardBaseUrl(env: NodeJS.ProcessEnv = process.env): string {
return (env.DASHBOARD_PUBLIC_URL ?? env.NEXT_PUBLIC_DASHBOARD_URL ?? "http://localhost:3001").replace(/\/+$/, "");
}
export async function loadTeam(ctx: AppContext, organizationId: string): Promise<TeamSettings> {
const settings = await ctx.orgSettings.get(organizationId);
return { members: [...(settings.team?.members ?? [])], invitations: [...(settings.team?.invitations ?? [])] };
}
export async function saveTeam(ctx: AppContext, organizationId: string, team: TeamSettings): Promise<void> {
await ctx.orgSettings.update(organizationId, { team });
}
/** The caller's role: a session's role, or owner for API keys / bootstrap. */
function callerRole(c: Context<AppEnv>): string {
return c.get("teamRole") ?? "owner";
}
/** Make sure the org's creator appears as owner once someone opens the team page. */
async function withCreator(c: Context<AppEnv>, team: TeamSettings): Promise<TeamSettings> {
const apiKeyId = c.get("apiKeyId") ?? "";
if (!apiKeyId.startsWith("session:") || c.get("teamRole") !== "owner") return team;
const accountId = apiKeyId.slice("session:".length);
if (team.members.some((m) => m.accountId === accountId)) return team;
const account = await c.get("ctx").auth.findAccountById(accountId);
if (!account) return team;
const creator: TeamMember = { accountId, email: account.email, role: "owner", joinedAt: account.createdAt };
const next = { ...team, members: [creator, ...team.members] };
await saveTeam(c.get("ctx"), requireOrg(c), next);
return next;
}
function publicInvitation(inv: TeamInvitation) {
const { tokenHash: _h, ...rest } = inv;
void _h;
return rest;
}
function assertCanGrant(c: Context<AppEnv>, role: string): void {
if (role === "owner" && callerRole(c) !== "owner") {
throw new SettleKitError({ code: "forbidden", message: "Only an owner can grant the owner role" });
}
}
function ownersAfter(team: TeamSettings, accountId: string, nextRole: string | null): number {
return team.members.filter((m) => (m.accountId === accountId ? nextRole === "owner" : m.role === "owner")).length;
}
export function teamRoutes(): Hono<AppEnv> {
const app = new Hono<AppEnv>();
app.get("/", async (c) => {
const ctx = c.get("ctx");
const org = requireOrg(c);
const team = await withCreator(c, await loadTeam(ctx, org));
const now = new Date();
return data(c, {
members: team.members,
invitations: team.invitations
.map((inv) => (inv.status === "pending" && !isInvitationOpen(inv, now) ? { ...inv, status: "expired" as const } : inv))
.filter((inv) => inv.status === "pending" || inv.status === "expired")
.map(publicInvitation),
roles: TEAM_ROLES,
});
});
app.post("/invitations", async (c) => {
const ctx = c.get("ctx");
const org = requireOrg(c);
const body = await parseBody(c, inviteSchema);
assertCanGrant(c, body.role);
const team = await withCreator(c, await loadTeam(ctx, org));
const email = body.email.toLowerCase();
if (team.members.some((m) => m.email.toLowerCase() === email)) throw conflict("This person is already on the team");
const existing = await ctx.auth.findAccountByEmail(email);
if (existing?.organizationId && existing.organizationId !== org) {
throw conflict("This email already belongs to another SettleKit organization");
}
const token = inviteToken(org);
const base = createInvitation({ email, role: body.role, token });
const now = new Date().toISOString();
const invitation: TeamInvitation = {
id: `inv_team_${generateSecret(9)}`,
email: base.email,
role: base.role,
tokenHash: hashInviteToken(token),
status: base.status,
expiresAt: base.expiresAt,
invitedBy: c.get("apiKeyId") ?? "unknown",
createdAt: now,
};
// One open invitation per email: a new one replaces the old.
const others = team.invitations.map((inv) =>
inv.email === email && inv.status === "pending" ? { ...inv, status: "revoked" as const } : inv,
);
await saveTeam(ctx, org, { ...team, invitations: [...others, invitation] });
const inviteUrl = `${dashboardBaseUrl()}/invite/${encodeURIComponent(token)}`;
let emailed = false;
if (ctx.email) {
const settings = await ctx.orgSettings.get(org);
try {
await ctx.email.send({
to: email,
subject: `You are invited to ${settings.orgName} on SettleKit`,
text: `You were invited to join ${settings.orgName} on SettleKit as ${body.role}.\n\nAccept: ${inviteUrl}\n\nThe link expires in 7 days.`,
html: `<p>You were invited to join <strong>${settings.orgName.replace(/[<>&"]/g, "")}</strong> on SettleKit as ${body.role}.</p><p><a href="${inviteUrl}">Accept the invitation</a></p><p>The link expires in 7 days.</p>`,
tags: [{ name: "type", value: "team_invite" }],
});
emailed = true;
} catch {
emailed = false;
}
}
return created(c, { invitation: publicInvitation(invitation), inviteUrl, emailed });
});
app.post("/invitations/:id/revoke", async (c) => {
const ctx = c.get("ctx");
const org = requireOrg(c);
const team = await loadTeam(ctx, org);
const target = team.invitations.find((inv) => inv.id === c.req.param("id"));
if (!target) throw notFound("invitation not found");
const closed = revokeInvitation({ email: target.email, role: target.role as InvitationRole, token: "", status: target.status, expiresAt: target.expiresAt });
const revoked = { ...target, status: closed.status };
await saveTeam(ctx, org, { ...team, invitations: team.invitations.map((inv) => (inv.id === target.id ? revoked : inv)) });
return data(c, publicInvitation(revoked));
});
app.patch("/members/:accountId", async (c) => {
const ctx = c.get("ctx");
const org = requireOrg(c);
const accountId = c.req.param("accountId");
const body = await parseBody(c, roleSchema);
const team = await withCreator(c, await loadTeam(ctx, org));
const member = team.members.find((m) => m.accountId === accountId);
if (!member) throw notFound("member not found");
assertCanGrant(c, body.role);
if (member.role === "owner") assertCanGrant(c, "owner");
if (ownersAfter(team, accountId, body.role) === 0) throw validationError("The team needs at least one owner");
unwrap(await ctx.auth.assignOrganization(accountId, org, body.role));
const next = { ...member, role: body.role };
await saveTeam(ctx, org, { ...team, members: team.members.map((m) => (m.accountId === accountId ? next : m)) });
return data(c, next);
});
app.delete("/members/:accountId", async (c) => {
const ctx = c.get("ctx");
const org = requireOrg(c);
const accountId = c.req.param("accountId");
const team = await withCreator(c, await loadTeam(ctx, org));
const member = team.members.find((m) => m.accountId === accountId);
if (!member) throw notFound("member not found");
if (member.role === "owner") assertCanGrant(c, "owner");
if (ownersAfter(team, accountId, null) === 0) throw validationError("The team needs at least one owner");
unwrap(await ctx.auth.assignOrganization(accountId, undefined));
await saveTeam(ctx, org, { ...team, members: team.members.filter((m) => m.accountId !== accountId) });
return data(c, { removed: accountId });
});
return app;
}
function unwrap<T>(result: { ok: true; value: T } | { ok: false; error: SettleKitError }): T {
if (!result.ok) throw result.error;
return result.value;
}

View File

@ -9,23 +9,35 @@
import { Hono } from "hono";
import { z } from "zod";
import { generateId, generateSecret, notFound, type WebhookEndpoint } from "@settlekit/common";
import {
deliveryView,
enableEndpoint,
rotateEndpointSecret,
subscribedEndpoints,
} from "@settlekit/persistence";
import type { Context } from "hono";
import { queueManualDelivery } from "../webhooks/outbox.js";
import { buildWebhookEvent, signPayload, serializeEvent } from "@settlekit/webhooks";
import type { AppEnv } from "../context.js";
import { created, data } from "../http/respond.js";
import { parseBody } from "../http/validate.js";
import { parseBody, validate } from "../http/validate.js";
import { requireOrg, requireOwned } from "../http/tenant.js";
const EVENT_TYPES = [
"payment.confirmed",
"payment.failed",
"payment.refunded",
"refund.succeeded",
"subscription.created",
"subscription.charged",
"subscription.renewed",
"subscription.canceled",
"entitlement.granted",
"entitlement.revoked",
"delivery.succeeded",
"delivery.failed",
"invoice.paid",
"webhook.test",
] as const;
const createEndpointSchema = z.object({
@ -42,6 +54,29 @@ const emitSchema = z.object({
data: z.record(z.unknown()).default({}),
});
const resendSchema = z.object({
/** Only this endpoint; default: every active endpoint subscribed to the event. */
endpointId: z.string().min(1).optional(),
});
const rotateSchema = z.object({
/** How long the previous secret keeps signing deliveries (0-168 hours). */
graceHours: z.number().int().min(0).max(168).default(24),
});
/** Load an endpoint of the caller's org (404 otherwise). */
async function ownedEndpoint(c: Context<AppEnv>, id: string): Promise<WebhookEndpoint> {
return requireOwned(c, await c.get("ctx").webhookEndpoints.findById(id), "webhook endpoint", id);
}
/** Endpoint without secrets, for listings that do not need them. */
function publicEndpoint(endpoint: WebhookEndpoint) {
const { signingSecret: _s, previousSigningSecret: _p, ...rest } = endpoint;
void _s;
void _p;
return rest;
}
export function webhookRoutes(): Hono<AppEnv> {
const app = new Hono<AppEnv>();
@ -117,5 +152,89 @@ export function webhookRoutes(): Hono<AppEnv> {
return data(c, requireOwned(c, await c.get("ctx").webhookEvents.findById(id), "webhook event", id));
});
// Delivery log: one row per (event, endpoint) with every attempt.
app.get("/deliveries", async (c) => {
const ctx = c.get("ctx");
const eventId = c.req.query("eventId");
const endpointId = c.req.query("endpointId");
const status = c.req.query("status");
const limit = Math.min(Math.max(Number(c.req.query("limit") ?? 100) || 100, 1), 500);
const jobs = (await ctx.webhookJobs.listByOrganization(requireOrg(c), 1_000))
.filter((j) => (eventId ? j.event.id === eventId : true))
.filter((j) => (endpointId ? j.endpoint.id === endpointId : true))
.filter((j) => (status ? j.status === status : true))
.slice(0, limit);
return data(c, jobs.map(deliveryView));
});
app.get("/deliveries/:id", async (c) => {
const id = c.req.param("id");
const job = await c.get("ctx").webhookJobs.findById(id);
if (!job || job.event.organizationId !== requireOrg(c)) throw notFound("webhook delivery not found", { id });
return data(c, deliveryView(job));
});
// Resend an event (fresh delivery with a new signature and attempt log).
app.post("/events/:id/resend", async (c) => {
const ctx = c.get("ctx");
const id = c.req.param("id");
const event = requireOwned(c, await ctx.webhookEvents.findById(id), "webhook event", id);
const raw = await c.req.json().catch(() => ({}));
const body = validate(resendSchema, raw);
const endpoints = body.endpointId
? [await ownedEndpoint(c, body.endpointId)]
: subscribedEndpoints(await ctx.webhookEndpoints.list(), event.organizationId, event.type);
const jobs = [];
for (const endpoint of endpoints) {
jobs.push(await queueManualDelivery(ctx.db, ctx.webhookJobs, event, endpoint, "resend"));
}
return created(c, jobs.map(deliveryView));
});
// Send a signed webhook.test event to one endpoint (ignores enabledEvents).
app.post("/endpoints/:id/test", async (c) => {
const ctx = c.get("ctx");
const endpoint = await ownedEndpoint(c, c.req.param("id"));
const event = await ctx.webhookEvents.save(
buildWebhookEvent("webhook.test", { endpointId: endpoint.id, message: "Test event from SettleKit" }, {
organizationId: endpoint.organizationId,
}),
);
const job = await queueManualDelivery(ctx.db, ctx.webhookJobs, event, endpoint, "test");
return created(c, deliveryView(job));
});
// Rotate the signing secret; the old one keeps signing during the grace window.
app.post("/endpoints/:id/rotate-secret", async (c) => {
const ctx = c.get("ctx");
const endpoint = await ownedEndpoint(c, c.req.param("id"));
const raw = await c.req.json().catch(() => ({}));
const body = validate(rotateSchema, raw);
const rotated = await ctx.webhookEndpoints.save(rotateEndpointSecret(endpoint, new Date(), body.graceHours * 3_600_000));
return data(c, {
...publicEndpoint(rotated),
signingSecret: rotated.signingSecret,
previousSecretExpiresAt: rotated.previousSecretExpiresAt ?? null,
});
});
app.post("/endpoints/:id/disable", async (c) => {
const ctx = c.get("ctx");
const endpoint = await ownedEndpoint(c, c.req.param("id"));
const saved = await ctx.webhookEndpoints.save({
...endpoint,
active: false,
disabledAt: new Date().toISOString(),
disabledReason: "disabled by the merchant",
});
return data(c, publicEndpoint(saved));
});
app.post("/endpoints/:id/enable", async (c) => {
const ctx = c.get("ctx");
const endpoint = await ownedEndpoint(c, c.req.param("id"));
return data(c, publicEndpoint(await ctx.webhookEndpoints.save(enableEndpoint(endpoint))));
});
return app;
}

View File

@ -6,6 +6,7 @@ import { serve } from "@hono/node-server";
import { createApp } from "./app.js";
import { createContext } from "./context.js";
import { assertChainIdsAtBoot } from "./config/boot-checks.js";
import { startStatementScheduler } from "./platform/statement-scheduler.js";
/** Create the server (without starting it) — handy for embedding / testing. */
export async function createServer() {
@ -25,6 +26,7 @@ export async function startServer(port = Number(process.env.PORT ?? 8787)) {
const ctx = await createContext();
await assertChainIdsAtBoot(ctx.evmVerifiers, log);
const app = createApp(ctx);
const stopStatements = startStatementScheduler(ctx, log);
const server = serve({ fetch: app.fetch, port }, (info) => {
log("api listening", { port: info.port, url: `http://localhost:${info.port}` });
});
@ -38,6 +40,7 @@ export async function startServer(port = Number(process.env.PORT ?? 8787)) {
process.exit(1);
}
shuttingDown = true;
stopStatements();
log("api shutting down", { signal });
const force = setTimeout(() => {
log("api shutdown timed out; forcing exit", {});

View File

@ -0,0 +1,115 @@
/**
* Seller webhooks from the API. Postgres mode uses the shared outbox (events
* + worker_webhook_jobs, delivered and retried by the worker). In-memory mode
* (no DATABASE_URL, local dev) saves the event and delivers it in-process with
* a short signed retry, so a developer still receives webhooks.
*/
import type { WebhookEndpoint, WebhookEvent } from "@settlekit/common";
import {
InMemoryWebhookJobStore,
PgWebhookJobStore,
PgWebhookOutbox,
manualJob,
recordJobAttempts,
webhookJobId,
type WebhookAttempt,
type WebhookDeliveryJob,
type WebhookJobStore,
buildOutboxEvent,
emitWebhookSafely,
subscribedEndpoints,
type EntityStore,
type WebhookEmitInput,
type WebhookEmitResult,
type WebhookOutbox,
} from "@settlekit/persistence";
import type { Database } from "@settlekit/database";
import { deliverWithRetry } from "@settlekit/webhooks";
const IN_PROCESS_SCHEDULE = [0, 2, 10] as const;
/** Deliver a job in this process and record its attempts (no-database mode). */
export async function deliverInProcess(
jobs: WebhookJobStore,
job: WebhookDeliveryJob,
schedule: readonly number[] = IN_PROCESS_SCHEDULE,
): Promise<WebhookDeliveryJob> {
let attempts: WebhookAttempt[];
try {
const outcome = await deliverWithRetry({ endpoint: job.endpoint, event: job.event, schedule });
attempts = outcome.attempts.map((a) => ({
at: new Date(a.at).toISOString(),
status: a.result.status,
ok: a.result.ok,
...(a.result.ok ? {} : { error: a.result.error ?? `HTTP ${a.result.status}` }),
}));
} catch (error) {
attempts = [{ at: new Date().toISOString(), status: 0, ok: false, error: error instanceof Error ? error.message : String(error) }];
}
return jobs.save(recordJobAttempts(job, attempts, new Date()));
}
export class InProcessWebhookOutbox implements WebhookOutbox {
constructor(
private readonly endpoints: EntityStore<WebhookEndpoint>,
private readonly events: EntityStore<WebhookEvent>,
private readonly jobs: WebhookJobStore = new InMemoryWebhookJobStore(),
) {}
async enqueue(input: WebhookEmitInput): Promise<WebhookEmitResult> {
const event = buildOutboxEvent(input);
if (await this.events.findById(event.id)) return { eventId: event.id, queued: 0, duplicate: true };
await this.events.save(event);
const targets = subscribedEndpoints(await this.endpoints.list(), input.organizationId, input.type);
for (const endpoint of targets) {
const job: WebhookDeliveryJob = {
id: webhookJobId(event.id, endpoint.id),
endpoint,
event,
status: "pending",
attempts: 0,
createdAt: event.createdAt,
};
await this.jobs.save(job);
void deliverInProcess(this.jobs, job).catch((error: unknown) => {
console.warn(`[webhooks] delivery to ${endpoint.url} failed:`, error instanceof Error ? error.message : error);
});
}
return { eventId: event.id, queued: targets.length, duplicate: false };
}
}
/** The delivery log store: the worker's queue table, or memory without a database. */
export function createWebhookJobStore(db: Database | null): WebhookJobStore {
return db ? new PgWebhookJobStore(db) : new InMemoryWebhookJobStore();
}
export function createWebhookOutbox(
db: Database | null,
endpoints: EntityStore<WebhookEndpoint>,
events: EntityStore<WebhookEvent>,
jobs: WebhookJobStore = createWebhookJobStore(db),
): WebhookOutbox {
return db ? new PgWebhookOutbox(db) : new InProcessWebhookOutbox(endpoints, events, jobs);
}
/**
* Queue a merchant-requested delivery (resend or test) to one endpoint. With
* a database the worker delivers it on its next tick; without one it is
* delivered right away (one attempt) and the result is returned.
*/
export async function queueManualDelivery(
db: Database | null,
jobs: WebhookJobStore,
event: WebhookEvent,
endpoint: WebhookEndpoint,
kind: "resend" | "test",
): Promise<WebhookDeliveryJob> {
const job = await jobs.save(manualJob(event, endpoint, kind, new Date()));
return db ? job : deliverInProcess(jobs, job, [0]);
}
/** Queue a seller webhook; never throws (a webhook must not undo money movement). */
export function emitWebhook(outbox: WebhookOutbox, input: WebhookEmitInput): Promise<void> {
return emitWebhookSafely(outbox, input);
}

View File

@ -167,7 +167,7 @@ function buildGithubClient(deps: DeliveryWiringDeps): GithubAccessClient {
}
/** A Discord role adapter backed by the real granter/revoker functions. */
function buildDiscordClient(deps: DeliveryWiringDeps): DiscordRoleClient {
export function buildDiscordClient(deps: Pick<DeliveryWiringDeps, "discordApi" | "grants">): DiscordRoleClient {
return {
async addRole(input) {
const grant = await grantDiscordRole(deps.discordApi, {

View File

@ -829,24 +829,24 @@ describe("SettleKit API", () => {
});
it("applies the platform take-rate to the merchant's withdrawable balance", async () => {
// Settle a 40.00 USDC payment. Default take-rate is 2.5% + 0.30:
// fee = 1.00 + 0.30 = 1.30 ; net = 38.70.
// Settle a 40.00 USDC payment. Default take-rate is 1%, no fixed fee:
// fee = 0.40 ; net = 39.60.
await makeConfirmedPayment(app);
const balance = await call(app, "GET", "/v1/payouts/balance");
expect(balance.status).toBe(200);
expect(balance.json.data.grossVolume.amount).toBe("40");
expect(balance.json.data.platformFees.amount).toBe("1.3");
expect(balance.json.data.netToMerchant.amount).toBe("38.7");
expect(balance.json.data.platformFees.amount).toBe("0.4");
expect(balance.json.data.netToMerchant.amount).toBe("39.6");
// Withdrawable is net of the platform fee (no prior payouts yet).
expect(balance.json.data.available.amount).toBe("38.7");
expect(balance.json.data.feeSchedule.bps).toBe(250);
expect(balance.json.data.available.amount).toBe("39.6");
expect(balance.json.data.feeSchedule.bps).toBe(100);
// A payout for the net amount succeeds; one cent more than net is rejected
// because the platform's cut is reserved and cannot be withdrawn.
const ok = await call(app, "POST", "/v1/payouts", {
walletAddress: "0xMerchantWallet",
amount: "38.70",
amount: "39.60",
network: "arc",
});
expect(ok.status).toBe(201);

View File

@ -0,0 +1,109 @@
/**
* Promo codes reach checkout through the API: session create (`couponCode`)
* and payment-link visits (`promo`). The verifier expects the discounted
* amount and the code is redeemed once the payment confirms.
*/
import { randomBytes } from "node:crypto";
import { beforeEach, describe, expect, it } from "vitest";
import type { Hono } from "hono";
import type { SettlementVerifier } from "@settlekit/chains";
import { createApp } from "../src/app.js";
import { createContext, type AppContext, type AppEnv } from "../src/context.js";
const BOOTSTRAP = "test-bootstrap-key";
const PAY_TO = "0x7777777777777777777777777777777777777777";
let app: Hono<AppEnv>;
let ctx: AppContext;
const verified: { amount: string }[] = [];
const recordingVerifier: SettlementVerifier = async (proof, requirements) => {
verified.push({ amount: (requirements as unknown as { amount: string }).amount });
return proof.network === requirements.network ? { ok: true } : { ok: false, reason: "network mismatch" };
};
async function call(method: string, path: string, body?: unknown, auth = true) {
const res = await app.request(path, {
method,
headers: { ...(auth ? { authorization: `Bearer ${BOOTSTRAP}` } : {}), "content-type": "application/json" },
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
});
return { status: res.status, json: (await res.json()) as { data?: any; error?: { code: string; message: string } } };
}
beforeEach(async () => {
process.env.API_BOOTSTRAP_KEY = BOOTSTRAP;
const base = await createContext();
ctx = { ...base, verifiers: { ...base.verifiers, base: recordingVerifier } };
app = createApp(ctx);
verified.length = 0;
expect((await call("POST", "/v1/coupons", { code: "launch20", discount: { type: "percent", percentOff: 20 }, maxRedemptions: 5 })).status).toBe(201);
});
async function catalogPrice(amount: string): Promise<{ productId: string; priceId: string }> {
const product = await call("POST", "/v1/products", { merchantId: "mch_1", name: "Pro", type: "digital_download", deliveryMode: "file_download" });
const price = await call("POST", `/v1/products/${product.json.data.id}/prices`, { amount });
return { productId: product.json.data.id, priceId: price.json.data.id };
}
describe("coupons at checkout", () => {
it("creates a discounted session, verifies the discounted amount and redeems on confirm", async () => {
const { productId, priceId } = await catalogPrice("50");
const customer = await call("POST", "/v1/customers", { email: "b@x.test" });
const session = await call("POST", "/v1/checkout-sessions", {
merchantId: "mch_1",
customerId: customer.json.data.id,
items: [{ priceId, productId, quantity: 2 }],
payToAddress: PAY_TO,
network: "base",
couponCode: "LAUNCH20",
});
expect(session.status).toBe(201);
expect(session.json.data.amount.amount).toBe("80");
expect(session.json.data.discount).toMatchObject({ couponCode: "LAUNCH20", subtotal: { amount: "100" }, amountOff: { amount: "20" } });
const payment = await call("POST", "/v1/payments", { checkoutSessionId: session.json.data.id });
expect(payment.json.data.amount.amount).toBe("80");
const confirmed = await call("POST", `/v1/payments/${payment.json.data.id}/confirm`, {
txHash: `0x${randomBytes(32).toString("hex")}`,
confirmations: 3,
});
expect(confirmed.status).toBe(200);
expect(verified.at(-1)?.amount).toBe("80");
expect((await call("GET", "/v1/coupons/LAUNCH20")).json.data.redeemedCount).toBe(1);
const stored = await ctx.checkouts.findById(session.json.data.id);
expect(stored?.discount?.redeemedAt).toBeDefined();
});
it("refuses an unknown code and leaves sessions without a code unchanged", async () => {
const { productId, priceId } = await catalogPrice("50");
const base = { merchantId: "mch_1", items: [{ priceId, productId, quantity: 1 }], payToAddress: PAY_TO, network: "base" };
const bad = await call("POST", "/v1/checkout-sessions", { ...base, couponCode: "NOPE" });
expect(bad.status).toBe(400);
expect(bad.json.error?.message).toMatch(/not valid/);
const plain = await call("POST", "/v1/checkout-sessions", base);
expect(plain.json.data.amount.amount).toBe("50");
expect(plain.json.data.discount).toBeUndefined();
});
it("applies ?promo= on a payment link visit", async () => {
expect(
(await call("POST", "/v1/merchant/profile", { orgName: "Shop", acceptedNetworks: ["base"], addresses: { evm: PAY_TO } })).status,
).toBe(200);
const product = await call("POST", "/v1/merchant/products", {
name: "Course",
description: "Video course",
priceUsd: "40",
interval: "one_time",
delivery: { kind: "license_key", machineLimit: 1 },
});
const slug = product.json.data.slug as string;
const withPromo = await call("POST", `/v1/public/links/${slug}/sessions`, { promo: "launch20" }, false);
expect(withPromo.status).toBe(201);
expect((await ctx.checkouts.findById(withPromo.json.data.sessionId))?.amount.amount).toBe("32");
const refused = await call("POST", `/v1/public/links/${slug}/sessions`, { promo: "WRONG" }, false);
expect(refused.status).toBe(400);
const full = await call("POST", `/v1/public/links/${slug}/sessions`, {}, false);
expect((await ctx.checkouts.findById(full.json.data.sessionId))?.amount.amount).toBe("40");
});
});

View File

@ -0,0 +1,140 @@
/**
* Checkout tax + tax-grade receipts: the seller's settings add tax on top of
* the net price, the buyer's country / VAT ID pick the rate, onchain
* verification expects the tax-inclusive total, and the receipt PDF is served
* for the settled checkout.
*/
import { randomBytes } from "node:crypto";
import { beforeEach, describe, expect, it } from "vitest";
import type { Hono } from "hono";
import type { SettlementVerifier } from "@settlekit/chains";
import { createApp } from "../src/app.js";
import { createContext, type AppContext, type AppEnv } from "../src/context.js";
const BOOTSTRAP = "test-bootstrap-key";
const PAY_TO = "0x8888888888888888888888888888888888888888";
let app: Hono<AppEnv>;
let ctx: AppContext;
const verifiedAmounts: string[] = [];
const verifier: SettlementVerifier = async (proof, requirements) => {
verifiedAmounts.push((requirements as unknown as { amount: string }).amount);
return proof.network === requirements.network ? { ok: true } : { ok: false, reason: "network mismatch" };
};
async function call(method: string, path: string, body?: unknown, auth = true) {
const res = await app.request(path, {
method,
headers: { ...(auth ? { authorization: `Bearer ${BOOTSTRAP}` } : {}), "content-type": "application/json" },
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
});
if ((res.headers.get("content-type") ?? "").includes("application/pdf")) {
return { status: res.status, json: {} as { data?: any; error?: any }, pdf: Buffer.from(await res.arrayBuffer()) };
}
return { status: res.status, json: (await res.json()) as { data?: any; error?: { message: string } }, pdf: null };
}
const TAX = {
enabled: true,
label: "VAT",
sellerCountry: "de",
taxId: "DE123456789",
legalName: "Acme Software GmbH",
defaultRateBps: 0,
rates: { DE: 1900, FR: 2000 },
reverseCharge: true,
};
beforeEach(async () => {
process.env.API_BOOTSTRAP_KEY = BOOTSTRAP;
const base = await createContext();
ctx = { ...base, verifiers: { ...base.verifiers, base: verifier } };
app = createApp(ctx);
verifiedAmounts.length = 0;
});
async function price(amount: string) {
const product = await call("POST", "/v1/products", { merchantId: "mch_1", name: "Pro license", type: "license_key", deliveryMode: "license_key" });
const p = await call("POST", `/v1/products/${product.json.data.id}/prices`, { amount });
return { productId: product.json.data.id as string, priceId: p.json.data.id as string };
}
describe("checkout tax", () => {
it("validates and stores tax settings", async () => {
const saved = await call("POST", "/v1/settings", { tax: TAX });
expect(saved.status).toBe(200);
expect(saved.json.data.tax).toMatchObject({ enabled: true, sellerCountry: "DE", rates: { DE: 1900, FR: 2000 } });
const bad = await call("POST", "/v1/settings", { tax: { ...TAX, rates: { France: 2000 } } });
expect(bad.status).toBe(400);
});
it("charges the buyer's rate, verifies the taxed total and serves a tax-grade receipt", async () => {
await call("POST", "/v1/settings", { tax: TAX });
const { productId, priceId } = await price("100");
const customer = await call("POST", "/v1/customers", { email: "ap@client.fr" });
const base = { merchantId: "mch_1", customerId: customer.json.data.id, items: [{ priceId, productId, quantity: 1 }], payToAddress: PAY_TO, network: "base" };
const domestic = await call("POST", "/v1/checkout-sessions", base);
expect(domestic.json.data.amount.amount).toBe("119");
expect(domestic.json.data.tax).toMatchObject({ rateBps: 1900, jurisdiction: "DE", amount: { amount: "19" }, net: { amount: "100" } });
const b2b = await call("POST", "/v1/checkout-sessions", { ...base, billingCountry: "FR", vatId: "FR12345678901" });
expect(b2b.json.data.amount.amount).toBe("100");
expect(b2b.json.data.tax).toMatchObject({ reverseCharge: true, vatId: "FR12345678901" });
const consumer = await call("POST", "/v1/checkout-sessions", { ...base, billingCountry: "FR", collectedFields: { email: "ap@client.fr" } });
expect(consumer.json.data.amount.amount).toBe("120");
const sessionId = consumer.json.data.id as string;
// Receipt is only available once the checkout settled.
expect((await call("GET", `/v1/public/receipts/${sessionId}/pdf`, undefined, false)).status).toBe(404);
const payment = await call("POST", "/v1/payments", { checkoutSessionId: sessionId });
await call("POST", `/v1/payments/${payment.json.data.id}/confirm`, { txHash: `0x${randomBytes(32).toString("hex")}`, confirmations: 3 });
expect(verifiedAmounts.at(-1)).toBe("120");
const receipt = await call("GET", `/v1/public/receipts/${sessionId}/pdf`, undefined, false);
expect(receipt.status).toBe(200);
expect(receipt.pdf?.subarray(0, 5).toString()).toBe("%PDF-");
expect(receipt.pdf!.length).toBeGreaterThan(1500);
});
it("combines a promo with tax without compounding", async () => {
await call("POST", "/v1/settings", { tax: TAX });
await call("POST", "/v1/coupons", { code: "TEN", discount: { type: "amount", amountOff: "10" } });
const { productId, priceId } = await price("100");
const s = await call("POST", "/v1/checkout-sessions", {
merchantId: "mch_1",
items: [{ priceId, productId, quantity: 1 }],
payToAddress: PAY_TO,
network: "base",
couponCode: "TEN",
});
expect(s.json.data.tax.net.amount).toBe("90");
expect(s.json.data.amount.amount).toBe("107.1");
});
it("leaves checkout untaxed when the seller has no tax settings", async () => {
const { productId, priceId } = await price("100");
const s = await call("POST", "/v1/checkout-sessions", {
merchantId: "mch_1",
items: [{ priceId, productId, quantity: 1 }],
payToAddress: PAY_TO,
network: "base",
billingCountry: "FR",
});
expect(s.json.data.amount.amount).toBe("100");
expect(s.json.data.tax).toBeUndefined();
});
});
describe("embed origins setting", () => {
it("stores exact https origins and rejects paths or plain http", async () => {
const ok = await call("POST", "/v1/settings", { embedOrigins: ["https://Shop.Example.com", "https://shop.example.com", "http://localhost:3000"] });
expect(ok.status).toBe(200);
expect(ok.json.data.embedOrigins).toEqual(["https://shop.example.com", "http://localhost:3000"]);
expect((await call("POST", "/v1/settings", { embedOrigins: ["https://shop.example.com/cart"] })).status).toBe(400);
expect((await call("POST", "/v1/settings", { embedOrigins: ["http://shop.example.com"] })).status).toBe(400);
});
});

View File

@ -0,0 +1,47 @@
import { Hono } from "hono";
import { afterEach, describe, expect, it, vi } from "vitest";
import { error } from "../src/http/respond.js";
import { errorMiddleware } from "../src/middleware/error.js";
function appThatThrows(): Hono {
const app = new Hono();
app.use("*", errorMiddleware());
app.get("/boom", () => {
throw new Error('Failed query: insert into "prices" ... params: secret-value');
});
app.onError((err, c) => error(c, err));
return app;
}
describe("unhandled error envelope", () => {
const originalEnv = process.env.NODE_ENV;
afterEach(() => {
process.env.NODE_ENV = originalEnv;
vi.restoreAllMocks();
});
it("hides internals from the caller in production and logs them server-side", async () => {
process.env.NODE_ENV = "production";
const writes: string[] = [];
vi.spyOn(process.stderr, "write").mockImplementation((chunk: string | Uint8Array) => {
writes.push(String(chunk));
return true;
});
const res = await appThatThrows().request("/boom");
const body = (await res.json()) as { error: { code: string; message: string } };
expect(res.status).toBe(500);
expect(body.error.code).toBe("internal_error");
expect(body.error.message).not.toContain("Failed query");
expect(body.error.message).not.toContain("secret-value");
expect(writes.join("")).toContain("Failed query");
});
it("keeps the detailed message outside production", async () => {
process.env.NODE_ENV = "test";
const res = await appThatThrows().request("/boom");
const body = (await res.json()) as { error: { message: string } };
expect(body.error.message).toContain("Failed query");
});
});

View File

@ -0,0 +1,100 @@
/** Merchant accounting exports: tenant-scoped CSVs incl. Xero / QuickBooks imports. */
import { randomBytes } from "node:crypto";
import { beforeEach, describe, expect, it } from "vitest";
import type { Hono } from "hono";
import type { SettlementVerifier } from "@settlekit/chains";
import { createApp } from "../src/app.js";
import { createContext, type AppContext, type AppEnv } from "../src/context.js";
const BOOTSTRAP = "test-bootstrap-key";
const PAY_TO = "0x9999999999999999999999999999999999999999";
let app: Hono<AppEnv>;
let ctx: AppContext;
let otherKey: string;
const verifier: SettlementVerifier = async (proof, req) =>
proof.network === req.network ? { ok: true } : { ok: false, reason: "network mismatch" };
async function call(method: string, path: string, body?: unknown, key = BOOTSTRAP) {
const res = await app.request(path, {
method,
headers: { authorization: `Bearer ${key}`, "content-type": "application/json" },
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
});
const type = res.headers.get("content-type") ?? "";
return {
status: res.status,
type,
disposition: res.headers.get("content-disposition") ?? "",
text: type.includes("text/csv") ? await res.text() : "",
json: type.includes("json") ? ((await res.json()) as { data?: any; error?: { message: string } }) : {},
};
}
beforeEach(async () => {
process.env.API_BOOTSTRAP_KEY = BOOTSTRAP;
const base = await createContext();
ctx = { ...base, verifiers: { ...base.verifiers, base: verifier } };
app = createApp(ctx);
otherKey = (
await ctx.apiKeys.issue({ organizationId: "org_other", customerId: "c", productId: "__platform__", entitlementId: "e", scopes: ["*"], env: "live" })
).plaintext;
const product = await call("POST", "/v1/products", { merchantId: "mch_1", name: "=cmd|' /C calc'!A0", type: "license_key", deliveryMode: "license_key" });
const price = await call("POST", `/v1/products/${product.json.data.id}/prices`, { amount: "25" });
const customer = await call("POST", "/v1/customers", { email: "buyer@example.com" });
const session = await call("POST", "/v1/checkout-sessions", {
merchantId: "mch_1",
customerId: customer.json.data.id,
items: [{ priceId: price.json.data.id, productId: product.json.data.id, quantity: 1 }],
payToAddress: PAY_TO,
network: "base",
});
const payment = await call("POST", "/v1/payments", { checkoutSessionId: session.json.data.id });
await call("POST", `/v1/payments/${payment.json.data.id}/confirm`, { txHash: `0x${randomBytes(32).toString("hex")}`, confirmations: 3 });
const refund = await call("POST", "/v1/refunds", { paymentId: payment.json.data.id, customerId: customer.json.data.id, amount: "5", reason: "customer_request" });
await call("POST", `/v1/refunds/${refund.json.data.id}/succeed`, { txHash: `0x${randomBytes(32).toString("hex")}` });
});
describe("accounting exports", () => {
it("downloads payments as CSV with formula cells neutralized", async () => {
const res = await call("GET", "/v1/exports/payments.csv");
expect(res.status).toBe(200);
expect(res.type).toContain("text/csv");
expect(res.disposition).toMatch(/attachment; filename="settlekit-.*-payments\.csv"/);
const [header, row] = res.text.split("\n");
expect(header).toContain('"id","created_at","confirmed_at","status","amount"');
expect(row).toContain('"confirmed","25","USDC","base"');
expect(row).toContain('"buyer@example.com"');
expect(row).toContain(`"'=cmd|' /C calc'!A0"`);
});
it("builds Xero and QuickBooks bank statements from payments and refunds", async () => {
const xero = (await call("GET", "/v1/exports/xero.csv")).text.split("\n");
expect(xero[0]).toBe('"*Date","*Amount","Payee","Description","Reference"');
expect(xero).toHaveLength(3);
expect(xero[1]).toContain('"25","buyer@example.com"');
expect(xero.some((l) => l.includes('"-5"'))).toBe(true);
const qb = (await call("GET", "/v1/exports/quickbooks.csv")).text.split("\n");
expect(qb[0]).toBe('"Date","Description","Amount"');
expect(qb).toHaveLength(3);
expect((await call("GET", "/v1/exports/ledger.csv")).text).toContain('"refund","-5","USDC"');
});
it("filters by date and rejects malformed dates", async () => {
const future = await call("GET", "/v1/exports/ledger.csv?from=2999-01-01");
expect(future.text.split("\n")).toHaveLength(1);
expect((await call("GET", "/v1/exports/ledger.csv?from=yesterday")).status).toBe(400);
});
it("exports refunds, invoices and payouts and never another tenant's data", async () => {
expect((await call("GET", "/v1/exports/refunds.csv")).text.split("\n")).toHaveLength(2);
expect((await call("GET", "/v1/exports/invoices.csv")).status).toBe(200);
expect((await call("GET", "/v1/exports/payouts.csv")).status).toBe(200);
const other = await call("GET", "/v1/exports/payments.csv", undefined, otherKey);
expect(other.text.split("\n")).toHaveLength(1);
expect((await call("GET", "/v1/exports/xero.csv", undefined, otherKey)).text.split("\n")).toHaveLength(1);
expect((await call("GET", "/v1/exports/refunds.csv", undefined, otherKey)).text.split("\n")).toHaveLength(1);
});
});

View File

@ -0,0 +1,179 @@
/**
* Fiat pricing: prices set in EUR/GBP settle in USDC at a live rate
* (frankfurter, ECB) locked on each checkout session.
*/
import { randomBytes } from "node:crypto";
import { beforeEach, describe, expect, it } from "vitest";
import type { Hono } from "hono";
import type { SettlementVerifier } from "@settlekit/chains";
import { createApp } from "../src/app.js";
import { createContext, type AppContext, type AppEnv } from "../src/context.js";
import { createFrankfurterSource, type FxRateSource } from "../src/fx/rates.js";
const BOOTSTRAP = "test-bootstrap-key";
const PAY_TO = "0x1212121212121212121212121212121212121212";
let app: Hono<AppEnv>;
let ctx: AppContext;
let eurRate = "1.0834";
const verified: string[] = [];
const fakeRates: FxRateSource = {
async usdPer(currency) {
if (currency === "USD") return { rate: "1", date: "2026-09-29", source: "USDC par" };
if (currency === "EUR") return { rate: eurRate, date: "2026-09-29", source: "ECB via frankfurter" };
if (currency === "GBP") return { rate: "1.27", date: "2026-09-29", source: "ECB via frankfurter" };
throw new Error("unexpected currency");
},
};
const verifier: SettlementVerifier = async (proof, req) => {
verified.push((req as unknown as { amount: string }).amount);
return proof.network === req.network ? { ok: true } : { ok: false, reason: "network mismatch" };
};
async function call(method: string, path: string, body?: unknown, auth = true) {
const res = await app.request(path, {
method,
headers: { ...(auth ? { authorization: `Bearer ${BOOTSTRAP}` } : {}), "content-type": "application/json" },
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
});
return { status: res.status, json: (await res.json()) as { data?: any; error?: { message: string } } };
}
beforeEach(async () => {
process.env.API_BOOTSTRAP_KEY = BOOTSTRAP;
eurRate = "1.0834";
verified.length = 0;
const base = await createContext();
ctx = { ...base, fxRates: fakeRates, verifiers: { ...base.verifiers, base: verifier } };
app = createApp(ctx);
});
async function eurProduct(displayAmount = "29") {
const product = await call("POST", "/v1/products", { merchantId: "mch_1", name: "Kurs", type: "license_key", deliveryMode: "license_key" });
const price = await call("POST", `/v1/products/${product.json.data.id}/prices`, { displayCurrency: "EUR", displayAmount });
return { productId: product.json.data.id as string, price: price };
}
describe("frankfurter rate source", () => {
it("parses, caches and sanity-checks rates", async () => {
let calls = 0;
let t = 0;
const source = createFrankfurterSource({
baseUrl: "https://fx.test/v1/",
now: () => t,
fetch: (async (url: string) => {
calls += 1;
expect(url).toBe("https://fx.test/v1/latest?base=EUR&symbols=USD");
return new Response(JSON.stringify({ amount: 1, base: "EUR", date: "2026-09-29", rates: { USD: 1.0834 } }));
}) as unknown as typeof fetch,
});
expect(await source.usdPer("EUR")).toEqual({ rate: "1.0834", date: "2026-09-29", source: "ECB via frankfurter" });
await source.usdPer("EUR");
expect(calls).toBe(1);
t = 600_001;
await source.usdPer("EUR");
expect(calls).toBe(2);
expect((await source.usdPer("USD")).rate).toBe("1");
});
it("fails closed on errors and implausible rates", async () => {
const down = createFrankfurterSource({ fetch: (async () => new Response("", { status: 502 })) as unknown as typeof fetch });
await expect(down.usdPer("EUR")).rejects.toMatchObject({ code: "integration_error" });
const junk = createFrankfurterSource({
fetch: (async () => new Response(JSON.stringify({ date: "2026-09-29", rates: { USD: 0 } }))) as unknown as typeof fetch,
});
await expect(junk.usdPer("GBP")).rejects.toThrow(/temporarily unavailable/);
const offline = createFrankfurterSource({
fetch: (async () => {
throw new TypeError("fetch failed");
}) as unknown as typeof fetch,
});
await expect(offline.usdPer("EUR")).rejects.toThrow(/unreachable/);
});
});
describe("fiat-priced checkout", () => {
it("stores a EUR price with a USDC reference and refuses fiat subscriptions", async () => {
const { price, productId } = await eurProduct("29");
expect(price.status).toBe(201);
expect(price.json.data).toMatchObject({ displayCurrency: "EUR", displayAmount: "29", amount: "31.42", currency: "USDC" });
const sub = await call("POST", `/v1/products/${productId}/prices`, { displayCurrency: "EUR", displayAmount: "9", interval: "monthly" });
expect(sub.status).toBe(400);
const half = await call("POST", `/v1/products/${productId}/prices`, { displayCurrency: "EUR" });
expect(half.status).toBe(400);
});
it("locks today's rate on the session and verifies the converted USDC amount", async () => {
const { price, productId } = await eurProduct("29");
eurRate = "1.1"; // the rate moved since the price was created
const session = await call("POST", "/v1/checkout-sessions", {
merchantId: "mch_1",
items: [{ priceId: price.json.data.id, productId, quantity: 2 }],
payToAddress: PAY_TO,
network: "base",
customerId: (await call("POST", "/v1/customers", { email: "k@x.test" })).json.data.id,
});
expect(session.status).toBe(201);
expect(session.json.data.amount.amount).toBe("63.8");
expect(session.json.data.fxQuote).toMatchObject({ currency: "EUR", amount: "58", rate: "1.1", usdcAmount: "63.8", rateDate: "2026-09-29" });
expect(session.json.data.fxQuote.expiresAt).toBe(session.json.data.expiresAt);
const payment = await call("POST", "/v1/payments", { checkoutSessionId: session.json.data.id });
await call("POST", `/v1/payments/${payment.json.data.id}/confirm`, { txHash: `0x${randomBytes(32).toString("hex")}`, confirmations: 3 });
expect(verified.at(-1)).toBe("63.8");
});
it("refuses mixing two fiat currencies in one checkout", async () => {
const eur = await eurProduct("10");
const gbpProduct = await call("POST", "/v1/products", { merchantId: "mch_1", name: "UK", type: "license_key", deliveryMode: "license_key" });
const gbp = await call("POST", `/v1/products/${gbpProduct.json.data.id}/prices`, { displayCurrency: "GBP", displayAmount: "10" });
const res = await call("POST", "/v1/checkout-sessions", {
merchantId: "mch_1",
items: [
{ priceId: eur.price.json.data.id, productId: eur.productId, quantity: 1 },
{ priceId: gbp.json.data.id, productId: gbpProduct.json.data.id, quantity: 1 },
],
payToAddress: PAY_TO,
network: "base",
});
expect(res.status).toBe(400);
});
it("prices a quick product in EUR, shows it on the link and discounts the converted amount", async () => {
await call("POST", "/v1/merchant/profile", { orgName: "Shop", acceptedNetworks: ["base"], addresses: { evm: PAY_TO } });
await call("POST", "/v1/coupons", { code: "HALF", discount: { type: "percent", percentOff: 50 } });
const product = await call("POST", "/v1/merchant/products", {
name: "Kurs",
priceUsd: "29",
currency: "EUR",
delivery: { kind: "license_key", machineLimit: 1 },
});
expect(product.status).toBe(201);
expect(product.json.data).toMatchObject({ displayCurrency: "EUR", displayAmount: "29" });
const slug = product.json.data.slug as string;
eurRate = "1.2";
const summary = await call("GET", `/v1/public/links/${slug}`, undefined, false);
expect(summary.json.data).toMatchObject({ displayCurrency: "EUR", displayAmount: "29", priceUsd: "34.8" });
const opened = await call("POST", `/v1/public/links/${slug}/sessions`, { promo: "HALF" }, false);
const session = await ctx.checkouts.findById(opened.json.data.sessionId);
expect(session?.fxQuote).toMatchObject({ currency: "EUR", rate: "1.2" });
expect(session?.amount.amount).toBe("17.4");
// Editing the price keeps the currency.
const patched = await call("PATCH", `/v1/merchant/products/${product.json.data.id}`, { priceUsd: "39" });
expect(patched.json.data).toMatchObject({ displayCurrency: "EUR", displayAmount: "39", priceUsd: "46.8" });
const monthly = await call("POST", "/v1/merchant/products", {
name: "Sub",
priceUsd: "9",
currency: "EUR",
interval: "monthly",
delivery: { kind: "license_key", machineLimit: 1 },
});
expect(monthly.status).toBe(400);
});
});

View File

@ -0,0 +1,130 @@
import { randomBytes } from "node:crypto";
import { describe, expect, it } from "vitest";
import { money, type CheckoutSession, type Payment, type Price, type Product, type Subscription } from "@settlekit/common";
import type { SettlementVerifier } from "@settlekit/chains";
import { computeGrowthMetrics } from "../src/analytics/metrics.js";
import { createApp } from "../src/app.js";
import { createContext } from "../src/context.js";
const NOW = new Date("2026-09-30T00:00:00.000Z");
const day = (n: number) => new Date(NOW.getTime() - n * 86_400_000).toISOString();
function session(id: string, productId: string, createdDaysAgo: number, status: CheckoutSession["status"] = "open"): CheckoutSession {
return {
id,
organizationId: "org_1",
merchantId: "m",
lineItems: [{ productId, priceId: `price_${productId}`, quantity: 1 }],
amount: money("10"),
status,
payToAddress: "0x",
network: "base",
expiresAt: day(createdDaysAgo - 1),
collectedFields: {},
createdAt: day(createdDaysAgo),
};
}
function payment(id: string, sessionId: string, customerId: string, amount: string, daysAgo: number): Payment {
return {
id,
organizationId: "org_1",
checkoutSessionId: sessionId,
customerId,
amount: money(amount),
network: "base",
confirmations: 3,
status: "confirmed",
createdAt: day(daysAgo),
confirmedAt: day(daysAgo),
};
}
function sub(id: string, status: Subscription["status"], periodEndDaysAgo: number): Subscription {
return {
id,
organizationId: "org_1",
customerId: "c",
productId: "prod_sub",
priceId: "price_sub",
status,
currentPeriodStart: day(periodEndDaysAgo + 30),
currentPeriodEnd: day(periodEndDaysAgo),
cancelAtPeriodEnd: false,
createdAt: day(100),
};
}
describe("growth metrics", () => {
it("computes conversion, per-link stats, repeat customers, churn and LTV", () => {
const sessions = [
session("s1", "prod_a", 3, "completed"),
session("s2", "prod_a", 2),
session("s3", "prod_a", 1, "completed"),
session("s4", "prod_b", 5),
session("s_old", "prod_a", 60, "completed"),
{ ...session("s_inv", "prod_inv", 1, "completed"), invoiceId: "inv_1" },
];
const payments = [
payment("p1", "s1", "cus_1", "10", 3),
payment("p3", "s3", "cus_1", "10", 1),
payment("p_old", "s_old", "cus_2", "20", 60),
];
const products = [
{ id: "prod_a", name: "Course", metadata: { paymentLinkSlug: "course-1" } },
{ id: "prod_b", name: "Kit", metadata: {} },
] as unknown as Product[];
const prices = [{ id: "price_sub", productId: "prod_sub", amount: "30", interval: "monthly" }] as unknown as Price[];
const subscriptions = [sub("a1", "active", -10), sub("a2", "active", -5), sub("a3", "active", -3), sub("c1", "canceled", 5)];
const m = computeGrowthMetrics({ sessions, payments, subscriptions, products, prices, now: NOW, days: 30 });
expect(m.checkouts).toEqual({ opened: 4, paid: 2, conversion: 0.5 });
expect(m.links[0]).toEqual({ productId: "prod_a", name: "Course", slug: "course-1", opened: 3, paid: 2, conversion: 0.6667, revenue: "20" });
expect(m.links[1]).toMatchObject({ productId: "prod_b", opened: 1, paid: 0, conversion: 0 });
expect(m.revenue).toEqual({ window: "20", allTime: "40" });
expect(m.customers).toEqual({ paying: 2, repeat: 1, repeatRate: 0.5 });
expect(m.averageRevenuePerCustomer).toBe("20");
expect(m.subscriptions).toMatchObject({ active: 3, churned: 1, churnRate: 0.25, arpu: "30" });
expect(m.subscriptions.estimatedLifetimeValue).toBe("120");
});
it("handles an empty account", () => {
const m = computeGrowthMetrics({ sessions: [], payments: [], subscriptions: [], products: [], prices: [], now: NOW, days: 7 });
expect(m.checkouts.conversion).toBe(0);
expect(m.subscriptions.estimatedLifetimeValue).toBeNull();
expect(m.averageRevenuePerCustomer).toBe("0");
});
it("serves /v1/analytics/metrics from live data", async () => {
process.env.API_BOOTSTRAP_KEY = "test-bootstrap-key";
const base = await createContext();
const ok: SettlementVerifier = async (proof, req) => (proof.network === req.network ? { ok: true } : { ok: false });
const app = createApp({ ...base, verifiers: { ...base.verifiers, base: ok } });
const call = async (method: string, path: string, body?: unknown) => {
const res = await app.request(path, {
method,
headers: { authorization: "Bearer test-bootstrap-key", "content-type": "application/json" },
...(body ? { body: JSON.stringify(body) } : {}),
});
return (await res.json()) as { data?: any };
};
const product = await call("POST", "/v1/products", { merchantId: "m", name: "Guide", type: "license_key", deliveryMode: "license_key" });
const price = await call("POST", `/v1/products/${product.data.id}/prices`, { amount: "9" });
const customer = await call("POST", "/v1/customers", { email: "a@b.test" });
const open = async () =>
call("POST", "/v1/checkout-sessions", {
merchantId: "m",
customerId: customer.data.id,
items: [{ priceId: price.data.id, productId: product.data.id, quantity: 1 }],
payToAddress: "0x1111111111111111111111111111111111111111",
network: "base",
});
const s1 = await open();
await open();
const pay = await call("POST", "/v1/payments", { checkoutSessionId: s1.data.id });
await call("POST", `/v1/payments/${pay.data.id}/confirm`, { txHash: `0x${randomBytes(32).toString("hex")}`, confirmations: 3 });
const metrics = await call("GET", "/v1/analytics/metrics?days=7");
expect(metrics.data.checkouts).toEqual({ opened: 2, paid: 1, conversion: 0.5 });
expect(metrics.data.links[0]).toMatchObject({ name: "Guide", opened: 2, paid: 1, revenue: "9" });
});
});

View File

@ -0,0 +1,335 @@
/**
* Payable invoices + payment requests, end to end through the real routes:
* send -> public pay page -> checkout session -> onchain-verified payment ->
* the invoice flips to paid on the next read.
*/
import { randomBytes } from "node:crypto";
import { beforeEach, describe, expect, it } from "vitest";
import type { Hono } from "hono";
import type { SettlementVerifier } from "@settlekit/chains";
import { createEmailClient, type EmailPayload } from "@settlekit/notifications";
import { createApp } from "../src/app.js";
import { createContext, type AppContext, type AppEnv } from "../src/context.js";
const BOOTSTRAP = "test-bootstrap-key";
const EVM_PAYTO = "0x2222222222222222222222222222222222222222";
const baseChainDouble: SettlementVerifier = async (proof, requirements) =>
proof.network === requirements.network ? { ok: true } : { ok: false, reason: "network mismatch" };
interface Json {
data?: any;
error?: { code: string; message: string };
}
interface Harness {
app: Hono<AppEnv>;
ctx: AppContext;
sent: EmailPayload[];
}
async function harness(withEmail = true): Promise<Harness> {
process.env.API_BOOTSTRAP_KEY = BOOTSTRAP;
process.env.CHECKOUT_PUBLIC_URL = "https://pay.test";
const base = await createContext();
const sent: EmailPayload[] = [];
const email = withEmail
? createEmailClient({
from: "SettleKit <billing@settlekit.test>",
transport: {
async send(payload: EmailPayload) {
sent.push(payload);
return { id: `msg_${sent.length}` };
},
},
})
: null;
const ctx: AppContext = { ...base, email, verifiers: { ...base.verifiers, base: baseChainDouble } };
return { app: createApp(ctx), ctx, sent };
}
async function call(app: Hono<AppEnv>, method: string, path: string, body?: unknown, auth = true) {
const res = await app.request(path, {
method,
headers: {
...(auth ? { authorization: `Bearer ${BOOTSTRAP}` } : {}),
"content-type": "application/json",
},
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
});
const type = res.headers.get("content-type") ?? "";
if (type.includes("application/pdf")) {
return { status: res.status, json: {} as Json, pdf: Buffer.from(await res.arrayBuffer()) };
}
return { status: res.status, json: (await res.json()) as Json, pdf: null };
}
async function onboard(app: Hono<AppEnv>): Promise<void> {
const res = await call(app, "POST", "/v1/merchant/profile", {
orgName: "Acme Studio",
acceptedNetworks: ["base"],
addresses: { evm: EVM_PAYTO },
});
expect(res.status).toBe(200);
}
async function customer(app: Hono<AppEnv>, email = "ap@client.test"): Promise<string> {
const res = await call(app, "POST", "/v1/customers", { email });
expect(res.status).toBe(201);
return res.json.data.id as string;
}
async function payOnchain(app: Hono<AppEnv>, sessionId: string): Promise<string> {
const txHash = `0x${randomBytes(32).toString("hex")}`;
const payment = await call(app, "POST", "/v1/payments", { checkoutSessionId: sessionId });
expect(payment.status).toBe(201);
const confirmed = await call(app, "POST", `/v1/payments/${payment.json.data.id}/confirm`, {
txHash,
confirmations: 3,
});
expect(confirmed.status).toBe(200);
return txHash;
}
function tokenOf(payUrl: string): string {
return payUrl.split("/i/")[1]!;
}
describe("payable invoices", () => {
let h: Harness;
beforeEach(async () => {
h = await harness();
});
it("sends an invoice, the client pays onchain, and it settles automatically", async () => {
await onboard(h.app);
const customerId = await customer(h.app);
const created = await call(h.app, "POST", "/v1/invoices", {
customerId,
lineItems: [
{ description: "Brand design", quantity: 1, unitAmount: "400" },
{ description: "Revisions", quantity: 2, unitAmount: "50" },
],
dueAt: "2026-10-30T00:00:00.000Z",
});
expect(created.status).toBe(201);
const id = created.json.data.id as string;
const sent = await call(h.app, "POST", `/v1/invoices/${id}/send`, {});
expect(sent.status).toBe(200);
const { invoice, payUrl, checkoutSessionId, emailedTo } = sent.json.data;
expect(invoice.status).toBe("open");
expect(payUrl).toMatch(/^https:\/\/pay\.test\/i\/[A-Za-z0-9_-]{16,}$/);
expect(emailedTo).toBe("ap@client.test");
expect(h.sent).toHaveLength(1);
expect(h.sent[0]!.subject).toContain(invoice.number);
expect(h.sent[0]!.html).toContain(payUrl);
// The session charges the invoice total to the merchant's wallet.
const session = await h.ctx.checkouts.findById(checkoutSessionId);
expect(session?.amount.amount).toBe("500");
expect(session?.payToAddress).toBe(EVM_PAYTO);
expect(session?.invoiceId).toBe(id);
expect(session?.customerId).toBe(customerId);
// Re-sending keeps the same link and the same open session.
const again = await call(h.app, "POST", `/v1/invoices/${id}/send`, {});
expect(again.json.data.payUrl).toBe(payUrl);
expect(again.json.data.checkoutSessionId).toBe(checkoutSessionId);
// Public pay page: no API key.
const token = tokenOf(payUrl);
const view = await call(h.app, "GET", `/v1/public/invoices/${token}`, undefined, false);
expect(view.status).toBe(200);
expect(view.json.data).toMatchObject({ number: invoice.number, total: "500", payable: true, merchantName: "Acme Studio" });
expect(view.json.data.customerId).toBeUndefined();
const opened = await call(h.app, "POST", `/v1/public/invoices/${token}/sessions`, {}, false);
expect(opened.status).toBe(201);
expect(opened.json.data.sessionId).toBe(checkoutSessionId);
const txHash = await payOnchain(h.app, checkoutSessionId);
const paid = await call(h.app, "GET", `/v1/invoices/${id}`);
expect(paid.json.data.status).toBe("paid");
expect(paid.json.data.metadata.paidTxHash).toBe(txHash);
const publicPaid = await call(h.app, "GET", `/v1/public/invoices/${token}`, undefined, false);
expect(publicPaid.json.data).toMatchObject({ status: "paid", payable: false, paidTxHash: txHash });
const reopen = await call(h.app, "POST", `/v1/public/invoices/${token}/sessions`, {}, false);
expect(reopen.status).toBe(400);
// The hidden invoice product never shows in the catalog.
const products = await call(h.app, "GET", "/v1/merchant/products");
expect(products.json.data).toHaveLength(0);
});
it("creates and sends an ad-hoc payment request to an email", async () => {
await onboard(h.app);
const res = await call(h.app, "POST", "/v1/invoices/requests", {
amount: "75.50",
description: "Consulting call, 1 hour",
payerEmail: "founder@client.test",
});
expect(res.status).toBe(201);
expect(res.json.data.invoice).toMatchObject({ status: "open", total: { amount: "75.5" } });
expect(res.json.data.invoice.metadata.kind).toBe("payment_request");
expect(res.json.data.emailedTo).toBe("founder@client.test");
const customerId = res.json.data.invoice.customerId as string;
expect((await h.ctx.customers.findById(customerId))?.email).toBe("founder@client.test");
// A second request to the same email reuses the customer.
const second = await call(h.app, "POST", "/v1/invoices/requests", {
amount: "10",
description: "Follow-up",
payerEmail: "FOUNDER@client.test",
});
expect(second.json.data.invoice.customerId).toBe(customerId);
const missing = await call(h.app, "POST", "/v1/invoices/requests", { amount: "10", description: "x" });
expect(missing.status).toBe(400);
const zero = await call(h.app, "POST", "/v1/invoices/requests", {
amount: "0",
description: "x",
payerEmail: "a@b.test",
});
expect(zero.status).toBe(400);
});
it("refuses to send before a receiving wallet is configured", async () => {
const customerId = await customer(h.app);
const created = await call(h.app, "POST", "/v1/invoices", {
customerId,
lineItems: [{ description: "Work", quantity: 1, unitAmount: "10" }],
});
const sent = await call(h.app, "POST", `/v1/invoices/${created.json.data.id}/send`, {});
expect(sent.status).toBe(400);
expect(sent.json.error?.message).toMatch(/receiving wallet/);
});
it("reports a skipped email when no transport is configured", async () => {
const noEmail = await harness(false);
await onboard(noEmail.app);
const res = await call(noEmail.app, "POST", "/v1/invoices/requests", {
amount: "5",
description: "Tip",
payerEmail: "x@y.test",
});
expect(res.status).toBe(201);
expect(res.json.data.emailedTo).toBeNull();
expect(res.json.data.emailSkipped).toMatch(/not configured/);
});
it("voiding cancels the open session so an old link cannot be paid", async () => {
await onboard(h.app);
const req = await call(h.app, "POST", "/v1/invoices/requests", {
amount: "20",
description: "Deposit",
payerEmail: "p@q.test",
});
const { invoice, checkoutSessionId, payUrl } = req.json.data;
const voided = await call(h.app, "POST", `/v1/invoices/${invoice.id}/void`);
expect(voided.json.data.status).toBe("void");
expect((await h.ctx.checkouts.findById(checkoutSessionId))?.status).toBe("canceled");
const view = await call(h.app, "GET", `/v1/public/invoices/${tokenOf(payUrl)}`, undefined, false);
expect(view.json.data).toMatchObject({ payable: false, status: "void" });
});
it("serves invoice PDFs to the merchant and the pay-link holder", async () => {
await onboard(h.app);
const req = await call(h.app, "POST", "/v1/invoices/requests", {
amount: "30",
description: "Logo",
payerEmail: "p@q.test",
});
const merchantPdf = await call(h.app, "GET", `/v1/invoices/${req.json.data.invoice.id}.pdf`);
expect(merchantPdf.status).toBe(200);
expect(merchantPdf.pdf?.subarray(0, 5).toString()).toBe("%PDF-");
const publicPdf = await call(h.app, "GET", `/v1/public/invoices/${tokenOf(req.json.data.payUrl)}/pdf`, undefined, false);
expect(publicPdf.status).toBe(200);
expect(publicPdf.pdf?.subarray(0, 5).toString()).toBe("%PDF-");
});
it("answers 404 for an unknown pay token and keeps invoices tenant-scoped", async () => {
const unknown = await call(h.app, "GET", "/v1/public/invoices/unknown_token_abcdefghij", undefined, false);
expect(unknown.status).toBe(404);
});
});
describe("payment requests for plugins", () => {
it("can skip the email and return the payer to the store after paying", async () => {
const h = await harness();
await onboard(h.app);
const res = await call(h.app, "POST", "/v1/invoices/requests", {
amount: "42.00",
description: "Order #1001",
payerEmail: "shopper@store.test",
sendEmail: false,
successUrl: "https://store.test/checkout/order-received/1001?key=wc_order_abc",
metadata: { wc_order_id: "1001" },
});
expect(res.status).toBe(201);
expect(res.json.data.emailedTo).toBeNull();
expect(h.sent).toHaveLength(0);
const session = await h.ctx.checkouts.findById(res.json.data.checkoutSessionId);
expect(session?.successUrl).toBe("https://store.test/checkout/order-received/1001?key=wc_order_abc");
expect(res.json.data.invoice.metadata.wc_order_id).toBe("1001");
const insecure = await call(h.app, "POST", "/v1/invoices/requests", {
amount: "1",
description: "x",
payerEmail: "a@b.test",
successUrl: "http://evil.test/",
});
expect(insecure.status).toBe(400);
});
});
describe("invoice settlement bindings cannot be forged", () => {
it("ignores reserved metadata and never settles from another org's payment", async () => {
const { app, ctx } = await harness(false);
await onboard(app);
const cus = await customer(app);
// Another org's confirmed payment.
await ctx.payments.save({
id: "pay_foreign",
organizationId: "org_someone_else",
checkoutSessionId: "cs_foreign_paid",
customerId: "cus_x",
amount: { amount: "500", currency: "USDC" },
network: "base",
txHash: `0x${randomBytes(32).toString("hex")}`,
confirmations: 3,
status: "confirmed",
createdAt: new Date().toISOString(),
confirmedAt: new Date().toISOString(),
} as never);
const createdRes = await call(app, "POST", "/v1/invoices", {
customerId: cus,
lineItems: [{ description: "Work", quantity: 1, unitAmount: "100" }],
metadata: { checkoutSessionIds: "cs_foreign_paid", payToken: "attackerChosenToken123", note: "kept" },
});
expect(createdRes.status).toBe(201);
const inv = createdRes.json.data;
expect(inv.metadata.checkoutSessionIds).toBeUndefined();
expect(inv.metadata.payToken).toBeUndefined();
expect(inv.metadata.note).toBe("kept");
// Even with a binding planted directly in storage, a foreign payment never settles it.
const stored = await ctx.invoices.get(inv.id);
if (!stored.ok) throw stored.error;
await ctx.invoices.save({ ...stored.value, status: "open", metadata: { ...stored.value.metadata, checkoutSessionIds: "cs_foreign_paid" } });
const read = await call(app, "GET", `/v1/invoices/${inv.id}`);
expect(read.json.data.status).toBe("open");
const request = await call(app, "POST", "/v1/invoices/requests", {
amount: "5",
description: "Quick job",
payerEmail: "p@client.test",
sendEmail: false,
metadata: { kind: "platform_fee", merchantOrgId: "org_victim", paidTxHash: "0xdead" },
});
expect(request.status).toBe(201);
expect(request.json.data.invoice.metadata.kind).toBe("payment_request");
expect(request.json.data.invoice.metadata.merchantOrgId).toBeUndefined();
expect(request.json.data.invoice.metadata.paidTxHash).toBeUndefined();
});
});

View File

@ -0,0 +1,66 @@
/**
* Postgres enforces prices.product_id -> products.id, so a quick product must
* be stored before its price. The in-memory repositories do not enforce the
* foreign key, so this test wraps the price repository to reject a price whose
* product does not exist yet (as Postgres does).
*/
import { beforeEach, describe, expect, it } from "vitest";
import type { Hono } from "hono";
import { createApp } from "../src/app.js";
import { createContext, type AppContext, type AppEnv } from "../src/context.js";
const BOOTSTRAP = "test-bootstrap-key";
let app: Hono<AppEnv>;
async function call(method: string, path: string, body?: unknown) {
const res = await app.request(path, {
method,
headers: { authorization: `Bearer ${BOOTSTRAP}`, "content-type": "application/json" },
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
});
return { status: res.status, json: (await res.json()) as { data?: any; error?: { code: string; message: string } } };
}
beforeEach(async () => {
process.env.API_BOOTSTRAP_KEY = BOOTSTRAP;
const base = await createContext();
const prices = base.prices;
const fkPrices = new Proxy(prices, {
get(target, prop, receiver) {
if (prop === "save") {
return async (price: { productId: string }) => {
if (!(await base.products.findById(price.productId))) {
throw new Error(`foreign key violation: product ${price.productId} does not exist`);
}
return target.save(price as never);
};
}
return Reflect.get(target, prop, receiver);
},
});
const ctx: AppContext = { ...base, prices: fkPrices };
app = createApp(ctx);
});
describe("merchant quick product", () => {
it("stores the product before its price and publishes it", async () => {
expect(
(
await call("POST", "/v1/merchant/profile", {
orgName: "Shop",
acceptedNetworks: ["base"],
addresses: { evm: "0x7777777777777777777777777777777777777777" },
})
).status,
).toBe(200);
const product = await call("POST", "/v1/merchant/products", {
name: "Pass",
priceUsd: "1",
delivery: { kind: "license_key", machineLimit: 1 },
});
expect(product.status, JSON.stringify(product.json.error)).toBe(201);
expect(product.json.data.status).toBe("active");
expect(typeof product.json.data.slug).toBe("string");
});
});

View File

@ -0,0 +1,48 @@
import { createHmac } from "node:crypto";
import { describe, expect, it } from "vitest";
import { configuredOfframps, offrampLinks } from "../src/payouts/offramp.js";
const WALLET = "0x7878787878787878787878787878787878787878";
describe("off-ramp hand-off", () => {
it("offers nothing until a partner key is configured", () => {
expect(offrampLinks({ network: "base", amount: "250", wallet: WALLET }, {})).toEqual([]);
expect(configuredOfframps({})).toEqual([]);
});
it("prefills amount, network and the merchant's own wallet per partner", () => {
const env = { TRANSAK_API_KEY: "tk_pub", RAMP_HOST_API_KEY: "ramp_pub", MOONPAY_PUBLISHABLE_KEY: "pk_x", MOONPAY_SECRET_KEY: "sk_x" };
const links = offrampLinks({ network: "base", amount: "250.5", wallet: WALLET, returnUrl: "https://dash.test/payouts" }, env);
expect(links.map((l) => l.provider)).toEqual(["transak", "moonpay", "ramp"]);
const transak = new URL(links[0]!.url);
expect(transak.origin).toBe("https://global.transak.com");
expect(Object.fromEntries(transak.searchParams)).toMatchObject({
apiKey: "tk_pub",
productsAvailed: "SELL",
cryptoCurrencyCode: "USDC",
network: "base",
cryptoAmount: "250.5",
walletAddress: WALLET,
});
const moonpay = new URL(links[1]!.url);
expect(moonpay.searchParams.get("baseCurrencyCode")).toBe("usdc_base");
const signed = links[1]!.url.slice(links[1]!.url.indexOf("?"), links[1]!.url.indexOf("&signature="));
expect(moonpay.searchParams.get("signature")).toBe(createHmac("sha256", "sk_x").update(signed).digest("base64"));
const ramp = new URL(links[2]!.url);
expect(Object.fromEntries(ramp.searchParams)).toMatchObject({ swapAsset: "BASE_USDC", swapAmount: "250500000", userAddress: WALLET, enabledFlows: "OFFRAMP" });
});
it("skips partners that do not support the network and validates the amount", () => {
const env = { TRANSAK_API_KEY: "tk", RAMP_HOST_API_KEY: "r" };
expect(offrampLinks({ network: "zcash", amount: "1", wallet: "t1abc" }, env)).toEqual([]);
expect(offrampLinks({ network: "solana", amount: "1", wallet: "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM" }, env).map((l) => l.provider)).toEqual(["transak", "ramp"]);
expect(() => offrampLinks({ network: "base", amount: "0", wallet: WALLET }, env)).toThrow(/positive/);
expect(() => offrampLinks({ network: "base", amount: "abc", wallet: WALLET }, env)).toThrow(/positive/);
expect(new URL(offrampLinks({ network: "base", amount: "1", wallet: WALLET }, { ...env, TRANSAK_ENV: "staging" })[0]!.url).origin).toBe(
"https://global-stg.transak.com",
);
});
});

View File

@ -0,0 +1,195 @@
/**
* Operator routes over Hono's app.request(), with a real operator runtime
* (in-memory store, LocalExecutor vault simulation, heuristic engine) and the
* real API-key auth middleware. Mounted exactly as app.ts mounts them: before
* the API-key-guarded v1 group.
*/
import { beforeEach, describe, expect, it } from "vitest";
import { Hono } from "hono";
import { DEFAULT_ORG_ID } from "@settlekit/persistence";
import { createOperatorRuntime, LocalExecutor, type OperatorRuntime } from "@settlekit/operator";
import type { AppContext, AppEnv } from "../src/context.js";
import { error } from "../src/http/respond.js";
import { authMiddleware } from "../src/middleware/auth.js";
import { operatorRoutes } from "../src/routes/operator.js";
const BOOTSTRAP = "operator-bootstrap";
const AGENT_KEY = "sk_agent";
const OTHER_ORG_KEY = "sk_other";
const VENDOR = "0x00000000000000000000000000000000007e2d02";
const STRANGER = "0x0000000000000000000000000000000000000bad";
const U = 1_000_000n;
const T0 = new Date("2026-10-04T12:00:00.000Z");
const fakeCtx = {
apiKeys: {
verify: async (key: string) =>
key === AGENT_KEY
? { valid: true, apiKey: { id: "key_agent", organizationId: DEFAULT_ORG_ID, scopes: ["platform:admin"], status: "active", productId: "__platform__" } }
: key === OTHER_ORG_KEY
? { valid: true, apiKey: { id: "key_other", organizationId: "org_other", scopes: ["platform:admin"], status: "active", productId: "__platform__" } }
: { valid: false },
recordUsage: async () => undefined,
},
auth: { authenticateSession: async () => ({ ok: false }) },
} as unknown as AppContext;
interface Setup {
readonly app: Hono<AppEnv>;
readonly runtime: OperatorRuntime;
readonly vault: LocalExecutor;
}
function setup(): Setup {
process.env.API_BOOTSTRAP_KEY = BOOTSTRAP;
const vault = new LocalExecutor({ caps: { perTxCap: 1000n * U, dailyCap: 1500n * U, escalateAbove: 500n * U }, allowlist: [VENDOR], now: () => T0 });
const runtime = createOperatorRuntime({ OPERATOR_ALLOWLIST: VENDOR }, DEFAULT_ORG_ID, { executor: vault, owner: vault, now: () => T0 });
const app = new Hono<AppEnv>();
app.use("*", async (c, next) => {
c.set("ctx", fakeCtx);
await next();
});
app.route("/", operatorRoutes({ runtime: () => runtime, proofTtlMs: 0 }));
const v1 = new Hono<AppEnv>();
v1.use("*", authMiddleware());
v1.get("/anything", (c) => c.json({ data: "guarded" }));
app.route("/v1", v1);
app.onError((err, c) => error(c, err));
return { app, runtime, vault };
}
async function call(app: Hono<AppEnv>, method: string, path: string, body?: unknown, key: string | null = BOOTSTRAP) {
const res = await app.request(path, {
method,
headers: { "content-type": "application/json", ...(key ? { authorization: `Bearer ${key}` } : {}) },
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
});
return { status: res.status, json: (await res.json()) as { data?: any; error?: { code: string; message: string; details?: any } } };
}
const sale = (id = "evt_sale_1", amount = 2000n * U) => ({ type: "revenue.received", id, at: T0.toISOString(), amount: amount.toString(), payer: "0x00000000000000000000000000000000000000aa", paymentRef: "0xpay" });
describe("operator routes", () => {
let s: Setup;
beforeEach(() => {
s = setup();
s.vault.deposit(2000n * U);
});
it("requires a credential and scopes to the operator org", async () => {
expect((await call(s.app, "GET", "/v1/operator/decisions", undefined, null)).status).toBe(401);
expect((await call(s.app, "GET", "/v1/operator/decisions", undefined, OTHER_ORG_KEY)).status).toBe(403);
expect((await call(s.app, "GET", "/v1/anything", undefined, null)).status).toBe(401);
});
it("handles an event once, forcing the caller's org, and replays duplicates", async () => {
const first = await call(s.app, "POST", "/v1/operator/events", { ...sale(), orgId: "org_attacker" }, AGENT_KEY);
expect(first.status).toBe(201);
expect(first.json.data).toMatchObject({ orgId: DEFAULT_ORG_ID, outcome: "executed", seq: 0 });
const replay = await call(s.app, "POST", "/v1/operator/events", sale(), AGENT_KEY);
expect(replay.status).toBe(200);
expect(replay.json.data.id).toBe(first.json.data.id);
const bad = await call(s.app, "POST", "/v1/operator/events", { type: "revenue.received", id: "x" }, AGENT_KEY);
expect(bad.status).toBe(400);
expect(bad.json.error?.details.issues.length).toBeGreaterThan(0);
const list = await call(s.app, "GET", "/v1/operator/decisions?limit=10");
expect(list.json.data).toHaveLength(1);
const one = await call(s.app, "GET", `/v1/operator/decisions/${first.json.data.id}`);
expect(one.json.data.hash).toBe(first.json.data.hash);
expect((await call(s.app, "GET", "/v1/operator/decisions/nope")).status).toBe(404);
});
it("takes bills, escalates unknown payees, and lets only the owner approve or reject", async () => {
await call(s.app, "POST", "/v1/operator/events", sale(), AGENT_KEY);
const paid = await call(s.app, "POST", "/v1/operator/bills", { payee: VENDOR, amountUsdc: "120", dueAt: T0.toISOString(), description: "Hosting" }, AGENT_KEY);
expect(paid.status).toBe(201);
expect(paid.json.data.bill.status).toBe("paid");
const unknown = await call(s.app, "POST", "/v1/operator/bills", { payee: STRANGER, amountUsdc: "75", dueAt: T0.toISOString(), description: "New contractor" }, AGENT_KEY);
expect(unknown.json.data.decision.outcome).toBe("escalated");
expect((await call(s.app, "POST", "/v1/operator/bills", { payee: "nope", amountUsdc: "x", dueAt: "y", description: "" })).status).toBe(400);
expect((await call(s.app, "POST", "/v1/operator/bills", { invoiceText: "Invoice" })).json.error?.message).toMatch(/ANTHROPIC_API_KEY/);
const pending = await call(s.app, "GET", "/v1/operator/escalations?status=pending");
const id = pending.json.data[0].id as string;
expect((await call(s.app, "POST", `/v1/operator/escalations/${id}/reject`, { reason: "unknown" }, AGENT_KEY)).status).toBe(403);
const rejected = await call(s.app, "POST", `/v1/operator/escalations/${id}/reject`, { reason: "not a vendor we use" });
expect(rejected.json.data).toMatchObject({ model: "owner", outcome: "denied" });
expect((await call(s.app, "POST", `/v1/operator/escalations/${id}/approve`)).status).toBe(409);
expect((await call(s.app, "POST", `/v1/operator/escalations/missing/approve`)).status).toBe(404);
expect((await call(s.app, "GET", "/v1/operator/bills?status=rejected")).json.data).toHaveLength(1);
});
it("approves a vault escalation above the threshold", async () => {
await call(s.app, "POST", "/v1/operator/events", sale(), AGENT_KEY);
const big = await call(s.app, "POST", "/v1/operator/bills", { payee: VENDOR, amountUsdc: "600", dueAt: T0.toISOString(), description: "Annual" }, AGENT_KEY);
expect(big.json.data.decision.outcome).toBe("escalated");
const [pending] = (await call(s.app, "GET", "/v1/operator/escalations?status=pending")).json.data;
expect(pending.vaultEscalationId).toBe(1);
const approved = await call(s.app, "POST", `/v1/operator/escalations/${pending.id}/approve`);
expect(approved.json.data.outcome).toBe("executed");
expect(s.vault.escalation(1)?.status).toBe("Approved");
});
it("serves vault state: buckets, spend vs caps and pending escalations", async () => {
await call(s.app, "POST", "/v1/operator/events", sale(), AGENT_KEY);
await call(s.app, "POST", "/v1/operator/bills", { payee: VENDOR, amountUsdc: "120", dueAt: T0.toISOString(), description: "Hosting" }, AGENT_KEY);
await call(s.app, "POST", "/v1/operator/bills", { payee: STRANGER, amountUsdc: "75", dueAt: T0.toISOString(), description: "New contractor" }, AGENT_KEY);
const state = await call(s.app, "GET", "/v1/operator/state", undefined, AGENT_KEY);
expect(state.status).toBe(200);
expect(state.json.data).toMatchObject({
orgId: DEFAULT_ORG_ID,
executor: "local-simulation",
vault: null,
spentToday: "120",
caps: { perTxCap: "1000", dailyCap: "1500", escalateAbove: "500" },
pendingEscalations: 1,
});
expect(Object.keys(state.json.data.buckets)).toEqual(["OPERATING", "TAX", "YIELD", "REFUND"]);
expect((await call(s.app, "GET", "/v1/operator/state", undefined, OTHER_ORG_KEY)).status).toBe(403);
});
it("serves policy and refuses drift from the vault", async () => {
const got = await call(s.app, "GET", "/v1/operator/policy", undefined, AGENT_KEY);
expect(got.json.data).toMatchObject({ executor: "local-simulation", engine: "heuristic", drift: [] });
expect(got.json.data.policy.perTxCap).toBe("1000");
const body = { ...got.json.data.policy, minFloat: "50" };
expect((await call(s.app, "PUT", "/v1/operator/policy", body, AGENT_KEY)).status).toBe(403);
const drift = await call(s.app, "PUT", "/v1/operator/policy", { ...body, dailyCap: "9000" });
expect(drift.status).toBe(409);
expect(drift.json.error?.details.drift[0]).toMatch(/dailyCap/);
expect((await call(s.app, "PUT", "/v1/operator/policy", { ...body, split: { OPERATING: 1 } })).status).toBe(400);
const saved = await call(s.app, "PUT", "/v1/operator/policy", body);
expect(saved.json.data.policy.minFloat).toBe("50");
});
it("publishes proof and verification without a key", async () => {
const decision = (await call(s.app, "POST", "/v1/operator/events", sale(), AGENT_KEY)).json.data;
const proof = await call(s.app, "GET", "/v1/public/operator/proof", undefined, null);
expect(proof.status).toBe(200);
expect(proof.json.data).toMatchObject({ orgs: 1, usdcIn: expect.stringMatching(/^2000/), executor: "local-simulation", decisions: { total: 1, executed: 1 } });
const verify = await call(s.app, "GET", `/v1/public/operator/verify/${decision.id}`, undefined, null);
// Local simulation: the log verifies, but a decision that moved money is not
// reported valid without an on-chain anchor check.
expect(verify.json.data).toMatchObject({ valid: false, commitment: "match", chain: { valid: true }, onChain: "not_configured" });
expect((await call(s.app, "GET", "/v1/public/operator/verify/nope", undefined, null)).status).toBe(404);
});
});
describe("operator routes without configuration", () => {
it("answers 503 instead of silently simulating", async () => {
const saved = { vault: process.env.OPERATOR_VAULT_ADDRESS, sim: process.env.OPERATOR_SIMULATION };
delete process.env.OPERATOR_VAULT_ADDRESS;
delete process.env.OPERATOR_SIMULATION;
try {
const app = new Hono<AppEnv>();
app.route("/", operatorRoutes());
app.onError((err, c) => error(c, err));
const res = await app.request("/v1/public/operator/proof");
expect(res.status).toBe(503);
} finally {
if (saved.vault !== undefined) process.env.OPERATOR_VAULT_ADDRESS = saved.vault;
if (saved.sim !== undefined) process.env.OPERATOR_SIMULATION = saved.sim;
}
});
});

View File

@ -0,0 +1,272 @@
/**
* SettleKit's own revenue: monthly fee statements issued from the platform org,
* paid through SettleKit's own checkout, with the free plan's product limit
* applied after the grace period.
*/
import { randomBytes } from "node:crypto";
import { afterAll, beforeEach, describe, expect, it } from "vitest";
import type { Hono } from "hono";
import { money, type Payment } from "@settlekit/common";
import type { SettlementVerifier } from "@settlekit/chains";
import { DEFAULT_ORG_ID } from "@settlekit/persistence";
import { createApp } from "../src/app.js";
import { createContext, type AppContext, type AppEnv } from "../src/context.js";
import { issueStatement, loadPlatformBillingConfig, runStatements } from "../src/platform/fee-statements.js";
const BOOTSTRAP = "test-bootstrap-key";
const PLATFORM_ORG = "org_platform";
const PLATFORM_WALLET = "0x5555555555555555555555555555555555555555";
const MERCHANT_WALLET = "0x6666666666666666666666666666666666666666";
const baseChainDouble: SettlementVerifier = async (proof, requirements) =>
proof.network === requirements.network ? { ok: true } : { ok: false, reason: "network mismatch" };
let app: Hono<AppEnv>;
let ctx: AppContext;
let platformKey: string;
let otherKey: string;
async function callAs(key: string, method: string, path: string, body?: unknown) {
const res = await app.request(path, {
method,
headers: { authorization: `Bearer ${key}`, "content-type": "application/json" },
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
});
return { status: res.status, json: (await res.json()) as { data?: any; error?: { code: string; message: string } } };
}
const merchant = (method: string, path: string, body?: unknown) => callAs(BOOTSTRAP, method, path, body);
const platform = (method: string, path: string, body?: unknown) => callAs(platformKey, method, path, body);
let paySeq = 0;
async function settledPayment(amount: string, confirmedAt: string, organizationId = DEFAULT_ORG_ID): Promise<void> {
paySeq += 1;
const payment: Payment = {
id: `pay_fee_${paySeq}`,
organizationId,
checkoutSessionId: `cs_fee_${paySeq}`,
customerId: "cus_buyer",
amount: money(amount),
network: "base",
txHash: `0x${randomBytes(32).toString("hex")}`,
confirmations: 3,
status: "confirmed",
createdAt: confirmedAt,
confirmedAt,
};
await ctx.payments.save(payment);
}
async function quickProduct(name: string) {
return merchant("POST", "/v1/merchant/products", {
name,
description: `${name} description`,
priceUsd: "10",
interval: "one_time",
delivery: { kind: "license_key", machineLimit: 1 },
});
}
beforeEach(async () => {
process.env.API_BOOTSTRAP_KEY = BOOTSTRAP;
process.env.PLATFORM_BILLING_ORG_ID = PLATFORM_ORG;
process.env.PLATFORM_BILLING_DUE_DAYS = "14";
process.env.PLATFORM_BILLING_GRACE_DAYS = "7";
process.env.PLATFORM_BILLING_MIN_USD = "1";
const base = await createContext();
ctx = { ...base, email: null, verifiers: { ...base.verifiers, base: baseChainDouble } };
app = createApp(ctx);
platformKey = (
await ctx.apiKeys.issue({
organizationId: PLATFORM_ORG,
customerId: "cus_platform",
productId: "__platform__",
entitlementId: "ent_platform",
scopes: ["*"],
env: "live",
})
).plaintext;
otherKey = (
await ctx.apiKeys.issue({
organizationId: "org_other",
customerId: "cus_other",
productId: "__platform__",
entitlementId: "ent_other",
scopes: ["*"],
env: "live",
})
).plaintext;
expect(
(await platform("POST", "/v1/merchant/profile", { orgName: "SettleKit", acceptedNetworks: ["base"], addresses: { evm: PLATFORM_WALLET } }))
.status,
).toBe(200);
expect(
(
await merchant("POST", "/v1/merchant/profile", {
orgName: "Merchant Co",
supportEmail: "owner@merchant.test",
acceptedNetworks: ["base"],
addresses: { evm: MERCHANT_WALLET },
})
).status,
).toBe(200);
});
afterAll(() => {
for (const key of ["PLATFORM_BILLING_ORG_ID", "PLATFORM_BILLING_DUE_DAYS", "PLATFORM_BILLING_GRACE_DAYS", "PLATFORM_BILLING_MIN_USD"]) {
delete process.env[key];
}
});
describe("platform fee statements", () => {
it("reads the config from env and stays off when unset", () => {
expect(loadPlatformBillingConfig({})).toBeNull();
expect(loadPlatformBillingConfig({ PLATFORM_BILLING_ORG_ID: "org_x" })).toEqual({
orgId: "org_x",
dueDays: 14,
graceDays: 14,
minimum: "1",
});
expect(() => loadPlatformBillingConfig({ PLATFORM_BILLING_ORG_ID: "org_x", PLATFORM_BILLING_GRACE_DAYS: "-1" })).toThrow();
});
it("bills a closed month, is paid through the platform checkout, and lifts the limit", async () => {
// Four active products (over the free limit of 3), then volume in Jan 2025.
for (const name of ["Alpha", "Beta", "Gamma"]) expect((await quickProduct(name)).status).toBe(201);
await settledPayment("300", "2025-01-10T00:00:00.000Z");
await settledPayment("200", "2025-01-31T23:00:00.000Z");
await settledPayment("999", "2025-02-01T00:00:00.000Z");
const accrued = await merchant("GET", "/v1/billing/fees");
expect(accrued.json.data).toMatchObject({ configured: true, standing: "good", schedule: { bps: 100 } });
expect(accrued.json.data.accrued).toMatchObject({ paymentCount: 3, fees: "14.99" });
// Only the platform operator can run statements.
expect((await callAs(otherKey, "POST", "/v1/billing/statements/run", { period: "2025-01" })).status).toBe(403);
const run = await platform("POST", "/v1/billing/statements/run", { period: "2025-01" });
expect(run.status).toBe(200);
expect(run.json.data.results).toEqual([
expect.objectContaining({ merchantOrgId: DEFAULT_ORG_ID, status: "issued" }),
]);
// Re-running is idempotent.
const again = await platform("POST", "/v1/billing/statements/run", { period: "2025-01" });
expect(again.json.data.results[0].status).toBe("exists");
// A month that has not ended cannot be billed.
expect((await platform("POST", "/v1/billing/statements/run", { period: "2999-01" })).json.data.results[0].status).toBe("error");
const fees = await merchant("GET", "/v1/billing/fees");
const [statement] = fees.json.data.statements;
expect(statement).toMatchObject({ period: "2025-01", status: "open", total: "5", paymentCount: 2, grossVolume: "500" });
expect(statement.payUrl).toMatch(/\/i\/[A-Za-z0-9_-]{16,}$/);
expect(statement.dueAt).toBe("2025-02-15T00:00:00.000Z");
// Long past due + grace: restricted.
expect(fees.json.data.standing).toBe("restricted");
expect(fees.json.data.accrued).toMatchObject({ paymentCount: 1, fees: "9.99" });
// The statement is an invoice of SettleKit's own org, paid to its wallet.
const invoice = await ctx.invoices.get(statement.id);
if (!invoice.ok) throw new Error("statement invoice missing");
expect(invoice.value.organizationId).toBe(PLATFORM_ORG);
const sessionId = invoice.value.metadata.checkoutSessionIds!;
const session = await ctx.checkouts.findById(sessionId);
expect(session).toMatchObject({ organizationId: PLATFORM_ORG, payToAddress: PLATFORM_WALLET, amount: { amount: "5" } });
// The merchant never sees the statement in their own invoices.
expect((await merchant("GET", "/v1/invoices")).json.data).toHaveLength(0);
// Restricted: the 4th active product is refused with the pay link.
const blocked = await quickProduct("Delta");
expect(blocked.status).toBe(402);
expect(blocked.json.error?.code).toBe("payment_required");
expect(blocked.json.error?.message).toContain(statement.payUrl);
// Pay the statement onchain through the platform checkout.
const payment = await platform("POST", "/v1/payments", { checkoutSessionId: sessionId });
expect(payment.status).toBe(201);
const confirmed = await platform("POST", `/v1/payments/${payment.json.data.id}/confirm`, {
txHash: `0x${randomBytes(32).toString("hex")}`,
confirmations: 3,
});
expect(confirmed.status).toBe(200);
const after = await merchant("GET", "/v1/billing/fees");
expect(after.json.data.statements[0].status).toBe("paid");
expect(after.json.data.standing).toBe("good");
expect((await quickProduct("Delta")).status).toBe(201);
});
it("issues one statement when runs overlap and sends a draft left by an interrupted run", async () => {
expect((await quickProduct("Overlap")).status).toBe(201);
await settledPayment("400", "2025-05-10T00:00:00.000Z");
const cfg = loadPlatformBillingConfig()!;
const now = new Date("2025-06-02T00:00:00.000Z");
const outcomes = await Promise.all([
runStatements(ctx, cfg, "2025-05", now),
runStatements(ctx, cfg, "2025-05", now),
runStatements(ctx, cfg, "2025-05", now),
]);
const statuses = outcomes.map((o) => o.results[0]!.status).sort();
expect(statuses).toEqual(["exists", "exists", "issued"]);
const open = (await ctx.invoices.list()).filter(
(inv) => inv.metadata.kind === "platform_fee" && inv.metadata.period === "2025-05" && inv.status !== "void",
);
expect(open).toHaveLength(1);
expect(open[0]!.status).toBe("open");
// A second instance raced in a duplicate draft: it loses to the sent one.
const loser = await issueStatement(ctx, cfg, DEFAULT_ORG_ID, "2025-05", now);
expect(loser.status).toBe("exists");
// A draft left by a crash between create and send is sent on the next run.
await settledPayment("300", "2025-06-10T00:00:00.000Z");
const [customer] = await ctx.customers.list((c) => c.organizationId === PLATFORM_ORG);
const draft = await ctx.invoices.create({
organizationId: PLATFORM_ORG,
customerId: customer!.id,
lineItems: [{ description: "June", quantity: 1, unitAmount: money("3") }],
metadata: { kind: "platform_fee", merchantOrgId: DEFAULT_ORG_ID, period: "2025-06", coverageEnd: "2025-07-01T00:00:00.000Z" },
});
if (!draft.ok) throw draft.error;
const resumed = await issueStatement(ctx, cfg, DEFAULT_ORG_ID, "2025-06", new Date("2025-07-02T00:00:00.000Z"));
expect(resumed.status).toBe("issued");
if (resumed.status !== "issued") throw new Error("not issued");
expect(resumed.invoice.id).toBe(draft.value.id);
expect(resumed.invoice.status).toBe("open");
});
it("carries fees below the minimum into the next statement and skips test accounts", async () => {
expect((await quickProduct("Solo")).status).toBe(201);
await settledPayment("50", "2025-03-05T00:00:00.000Z"); // 0.50 fee: below the 1 USDC minimum
const march = await platform("POST", "/v1/billing/statements/run", { period: "2025-03" });
expect(march.json.data.results[0]).toMatchObject({ status: "below_minimum", fees: "0.5" });
await settledPayment("100", "2025-04-05T00:00:00.000Z");
const april = await platform("POST", "/v1/billing/statements/run", { period: "2025-04" });
expect(april.json.data.results[0].status).toBe("issued");
const [statement] = (await merchant("GET", "/v1/billing/fees")).json.data.statements;
expect(statement).toMatchObject({ period: "2025-04", total: "1.5", paymentCount: 2 });
await merchant("POST", "/v1/merchant/profile", {
acceptedNetworks: ["base"],
addresses: { evm: MERCHANT_WALLET },
testAccount: true,
});
await settledPayment("500", "2025-05-05T00:00:00.000Z");
const may = await platform("POST", "/v1/billing/statements/run", { period: "2025-05" });
expect(may.json.data.results).toEqual([]);
});
});
describe("statement scheduler", () => {
it("bills the previous month on a tick and is disabled without config", async () => {
const { statementTick, startStatementScheduler } = await import("../src/platform/statement-scheduler.js");
expect((await quickProduct("Tick")).status).toBe(201);
await settledPayment("400", "2025-06-15T00:00:00.000Z");
const result = await statementTick(ctx, new Date("2025-07-02T00:00:00.000Z"));
expect(result?.period).toBe("2025-06");
expect(result?.results[0]).toMatchObject({ status: "issued" });
const stop = startStatementScheduler(ctx, () => {}, {});
stop();
delete process.env.PLATFORM_BILLING_ORG_ID;
expect(await statementTick(ctx)).toBeNull();
});
});

View File

@ -0,0 +1,131 @@
/**
* Refund to payer: SettleKit prepares the transfer back to the buyer, the
* merchant signs it, and the refund settles only after onchain verification.
*/
import { randomBytes } from "node:crypto";
import { beforeEach, describe, expect, it } from "vitest";
import type { Hono } from "hono";
import type { SettlementVerifier } from "@settlekit/chains";
import { parseSolanaPayUrl } from "@settlekit/solana";
import { createApp } from "../src/app.js";
import { createContext, type AppContext, type AppEnv } from "../src/context.js";
import { erc20TransferData } from "../src/merchant/refund-to-payer.js";
const BOOTSTRAP = "test-bootstrap-key";
const MERCHANT = "0x3434343434343434343434343434343434343434";
const BUYER = "0x5656565656565656565656565656565656565656";
const SOL_BUYER = "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM";
let app: Hono<AppEnv>;
let ctx: AppContext;
let verifyOk = true;
const checks: { payTo: string; amount: string; reference?: string }[] = [];
const verifier: SettlementVerifier = async (proof, req) => {
const r = req as unknown as { payTo: string; amount: string; reference?: string };
checks.push({ payTo: r.payTo, amount: r.amount, ...(r.reference ? { reference: r.reference } : {}) });
if (proof.network !== req.network) return { ok: false, reason: "network mismatch" };
return verifyOk ? { ok: true } : { ok: false, reason: "no matching transfer" };
};
const tx = () => `0x${randomBytes(32).toString("hex")}`;
async function call(method: string, path: string, body?: unknown) {
const res = await app.request(path, {
method,
headers: { authorization: `Bearer ${BOOTSTRAP}`, "content-type": "application/json" },
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
});
return { status: res.status, json: (await res.json()) as { data?: any; error?: { message: string } } };
}
beforeEach(async () => {
process.env.API_BOOTSTRAP_KEY = BOOTSTRAP;
verifyOk = true;
checks.length = 0;
const base = await createContext();
ctx = { ...base, verifiers: { ...base.verifiers, base: verifier, solana: verifier } };
app = createApp(ctx);
});
async function paidPayment(network: "base" | "solana", amount = "40", payer: string | null = BUYER): Promise<string> {
const product = await call("POST", "/v1/products", { merchantId: "mch_1", name: "Course", type: "license_key", deliveryMode: "license_key" });
const price = await call("POST", `/v1/products/${product.json.data.id}/prices`, { amount });
const customer = await call("POST", "/v1/customers", { email: "buyer@x.test" });
const session = await call("POST", "/v1/checkout-sessions", {
merchantId: "mch_1",
customerId: customer.json.data.id,
items: [{ priceId: price.json.data.id, productId: product.json.data.id, quantity: 1 }],
payToAddress: network === "base" ? MERCHANT : "7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU",
network,
});
const stored = await ctx.checkouts.findById(session.json.data.id);
if (payer) await ctx.checkouts.save({ ...stored!, payerAddress: payer });
const payment = await call("POST", "/v1/payments", { checkoutSessionId: session.json.data.id });
const hash = network === "base" ? tx() : "5".repeat(88);
const confirmed = await call("POST", `/v1/payments/${payment.json.data.id}/confirm`, { txHash: hash, confirmations: 3 });
expect(confirmed.status).toBe(200);
checks.length = 0;
return payment.json.data.id as string;
}
describe("refund to payer", () => {
it("prepares an ERC-20 transfer to the paying wallet and settles after onchain verification", async () => {
const paymentId = await paidPayment("base");
const prepared = await call("POST", `/v1/merchant/payments/${paymentId}/refund/prepare`, { amountUsd: "15" });
expect(prepared.status).toBe(201);
const { refund, plan } = prepared.json.data;
expect(refund).toMatchObject({ status: "pending", destination: BUYER, network: "base", source: "wallet" });
expect(plan.evm.data).toBe(erc20TransferData(BUYER, 15_000_000n));
expect(plan.evm.eip681).toContain(`/transfer?address=${BUYER}&uint256=15000000`);
verifyOk = false;
const failed = await call("POST", `/v1/merchant/refunds/${refund.id}/confirm`, { txHash: tx() });
expect(failed.status).toBe(400);
expect((await ctx.refundStore.findById(refund.id))?.status).toBe("pending");
verifyOk = true;
const hash = tx();
const done = await call("POST", `/v1/merchant/refunds/${refund.id}/confirm`, { txHash: hash });
expect(done.status).toBe(200);
expect(done.json.data.refund).toMatchObject({ status: "succeeded", txHash: hash });
expect(checks.at(-1)).toMatchObject({ payTo: BUYER, amount: "15" });
// Partial refund: the payment stays confirmed.
expect((await ctx.payments.findById(paymentId))?.status).toBe("confirmed");
// The same transaction cannot settle a second refund.
const second = (await call("POST", `/v1/merchant/payments/${paymentId}/refund/prepare`, {})).json.data.refund;
expect(second.amount.amount).toBe("25");
expect((await call("POST", `/v1/merchant/refunds/${second.id}/confirm`, { txHash: hash })).status).toBe(409);
const rest = await call("POST", `/v1/merchant/refunds/${second.id}/confirm`, { txHash: tx() });
expect(rest.status).toBe(200);
expect((await ctx.payments.findById(paymentId))?.status).toBe("refunded");
});
it("prepares a Solana Pay transfer request bound to a reference", async () => {
const paymentId = await paidPayment("solana", "12", SOL_BUYER);
const prepared = await call("POST", `/v1/merchant/payments/${paymentId}/refund/prepare`, {});
const { refund, plan } = prepared.json.data;
const parsed = parseSolanaPayUrl(plan.solana.url) as { recipient: string; amount?: string; references?: string[] };
expect(parsed.recipient).toBe(SOL_BUYER);
expect(parsed.amount).toBe("12");
expect(parsed.references).toEqual([plan.solana.reference]);
const done = await call("POST", `/v1/merchant/refunds/${refund.id}/confirm`, { txHash: "4".repeat(88) });
expect(done.status).toBe(200);
expect(checks.at(-1)).toMatchObject({ payTo: SOL_BUYER, reference: plan.solana.reference });
});
it("asks for an address when the payer is unknown and validates it", async () => {
const paymentId = await paidPayment("base", "10", null);
const missing = await call("POST", `/v1/merchant/payments/${paymentId}/refund/prepare`, {});
expect(missing.status).toBe(400);
expect(missing.json.error?.message).toMatch(/enter the address/);
expect((await call("POST", `/v1/merchant/payments/${paymentId}/refund/prepare`, { to: "not-an-address" })).status).toBe(400);
const ok = await call("POST", `/v1/merchant/payments/${paymentId}/refund/prepare`, { to: BUYER });
expect(ok.status).toBe(201);
const canceled = await call("POST", `/v1/merchant/refunds/${ok.json.data.refund.id}/cancel`);
expect(canceled.json.data.status).toBe("failed");
// Canceled refunds free the amount again.
expect((await call("POST", `/v1/merchant/payments/${paymentId}/refund/prepare`, { to: BUYER })).json.data.refund.amount.amount).toBe("10");
});
});

View File

@ -0,0 +1,85 @@
/** Hosted storefront: settings validation and the public store view. */
import { beforeEach, describe, expect, it } from "vitest";
import type { Hono } from "hono";
import { createApp } from "../src/app.js";
import { createContext, type AppContext, type AppEnv } from "../src/context.js";
const BOOTSTRAP = "test-bootstrap-key";
let app: Hono<AppEnv>;
let ctx: AppContext;
let otherKey: string;
async function call(method: string, path: string, body?: unknown, key: string | null = BOOTSTRAP) {
const res = await app.request(path, {
method,
headers: { ...(key ? { authorization: `Bearer ${key}` } : {}), "content-type": "application/json" },
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
});
return { status: res.status, json: (await res.json()) as { data?: any; error?: { message: string } } };
}
beforeEach(async () => {
process.env.API_BOOTSTRAP_KEY = BOOTSTRAP;
ctx = await createContext();
app = createApp(ctx);
otherKey = (
await ctx.apiKeys.issue({ organizationId: "org_other", customerId: "x", productId: "__platform__", entitlementId: "__platform__", scopes: ["*"], env: "live" })
).plaintext;
await call("POST", "/v1/merchant/profile", { orgName: "Pixel Tools", acceptedNetworks: ["base"], addresses: { evm: "0x9191919191919191919191919191919191919191" } });
});
const STORE = {
enabled: true,
slug: "pixel-tools",
title: "Pixel Tools",
tagline: "Icons and UI kits",
logoUrl: "https://cdn.pixel.test/logo.png",
accentColor: "#ff5500",
seoDescription: "Icon packs and UI kits paid in USDC.",
customDomain: "shop.pixel.test",
};
describe("hosted storefront", () => {
it("lists active products with branding by slug and custom domain", async () => {
expect((await call("POST", "/v1/settings", { store: STORE })).status).toBe(200);
await call("POST", "/v1/merchant/products", { name: "Icon pack", description: "2,000 icons", priceUsd: "29", delivery: { kind: "license_key", machineLimit: 1 } });
const archived = await call("POST", "/v1/merchant/products", { name: "Old", priceUsd: "5", delivery: { kind: "license_key", machineLimit: 1 } });
await call("PATCH", `/v1/merchant/products/${archived.json.data.id}`, { status: "archived" });
// A sent invoice creates a hidden product that must not appear.
await call("POST", "/v1/invoices/requests", { amount: "50", description: "Custom work", payerEmail: "c@x.test" });
const store = await call("GET", "/v1/public/stores/pixel-tools", undefined, null);
expect(store.status).toBe(200);
expect(store.json.data).toMatchObject({
title: "Pixel Tools",
tagline: "Icons and UI kits",
accentColor: "#ff5500",
merchantName: "Pixel Tools",
acceptingPayments: true,
});
const names = store.json.data.products.map((p: { name: string }) => p.name);
expect(names).toContain("Icon pack");
expect(names).not.toContain("Old");
expect(names.some((n: string) => n.startsWith("Invoice"))).toBe(false);
expect(store.json.data.products[0].slug).toMatch(/^icon-pack-/);
const byDomain = await call("GET", "/v1/public/stores/by-domain/shop.pixel.test", undefined, null);
expect(byDomain.json.data.slug).toBe("pixel-tools");
});
it("keeps slugs and domains unique and validates branding", async () => {
await call("POST", "/v1/settings", { store: STORE });
expect((await call("POST", "/v1/settings", { store: { ...STORE, customDomain: undefined } }, otherKey)).status).toBe(409);
expect((await call("POST", "/v1/settings", { store: { ...STORE, slug: "other-shop" } }, otherKey)).status).toBe(409);
expect((await call("POST", "/v1/settings", { store: { enabled: true, slug: "api" } }, otherKey)).status).toBe(400);
expect((await call("POST", "/v1/settings", { store: { enabled: true, slug: "ok-shop", logoUrl: "http://insecure.test/x.png" } }, otherKey)).status).toBe(400);
expect((await call("POST", "/v1/settings", { store: { enabled: true, slug: "ok-shop", accentColor: "red" } }, otherKey)).status).toBe(400);
expect((await call("POST", "/v1/settings", { store: { enabled: true, slug: "ok-shop" } }, otherKey)).status).toBe(200);
});
it("hides a disabled or unknown store", async () => {
await call("POST", "/v1/settings", { store: { ...STORE, enabled: false } });
expect((await call("GET", "/v1/public/stores/pixel-tools", undefined, null)).status).toBe(404);
expect((await call("GET", "/v1/public/stores/nope-nope", undefined, null)).status).toBe(404);
});
});

View File

@ -0,0 +1,147 @@
/**
* Team roles and API key scopes: buyer access keys can never act as the
* merchant, restricted platform keys only reach their scopes, keys cannot
* mint broader keys, and invited teammates get their role's permissions.
*/
import { beforeEach, describe, expect, it } from "vitest";
import type { Hono } from "hono";
import { createApp } from "../src/app.js";
import { createContext, type AppContext, type AppEnv } from "../src/context.js";
const BOOTSTRAP = "test-bootstrap-key";
let app: Hono<AppEnv>;
let ctx: AppContext;
async function call(method: string, path: string, body?: unknown, key: string | null = BOOTSTRAP) {
const res = await app.request(path, {
method,
headers: { ...(key ? { authorization: `Bearer ${key}` } : {}), "content-type": "application/json" },
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
});
return { status: res.status, json: (await res.json()) as { data?: any; error?: { code: string; message: string; details?: any } } };
}
beforeEach(async () => {
process.env.API_BOOTSTRAP_KEY = BOOTSTRAP;
ctx = { ...(await createContext()), email: null };
app = createApp(ctx);
});
describe("API key scopes", () => {
it("refuses buyer access keys on the management API, whatever their scopes", async () => {
for (const scopes of [["read"], ["*"], ["payments:read"]]) {
const buyerKey = await ctx.apiKeys.issue({
organizationId: "org_settlekit_default",
customerId: "cus_buyer",
productId: "prod_api_access",
entitlementId: "ent_1",
scopes,
env: "live",
});
const res = await call("GET", "/v1/payments", undefined, buyerKey.plaintext);
expect(res.status).toBe(403);
expect(res.json.error?.message).toMatch(/customer access key/);
}
});
it("limits a restricted platform key to its scopes", async () => {
const issued = await call("POST", "/v1/api-keys/platform", { scopes: ["payments:read", "access:read"], label: "reporting" });
expect(issued.status).toBe(201);
expect(issued.json.data.apiKey.kind).toBe("platform");
const key = issued.json.data.plaintext as string;
expect((await call("GET", "/v1/payments", undefined, key)).status).toBe(200);
const denied = await call("POST", "/v1/products", { merchantId: "m", name: "x", type: "license_key", deliveryMode: "license_key" }, key);
expect(denied.status).toBe(403);
expect(denied.json.error?.details?.requiredScope).toBe("products:write");
expect((await call("POST", "/v1/entitlements/verify", { customerId: "c", productId: "p" }, key)).status).toBe(200);
expect((await call("GET", "/v1/exports/payments.csv", undefined, key)).status).toBe(403);
});
it("cannot mint a key broader than itself and customer keys cannot carry management scopes", async () => {
const limited = (await call("POST", "/v1/api-keys/platform", { scopes: ["api_keys:write"] })).json.data.plaintext as string;
const escalate = await call("POST", "/v1/api-keys/platform", { scopes: ["platform:admin"] }, limited);
expect(escalate.status).toBe(403);
expect((await call("POST", "/v1/api-keys/platform", { scopes: ["payments:read"] }, limited)).status).toBe(403);
expect((await call("POST", "/v1/api-keys/platform", { scopes: ["api_keys:read"] }, limited)).status).toBe(201);
const customerStar = await call("POST", "/v1/api-keys", { customerId: "c", productId: "p", entitlementId: "e", scopes: ["*"] });
expect(customerStar.status).toBe(400);
});
it("lists and revokes only the organization's keys", async () => {
const other = await ctx.apiKeys.issue({ organizationId: "org_other", customerId: "x", productId: "__platform__", entitlementId: "__platform__", scopes: ["*"], env: "live" });
const mine = await call("POST", "/v1/api-keys/platform", { scopes: ["reports:read"] });
const list = await call("GET", "/v1/api-keys");
expect(list.json.data.map((k: { id: string }) => k.id)).toContain(mine.json.data.apiKey.id);
expect(list.json.data.map((k: { id: string }) => k.id)).not.toContain(other.apiKey.id);
expect((await call("POST", `/v1/api-keys/${other.apiKey.id}/revoke`)).status).toBe(404);
const revoked = await call("POST", `/v1/api-keys/${mine.json.data.apiKey.id}/revoke`);
expect(revoked.json.data.status).toBe("revoked");
expect((await call("GET", "/v1/payments", undefined, mine.json.data.plaintext)).status).toBe(401);
});
});
describe("team roles", () => {
async function registerOwner(): Promise<string> {
const res = await call("POST", "/v1/auth/register", { type: "merchant", email: "owner@acme.test", password: "correct horse 1" }, null);
expect(res.status).toBe(201);
return res.json.data.sessionToken as string;
}
async function invite(owner: string, email: string, role: string): Promise<string> {
const res = await call("POST", "/v1/team/invitations", { email, role }, owner);
expect(res.status).toBe(201);
expect(res.json.data.invitation.tokenHash).toBeUndefined();
return (res.json.data.inviteUrl as string).split("/invite/")[1]!;
}
it("invites a developer who gets exactly the developer permissions", async () => {
const owner = await registerOwner();
const token = decodeURIComponent(await invite(owner, "dev@acme.test", "developer"));
const team = await call("GET", "/v1/team", undefined, owner);
expect(team.json.data.members).toEqual([expect.objectContaining({ email: "owner@acme.test", role: "owner" })]);
expect(team.json.data.invitations).toEqual([expect.objectContaining({ email: "dev@acme.test", role: "developer", status: "pending" })]);
expect((await call("POST", "/v1/auth/invitations/accept", { token }, null)).status).toBe(400);
const accepted = await call("POST", "/v1/auth/invitations/accept", { token, password: "dev password 1" }, null);
expect(accepted.status).toBe(200);
const dev = accepted.json.data.sessionToken as string;
expect(accepted.json.data.account.organizationId).toBe(team.json.data.members[0] ? (await call("GET", "/v1/auth/session", undefined, owner)).json.data.account.organizationId : "");
// Token is single use.
expect((await call("POST", "/v1/auth/invitations/accept", { token, password: "again password" }, null)).status).toBe(404);
expect((await call("GET", "/v1/payments", undefined, dev)).status).toBe(200);
expect((await call("POST", "/v1/merchant/products", { name: "X", priceUsd: "5", delivery: { kind: "license_key", machineLimit: 1 } }, dev)).status).not.toBe(403);
const settings = await call("POST", "/v1/settings", { orgName: "Hijack" }, dev);
expect(settings.status).toBe(403);
expect((await call("POST", "/v1/team/invitations", { email: "x@acme.test", role: "viewer" }, dev)).status).toBe(403);
});
it("protects the owner role and removes members", async () => {
const owner = await registerOwner();
const token = decodeURIComponent(await invite(owner, "admin@acme.test", "admin"));
const admin = (await call("POST", "/v1/auth/invitations/accept", { token, password: "admin password" }, null)).json.data.sessionToken as string;
// An admin cannot mint owners.
expect((await call("POST", "/v1/team/invitations", { email: "o2@acme.test", role: "owner" }, admin)).status).toBe(403);
const members = (await call("GET", "/v1/team", undefined, owner)).json.data.members as { accountId: string; role: string }[];
const ownerId = members.find((m) => m.role === "owner")!.accountId;
const adminId = members.find((m) => m.role === "admin")!.accountId;
expect((await call("PATCH", `/v1/team/members/${ownerId}`, { role: "viewer" }, owner)).status).toBe(400);
expect((await call("PATCH", `/v1/team/members/${adminId}`, { role: "viewer" }, owner)).json.data.role).toBe("viewer");
// Viewer now: reads only.
expect((await call("GET", "/v1/payments", undefined, admin)).status).toBe(200);
expect((await call("POST", "/v1/coupons", { code: "X", discount: { type: "percent", percentOff: 5 } }, admin)).status).toBe(403);
expect((await call("DELETE", `/v1/team/members/${adminId}`, undefined, owner)).status).toBe(200);
expect((await call("GET", "/v1/payments", undefined, admin)).status).toBe(401);
});
it("revokes invitations", async () => {
const owner = await registerOwner();
const token = decodeURIComponent(await invite(owner, "late@acme.test", "viewer"));
const inv = (await call("GET", "/v1/team", undefined, owner)).json.data.invitations[0];
expect((await call("POST", `/v1/team/invitations/${inv.id}/revoke`, undefined, owner)).json.data.status).toBe("revoked");
expect((await call("POST", "/v1/auth/invitations/accept", { token, password: "late password" }, null)).status).toBe(404);
});
});

View File

@ -214,7 +214,7 @@ beforeAll(async () => {
const issued = await ctx.apiKeys.issue({
organizationId: "org_intruder",
customerId: "cus_intruder",
productId: "prod_intruder",
productId: "__platform__",
entitlementId: "ent_intruder",
scopes: ["*"],
env: "live",

View File

@ -0,0 +1,85 @@
/**
* Registration can never join an existing merchant organization: a merchant
* always gets a fresh org, and a customer account (portal buyers, who do
* carry the seller's org id) never gets management access through its
* session.
*/
import { beforeEach, describe, expect, it } from "vitest";
import type { Hono } from "hono";
import { createApp } from "../src/app.js";
import { createContext, type AppContext, type AppEnv } from "../src/context.js";
let app: Hono<AppEnv>;
let ctx: AppContext;
async function call(method: string, path: string, body?: unknown, key: string | null = null) {
const res = await app.request(path, {
method,
headers: { ...(key ? { authorization: `Bearer ${key}` } : {}), "content-type": "application/json" },
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
});
return { status: res.status, json: (await res.json()) as { data?: any; error?: { code: string; message: string } } };
}
beforeEach(async () => {
delete process.env.API_BOOTSTRAP_KEY;
ctx = { ...(await createContext()), email: null };
app = createApp(ctx);
});
describe("registration tenant boundary", () => {
async function victim(): Promise<{ org: string; key: string }> {
const res = await call("POST", "/v1/auth/register", { type: "merchant", email: "victim@shop.test", password: "victim password 1" });
expect(res.status).toBe(201);
return { org: res.json.data.account.organizationId as string, key: res.json.data.apiKey as string };
}
it("gives a merchant who names another org its own fresh org and key", async () => {
const v = await victim();
const product = await call("POST", "/v1/merchant/products", {
name: "Secret",
priceUsd: "10",
delivery: { kind: "access", accessUrl: "https://example.com/x" },
}, v.key);
expect(product.status).toBe(201);
const attacker = await call("POST", "/v1/auth/register", {
type: "merchant",
email: "attacker@evil.test",
password: "attacker password 1",
organizationId: v.org,
});
expect(attacker.status).toBe(201);
expect(attacker.json.data.account.organizationId).not.toBe(v.org);
const listed = await call("GET", "/v1/merchant/products", undefined, attacker.json.data.apiKey);
expect(listed.status).toBe(200);
expect(listed.json.data).toEqual([]);
const viaSession = await call("GET", "/v1/merchant/products", undefined, attacker.json.data.sessionToken);
expect(viaSession.json.data).toEqual([]);
});
it("refuses the management API to customer sessions that carry the seller's org", async () => {
const v = await victim();
const buyer = await call("POST", "/v1/auth/register", {
type: "customer",
email: "buyer@mail.test",
password: "buyer password 1",
organizationId: v.org,
});
expect(buyer.status).toBe(201);
expect(buyer.json.data.apiKey).toBeUndefined();
const token = buyer.json.data.sessionToken as string;
// The session itself still works for the customer portal.
expect((await call("GET", "/v1/auth/session", undefined, token)).status).toBe(200);
for (const [method, path] of [
["GET", "/v1/payments"],
["GET", "/v1/merchant/products"],
["GET", "/v1/api-keys"],
["POST", "/v1/api-keys/platform"],
] as const) {
const res = await call(method, path, method === "POST" ? { scopes: ["platform:admin"] } : undefined, token);
expect(res.status, `${method} ${path}`).toBeGreaterThanOrEqual(401);
expect(res.status, `${method} ${path}`).toBeLessThanOrEqual(403);
}
});
});

View File

@ -0,0 +1,124 @@
/**
* Webhook event log: per-attempt delivery records, resend, test events,
* secret rotation with a grace window, and enable/disable. No database, so
* deliveries run in-process against a stubbed fetch.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { Hono } from "hono";
import { verifySignature } from "@settlekit/webhooks";
import { createApp } from "../src/app.js";
import { createContext, type AppContext, type AppEnv } from "../src/context.js";
const BOOTSTRAP = "test-bootstrap-key";
let app: Hono<AppEnv>;
let ctx: AppContext;
let otherKey: string;
const received: { url: string; body: string; signature: string }[] = [];
let respondWith = 200;
async function call(method: string, path: string, body?: unknown, key = BOOTSTRAP) {
const res = await app.request(path, {
method,
headers: { authorization: `Bearer ${key}`, "content-type": "application/json" },
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
});
return { status: res.status, json: (await res.json()) as { data?: any; error?: { message: string } } };
}
beforeEach(async () => {
process.env.API_BOOTSTRAP_KEY = BOOTSTRAP;
received.length = 0;
respondWith = 200;
vi.stubGlobal("fetch", async (url: string, init: RequestInit) => {
const headers = init.headers as Record<string, string>;
received.push({ url, body: String(init.body), signature: headers["SettleKit-Signature"] ?? "" });
return new Response("", { status: respondWith });
});
ctx = await createContext();
app = createApp(ctx);
otherKey = (
await ctx.apiKeys.issue({ organizationId: "org_other", customerId: "c", productId: "__platform__", entitlementId: "e", scopes: ["*"], env: "live" })
).plaintext;
});
afterEach(() => vi.unstubAllGlobals());
async function endpoint(events = ["payment.confirmed"]) {
const res = await call("POST", "/v1/webhooks/endpoints", { url: "https://hooks.test/settlekit", enabledEvents: events });
expect(res.status).toBe(201);
return res.json.data as { id: string; signingSecret: string };
}
async function settle(): Promise<void> {
await new Promise((r) => setTimeout(r, 20));
}
describe("webhook event log", () => {
it("sends a signed test event and logs the attempt", async () => {
const ep = await endpoint();
const test = await call("POST", `/v1/webhooks/endpoints/${ep.id}/test`);
expect(test.status).toBe(201);
expect(test.json.data).toMatchObject({ eventType: "webhook.test", status: "delivered", attempts: 1, lastStatus: 200, manual: "test" });
expect(received).toHaveLength(1);
expect(verifySignature(ep.signingSecret, received[0]!.body, received[0]!.signature, 300)).toBe(true);
const log = await call("GET", `/v1/webhooks/deliveries?endpointId=${ep.id}`);
expect(log.json.data).toHaveLength(1);
expect(JSON.stringify(log.json.data)).not.toContain(ep.signingSecret);
});
it("records failures with status codes and resends an event", async () => {
const ep = await endpoint();
respondWith = 500;
const failed = await call("POST", `/v1/webhooks/endpoints/${ep.id}/test`);
expect(failed.json.data).toMatchObject({ status: "failed", lastStatus: 500, lastError: "HTTP 500" });
expect(failed.json.data.nextAttemptAt).toBeTruthy();
// A real event emitted by the outbox lands in the log too.
await ctx.webhookOutbox.enqueue({ organizationId: "org_settlekit_default", type: "payment.confirmed", key: "pay_1", data: { paymentId: "pay_1" } });
await settle();
const events = await call("GET", "/v1/webhooks/deliveries");
const eventId = events.json.data.find((d: { eventType: string }) => d.eventType === "payment.confirmed").eventId;
respondWith = 200;
const resent = await call("POST", `/v1/webhooks/events/${eventId}/resend`, {});
expect(resent.status).toBe(201);
expect(resent.json.data).toHaveLength(1);
expect(resent.json.data[0]).toMatchObject({ status: "delivered", manual: "resend", eventId });
const single = await call("GET", `/v1/webhooks/deliveries/${resent.json.data[0].id}`);
expect(single.json.data.history).toHaveLength(1);
});
it("rotates the secret with a grace window so both secrets verify", async () => {
const ep = await endpoint();
const rotated = await call("POST", `/v1/webhooks/endpoints/${ep.id}/rotate-secret`, { graceHours: 24 });
expect(rotated.status).toBe(200);
const next = rotated.json.data.signingSecret as string;
expect(next).not.toBe(ep.signingSecret);
expect(rotated.json.data.previousSigningSecret).toBeUndefined();
await call("POST", `/v1/webhooks/endpoints/${ep.id}/test`);
const { body, signature } = received.at(-1)!;
expect(verifySignature(next, body, signature, 300)).toBe(true);
expect(verifySignature(ep.signingSecret, body, signature, 300)).toBe(true);
await call("POST", `/v1/webhooks/endpoints/${ep.id}/rotate-secret`, { graceHours: 0 });
await call("POST", `/v1/webhooks/endpoints/${ep.id}/test`);
const last = received.at(-1)!;
expect(verifySignature(next, last.body, last.signature, 300)).toBe(false);
expect((await call("POST", `/v1/webhooks/endpoints/${ep.id}/rotate-secret`, { graceHours: 500 })).status).toBe(400);
});
it("disables and re-enables an endpoint and keeps other tenants out", async () => {
const ep = await endpoint();
const off = await call("POST", `/v1/webhooks/endpoints/${ep.id}/disable`);
expect(off.json.data).toMatchObject({ active: false, disabledReason: "disabled by the merchant" });
expect(off.json.data.signingSecret).toBeUndefined();
await ctx.webhookOutbox.enqueue({ organizationId: "org_settlekit_default", type: "payment.confirmed", key: "pay_2", data: {} });
await settle();
expect(received).toHaveLength(0);
const on = await call("POST", `/v1/webhooks/endpoints/${ep.id}/enable`);
expect(on.json.data).toMatchObject({ active: true, consecutiveFailures: 0 });
expect((await call("POST", `/v1/webhooks/endpoints/${ep.id}/test`, undefined, otherKey)).status).toBe(404);
expect((await call("GET", "/v1/webhooks/deliveries", undefined, otherKey)).json.data).toHaveLength(0);
});
});

View File

@ -9,10 +9,14 @@
"references": [
{ "path": "../../packages/onchain-billing" },
{ "path": "../../packages/common" },
{ "path": "../../packages/pricing" },
{ "path": "../../packages/exports" },
{ "path": "../../packages/invitations" },
{ "path": "../../packages/solana" },
{ "path": "../../packages/zcash" },
{ "path": "../../packages/chains" },
{ "path": "../../packages/hyperliquid" },
{ "path": "../../packages/operator" },
{ "path": "../../packages/auth" },
{ "path": "../../packages/database" },
{ "path": "../../packages/persistence" },
@ -46,6 +50,7 @@
{ "path": "../../packages/disputes" },
{ "path": "../../packages/payouts" },
{ "path": "../../packages/platform-billing" },
{ "path": "../../packages/circle" },
{ "path": "../../packages/circle-wallets" },
{ "path": "../../packages/compliance" },
{ "path": "../../packages/cctp" },

View File

@ -17,6 +17,25 @@
# CHECKOUT_DELIVERY_SECRET=
# CHECKOUT_DOWNLOAD_BASE=
# --- Subscriptions (onchain billing through the SettleKit API) --------------------
# Recurring products offer "Subscribe" (spend permission / Permit2 / SPL delegate /
# renewal invoices). The checkout calls the API's /v1/onchain-billing server-side
# with a platform service token; the API must have the SAME SETTLEKIT_SERVICE_TOKEN
# (32+ chars, e.g. `openssl rand -hex 32`) and onchain billing configured.
# SETTLEKIT_API_URL=https://api.example.com
# SETTLEKIT_SERVICE_TOKEN=
# Signs buyer "manage subscription" links (/s/<token>); defaults to CHECKOUT_DELIVERY_SECRET.
# CHECKOUT_MANAGE_SECRET=
# --- Discord role delivery ----------------------------------------------------------
# Buyers connect Discord (OAuth2 identify) at checkout; the bot adds the product's
# role. Without DISCORD_BOT_TOKEN, Discord purchases show "pending setup" and the
# worker grants the role once the bot is configured. Redirect URI to register in
# the Discord developer portal: <CHECKOUT_PUBLIC_URL>/api/discord/callback
# DISCORD_BOT_TOKEN=
# DISCORD_CLIENT_ID=
# DISCORD_CLIENT_SECRET=
# --- EVM chains (USD stablecoins, 6 decimals) -------------------------------------
# mainnet | testnet for every EVM chain (default testnet); per-chain <KEY>_NETWORK.
SETTLEKIT_CHAIN_ENV=testnet

View File

@ -0,0 +1,25 @@
/**
* GET /api/discord/authorize?session=<checkoutSessionId>
*
* Starts "Connect Discord" for a checkout whose product grants a Discord role.
*/
import { NextResponse } from "next/server";
import { authorizeUrl, discordOAuthSetup } from "@/lib/discord-connect";
import { publicOrigin } from "@/lib/origin";
import { getResolvedSession } from "@/lib/store";
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
export async function GET(request: Request): Promise<NextResponse> {
const sessionId = new URL(request.url).searchParams.get("session") ?? "";
const origin = publicOrigin(request);
const setup = discordOAuthSetup();
const resolved = sessionId ? await getResolvedSession(sessionId) : undefined;
if (!resolved) return NextResponse.json({ error: "Checkout session not found." }, { status: 404 });
if (!setup || resolved.deliveryAction.type !== "discord_role_add") {
return NextResponse.redirect(`${origin}/c/${encodeURIComponent(sessionId)}?discord=unavailable`);
}
return NextResponse.redirect(authorizeUrl(setup, origin, sessionId));
}

View File

@ -0,0 +1,42 @@
/**
* GET /api/discord/callback?code=&state=
*
* Saves the buyer's Discord id on the checkout session that started the flow
* and adds them to the product's server (no paid role until payment settles).
*/
import { NextResponse } from "next/server";
import { discordOAuthSetup, identify, readState } from "@/lib/discord-connect";
import { getDiscordDelivery, joinGuild, resolveDiscordTarget } from "@/lib/discord-delivery";
import { publicOrigin } from "@/lib/origin";
import { getResolvedSession, saveCollectedFields } from "@/lib/store";
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
export async function GET(request: Request): Promise<NextResponse> {
const url = new URL(request.url);
const origin = publicOrigin(request);
const sessionId = readState(url.searchParams.get("state") ?? "");
if (!sessionId) return NextResponse.json({ error: "This Discord link expired. Go back to the checkout and connect again." }, { status: 400 });
const back = (status: string) => NextResponse.redirect(`${origin}/c/${encodeURIComponent(sessionId)}?discord=${status}`);
const code = url.searchParams.get("code");
const setup = discordOAuthSetup();
if (!code || !setup) return back("canceled");
const resolved = await getResolvedSession(sessionId);
if (!resolved || resolved.session.status !== "open") return back("closed");
try {
const identity = await identify(setup, origin, code);
await saveCollectedFields(sessionId, { discordUserId: identity.userId, discordUsername: identity.username });
const action = resolved.deliveryAction;
if (action.type === "discord_role_add") {
const target = resolveDiscordTarget(action, resolved.product);
if (target) await joinGuild(getDiscordDelivery(), target.guildId, identity.userId, identity.accessToken);
}
return back("connected");
} catch (error) {
console.error("[checkout] discord connect failed:", error);
return back("failed");
}
}

View File

@ -0,0 +1,28 @@
/**
* POST /api/subscriptions/:token/cancel
*
* Buyer cancel from the manage page. Stops charges at the end of the paid
* period and returns the wallet action that revokes the on-chain allowance
* (the operator stops pulling either way).
*/
import { NextResponse } from "next/server";
import { cancelManagedSubscription } from "@/lib/manage-subscription";
import { errorReply } from "@/lib/route-helpers";
import { assertSameOrigin } from "@/lib/same-origin";
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
interface RouteContext {
params: { token: string };
}
export async function POST(request: Request, context: RouteContext): Promise<NextResponse> {
try {
assertSameOrigin(request);
return NextResponse.json(await cancelManagedSubscription(context.params.token));
} catch (error) {
return errorReply(error, "Could not cancel the subscription.", "subscription cancel");
}
}

View File

@ -0,0 +1,36 @@
/**
* POST /api/v1/checkout-sessions/:sessionId/promo
*
* Body: { code: string }
*
* Applies a seller promo code while the session is open and unpaid; the
* discounted total becomes the amount due. 400 with the reason when the code
* is refused, 409 when the session can no longer change.
*/
import { NextResponse } from "next/server";
import { applyPromoCode } from "@/lib/promo";
import { errorReply, readJsonObject } from "@/lib/route-helpers";
import { assertSameOrigin } from "@/lib/same-origin";
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
interface RouteContext {
params: { sessionId: string };
}
export async function POST(request: Request, context: RouteContext): Promise<NextResponse> {
try {
assertSameOrigin(request);
const body = await readJsonObject(request);
const session = await applyPromoCode(context.params.sessionId, body.code);
return NextResponse.json({
amount: session.amount,
discount: session.discount ?? null,
settlementQuote: session.settlementQuote ?? null,
});
} catch (error) {
return errorReply(error, "Could not apply the promo code.", "promo");
}
}

View File

@ -0,0 +1,34 @@
/**
* POST /api/v1/checkout-sessions/:sessionId/subscription/grant
*
* Body: { subscriptionId, signature? (EIP-712), approveSignature? (Solana) }
* Forwards the buyer's signed authorization; the API registers it, charges
* the first period and delivers access. Returns the buyer's manage link.
*/
import { NextResponse } from "next/server";
import { errorReply, readJsonObject } from "@/lib/route-helpers";
import { assertSameOrigin } from "@/lib/same-origin";
import { completeSubscription } from "@/lib/subscription-checkout";
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
interface RouteContext {
params: { sessionId: string };
}
export async function POST(request: Request, context: RouteContext): Promise<NextResponse> {
try {
assertSameOrigin(request);
const body = await readJsonObject(request);
const result = await completeSubscription(context.params.sessionId, {
subscriptionId: body.subscriptionId,
signature: body.signature,
approveSignature: body.approveSignature,
});
return NextResponse.json(result);
} catch (error) {
return errorReply(error, "Could not activate the subscription.", "subscription grant");
}
}

View File

@ -0,0 +1,41 @@
/**
* GET /api/v1/checkout-sessions/:sessionId/subscription
* What subscribing looks like on the session's network (methods, cap, expiry).
* POST /api/v1/checkout-sessions/:sessionId/subscription
* Body: { method, payer?, fields } -> the intent the buyer's wallet signs/sends.
*/
import { NextResponse } from "next/server";
import { errorReply, fieldsOf, readJsonObject } from "@/lib/route-helpers";
import { assertSameOrigin } from "@/lib/same-origin";
import { getSubscriptionOffer, startSubscription } from "@/lib/subscription-checkout";
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
interface RouteContext {
params: { sessionId: string };
}
export async function GET(_request: Request, context: RouteContext): Promise<NextResponse> {
try {
return NextResponse.json(await getSubscriptionOffer(context.params.sessionId));
} catch (error) {
return errorReply(error, "Could not load subscription options.", "subscription offer");
}
}
export async function POST(request: Request, context: RouteContext): Promise<NextResponse> {
try {
assertSameOrigin(request);
const body = await readJsonObject(request);
const result = await startSubscription(context.params.sessionId, {
method: body.method,
payer: body.payer,
fields: fieldsOf(body),
});
return NextResponse.json(result);
} catch (error) {
return errorReply(error, "Could not start the subscription.", "subscription start");
}
}

View File

@ -0,0 +1,31 @@
/**
* POST /api/v1/checkout-sessions/:sessionId/tax
*
* Body: { country: "FR", vatId?: "FR12345678901" }
*
* Sets the buyer's billing country (and optional VAT ID) and recomputes the
* tax-inclusive amount due while the session is open and unpaid.
*/
import { NextResponse } from "next/server";
import { applyBuyerTax } from "@/lib/buyer-tax";
import { errorReply, readJsonObject } from "@/lib/route-helpers";
import { assertSameOrigin } from "@/lib/same-origin";
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
interface RouteContext {
params: { sessionId: string };
}
export async function POST(request: Request, context: RouteContext): Promise<NextResponse> {
try {
assertSameOrigin(request);
const body = await readJsonObject(request);
const session = await applyBuyerTax(context.params.sessionId, { country: body.country, vatId: body.vatId });
return NextResponse.json({ amount: session.amount, tax: session.tax ?? null });
} catch (error) {
return errorReply(error, "Could not update the billing details.", "tax");
}
}

View File

@ -3,15 +3,26 @@ import { notFound, redirect } from "next/navigation";
import { getCheckoutSession, ApiClientError } from "@/lib/api";
import { badgeDescription, badgeText, formatAmount, formatExpiry, formatMoney } from "@/lib/format";
import { OrderSummary } from "@/components/OrderSummary";
import { PromoCode } from "@/components/PromoCode";
import { TaxDetails } from "@/components/TaxDetails";
import { orderLabels, promoLabels, serverT, taxLabels } from "@/lib/i18n";
import { NetworkPicker } from "@/components/NetworkPicker";
import { AnyTokenPay, EvmPay, HyperCorePay, SolanaPay, WalletPay, ZcashPay } from "@/components/LazyPay";
import { AnyTokenPay, EvmPay, HyperCorePay, SolanaPay, SubscribePay, WalletPay, ZcashPay } from "@/components/LazyPay";
export const dynamic = "force-dynamic";
interface PageProps {
params: { sessionId: string };
searchParams: { discord?: string; promo?: string; lang?: string };
}
const DISCORD_NOTICE: Record<string, { ok: boolean; text: string }> = {
connected: { ok: true, text: "Discord connected. Your role is added as soon as the payment settles." },
failed: { ok: false, text: "Discord did not connect. Try again, or enter your user ID manually." },
canceled: { ok: false, text: "Discord connection was canceled." },
unavailable: { ok: false, text: "Connecting Discord is not available on this checkout; enter your user ID instead." },
};
/**
* Hosted checkout page. Server-fetches the checkout session from the SettleKit
* API, renders the order summary, a network picker (accepted networks this
@ -21,7 +32,7 @@ interface PageProps {
* the network. Expired sessions redirect to the
* /expired page; completed sessions redirect to /success.
*/
export default async function CheckoutPage({ params }: PageProps) {
export default async function CheckoutPage({ params, searchParams }: PageProps) {
const { sessionId } = params;
let session;
@ -48,26 +59,70 @@ export default async function CheckoutPage({ params }: PageProps) {
// The Arc demo wallet (offline simulation) only applies to Arc sessions.
const isArc = session.network === "arc";
const discordNotice = searchParams.discord ? DISCORD_NOTICE[searchParams.discord] : undefined;
const t = serverT(searchParams.lang);
return (
<div>
{discordNotice ? (
<div className={`alert ${discordNotice.ok ? "alert-success" : "alert-error"}`} role="status">
{discordNotice.text}
</div>
) : null}
<div className="card">
<h2>Order summary</h2>
<p className="merchant">Sold by {session.merchantName}</p>
<OrderSummary lines={session.lines} total={session.amount} />
<h2>{t("order.title")}</h2>
<p className="merchant">{t("order.soldBy", { merchant: session.merchantName })}</p>
<OrderSummary lines={session.lines} total={session.amount} discount={session.discount} tax={session.tax} labels={orderLabels(t)} />
{session.fx ? (
<p className="muted" style={{ marginTop: 6 }}>
{t("fx.note", {
amount: session.fx.amount,
currency: session.fx.currency,
rate: session.fx.rate,
source: session.fx.source,
date: session.fx.rateDate,
})}
</p>
) : null}
{searchParams.promo === "refused" && !session.discount ? (
<p className="field-error" role="status">
{t("promo.refused")}
</p>
) : null}
{session.promoAllowed ? <PromoCode sessionId={session.id} labels={promoLabels(t)} /> : null}
{session.tax && session.taxEditable ? (
<TaxDetails sessionId={session.id} country={session.tax.country} vatId={session.tax.vatId} labels={taxLabels(t)} />
) : null}
</div>
{session.recurring && option.available ? (
<div className="card">
<h2>{t("pay.subscribe")}</h2>
<SubscribePay
key={session.network}
sessionId={session.id}
requiredFields={session.requiredFields}
initialValues={session.collectedFields}
/>
</div>
) : null}
<div className="card">
<h2>Payment</h2>
<h2>
{session.recurring
? t("pay.oneOff", { period: t(session.recurring === "yearly" ? "pay.year" : "pay.month") })
: t("pay.title")}
</h2>
<NetworkPicker sessionId={session.id} current={session.network} options={session.networkOptions} />
<div className="payto">
<div className="payto-row">
<span className="label">Amount due</span>
<span className="label">{t("pay.amountDue")}</span>
<span className="line-amount">
{family === "zcash" ? `${formatMoney(session.amount)} in ZEC` : amountLabel}
</span>
</div>
<div className="payto-row">
<span className="label">Network</span>
<span className="label">{t("pay.network")}</span>
<span className="network-badges">
<span className="badge badge-network">{option.name}</span>
{option.badges.map((badge) => (
@ -78,7 +133,7 @@ export default async function CheckoutPage({ params }: PageProps) {
</span>
</div>
<div className="payto-row">
<span className="label">Window</span>
<span className="label">{t("pay.window")}</span>
<span className="badge badge-expiry">
{formatExpiry(session.expiresAt)}
</span>
@ -132,7 +187,7 @@ export default async function CheckoutPage({ params }: PageProps) {
{option.available && session.anyToken.available ? (
<div className="card">
<h2>Pay with any token</h2>
<h2>{t("pay.anyToken")}</h2>
<AnyTokenPay
key={session.network}
sessionId={session.id}

View File

@ -0,0 +1,26 @@
import { NextResponse } from "next/server";
import { apiBaseUrl } from "@/lib/payment-link";
export const dynamic = "force-dynamic";
const SESSION_RE = /^[A-Za-z0-9_-]{8,100}$/;
/** GET /c/:sessionId/receipt: the tax-grade receipt PDF of a settled checkout. */
export async function GET(_request: Request, { params }: { params: { sessionId: string } }) {
if (!SESSION_RE.test(params.sessionId)) return NextResponse.json({ error: "not found" }, { status: 404 });
const upstream = await fetch(`${apiBaseUrl()}/v1/public/receipts/${encodeURIComponent(params.sessionId)}/pdf`, {
cache: "no-store",
});
if (!upstream.ok || !upstream.body) {
return NextResponse.json({ error: "receipt unavailable" }, { status: upstream.status === 404 ? 404 : 502 });
}
return new NextResponse(upstream.body, {
status: 200,
headers: {
"content-type": "application/pdf",
"content-disposition": upstream.headers.get("content-disposition") ?? "inline",
"cache-control": "private, no-store",
},
});
}

View File

@ -8,6 +8,9 @@ import {
} from "@/lib/format";
import { OrderSummary } from "@/components/OrderSummary";
import { AccessList } from "@/components/AccessList";
import { EmbedSuccess } from "@/components/EmbedSuccess";
import { embedOriginsForSession } from "@/lib/embed";
import { orderLabels, serverT } from "@/lib/i18n";
export const dynamic = "force-dynamic";
@ -35,24 +38,31 @@ export default async function SuccessPage({ params }: PageProps) {
throw error;
}
const embedOrigins = await embedOriginsForSession(sessionId).catch(() => []);
const t = serverT();
// The receipt amount is the authoritative settled total.
const total = receipt.amount;
const buyerEntries = Object.entries(receipt.buyer);
const INTERNAL_FIELDS = new Set(["subscribeIntentId", "onchainSubscriptionId", "periodIndex"]);
const buyerEntries = Object.entries(receipt.buyer).filter(([key]) => !INTERNAL_FIELDS.has(key));
return (
<div>
<EmbedSuccess sessionId={sessionId} paymentId={receipt.paymentId} allowedOrigins={embedOrigins} />
<div className="card center">
<div className="big-status">Payment confirmed</div>
<div className="big-status">{t("success.title")}</div>
<p className="muted">
{receipt.access.some((item) => item.pending)
? "Your USDC payment settled. Some access is still pending; details below."
: "Your USDC payment settled and access has been delivered."}
{receipt.access.some((item) => item.pending) ? t("success.pending") : t("success.delivered")}
</p>
</div>
<div className="card">
<h2>Receipt</h2>
<OrderSummary lines={receipt.lines} total={total} />
<h2>{t("success.receipt")}</h2>
<OrderSummary lines={receipt.lines} total={total} discount={receipt.discount} tax={receipt.tax} labels={orderLabels(t)} />
<p style={{ marginTop: 8 }}>
<a className="link" href={`/c/${encodeURIComponent(sessionId)}/receipt`} target="_blank" rel="noreferrer">
{t("success.downloadReceipt")}
</a>
</p>
<div className="divider" />
<div className="payto-row">
<span className="label">Paid</span>
@ -109,9 +119,15 @@ export default async function SuccessPage({ params }: PageProps) {
</div>
<div className="center">
<Link className="link" href="/">
Back to checkout
</Link>
{receipt.returnUrl ? (
<a className="btn btn-primary" href={receipt.returnUrl}>
Continue to {new URL(receipt.returnUrl).host}
</a>
) : (
<Link className="link" href="/">
Back to checkout
</Link>
)}
</div>
</div>
);

View File

@ -276,19 +276,19 @@ body {
.alert-error {
background: rgba(239, 93, 107, 0.12);
border: 1px solid rgba(239, 93, 107, 0.4);
color: #ffc6cc;
color: var(--danger);
}
.alert-info {
background: rgba(79, 140, 255, 0.1);
border: 1px solid rgba(79, 140, 255, 0.35);
color: #cfe0ff;
color: var(--accent-2);
}
.alert-success {
background: rgba(41, 192, 138, 0.12);
border: 1px solid rgba(41, 192, 138, 0.4);
color: #b7f3dc;
color: var(--success);
}
.badge {
@ -642,3 +642,119 @@ a.link:hover {
align-items: center;
font-size: 14px;
}
/* --- Subscriptions (SubscribePay, ManageSubscription) --------------------- */
.plain-list {
list-style: none;
margin: 0;
padding: 0;
}
.sub-headline {
margin: 0 0 14px;
}
.sub-methods {
border: 0;
margin: 0 0 16px;
padding: 0;
display: grid;
gap: 8px;
}
.sub-method {
display: flex;
gap: 10px;
align-items: flex-start;
padding: 10px 12px;
border: 1px solid var(--border);
border-radius: var(--radius);
background: var(--panel);
cursor: pointer;
}
.sub-method.selected {
border-color: var(--accent);
}
.sub-method .help {
display: block;
margin-top: 2px;
}
.sub-authorize {
margin-bottom: 18px;
}
.sub-terms li {
padding: 4px 0;
font-size: 14px;
}
.sub-spender {
font-size: 12px;
margin: 8px 0 0;
word-break: break-all;
}
.sub-grid {
display: grid;
grid-template-columns: max-content 1fr;
gap: 8px 16px;
margin: 12px 0 18px;
}
.sub-grid dt {
color: var(--muted);
}
.sub-grid dd {
margin: 0;
word-break: break-word;
}
.badge-status-active {
background: var(--success);
color: #fff;
}
.badge-status-past_due,
.badge-status-pending_grant {
background: var(--warn);
color: #fff;
}
.badge-status-suspended,
.badge-status-canceled {
background: var(--panel-2);
color: var(--text);
}
/* --- Connect Discord ------------------------------------------------------- */
.connect-row {
display: flex;
gap: 10px;
align-items: center;
flex-wrap: wrap;
}
.connect-manual {
margin-top: 8px;
}
.connect-manual summary {
cursor: pointer;
font-size: 13px;
margin-bottom: 6px;
}
/* ---------- Promo code ---------- */
.link-button {
background: none;
border: 0;
padding: 0;
margin-top: 12px;
color: inherit;
text-decoration: underline;
cursor: pointer;
font: inherit;
opacity: 0.8;
}
.promo {
margin-top: 12px;
}
.field-error {
color: #d64545;
font-size: 13px;
margin-top: 6px;
}
.line-discount {
display: flex;
justify-content: space-between;
opacity: 0.85;
padding: 6px 0;
}

View File

@ -0,0 +1,105 @@
import { notFound } from "next/navigation";
import { InvoiceLinkError, getInvoice } from "@/lib/invoice-link";
import { serverT } from "@/lib/i18n";
export const dynamic = "force-dynamic";
interface PageProps {
params: { token: string };
searchParams: { error?: string; lang?: string };
}
function day(iso: string | null): string | null {
return iso ? iso.slice(0, 10) : null;
}
/**
* Public invoice / payment request page. Shows what is owed and one action:
* pay in USDC (opens the invoice's checkout session) or, once paid, the
* receipt with the settlement transaction.
*/
export default async function InvoicePage({ params, searchParams }: PageProps) {
let invoice;
try {
invoice = await getInvoice(params.token);
} catch (error) {
if (error instanceof InvoiceLinkError && error.status === 404) notFound();
return (
<div className="card">
<h2>Invoice unavailable</h2>
<p className="muted">
{error instanceof Error ? error.message : "This invoice could not be loaded."} Try again in a minute.
</p>
</div>
);
}
const pdfHref = `/i/${encodeURIComponent(params.token)}/pdf`;
const t = serverT(searchParams.lang);
return (
<div>
<div className="card">
<p className="merchant">{t("invoice.from", { merchant: invoice.merchantName })}</p>
<h2>{invoice.number}</h2>
{invoice.dueAt && invoice.status === "open" ? <p className="muted">{t("invoice.due", { date: day(invoice.dueAt) ?? "" })}</p> : null}
<ul className="line-items">
{invoice.lineItems.map((line, i) => (
<li key={i} className="line-desc">
{line.quantity > 1 ? `${line.quantity} x ` : ""}
{line.description}: {line.unitAmount} {invoice.currency}
</li>
))}
</ul>
{invoice.discount ? (
<div className="total">
<span>{t("invoice.discount")}</span>
<span>-{invoice.discount} {invoice.currency}</span>
</div>
) : null}
{invoice.tax ? (
<div className="total">
<span>{t("invoice.tax")}</span>
<span>
{invoice.tax} {invoice.currency}
</span>
</div>
) : null}
<div className="total">
<span>{t("order.total")}</span>
<span>
{invoice.total} {invoice.currency}
</span>
</div>
</div>
<div className="card">
{searchParams.error ? (
<div className="alert alert-error" role="alert">
We could not open the payment just now. Please try again.
</div>
) : null}
{invoice.status === "paid" ? (
<div>
<h3>{t("invoice.paid")}</h3>
<p className="muted">
{t("invoice.paidOn", { date: day(invoice.paidAt) ?? "" })}
{invoice.paidNetwork ? ` on ${invoice.paidNetwork}` : ""}.
</p>
{invoice.paidTxHash ? <p className="mono">{invoice.paidTxHash}</p> : null}
</div>
) : invoice.payable ? (
<form method="post" action={`/i/${encodeURIComponent(params.token)}/start`}>
<button type="submit" className="btn btn-primary">
{t("invoice.pay", { amount: invoice.total, currency: invoice.currency })}
</button>
</form>
) : (
<p className="muted">{invoice.unpayableReason}</p>
)}
<p style={{ marginTop: 12 }}>
<a href={pdfHref}>{invoice.status === "paid" ? t("invoice.downloadReceipt") : t("invoice.downloadInvoice")}</a>
</p>
</div>
</div>
);
}

View File

@ -0,0 +1,22 @@
import { NextResponse } from "next/server";
import { invoicePdfApiUrl, isInvoiceToken } from "@/lib/invoice-link";
export const dynamic = "force-dynamic";
/** GET /i/:token/pdf: stream the invoice (or receipt, once paid) PDF. */
export async function GET(_request: Request, { params }: { params: { token: string } }) {
if (!isInvoiceToken(params.token)) return NextResponse.json({ error: "not found" }, { status: 404 });
const upstream = await fetch(invoicePdfApiUrl(params.token), { cache: "no-store" });
if (!upstream.ok || !upstream.body) {
return NextResponse.json({ error: "invoice unavailable" }, { status: upstream.status === 404 ? 404 : 502 });
}
return new NextResponse(upstream.body, {
status: 200,
headers: {
"content-type": "application/pdf",
"content-disposition": upstream.headers.get("content-disposition") ?? "inline",
"cache-control": "private, no-store",
},
});
}

View File

@ -0,0 +1,20 @@
import { NextResponse } from "next/server";
import { InvoiceLinkError, startInvoicePayment } from "@/lib/invoice-link";
export const dynamic = "force-dynamic";
/**
* POST /i/:token/start: open (or reuse) the invoice's checkout session and
* move the payer to it. A plain form POST works without JavaScript.
*/
export async function POST(request: Request, { params }: { params: { token: string } }) {
try {
const sessionId = await startInvoicePayment(params.token);
return NextResponse.redirect(new URL(`/c/${encodeURIComponent(sessionId)}`, request.url), 303);
} catch (error) {
const status = error instanceof InvoiceLinkError ? error.status : 502;
const target = status === 404 ? "/not-found" : `/i/${encodeURIComponent(params.token)}?error=1`;
return NextResponse.redirect(new URL(target, request.url), 303);
}
}

View File

@ -0,0 +1,93 @@
import { notFound } from "next/navigation";
import { PaymentLinkError, getPaymentLink } from "@/lib/payment-link";
import { StartCheckout } from "@/components/StartCheckout";
import { serverT, startLabels } from "@/lib/i18n";
export const dynamic = "force-dynamic";
interface PageProps {
params: { slug: string };
searchParams: { error?: string; promo?: string; lang?: string };
}
/** A promo code from the URL, or undefined when absent or malformed. */
function cleanPromo(raw: string | undefined): string | undefined {
const code = raw?.trim();
return code && /^[A-Za-z0-9_-]{1,64}$/.test(code) ? code : undefined;
}
const INTERVAL_LABEL: Record<string, string> = { monthly: " / month", yearly: " / year" };
/**
* Reusable payment link landing. Shows what the buyer is paying for, then
* opens a fresh checkout session (client-side, so link unfurlers and
* crawlers never create sessions) and moves the buyer to it.
*/
export default async function PaymentLinkPage({ params, searchParams }: PageProps) {
let link;
try {
link = await getPaymentLink(params.slug);
} catch (error) {
if (error instanceof PaymentLinkError && error.status === 404) notFound();
return (
<div className="card">
<h2>Checkout unavailable</h2>
<p className="muted">
{error instanceof Error ? error.message : "This payment link could not be loaded."} Try again in a minute.
</p>
</div>
);
}
const promo = cleanPromo(searchParams.promo);
const t = serverT(searchParams.lang);
return (
<div>
<div className="card">
<p className="merchant">{t("order.soldBy", { merchant: link.merchantName })}</p>
<h2>{link.name}</h2>
{link.description ? <p className="line-desc">{link.description}</p> : null}
<div className="total">
<span>{t("link.price")}</span>
<span>
{link.displayCurrency && link.displayAmount ? `${link.displayAmount} ${link.displayCurrency}` : `$${link.priceUsd}`}
{INTERVAL_LABEL[link.interval] ?? ""}
</span>
</div>
{link.displayCurrency ? (
<p className="muted" style={{ marginTop: 8 }}>
Paid in USDC at the live exchange rate, about {link.priceUsd} USDC now.
</p>
) : null}
{INTERVAL_LABEL[link.interval] ? (
<p className="muted" style={{ marginTop: 8 }}>
Subscribe with one wallet approval capped at the price per period (or renewal invoices by email). Cancel any
time from your manage link.
</p>
) : null}
<div className="network-badges" style={{ marginTop: 12 }}>
{link.networks.map((n) => (
<span key={n.network} className="badge badge-network" title={`${n.asset} on ${n.name}`}>
{n.name} {n.asset}
{n.env === "testnet" ? " (testnet)" : ""}
</span>
))}
</div>
</div>
<div className="card">
{searchParams.error ? (
<div className="alert alert-error" role="alert">
We could not open a checkout just now. Please try again.
</div>
) : null}
{promo ? (
<p className="muted" style={{ marginBottom: 10 }}>
{t("link.promo", { code: promo })}
</p>
) : null}
<StartCheckout slug={link.slug} auto={!searchParams.error} labels={startLabels(t)} {...(promo ? { promo } : {})} />
</div>
</div>
);
}

View File

@ -0,0 +1,26 @@
import { NextResponse } from "next/server";
import { PaymentLinkError, startPaymentLinkWithPromo } from "@/lib/payment-link";
export const dynamic = "force-dynamic";
/**
* POST /l/:slug/start — open a fresh checkout session for this visit.
* JSON callers get `{ url }`; a plain form POST (no JavaScript) is
* redirected straight to the checkout.
*/
export async function POST(request: Request, { params }: { params: { slug: string } }) {
const wantsJson = request.headers.get("accept")?.includes("application/json") ?? false;
try {
const promo = new URL(request.url).searchParams.get("promo") ?? undefined;
const started = await startPaymentLinkWithPromo(params.slug, promo);
const url = `/c/${encodeURIComponent(started.sessionId)}${started.promo === "refused" ? "?promo=refused" : ""}`;
if (wantsJson) return NextResponse.json({ url });
return NextResponse.redirect(new URL(url, request.url), 303);
} catch (error) {
const status = error instanceof PaymentLinkError ? error.status : 502;
const message = error instanceof Error ? error.message : "Could not open checkout";
if (wantsJson) return NextResponse.json({ error: message }, { status: status >= 400 ? status : 502 });
return NextResponse.redirect(new URL(`/l/${encodeURIComponent(params.slug)}?error=1`, request.url), 303);
}
}

View File

@ -3,6 +3,8 @@ import type { ReactNode } from "react";
import { Archivo, IBM_Plex_Mono } from "next/font/google";
import "./globals.css";
import { EmbedBridge } from "@/components/EmbedBridge";
import { checkoutLocale, serverT } from "@/lib/i18n";
const archivo = Archivo({
subsets: ["latin"],
@ -30,8 +32,9 @@ export default function RootLayout({
children: ReactNode;
}) {
return (
<html lang="en" className={`${archivo.variable} ${plexMono.variable}`}>
<html lang={checkoutLocale()} className={`${archivo.variable} ${plexMono.variable}`}>
<body>
<EmbedBridge />
<div className="page">
<header className="topbar">
<span className="brand">SettleKit</span>
@ -39,9 +42,7 @@ export default function RootLayout({
</header>
<main className="content">{children}</main>
<footer className="footer">
<span>
Payments settle in USDC. Access is delivered automatically.
</span>
<span>{serverT()("footer.note")}</span>
</footer>
</div>
</body>

View File

@ -0,0 +1,35 @@
import { notFound } from "next/navigation";
import { ManageSubscription } from "@/components/ManageSubscription";
import { CheckoutError } from "@/lib/errors";
import { getManagedSubscription } from "@/lib/manage-subscription";
import { verifyManageToken } from "@/lib/manage-token";
import { configuredSolanaCluster } from "@/lib/solana";
export const dynamic = "force-dynamic";
interface PageProps {
params: { token: string };
}
/**
* Buyer "manage subscription" page. The signed link (shown after subscribing)
* is the credential: it shows the status, next charge, what the wallet
* authorized and every charge, and lets the buyer cancel and revoke.
*/
export default async function ManageSubscriptionPage({ params }: PageProps) {
if (!verifyManageToken(params.token)) notFound();
let managed;
try {
managed = await getManagedSubscription(params.token);
} catch (error) {
if (error instanceof CheckoutError && error.code === "session_not_found") notFound();
return (
<div className="card">
<h2>Subscription</h2>
<p className="muted">{error instanceof Error ? error.message : "This subscription could not be loaded."} Try again in a minute.</p>
</div>
);
}
return <ManageSubscription token={params.token} initial={managed.view} solanaCluster={configuredSolanaCluster()} />;
}

View File

@ -0,0 +1,29 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { StorefrontView } from "@/components/StorefrontView";
import { getStorefront } from "@/lib/storefront";
export const dynamic = "force-dynamic";
interface PageProps {
params: { slug: string };
}
export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
const store = await getStorefront({ slug: params.slug }).catch(() => null);
if (!store) return { title: "Store not found" };
const description = store.seoDescription ?? store.tagline ?? `Products from ${store.merchantName}, paid in USDC.`;
return {
title: store.title,
description,
openGraph: { title: store.title, description, ...(store.logoUrl ? { images: [store.logoUrl] } : {}) },
};
}
/** Hosted storefront: the merchant's branded product list. */
export default async function StorePage({ params }: PageProps) {
const store = await getStorefront({ slug: params.slug });
if (!store) notFound();
return <StorefrontView store={store} />;
}

View File

@ -0,0 +1,25 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { StorefrontView } from "@/components/StorefrontView";
import { getStorefront } from "@/lib/storefront";
export const dynamic = "force-dynamic";
interface PageProps {
params: { domain: string };
}
export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
const store = await getStorefront({ domain: decodeURIComponent(params.domain) }).catch(() => null);
if (!store) return { title: "Store not found" };
const description = store.seoDescription ?? store.tagline ?? `Products from ${store.merchantName}, paid in USDC.`;
return { title: store.title, description };
}
/** Storefront served on a merchant's custom domain (see middleware.ts). */
export default async function DomainStorePage({ params }: PageProps) {
const store = await getStorefront({ domain: decodeURIComponent(params.domain) });
if (!store) notFound();
return <StorefrontView store={store} />;
}

View File

@ -3,6 +3,7 @@
import { useCallback, useState } from "react";
import type { CollectedFieldSpec } from "@/lib/types";
import { ConnectField } from "./ConnectField";
/** Controlled state for the buyer's delivery fields. */
export function useBuyerFields(requiredFields: CollectedFieldSpec[], initialValues: Record<string, string>) {
@ -29,6 +30,18 @@ export function BuyerFields({ idPrefix, requiredFields, fields, onChange, disabl
<>
{requiredFields.map((spec) => {
const id = `${idPrefix}-field-${spec.key}`;
if (spec.connect) {
return (
<ConnectField
key={spec.key}
id={id}
spec={{ ...spec, connect: spec.connect }}
value={fields[spec.key] ?? ""}
onChange={(value) => onChange(spec.key, value)}
{...(disabled !== undefined ? { disabled } : {})}
/>
);
}
return (
<div className="field" key={spec.key}>
<label htmlFor={id}>{spec.label}</label>

Some files were not shown because too many files have changed in this diff Show More