Compare commits

..

1 Commits

Author SHA1 Message Date
5a834aa579 number one 2026-06-22 22:36:04 +03:00
855 changed files with 2552 additions and 76032 deletions

View File

@ -32,56 +32,6 @@ ARC_CHAIN_ID=5042002
# Required only for an unknown ARC_CHAIN_ID.
# ARC_USDC_ADDRESS=0x3600000000000000000000000000000000000000
# --- Multi-chain payments (EVM stablecoins, Solana, Zcash) -------------------
#
# Every network FAILS CLOSED until enabled: a payment on a disabled network can
# never be confirmed. Chain ids, RPCs and token addresses come from the verified
# @settlekit/chains registry (see docs/colosseum/MULTICHAIN-PLAN.md).
#
# mainnet | testnet for every EVM chain (default testnet). Per-chain override:
# <KEY>_NETWORK. Keys: ethereum, base, arbitrum, robinhood, hyperevm, tempo, arc.
# SETTLEKIT_CHAIN_ENV=testnet
# Comma list of EVM chains to verify (BASE_RPC_URL / ARC_CHAIN_ID also enable
# Base / Arc for backwards compatibility).
# ENABLED_EVM_CHAINS=base,arbitrum,tempo
# Per-chain RPC (defaults to the registry's public RPC; use your own in prod,
# the public HyperEVM RPC is limited to 100 req/min/IP) and confirmation depth
# (defaults: ethereum 12, base/arbitrum/robinhood/arc 3, hyperevm/tempo 1).
# ETHEREUM_RPC_URL=
# ETHEREUM_NETWORK=
# ETHEREUM_MIN_CONFIRMATIONS=
# BASE_RPC_URL=
# BASE_NETWORK=
# BASE_MIN_CONFIRMATIONS=
# ARBITRUM_RPC_URL=
# ARBITRUM_NETWORK=
# ARBITRUM_MIN_CONFIRMATIONS=
# ROBINHOOD_RPC_URL=
# ROBINHOOD_NETWORK=
# ROBINHOOD_MIN_CONFIRMATIONS=
# HYPEREVM_RPC_URL=
# HYPEREVM_NETWORK=
# HYPEREVM_MIN_CONFIRMATIONS=
# TEMPO_RPC_URL=
# TEMPO_NETWORK=
# TEMPO_MIN_CONFIRMATIONS=
# <KEY>_TOKEN_ADDRESS overrides a token for local testing only; production
# refuses any value other than the registry address.
#
# Solana (mainnet | devnet); RPC and USDC mint default from the cluster.
# SOLANA_CLUSTER=devnet
# SOLANA_RPC_URL=
#
# Zcash: transparent t-addresses only, mainnet, verified via Blockchair
# (keyless tier: 1000 requests/day, 30/min). Quotes lock for ZCASH_QUOTE_TTL_SEC.
# ZCASH_ENABLED=false
# ZCASH_EXPLORER_URL=https://api.blockchair.com/zcash
# BLOCKCHAIR_API_KEY=
# ZCASH_MIN_CONFIRMATIONS=3
# ZCASH_QUOTE_TTL_SEC=900
# Worker: how often open Zcash sessions' addresses are polled (ms).
# WORKER_ZCASH_WATCH_INTERVAL_MS=90000
# --- Circle (Gateway / x402 payment rails) ------------------------------------
# Circle API key for Gateway and x402 paid-API settlement.
@ -151,15 +101,8 @@ GITHUB_WEBHOOK_SECRET=replace_with_github_webhook_secret
# --- Discord (community / role access delivery) -------------------------------
# Bot token used to add/remove Discord roles on purchase (API, worker, checkout).
# Unset = Discord purchases show "pending setup"; roles are granted once set.
# Bot token used to add/remove Discord roles on purchase.
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) ----------------------------------------
@ -193,37 +136,6 @@ 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
@ -270,10 +182,6 @@ ARC_MIN_CONFIRMATIONS=3
# Default installation id the API/worker authenticate as (required with the
# GITHUB_APP_* group above).
GITHUB_INSTALLATION_ID=12345678
# The checkout app reads GITHUB_APP_INSTALLATION_ID; the worker accepts either.
# Worker: how often pending GitHub entitlements from checkout are re-delivered
# once an installation id is configured (ms).
# WORKER_GITHUB_RETRY_INTERVAL_MS=120000
# --- File delivery: API process (FILE_DOWNLOAD_*) -----------------------------
@ -292,50 +200,6 @@ FILE_DOWNLOAD_MAX_DOWNLOADS=3
# Set to your real wallet to actually receive payment. (read in routes/x402.ts)
X402_PAY_TO=0x0000000000000000000000000000000000000000
# --- Agent payments: x402 v2 on every chain + MPP on Tempo (/v1/x402, /v1/mpp) -
# A network is offered only with a payTo + a facilitator. Remote (PayAI, no key)
# serves Solana/Base/Arbitrum; the self-hosted facilitator (relayer hot key)
# serves Ethereum/HyperEVM/Robinhood. Chain env follows SETTLEKIT_CHAIN_ENV,
# <KEY>_NETWORK and SOLANA_CLUSTER. See apps/api/src/agent-payments/config.ts.
# X402_EVM_PAY_TO=0x...
# X402_SOLANA_PAY_TO=
# X402_PAY_TO_HYPEREVM=0x... # per-network override
# X402_NETWORKS=solana,base,arbitrum,ethereum,hyperevm,robinhood
# X402_REMOTE_FACILITATOR_URL=https://facilitator.payai.network
# X402_REMOTE_FACILITATOR_API_KEY= # only for keyed facilitators (e.g. CDP)
# X402_RESEARCH_PRICE=0.01
# Self-hosted facilitator (@settlekit/x402-facilitator). Unset key = off.
# X402_RELAYER_PRIVATE_KEY=0x... # hot key: fund with gas only
# X402_FACILITATOR_NETWORKS=ethereum,hyperevm,robinhood
# X402_FACILITATOR_MAX_AMOUNT=100 # USD per settlement
# X402_FACILITATOR_ALLOWED_PAY_TO=0x... # recipients the relayer will settle to (default: X402_EVM_PAY_TO +
# # X402_PAY_TO_<CHAIN>; "*" = any recipient; empty = refuse all)
# Replay protection uses the x402_nonces table when DATABASE_URL is set (in-memory otherwise, dev only).
# X402_FACILITATOR_KILL=0 # 1 = refuse every verify/settle
# X402_FACILITATOR_TOKEN= # bearer for POST /v1/x402/facilitator/*
# X402_FACILITATOR_ALLOW_EXPERIMENTAL=0 # 1 = Tempo Permit2 / Robinhood testnet
# X402_GAS_MAX_FEE_ETHEREUM=3000000000000000 # native base units per settlement
# X402_GAS_DAILY_BUDGET_ETHEREUM=50000000000000000
# MPP on Tempo (mppx): USDC.e on mainnet, pathUSD on Moderato.
# MPP_SECRET_KEY= # >= 32 bytes, e.g. openssl rand -base64 32
# MPP_TEMPO_RECIPIENT=0x...
# TEMPO_NETWORK=mainnet
# --- Onchain billing (subscriptions, Base escrow, refunds) --------------------
# 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)
# =============================================================================
# Worker (apps/worker) — background jobs. Required integrations fail boot if
# missing. File-delivery uses FILE_DELIVERY_* (note: different prefix from API).
@ -449,97 +313,3 @@ 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

View File

@ -1,82 +0,0 @@
# 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 }}

View File

@ -1,37 +0,0 @@
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

View File

@ -1 +1 @@
22
20

View File

@ -15,7 +15,7 @@
ARG APP_PORT=3000
# ---- Base: Node 20 + pnpm via Corepack -------------------------------------
FROM node:22-alpine AS base
FROM node:20-alpine AS base
ENV PNPM_HOME=/pnpm
ENV PATH=$PNPM_HOME:$PATH
ENV NEXT_TELEMETRY_DISABLED=1

21
LICENSE
View File

@ -1,21 +0,0 @@
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.

152
README.md
View File

@ -1,64 +1,23 @@
# SettleKit
> **Get paid in stablecoins on any chain, by people or AI agents, and deliver access automatically.**
> **SettleKit lets developers sell private repos, SaaS, APIs, templates, and AI tools in USDC — and automatically delivers access after payment.**
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.
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.
| 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.
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.
```text
Create product -> Share link -> Buyer pays on any chain (or an agent pays) -> Verified on-chain -> Access delivered
Create product → Set price → Buyer pays → 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 (pre-hackathon, Arc USDC)
## Demo
<p align="center">
<a href="https://github.com/caelum0x/settlekit/releases/download/demo-2026-06-22/settlekit-demo.mp4">
@ -72,69 +31,22 @@ disclosure, and [docs/tameion/](./docs/tameion/) for the plan.
---
## 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 runs on Render's free plan in **testnet mode**. Every service auto-deploys from `main`:
SettleKit is live — API on Render, frontends on Vercel:
| Surface | URL |
| --- | --- |
| 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 |
| 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 |
> 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).
> 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).
---
@ -309,26 +221,6 @@ Every variable the system reads is documented in
Validate that required secrets are present at startup; never commit a real
`.env`.
### Chain support
Checkout, API and worker share one registry (`@settlekit/chains`) and fail
closed per network. Full matrix with finality notes:
[apps/checkout/README.md](./apps/checkout/README.md#chain-support).
| Network | Asset | Environments | Label |
| --- | --- | --- | --- |
| 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
@ -416,8 +308,4 @@ 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)

View File

@ -1,141 +0,0 @@
# 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

@ -1 +1 @@
22
20

View File

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

View File

@ -1 +1 @@
22
20

View File

@ -1 +1 @@
22
20

View File

@ -2,22 +2,19 @@
# Multi-stage build for the SettleKit API (@settlekit/api).
# Build context is the monorepo root: `docker build -f apps/api/Dockerfile .`
# ---- Base: Node 22 + pnpm via Corepack -------------------------------------
FROM node:22-alpine AS base
# ---- Base: Node 20 + pnpm via Corepack -------------------------------------
FROM node:20-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 only the api and its workspace deps (frozen) ----
# ---- Dependencies: install the full workspace (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 --filter settlekit --filter "@settlekit/api..."
RUN pnpm install --frozen-lockfile
# ---- Build: compile package deps + the api via tsc project references ------
FROM deps AS build
@ -47,15 +44,4 @@ COPY --from=prod-deps /app/apps/api/node_modules ./apps/api/node_modules
WORKDIR /app/apps/api
EXPOSE 8787
# 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"]
CMD ["node", "dist/server.js"]

View File

@ -3,7 +3,7 @@
"version": "0.0.0",
"private": true,
"type": "module",
"description": "SettleKit REST API — Hono on Node. Mounts real route modules per resource under /v1 backed by the @settlekit domain packages and their in-memory repositories.",
"description": "SettleKit REST API \u2014 Hono on Node. Mounts real route modules per resource under /v1 backed by the @settlekit domain packages and their in-memory repositories.",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
@ -27,17 +27,21 @@
"@settlekit/agent": "workspace:*",
"@settlekit/agent-economy": "workspace:*",
"@settlekit/agent-services": "workspace:*",
"@settlekit/oss-fund": "workspace:*",
"@settlekit/api-keys": "workspace:*",
"@settlekit/citation-toll": "workspace:*",
"@settlekit/arc": "workspace:*",
"@settlekit/auth": "workspace:*",
"@settlekit/bundles": "workspace:*",
"@settlekit/cctp": "workspace:*",
"@settlekit/chains": "workspace:*",
"@settlekit/circle": "workspace:*",
"@settlekit/circle-wallets": "workspace:*",
"@settlekit/citation-toll": "workspace:*",
"@settlekit/common": "workspace:*",
"@settlekit/compliance": "workspace:*",
"@settlekit/gateway": "workspace:*",
"@settlekit/onchain": "workspace:*",
"@settlekit/paymaster": "workspace:*",
"@settlekit/stablefx": "workspace:*",
"@settlekit/coupons": "workspace:*",
"@settlekit/database": "workspace:*",
"@settlekit/delivery": "workspace:*",
@ -46,48 +50,27 @@
"@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:*",
"@settlekit/saas": "workspace:*",
"@settlekit/solana": "workspace:*",
"@settlekit/stablefx": "workspace:*",
"@settlekit/streaming": "workspace:*",
"@settlekit/usage": "workspace:*",
"@settlekit/webhooks": "workspace:*",
"@settlekit/x402": "workspace:*",
"@settlekit/x402-client": "workspace:*",
"@settlekit/zcash": "workspace:*",
"hono": "^4.12.25",
"zod": "^3.24.1",
"@settlekit/x402-facilitator": "workspace:*",
"@x402/core": "~2.27.0",
"@x402/evm": "~2.27.0",
"@x402/svm": "~2.27.0",
"@x402/hono": "~2.27.0",
"@solana/kit": "5.5.1",
"mppx": "^0.11.0",
"viem": "^2.54.0"
"@settlekit/streaming": "workspace:*",
"hono": "^4.6.14",
"zod": "^3.24.1"
},
"devDependencies": {
"@types/node": "^20.14.0",

View File

@ -1,272 +0,0 @@
/**
* Agent payments runtime (x402 v2 on every chain + MPP on Tempo), built once
* from env at boot and attached to the AppContext.
*
* Facilitator routing:
* - remote (PayAI by default, no key): Solana, Base, Arbitrum
* - local (@settlekit/x402-facilitator, relayer hot key): Ethereum,
* HyperEVM, Robinhood (+ Tempo Permit2 when explicitly enabled)
* A network is offered only when it has a payTo address and a facilitator.
*
* X402_EVM_PAY_TO / X402_SOLANA_PAY_TO merchant recipients (X402_PAY_TO_<KEY> per network)
* X402_NETWORKS networks to offer (default: all routable)
* X402_REMOTE_FACILITATOR_URL default https://facilitator.payai.network
* X402_REMOTE_FACILITATOR_API_KEY optional bearer for a keyed facilitator
* X402_REMOTE_NETWORKS default solana,base,arbitrum
* X402_RESEARCH_PRICE sample resource price, USD (default 0.01)
* X402_FACILITATOR_TOKEN bearer for POST /v1/x402/facilitator/{verify,settle}
* X402_ORGANIZATION_ID org credited for the sample resource
* MPP_SECRET_KEY / MPP_TEMPO_RECIPIENT / MPP_REALM Tempo MPP (mppx)
* plus @settlekit/x402-facilitator env (X402_RELAYER_PRIVATE_KEY, ...),
* SETTLEKIT_CHAIN_ENV / <KEY>_NETWORK and SOLANA_CLUSTER.
*/
import type { PaymentNetwork } from "@settlekit/common";
import { DEFAULT_ORG_ID } from "@settlekit/persistence";
import {
SOLANA_CAIP2,
checkPayTo,
getEvmChain,
isEvmChainKey,
parseChainEnv,
readEnv,
type ChainEnv,
type Env,
type EvmChainKey,
} from "@settlekit/chains";
import { parseSolanaCluster, getSolanaCluster } from "@settlekit/solana";
import { PAYAI_FACILITATOR_URL, routeFacilitators, type FacilitatorRoute } from "@settlekit/x402";
import {
getFacilitatorAsset,
loadFacilitatorFromEnv,
requirementsExtraFor,
type NonceStore,
type SettleKitFacilitator,
} from "@settlekit/x402-facilitator";
import { HTTPFacilitatorClient, type FacilitatorClient } from "@x402/core/server";
import type { Network } from "@x402/core/types";
import { buildMppRuntime, type MppRuntime } from "./mpp.js";
export type FacilitatorKind = "remote" | "local";
/** One network an agent can pay on. */
export interface AgentPaymentNetwork {
network: PaymentNetwork;
caip2: Network;
env: ChainEnv;
symbol: string;
/** Token address (EVM) or mint (Solana). */
asset: string;
decimals: number;
payTo: string;
facilitator: FacilitatorKind;
/** Requirements `extra` (EIP-712 domain or Permit2 transfer method). */
extra: Record<string, unknown>;
experimental: boolean;
}
export interface AgentPaymentsRuntime {
networks: readonly AgentPaymentNetwork[];
/** Network-scoped facilitator clients handed to the x402 resource server. */
facilitators: readonly FacilitatorClient[];
/** The in-process self-hosted facilitator, when a relayer key is configured. */
localFacilitator: SettleKitFacilitator | null;
facilitatorToken?: string;
/** Sample resource price, decimal USD. */
researchPrice: string;
/** Organization credited for the sample resource. */
organizationId: string;
maxTimeoutSeconds: number;
/** Why a configured network is not offered. */
notes: readonly string[];
mpp: MppRuntime | null;
}
export const DEFAULT_REMOTE_NETWORKS: readonly PaymentNetwork[] = ["solana", "base", "arbitrum"];
const OFFERABLE: readonly PaymentNetwork[] = ["solana", "base", "arbitrum", "ethereum", "hyperevm", "robinhood", "tempo"];
function chainEnvFor(env: Env, key: EvmChainKey): ChainEnv {
return (
parseChainEnv(readEnv(env, `${key.toUpperCase()}_NETWORK`), `${key.toUpperCase()}_NETWORK`) ??
parseChainEnv(readEnv(env, "SETTLEKIT_CHAIN_ENV"), "SETTLEKIT_CHAIN_ENV") ??
"testnet"
);
}
function solanaEnv(env: Env): ChainEnv {
const cluster = readEnv(env, "SOLANA_CLUSTER");
if (cluster !== undefined) return parseSolanaCluster(cluster) === "mainnet" ? "mainnet" : "testnet";
return parseChainEnv(readEnv(env, "SETTLEKIT_CHAIN_ENV"), "SETTLEKIT_CHAIN_ENV") ?? "testnet";
}
function payToFor(env: Env, network: PaymentNetwork): string | undefined {
const specific = readEnv(env, `X402_PAY_TO_${network.toUpperCase()}`);
if (specific !== undefined) return specific;
return network === "solana" ? readEnv(env, "X402_SOLANA_PAY_TO") : readEnv(env, "X402_EVM_PAY_TO");
}
function listEnv(env: Env, key: string, fallback: readonly PaymentNetwork[]): PaymentNetwork[] {
const raw = readEnv(env, key);
if (raw === undefined) return [...fallback];
return raw
.split(",")
.map((part) => part.trim().toLowerCase())
.filter((part): part is PaymentNetwork => (OFFERABLE as readonly string[]).includes(part));
}
/** The remote-facilitated network entry (asset from the registry / Solana cluster). */
function remoteNetwork(env: Env, network: PaymentNetwork, payTo: string): AgentPaymentNetwork | string {
if (network === "solana") {
const chainEnv = solanaEnv(env);
const cluster = getSolanaCluster(chainEnv === "mainnet" ? "mainnet" : "devnet");
return {
network,
caip2: SOLANA_CAIP2[chainEnv] as Network,
env: chainEnv,
symbol: "USDC",
asset: cluster.usdcMint,
decimals: 6,
payTo,
facilitator: "remote",
extra: {},
experimental: false,
};
}
if (!isEvmChainKey(network)) return `${network}: not an x402 network`;
const chainEnv = chainEnvFor(env, network);
const asset = getFacilitatorAsset(network, chainEnv);
if (!asset || asset.transferMethod !== "eip3009") return `${network}: no EIP-3009 asset on ${chainEnv}`;
return {
network,
caip2: asset.caip2,
env: chainEnv,
symbol: asset.symbol,
asset: asset.address,
decimals: asset.decimals,
payTo,
facilitator: "remote",
extra: requirementsExtraFor(asset),
experimental: false,
};
}
export interface LoadAgentPaymentsOptions {
/** Inject the local facilitator (tests); defaults to loading it from env. */
localFacilitator?: SettleKitFacilitator | null;
/** Shared replay store for the local facilitator (Postgres when DATABASE_URL is set). */
nonceStore?: NonceStore;
/** Boot warnings sink (default console.warn). */
warn?: (message: string) => void;
}
/**
* This deployment's own EVM receiving addresses: X402_EVM_PAY_TO plus every
* per-chain X402_PAY_TO_<CHAIN> (Solana excluded; the local relayer is EVM-only).
*/
export function ownEvmRecipients(env: Env): string[] {
return Object.keys(env)
.filter((key) => key === "X402_EVM_PAY_TO" || /^X402_PAY_TO_(?!SOLANA$)[A-Z]+$/.test(key))
.map((key) => readEnv(env, key))
.filter((value): value is string => value !== undefined && /^0x[0-9a-fA-F]{40}$/.test(value));
}
/** Build the runtime from env, or null when no network can be offered and MPP is off. */
export function loadAgentPayments(env: Env = process.env, options: LoadAgentPaymentsOptions = {}): AgentPaymentsRuntime | null {
const notes: string[] = [];
// The relayer only settles to this deployment's own EVM recipients unless
// X402_FACILITATOR_ALLOWED_PAY_TO names others (or "*" opens it).
const loaded =
options.localFacilitator === undefined
? loadFacilitatorFromEnv(env, {
defaultAllowedPayTo: ownEvmRecipients(env),
...(options.nonceStore ? { nonceStore: options.nonceStore } : {}),
})
: null;
const local = options.localFacilitator === undefined ? (loaded?.facilitator ?? null) : options.localFacilitator;
if (loaded) {
notes.push(...loaded.skipped.map((reason) => `local facilitator skipped ${reason}`));
const warn = options.warn ?? ((message: string) => console.warn(`[x402] ${message}`));
for (const warning of loaded.warnings) {
notes.push(warning);
warn(warning);
}
}
const wanted = new Set(listEnv(env, "X402_NETWORKS", OFFERABLE));
const remoteWanted = listEnv(env, "X402_REMOTE_NETWORKS", DEFAULT_REMOTE_NETWORKS);
const networks: AgentPaymentNetwork[] = [];
for (const asset of local?.assets() ?? []) {
if (!wanted.has(asset.network)) continue;
const payTo = payToFor(env, asset.network);
if (payTo === undefined || !checkPayTo(asset.network, payTo).ok) {
notes.push(`${asset.network}: set a valid X402_EVM_PAY_TO or X402_PAY_TO_${asset.network.toUpperCase()}`);
continue;
}
networks.push({
network: asset.network,
caip2: asset.caip2,
env: asset.env,
symbol: asset.symbol,
asset: asset.address,
decimals: asset.decimals,
payTo,
facilitator: "local",
extra: requirementsExtraFor(asset),
experimental: asset.experimental,
});
}
for (const network of remoteWanted) {
if (!wanted.has(network) || networks.some((entry) => entry.network === network)) continue;
const payTo = payToFor(env, network);
if (payTo === undefined || !checkPayTo(network, payTo).ok) {
notes.push(`${network}: set a valid ${network === "solana" ? "X402_SOLANA_PAY_TO" : "X402_EVM_PAY_TO"}`);
continue;
}
const entry = remoteNetwork(env, network, payTo);
if (typeof entry === "string") notes.push(entry);
else networks.push(entry);
}
const routes: FacilitatorRoute[] = [];
const remoteNets = networks.filter((entry) => entry.facilitator === "remote").map((entry) => entry.caip2);
if (remoteNets.length > 0) {
const apiKey = readEnv(env, "X402_REMOTE_FACILITATOR_API_KEY");
const client = new HTTPFacilitatorClient({
url: readEnv(env, "X402_REMOTE_FACILITATOR_URL") ?? PAYAI_FACILITATOR_URL,
...(apiKey
? {
createAuthHeaders: async () => {
const headers = { Authorization: `Bearer ${apiKey}` };
return { verify: headers, settle: headers, supported: headers };
},
}
: {}),
});
routes.push({ name: "remote", client, networks: remoteNets });
}
const localNets = networks.filter((entry) => entry.facilitator === "local").map((entry) => entry.caip2);
if (local && localNets.length > 0) routes.push({ name: "local", client: local, networks: localNets });
const mpp = buildMppRuntime(env, notes);
if (networks.length === 0 && mpp === null && local === null) return null;
const token = readEnv(env, "X402_FACILITATOR_TOKEN");
return {
networks,
facilitators: routeFacilitators(routes),
localFacilitator: local,
...(token ? { facilitatorToken: token } : {}),
researchPrice: readEnv(env, "X402_RESEARCH_PRICE") ?? "0.01",
organizationId: readEnv(env, "X402_ORGANIZATION_ID") ?? DEFAULT_ORG_ID,
maxTimeoutSeconds: 300,
notes,
mpp,
};
}
/** The Tempo registry token for `env` (MPP currency). */
export function tempoToken(chainEnv: ChainEnv): { address: string; symbol: string; decimals: number; chainId: number } | null {
const spec = getEvmChain("tempo", chainEnv);
return spec ? { address: spec.token.address, symbol: spec.token.symbol, decimals: spec.token.decimals, chainId: spec.chainId } : null;
}

View File

@ -1,23 +0,0 @@
/**
* Delivery actions for an agent purchase (derivation shared with the worker
* via `@settlekit/delivery` `deliveryActionsFor`). Actions that need a buyer identity
* (GitHub login, Discord user, email) report it as a required field so the
* API can reject the request BEFORE any payment is settled.
*/
import type { DeliveryAction } from "@settlekit/common";
import { deliveryActionsFor } from "@settlekit/delivery";
export { deliveryActionsFor };
export type BuyerField = "githubUsername" | "discordUserId" | "email";
/** Buyer fields the actions need to execute. */
export function requiredBuyerFields(actions: readonly DeliveryAction[]): BuyerField[] {
const fields = new Set<BuyerField>();
for (const action of actions) {
if (action.type === "github_invite" || action.type === "github_team_add") fields.add("githubUsername");
if (action.type === "discord_role_add") fields.add("discordUserId");
if (action.type === "email_send") fields.add("email");
}
return [...fields];
}

View File

@ -1,217 +0,0 @@
/**
* Fulfil an agent purchase whose payment has ALREADY settled on-chain
* (x402 facilitator settle or MPP receipt):
*
* 1. the transaction hash is normalized per network and must be unused
* (one on-chain transfer backs at most one payment -> 409 otherwise)
* 2. the payer becomes (or matches) a customer of the product's org
* 3. a confirmed Payment is recorded
* 4. an entitlement is granted for the product
* 5. the product's delivery actions run inline through the real handler
* registry; the run is persisted and its outputs returned as the artifact
*
* Delivery failures do not undo the payment: the run is stored as failed /
* partially_failed and can be retried via POST /v1/delivery-runs/:id/retry.
*/
import {
conflict,
generateId,
money,
toIso,
type Customer,
type DeliveryPlan,
type DeliveryRun,
type Entitlement,
type Money,
type Payment,
type PaymentNetwork,
type Price,
type Product,
} 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";
export type AgentRail = "x402" | "mpp";
export interface BuyerDetails {
email?: string;
githubUsername?: string;
discordUserId?: string;
}
export interface AgentPurchaseInput {
product: Product;
price: Price;
rail: AgentRail;
network: PaymentNetwork;
/** Settlement transaction hash / signature reported by the facilitator or MPP receipt. */
txHash: string;
/** Paying wallet, when known. */
payer?: string;
/** Token symbol actually paid (USDC, USDG, USDC.e, pathUSD). */
assetSymbol: string;
buyer: BuyerDetails;
}
export interface DeliveredArtifact {
type: string;
status: string;
output?: Record<string, unknown>;
error?: string;
}
export interface AgentPurchaseResult {
payment: Payment;
entitlement: Entitlement;
delivery: { runId: string | null; status: DeliveryRun["status"] | "none"; artifacts: DeliveredArtifact[] };
settlement: { rail: AgentRail; network: PaymentNetwork; txHash: string; payer?: string; asset: string };
}
const INLINE_RETRY = { maxAttempts: 2, baseDelayMs: 250 } as const;
function sameWallet(network: PaymentNetwork, a: string | undefined, b: string): boolean {
if (a === undefined) return false;
return network === "solana" ? a === b : a.toLowerCase() === b.toLowerCase();
}
async function resolveCustomer(ctx: AppContext, input: AgentPurchaseInput): Promise<Customer> {
const organizationId = input.product.organizationId;
const payer = input.payer;
if (payer) {
const [existing] = await ctx.customers.list(
(customer) => customer.organizationId === organizationId && sameWallet(input.network, customer.walletAddress, payer),
);
if (existing) return existing;
}
const customer: Customer = {
id: generateId("customer"),
organizationId,
email: input.buyer.email ?? "",
...(payer ? { walletAddress: payer } : {}),
...(input.buyer.githubUsername ? { githubUsername: input.buyer.githubUsername } : {}),
...(input.buyer.discordUserId ? { discordUserId: input.buyer.discordUserId } : {}),
metadata: { source: `agent_${input.rail}`, network: input.network },
createdAt: toIso(new Date()),
};
return ctx.customers.save(customer);
}
/**
* The GitHub App installation for GitHub actions: the product's pinned
* `metadata.githubInstallationId`, else the org's connected installation,
* else GITHUB_APP_INSTALLATION_ID.
*/
export async function githubInstallationFor(ctx: Pick<AppContext, "githubInstallations">, product: Product): Promise<number | undefined> {
const pinned = product.metadata?.githubInstallationId;
if (typeof pinned === "number" && Number.isInteger(pinned) && pinned > 0) return pinned;
const [installation] = await ctx.githubInstallations.list((entry) => entry.organizationId === product.organizationId);
if (installation) return installation.installationId;
const fromEnv = Number(process.env.GITHUB_APP_INSTALLATION_ID);
return Number.isInteger(fromEnv) && fromEnv > 0 ? fromEnv : undefined;
}
async function runDelivery(
ctx: AppContext,
input: AgentPurchaseInput,
payment: Payment,
entitlement: Entitlement,
): Promise<AgentPurchaseResult["delivery"]> {
const actions = deliveryActionsFor(input.product);
if (actions.length === 0) return { runId: null, status: "none", artifacts: [] };
const plan: DeliveryPlan = {
id: generateId("deliveryPlan"),
organizationId: payment.organizationId,
productId: input.product.id,
actions,
createdAt: toIso(new Date()),
};
const needsGithub = actions.some((action) => action.type === "github_invite" || action.type === "github_team_add");
const githubInstallationId = needsGithub ? await githubInstallationFor(ctx, input.product) : undefined;
const deliveryCtx: DeliveryContext = {
organizationId: payment.organizationId,
customerId: payment.customerId,
productId: input.product.id,
paymentId: payment.id,
entitlementId: entitlement.id,
...(githubInstallationId !== undefined ? { githubInstallationId } : {}),
...(input.buyer.githubUsername ? { githubUsername: input.buyer.githubUsername } : {}),
...(input.buyer.discordUserId ? { discordUserId: input.buyer.discordUserId } : {}),
...(input.buyer.email ? { customerEmail: input.buyer.email } : {}),
clients: ctx.deliveryClients,
};
const runner = new DeliveryRunner(ctx.deliveryRegistry, { retry: INLINE_RETRY });
const run = await runner.run(plan, deliveryCtx, { paymentId: payment.id, customerId: payment.customerId });
const saved = await ctx.deliveryRuns.save(run);
return {
runId: saved.id,
status: saved.status,
artifacts: saved.actionRuns.map((actionRun) => ({
type: actionRun.action.type,
status: actionRun.status,
...(actionRun.output ? { output: actionRun.output } : {}),
...(actionRun.lastError ? { error: actionRun.lastError } : {}),
})),
};
}
/**
* Persist the payment. A concurrent request for the same tx hash that won the
* race (Postgres unique index on tx_hash) surfaces as 409, never a second delivery.
*/
async function savePaymentOnce(ctx: AppContext, payment: Payment): Promise<Payment> {
try {
return await ctx.payments.save(payment);
} catch (err) {
const winner = payment.txHash ? await ctx.payments.findByTxHash(payment.txHash) : null;
if (winner && winner.id !== payment.id) {
throw conflict("transaction hash already used by another payment", { txHash: payment.txHash, paymentId: winner.id });
}
throw err;
}
}
/** Record, entitle and deliver a settled agent purchase. Throws 409 on a reused tx hash. */
export async function fulfilAgentPurchase(ctx: AppContext, input: AgentPurchaseInput): Promise<AgentPurchaseResult> {
const txHash = requireTxHash(input.network, input.txHash);
await assertTxHashUnused(ctx, txHash);
const customer = await resolveCustomer(ctx, input);
const amount = { amount: money(input.price.amount).amount, currency: input.price.currency } as Money;
const pending = recordPendingPayment({
organizationId: input.product.organizationId,
checkoutSessionId: `${input.rail}:${input.network}:${txHash}`,
customerId: customer.id,
amount,
network: input.network,
txHash,
});
// The facilitator / MPP verifier already waited for the settlement receipt.
const payment = await savePaymentOnce(ctx, confirmPayment(pending, txHash, 1, 1));
const entitlement = await ctx.entitlements.grantFromPayment({
payment,
product: input.product,
...(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,
delivery,
settlement: {
rail: input.rail,
network: input.network,
txHash,
...(input.payer ? { payer: input.payer } : {}),
asset: input.assetSymbol,
},
};
}

View File

@ -1,75 +0,0 @@
/**
* Machine Payments Protocol (MPP) runtime for Tempo, via `mppx` (wevm, MIT).
*
* The agent pays a TIP-20 transfer on Tempo (USDC.e on mainnet, pathUSD on
* Moderato) and presents the credential in `Authorization: Payment ...`;
* mppx verifies the transfer on-chain (amount, currency, recipient, memo
* binding, success, replay) and returns a receipt whose `reference` is the
* transaction hash.
*
* MPP_SECRET_KEY >= 32 bytes; binds challenges (required to enable)
* MPP_TEMPO_RECIPIENT merchant address (falls back to X402_PAY_TO_TEMPO / X402_EVM_PAY_TO)
* MPP_REALM challenge realm (default "settlekit")
* TEMPO_NETWORK / SETTLEKIT_CHAIN_ENV mainnet (USDC.e) | testnet (Moderato pathUSD)
*/
import { checkPayTo, getEvmChain, parseChainEnv, readEnv, type ChainEnv, type Env } from "@settlekit/chains";
import type { Method } from "mppx";
import { tempo } from "mppx/server";
export interface MppRuntime {
secretKey: string;
realm: string;
env: ChainEnv;
chainId: number;
/** TIP-20 token address the charge is denominated in. */
currency: string;
symbol: string;
decimals: number;
recipient: string;
/** The server charge method (real `tempo.charge` in production; injectable). */
charge: Method.AnyServer;
}
const MIN_SECRET_BYTES = 32;
/** Build the MPP runtime from env, or null (with a note) when not configured. */
export function buildMppRuntime(env: Env, notes: string[]): MppRuntime | null {
const secretKey = readEnv(env, "MPP_SECRET_KEY");
if (secretKey === undefined) return null;
if (Buffer.byteLength(secretKey) < MIN_SECRET_BYTES) {
notes.push(`mpp: MPP_SECRET_KEY must be at least ${MIN_SECRET_BYTES} bytes`);
return null;
}
const chainEnv =
parseChainEnv(readEnv(env, "TEMPO_NETWORK"), "TEMPO_NETWORK") ??
parseChainEnv(readEnv(env, "SETTLEKIT_CHAIN_ENV"), "SETTLEKIT_CHAIN_ENV") ??
"testnet";
const spec = getEvmChain("tempo", chainEnv);
if (!spec) {
notes.push(`mpp: no Tempo chain for ${chainEnv}`);
return null;
}
const recipient =
readEnv(env, "MPP_TEMPO_RECIPIENT") ?? readEnv(env, "X402_PAY_TO_TEMPO") ?? readEnv(env, "X402_EVM_PAY_TO");
if (recipient === undefined || !checkPayTo("tempo", recipient).ok) {
notes.push("mpp: set a valid MPP_TEMPO_RECIPIENT");
return null;
}
const charge = tempo.charge({
currency: spec.token.address,
decimals: spec.token.decimals,
recipient: recipient as `0x${string}`,
testnet: chainEnv === "testnet",
});
return {
secretKey,
realm: readEnv(env, "MPP_REALM") ?? "settlekit",
env: chainEnv,
chainId: spec.chainId,
currency: spec.token.address,
symbol: spec.token.symbol,
decimals: spec.token.decimals,
recipient,
charge: charge as unknown as Method.AnyServer,
};
}

View File

@ -1,59 +0,0 @@
/**
* Everything an agent purchase must satisfy BEFORE a payment challenge is
* issued or settled: the product exists and is published, it has a one-time
* fixed price, and the buyer supplied every identity its delivery needs.
* Failing here costs the agent nothing.
*/
import { z } from "zod";
import { notFound, validationError, type Price, type Product } from "@settlekit/common";
import type { AppContext } from "../context.js";
import { deliveryActionsFor, requiredBuyerFields } from "./delivery-action.js";
import type { BuyerDetails } from "./fulfil.js";
export const buyerSchema = z
.object({
email: z.string().email().optional(),
githubUsername: z.string().regex(/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/, "must be a GitHub login").optional(),
discordUserId: z.string().regex(/^\d{5,25}$/, "must be a Discord user id").optional(),
})
.strict();
export interface Purchasable {
product: Product;
price: Price;
buyer: BuyerDetails;
}
/** Parse the optional JSON body of a buy request (empty body = no buyer details). */
export async function readBuyer(request: Request): Promise<BuyerDetails> {
const text = await request.clone().text();
if (text.trim().length === 0) return {};
let raw: unknown;
try {
raw = JSON.parse(text);
} catch {
throw validationError("request body must be JSON");
}
const parsed = buyerSchema.safeParse(raw);
if (!parsed.success) {
throw validationError("invalid buyer details", { issues: parsed.error.issues.map((issue) => issue.message) });
}
return Object.fromEntries(Object.entries(parsed.data).filter(([, value]) => value !== undefined)) as BuyerDetails;
}
/** Resolve the product, its one-time price and validated buyer details. */
export async function resolvePurchasable(ctx: AppContext, productId: string, buyer: BuyerDetails): Promise<Purchasable> {
const product = await ctx.products.findById(productId);
if (!product || product.status !== "active") throw notFound("product not found", { id: productId });
const prices = await ctx.prices.list(
(price) => price.productId === productId && price.active && price.interval === "one_time" && !price.usageBased,
);
const price = prices.sort((a, b) => a.createdAt.localeCompare(b.createdAt))[0];
if (!price) throw validationError("product has no active one-time price", { id: productId });
const missing = requiredBuyerFields(deliveryActionsFor(product)).filter((field) => buyer[field] === undefined);
if (missing.length > 0) {
throw validationError(`delivery of this product needs: ${missing.join(", ")}`, { missing });
}
return { product, price, buyer };
}

View File

@ -1,132 +0,0 @@
/**
* "Settle first, then deliver" x402 middleware for purchases.
*
* `@x402/hono`'s `paymentMiddleware` verifies, runs the handler and settles
* AFTER it (right for metered content). A purchase must never deliver an
* artifact for a payment that has not settled, so this middleware drives the
* same `x402HTTPResourceServer` with the `upfront` payment flow: the
* facilitator settles BEFORE the handler, the handler reads the settlement
* (`c.get("x402Settled")`) to record the payment and deliver, and the
* PAYMENT-RESPONSE receipt is echoed on whatever the handler returns.
*/
import type { Context, MiddlewareHandler } from "hono";
import { basePath } from "hono/route";
import { HonoAdapter } from "@x402/hono";
import {
getFacilitatorResponseError,
type HTTPRequestContext,
type x402HTTPResourceServer,
} from "@x402/core/server";
import type { PaymentPayload, PaymentRequirements, SettleResponse } from "@x402/core/types";
/** Hono adapter that keeps the Hono context reachable from dynamic prices. */
export class ContextAdapter extends HonoAdapter {
constructor(readonly context: Context) {
super(context);
}
}
export interface SettledPayment {
payload: PaymentPayload;
requirements: PaymentRequirements;
settlement: SettleResponse;
}
export interface SettleFirstVariables {
x402Settled?: SettledPayment;
}
function decodedRoutePath(c: Context): string {
let path: string;
try {
path = decodeURIComponent(c.req.path);
} catch {
path = c.req.path;
}
let root = "";
try {
root = basePath(c);
} catch {
return path;
}
if (!root || root === "/" || !path.startsWith(root)) return path;
if (path === root) return "";
return path[root.length] === "/" ? path.slice(root.length) : path;
}
function withHeaders(res: Response, headers: Record<string, string>): Response {
const merged = new Headers(res.headers);
for (const [key, value] of Object.entries(headers)) merged.set(key, value);
return new Response(res.body, { status: res.status, statusText: res.statusText, headers: merged });
}
/** Build the middleware. Routes it guards must declare `extra.paymentFlow: "upfront"`. */
export function settleFirstPayment(httpServer: x402HTTPResourceServer): MiddlewareHandler {
let init: Promise<void> | null = null;
const initialize = async (): Promise<void> => {
init ??= httpServer.initialize();
try {
await init;
} catch (error) {
init = null;
throw error;
}
};
return async (c, next) => {
const adapter = new ContextAdapter(c);
const context: HTTPRequestContext = {
adapter,
path: c.req.path,
decodedPath: decodedRoutePath(c),
method: c.req.method,
...(adapter.getHeader("payment-signature") ?? adapter.getHeader("x-payment")
? { paymentHeader: (adapter.getHeader("payment-signature") ?? adapter.getHeader("x-payment")) as string }
: {}),
};
if (!httpServer.requiresPayment(context)) return next();
let result: Awaited<ReturnType<x402HTTPResourceServer["processHTTPRequest"]>>;
try {
await initialize();
result = await httpServer.processHTTPRequest(context);
} catch (error) {
const facilitatorError = getFacilitatorResponseError(error);
if (facilitatorError) return c.json({ error: { code: "facilitator_error", message: facilitatorError.message } }, 502);
throw error;
}
if (result.type === "no-payment-required") return next();
if (result.type === "payment-error") {
const { response } = result;
for (const [key, value] of Object.entries(response.headers)) c.header(key, value);
if (response.isHtml) return c.html(String(response.body ?? ""), response.status as 402);
return c.json(response.body ?? {}, response.status as 402);
}
const settled = result.beforeHandlerSettlement;
if (!settled || !settled.result.success) {
await result.cancellationDispatcher.cancel({ reason: "after_verify_aborted" });
return c.json({ error: { code: "configuration_error", message: "purchase routes must settle before delivery" } }, 500);
}
c.set("x402Settled" as never, {
payload: result.paymentPayload,
requirements: settled.requirements,
settlement: settled.result,
} satisfies SettledPayment as never);
try {
await next();
} finally {
const echo = await httpServer.processSettlement(
result.paymentPayload,
result.paymentRequirements,
result.declaredExtensions,
{ request: context },
undefined,
settled,
);
c.res = withHeaders(c.res, echo.headers);
}
};
}

View File

@ -1,36 +0,0 @@
/**
* A payment settled on-chain but fulfilment then failed unexpectedly (not a
* domain error such as a reused tx hash). Money has moved, so the settlement
* must never be lost silently: emit a structured error line for
* reconciliation and hand the agent the transaction so it can prove payment.
*/
import type { Context } from "hono";
import { SettleKitError } from "@settlekit/common";
import { error } from "../http/respond.js";
export interface SettlementRef {
rail: "x402" | "mpp";
network: string;
txHash: string;
productId: string;
payer?: string;
}
/** Map a fulfilment error to a response, logging settled-but-unfulfilled payments. */
export function fulfilmentError(c: Context, err: unknown, settlement: SettlementRef): Response {
if (SettleKitError.is(err)) return error(c, err);
const message = err instanceof Error ? err.message : String(err);
process.stderr.write(
`${JSON.stringify({ ts: new Date().toISOString(), app: "api", level: "error", msg: "agent purchase settled but not fulfilled", ...settlement, error: message })}\n`,
);
return c.json(
{
error: {
code: "fulfilment_failed",
message: "payment settled but fulfilment failed; it has been logged for reconciliation",
details: { ...settlement },
},
},
500,
);
}

View File

@ -1,139 +0,0 @@
/**
* 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,9 +45,6 @@ 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";
@ -64,12 +61,6 @@ 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> {
@ -123,10 +114,6 @@ export function createApp(ctx: AppContext): Hono<AppEnv> {
// are mounted outside the API-key guard (humans + AI agents pay per call).
app.route("/v1/paid", x402Routes());
// Agent payments are PUBLIC too: x402 v2 on every chain + MPP on Tempo.
app.route("/v1/x402", x402AgentRoutes(ctx.agentPayments));
app.route("/v1/mpp", mppTempoRoutes(ctx.agentPayments));
// Lepton hackathon demo is PUBLIC: self-contained, in-memory nanopayment
// modules (agent economy, citation tolls, streaming). No API key, no DB.
app.route("/v1/lepton", leptonRoutes());
@ -140,11 +127,6 @@ 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>();
@ -197,13 +179,8 @@ 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());
@ -211,10 +188,6 @@ 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());
@ -228,7 +201,6 @@ export function createApp(ctx: AppContext): Hono<AppEnv> {
v1.route("/mint", mintRoutes());
v1.route("/user-wallets", userWalletRoutes());
v1.route("/onchain-escrow", onchainEscrowRoutes());
v1.route("/onchain-billing", onchainBillingRoutes());
// paymaster + gas-station share one router (paths are /paymaster/* and /gas-station/*).
v1.route("/", paymasterRoutes());

View File

@ -24,8 +24,6 @@ export function circleChainForNetwork(network: string, defaultChain: string): st
return "BASE";
case "ethereum":
return "ETH";
case "solana":
return "SOL";
default:
// Arc (and anything else Circle does not list) screens against the
// configured default chain — sanctions hits are address-, not chain-, scoped.

View File

@ -1,24 +0,0 @@
/**
* Boot-time chain-id assertion: every enabled EVM chain's RPC must serve the
* chain the registry says it does. A mismatch refuses to boot (a mis-pointed
* RPC could otherwise confirm payments made on another chain). An unreachable
* RPC only warns: each verifier re-asserts the chain id before it verifies,
* so payments on that chain fail closed until the RPC answers correctly.
*/
import { checkEvmChainIds, type EvmVerifier } from "@settlekit/chains";
export type BootLog = (message: string, fields: Record<string, unknown>) => void;
export async function assertChainIdsAtBoot(verifiers: readonly EvmVerifier[], log: BootLog): Promise<void> {
const results = await checkEvmChainIds(verifiers);
const mismatched = results.filter((result) => result.mismatch);
if (mismatched.length > 0) {
throw new Error(
`Refusing to boot: RPC chain id mismatch for ${mismatched.map((r) => `${r.key} (${r.error ?? "mismatch"})`).join(", ")}`,
);
}
for (const result of results) {
if (!result.ok) log("evm rpc unreachable at boot; chain fails closed until it answers", { chain: result.key, error: result.error });
}
log("evm chains verified", { chains: results.filter((r) => r.ok).map((r) => r.key) });
}

View File

@ -1,35 +0,0 @@
/**
* Multi-chain configuration for the API: the enabled EVM chains (see
* `loadEvmChains` in @settlekit/chains — SETTLEKIT_CHAIN_ENV,
* ENABLED_EVM_CHAINS, per-chain RPC/NETWORK/MIN_CONFIRMATIONS, and the
* BASE_RPC_URL / ARC_CHAIN_ID aliases), transparent Zcash and HyperCore
* (HYPERCORE_ENABLED / HYPERCORE_NETWORK / HYPERCORE_API_URL). Chain config
* errors surface as {@link ConfigError} so boot fails fast.
*/
import {
ChainConfigError,
loadEvmChains,
loadZcashConfig,
type EvmChainsConfig,
type ZcashConfig,
} from "@settlekit/chains";
import { loadHyperCoreConfig, type HyperCoreConfig } from "@settlekit/hyperliquid";
import { ConfigError } from "./errors.js";
export interface ChainGroups {
evm: EvmChainsConfig;
zcash: ZcashConfig | null;
hypercore: HyperCoreConfig | null;
}
type Env = Record<string, string | undefined>;
export function loadChainGroups(env: Env): ChainGroups {
try {
return { evm: loadEvmChains(env), zcash: loadZcashConfig(env), hypercore: loadHyperCoreConfig(env) };
} catch (error) {
if (error instanceof ChainConfigError) throw new ConfigError(error.message);
throw error;
}
}

View File

@ -12,19 +12,14 @@
*/
import { getArcChain, isArcAddress, type ArcAddress } from "@settlekit/arc";
import {
getSolanaCluster,
isSolanaAddress,
parseSolanaCluster,
type SolanaCluster,
} from "@settlekit/solana";
import type { EvmChainsConfig, ZcashConfig } from "@settlekit/chains";
import type { HyperCoreConfig } from "@settlekit/hyperliquid";
import { ConfigError } from "./errors.js";
import { loadChainGroups } from "./chain-env.js";
export { ConfigError };
/** Raised when an environment group is partially set or a value is malformed. */
export class ConfigError extends Error {
constructor(message: string) {
super(message);
this.name = "ConfigError";
}
}
type Env = Record<string, string | undefined>;
@ -42,29 +37,6 @@ export interface ArcConfig {
minConfirmations: number;
}
/** Base mainnet chain id and its native Circle USDC contract. */
export const BASE_CHAIN_ID = 8453;
export const BASE_USDC_ADDRESS: ArcAddress = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
/**
* Legacy Base group, enabled by BASE_RPC_URL (Base mainnet). Verification now
* runs from {@link ApiConfig.evm}, where BASE_RPC_URL is an alias for
* enabling Base.
*/
export interface BaseConfig {
rpcUrl: string;
usdcAddress: ArcAddress;
chainId: number;
minConfirmations: number;
}
/** Solana USDC verification reader, enabled by SOLANA_CLUSTER. */
export interface SolanaConfig {
cluster: SolanaCluster;
rpcUrl: string;
usdcMint: string;
}
/** Circle REST client configuration. */
export interface CircleConfig {
apiKey: string;
@ -166,14 +138,6 @@ export interface ApiConfig {
/** Optional integration groups — null when their creds are absent. */
database: DatabaseConfig | null;
arc: ArcConfig | null;
base: BaseConfig | null;
/** Enabled EVM chains for payment verification (others fail closed). */
evm: EvmChainsConfig;
/** Transparent Zcash settlement; null unless ZCASH_ENABLED. */
zcash: ZcashConfig | null;
/** HyperCore USDC settlement; null unless HYPERCORE_ENABLED. */
hypercore: HyperCoreConfig | null;
solana: SolanaConfig | null;
circle: CircleConfig | null;
circleWallets: CircleWalletsConfig | null;
gasStation: GasStationConfig | null;
@ -187,10 +151,6 @@ export interface ApiConfig {
/** Presence flags derived from the groups above. */
hasDatabase: boolean;
hasArc: boolean;
hasBase: boolean;
hasZcash: boolean;
hasHyperCore: boolean;
hasSolana: boolean;
hasCircle: boolean;
hasCircleWallets: boolean;
hasGasStation: boolean;
@ -302,41 +262,6 @@ function loadArc(env: Env): ArcConfig | null {
};
}
function loadBase(env: Env): BaseConfig | null {
const rpcUrl = optionalRaw(env, "BASE_RPC_URL");
if (rpcUrl === undefined) return null;
return {
rpcUrl,
usdcAddress: BASE_USDC_ADDRESS,
chainId: BASE_CHAIN_ID,
minConfirmations: intInRange(env, "BASE_MIN_CONFIRMATIONS", 3, 1, 1_000),
};
}
function loadSolana(env: Env): SolanaConfig | null {
// Enabled by SOLANA_CLUSTER (mainnet | mainnet-beta | devnet). The RPC URL
// and USDC mint default from the cluster; override them for a dedicated RPC
// (e.g. Helius). Setting an override without a cluster is a misconfiguration.
const clusterRaw = optionalRaw(env, "SOLANA_CLUSTER");
if (clusterRaw === undefined) {
const stray = presentKeys(env, ["SOLANA_RPC_URL", "SOLANA_USDC_MINT"]);
if (stray.length > 0) {
throw new ConfigError(`Incomplete solana configuration: set [SOLANA_CLUSTER] or unset [${stray.join(", ")}]`);
}
return null;
}
const cluster = parseSolanaCluster(clusterRaw);
if (cluster === undefined) {
throw new ConfigError(`Environment variable SOLANA_CLUSTER must be mainnet or devnet, got "${clusterRaw}"`);
}
const known = getSolanaCluster(cluster);
const usdcMint = optionalRaw(env, "SOLANA_USDC_MINT") ?? known.usdcMint;
if (!isSolanaAddress(usdcMint)) {
throw new ConfigError("Environment variable SOLANA_USDC_MINT must be a base58 Solana address");
}
return { cluster, rpcUrl: optionalRaw(env, "SOLANA_RPC_URL") ?? known.rpcUrl, usdcMint };
}
function loadCircle(env: Env): CircleConfig | null {
if (requireComplete("circle", env, ["CIRCLE_API_KEY"]) === "absent") return null;
const baseUrl = optionalRaw(env, "CIRCLE_BASE_URL");
@ -512,9 +437,6 @@ function assertProductionReady(
export function loadConfig(env: Env = process.env): ApiConfig {
const database = loadDatabase(env);
const arc = loadArc(env);
const base = loadBase(env);
const chains = loadChainGroups(env);
const solana = loadSolana(env);
const circle = loadCircle(env);
const circleWallets = loadCircleWallets(env);
const gasStation = loadGasStation(env);
@ -543,11 +465,6 @@ export function loadConfig(env: Env = process.env): ApiConfig {
database,
arc,
base,
evm: chains.evm,
zcash: chains.zcash,
hypercore: chains.hypercore,
solana,
circle,
circleWallets,
gasStation,
@ -560,10 +477,6 @@ export function loadConfig(env: Env = process.env): ApiConfig {
hasDatabase: database !== null,
hasArc: arc !== null,
hasBase: base !== null,
hasZcash: chains.zcash !== null,
hasHyperCore: chains.hypercore !== null,
hasSolana: solana !== null,
hasCircle: circle !== null,
hasCircleWallets: circleWallets !== null,
hasGasStation: gasStation !== null,

View File

@ -1,7 +0,0 @@
/** Raised when an environment group is partially set or a value is malformed. */
export class ConfigError extends Error {
constructor(message: string) {
super(message);
this.name = "ConfigError";
}
}

View File

@ -11,9 +11,14 @@
* have stores can pass their own sink via {@link BuildIntegrationsOptions}.
*/
import { type DiscordRoleGrant, type GitHubRepoAccessGrant } from "@settlekit/common";
import { createArcClient, type ArcClient } from "@settlekit/arc";
import type { EvmVerifier } from "@settlekit/chains";
import { money, type DiscordRoleGrant, type GitHubRepoAccessGrant } from "@settlekit/common";
import {
createArcClient,
getArcChain,
isArcAsset,
type ArcAddress,
type ArcClient,
} from "@settlekit/arc";
import { createWalletsClient } from "@settlekit/circle-wallets";
import { createScreeningClient, type ScreeningClient } from "@settlekit/compliance";
import {
@ -35,15 +40,6 @@ import type { DeliveryClients } from "@settlekit/delivery";
import type { PaymentVerifier } from "@settlekit/x402";
import type { ApiConfig } from "./env.js";
import {
buildVerifierRegistry,
type PaymentVerifiers,
type VerifierRegistryDeps,
type ZcashRuntime,
} from "./verifier-registry.js";
export type { PaymentVerifiers, ZcashRuntime } from "./verifier-registry.js";
import {
buildDiscordClient,
createDeliveryClients,
type DeliveryGrantSink,
} from "../wiring/delivery-clients.js";
@ -61,15 +57,6 @@ export interface Integrations {
discordApi: DiscordApi;
/** Arc settlement verifier for x402 paid calls, or null when Arc is unset. */
arcVerifier: PaymentVerifier | null;
/**
* On-chain payment verifiers keyed by network. A network with no entry has
* NO way to confirm payments: confirm/observe fail closed for it.
*/
verifiers: PaymentVerifiers;
/** Raw EVM verifiers, for the boot-time chain-id assertion. */
evmVerifiers: readonly EvmVerifier[];
/** Zcash quote + explorer services, or null when Zcash is disabled. */
zcash: ZcashRuntime | null;
/** Raw Arc client (verify / fee-estimate / confirmations), or null when unset. */
arc: ArcClient | null;
/** Real Circle REST client, or null when Circle is unset. */
@ -94,8 +81,6 @@ export interface BuildIntegrationsOptions {
licenseStore?: LicenseStore;
apiKeyStore?: ApiKeyStore;
fileGrantStore?: GrantStore;
/** Inject chain RPCs / fetch for the verifier registry (tests). */
chains?: VerifierRegistryDeps;
}
/** A `DeliveryGrantSink` backed by plain in-memory maps. */
@ -124,6 +109,59 @@ function createInMemoryGrantSink(): DeliveryGrantSink {
};
}
/**
* Build an x402 {@link PaymentVerifier} over a real {@link ArcClient}. Confirms
* the proof's transaction transferred at least the advertised amount to the
* configured `payTo` address with enough confirmations.
*/
function buildArcVerifier(arc: ArcClient, minConfirmations: number): PaymentVerifier {
const chain = getArcChain(arc.config.chainId);
return async (proof, requirements) => {
if (proof.network !== "arc") {
return { ok: false, reason: `Unsupported network: ${proof.network}` };
}
if (!/^0x[a-fA-F0-9]{64}$/.test(proof.txHash)) {
return { ok: false, reason: "Malformed transaction hash" };
}
const txHash = proof.txHash as `0x${string}`;
const to = requirements.payTo as ArcAddress;
const minAmount = money(requirements.amount, requirements.asset);
// Widen to string: requirements.asset is typed as the literal "USDC", but
// EURC/USYC settlements flow through the same verifier at runtime.
const asset: string = requirements.asset;
// Resolve which token to look for. USDC uses the configured USDC address;
// other Arc stablecoins (EURC/USYC) resolve their contract from the chain
// definition so they settle through the same on-chain verification path.
let result;
if (asset === "USDC") {
result = await arc.verifyUsdcTransfer({ txHash, to, minAmount });
} else if (chain && isArcAsset(asset) && chain.tokens[asset]) {
result = await arc.verifyTokenTransfer({
txHash,
token: chain.tokens[asset].address,
to,
minAmount,
});
} else {
return { ok: false, reason: `Unsupported settlement asset on Arc: ${asset}` };
}
if (!result.confirmed) {
return { ok: false, reason: `No matching ${asset} transfer found` };
}
if (result.confirmations < minConfirmations) {
return {
ok: false,
reason: `Insufficient confirmations: ${result.confirmations} < ${minConfirmations}`,
};
}
return { ok: true };
};
}
/**
* Construct the full set of {@link Integrations} from an {@link ApiConfig}.
* Each group falls back to its in-memory double when its creds are absent.
@ -181,15 +219,11 @@ export function buildIntegrations(
: {}),
});
} else {
const inMemory = createInMemoryDeliveryClients({
deliveryClients = 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
@ -199,7 +233,8 @@ export function buildIntegrations(
chainId: config.arc.chainId,
})
: null;
const registry = buildVerifierRegistry(config, options.chains);
const arcVerifier =
arcClient && config.arc ? buildArcVerifier(arcClient, config.arc.minConfirmations) : null;
const circle = config.circle
? createCircleClient({
@ -239,10 +274,7 @@ export function buildIntegrations(
deliveryClients,
githubAccessClient,
discordApi,
arcVerifier: registry.arcVerifier,
verifiers: registry.verifiers,
evmVerifiers: registry.evmVerifiers,
zcash: registry.zcash,
arcVerifier,
arc: arcClient,
circle,
payoutExecutor,

View File

@ -1,181 +0,0 @@
/**
* The per-network on-chain verifier registry.
*
* One {@link SettlementVerifier} per ENABLED network: every EVM chain from
* `config.evm` (Arc included), Solana when SOLANA_CLUSTER is set, Zcash
* when ZCASH_ENABLED and HyperCore when HYPERCORE_ENABLED. A network without an entry fails closed — a tx hash
* alone can never confirm a payment on it.
*/
import { ARC_TESTNET, type FullEvmRpc } from "@settlekit/arc";
import {
createChainRpc,
createEvmSettlementVerifier,
createEvmVerifier,
createZcashSettlementVerifier,
type EvmChainKey,
type EvmChainRuntimeConfig,
type EvmVerifier,
type SettlementVerifier,
type ZcashConfig,
} from "@settlekit/chains";
import { toBaseUnits, type PaymentNetwork } from "@settlekit/common";
import { createHyperCoreClient, createHyperCoreSettlementVerifier, type HyperliquidTransport } from "@settlekit/hyperliquid";
import {
createKitSolanaRpc,
createSolanaPaymentVerifier,
isSolanaSignature,
verifySplTransfer,
type SolanaRpc,
} from "@settlekit/solana";
import {
createBlockchairExplorer,
createCoinbaseSource,
createKrakenSource,
type FetchLike,
type PriceSource,
type ZcashExplorer,
type ZcashNetwork,
} from "@settlekit/zcash";
import type { PaymentVerifier } from "@settlekit/x402";
import type { ApiConfig } from "./env.js";
/** Per-network verifier registry (absent network = fail closed). */
export type PaymentVerifiers = Readonly<Partial<Record<PaymentNetwork, SettlementVerifier>>>;
/** Zcash services used at checkout creation (quote lock) and verification. */
export interface ZcashRuntime {
network: ZcashNetwork;
explorer: ZcashExplorer;
/** Primary first (Coinbase), then fallbacks/cross-checks (Kraken). */
priceSources: readonly PriceSource[];
quoteTtlSec: number;
minConfirmations: number;
}
export interface VerifierRegistry {
verifiers: PaymentVerifiers;
/** The raw EVM verifiers, for the boot-time chain-id assertion. */
evmVerifiers: readonly EvmVerifier[];
/** x402 view of the Arc verifier (the x402 routes settle on Arc). */
arcVerifier: PaymentVerifier | null;
zcash: ZcashRuntime | null;
}
export interface VerifierRegistryDeps {
/** Inject RPCs per chain (tests); defaults to viem over the configured URL. */
evmRpcs?: Partial<Record<EvmChainKey, FullEvmRpc>>;
/** Inject the Solana RPC (tests); defaults to @solana/kit over the configured URL. */
solanaRpc?: SolanaRpc;
/** fetch used by Zcash price sources and the explorer. */
fetch?: FetchLike;
/** Hyperliquid API transport (tests inject recorded ledgers). */
hypercoreTransport?: HyperliquidTransport;
}
function buildEvm(chain: EvmChainRuntimeConfig, rpc: FullEvmRpc): { primary: EvmVerifier; settlement: SettlementVerifier } {
const primary = createEvmVerifier({
spec: chain.spec,
rpc,
minConfirmations: chain.minConfirmations,
tokenAddress: chain.tokenAddress,
});
// Arc also settles EURC / USYC (x402 calls): same rules, their own contracts.
const extra: Record<string, EvmVerifier> =
chain.key === "arc"
? {
EURC: createEvmVerifier({ spec: chain.spec, rpc, minConfirmations: chain.minConfirmations, tokenAddress: ARC_TESTNET.tokens.EURC.address }),
USYC: createEvmVerifier({ spec: chain.spec, rpc, minConfirmations: chain.minConfirmations, tokenAddress: ARC_TESTNET.tokens.USYC.address }),
}
: {};
return { primary, settlement: createEvmSettlementVerifier(primary, extra) };
}
/** Allowed skew between session creation and a routed Solana fill's block time (matches checkout/worker). */
export const ROUTED_FILL_SKEW_MS = 120_000;
/**
* A route provider's Solana fill carries no Solana Pay reference, so it is
* bound by payTo, mint, amount and block time (>= session creation - skew).
*/
async function verifyRoutedSolanaFill(
rpc: SolanaRpc,
mint: string,
proof: { txHash: string },
requirements: { payTo: string; amount: string; notBefore?: string },
): Promise<{ ok: boolean; reason?: string; retryable?: boolean }> {
if (!isSolanaSignature(proof.txHash)) return { ok: false, reason: "Malformed Solana transaction signature" };
const notBefore = requirements.notBefore ? new Date(requirements.notBefore).getTime() : Number.NaN;
if (Number.isNaN(notBefore)) return { ok: false, reason: "routed fill needs the session creation time" };
const result = await verifySplTransfer(rpc, {
signature: proof.txHash,
mint,
recipientOwner: requirements.payTo,
minAmount: toBaseUnits(requirements.amount),
commitment: "confirmed",
});
if (!result.ok) return { ok: false, reason: result.message, ...(result.reason === "not_found" ? { retryable: true } : {}) };
if (result.blockTime === null) return { ok: false, reason: "fill has no block time yet", retryable: true };
if (result.blockTime * 1000 < notBefore - ROUTED_FILL_SKEW_MS) return { ok: false, reason: "fill predates the checkout session" };
return { ok: true };
}
/** Adapt the x402-shaped Solana verifier to the settlement contract. */
function solanaVerifier(config: NonNullable<ApiConfig["solana"]>, rpc?: SolanaRpc): SettlementVerifier {
const solanaRpc = rpc ?? createKitSolanaRpc(config.rpcUrl);
const verify = createSolanaPaymentVerifier({
rpc: solanaRpc,
mint: config.usdcMint,
commitment: "confirmed",
});
return async (proof, requirements) => {
if (proof.network !== "solana" || requirements.network !== "solana") {
return { ok: false, reason: `Unsupported network: ${proof.network}` };
}
if (requirements.routedFill === true) return verifyRoutedSolanaFill(solanaRpc, config.usdcMint, proof, requirements);
return verify(
{ ...proof, network: "solana" },
{ ...requirements, scheme: "x402", network: "solana", asset: requirements.asset as "USDC" },
);
};
}
function zcashRuntime(config: ZcashConfig, fetchImpl: FetchLike): ZcashRuntime {
return {
network: config.network,
explorer: createBlockchairExplorer({
fetch: fetchImpl,
baseUrl: config.explorerUrl,
...(config.apiKey ? { apiKey: config.apiKey } : {}),
}),
priceSources: [createCoinbaseSource(fetchImpl), createKrakenSource(fetchImpl)],
quoteTtlSec: config.quoteTtlSec,
minConfirmations: config.minConfirmations,
};
}
/** Build every enabled network's verifier from `config`. */
export function buildVerifierRegistry(config: ApiConfig, deps: VerifierRegistryDeps = {}): VerifierRegistry {
const verifiers: Partial<Record<PaymentNetwork, SettlementVerifier>> = {};
const evmVerifiers: EvmVerifier[] = [];
for (const chain of Object.values(config.evm.enabled)) {
if (chain === undefined) continue;
const rpc = deps.evmRpcs?.[chain.key] ?? createChainRpc(chain.spec, chain.rpcUrl);
const built = buildEvm(chain, rpc);
evmVerifiers.push(built.primary);
verifiers[chain.key] = built.settlement;
}
if (config.solana) verifiers.solana = solanaVerifier(config.solana, deps.solanaRpc);
const zcash = config.zcash ? zcashRuntime(config.zcash, deps.fetch ?? (globalThis.fetch as FetchLike)) : null;
if (zcash) {
verifiers.zcash = createZcashSettlementVerifier({ explorer: zcash.explorer, minConfirmations: zcash.minConfirmations });
}
if (config.hypercore) {
const client = createHyperCoreClient(config.hypercore, deps.hypercoreTransport ? { transport: deps.hypercoreTransport } : {});
verifiers.hypercore = createHyperCoreSettlementVerifier(client);
}
return { verifiers, evmVerifiers, arcVerifier: verifiers.arc ?? null, zcash };
}

View File

@ -161,18 +161,10 @@ import {
PgAgentJobStore,
InMemoryAgentJobStore,
type AgentJobStore,
PgX402NonceStore,
} from "@settlekit/persistence";
import { loadConfig } from "./config/env.js";
import { buildIntegrations, type PaymentVerifiers, type ZcashRuntime } from "./config/integrations.js";
import type { EvmVerifier } from "@settlekit/chains";
import { buildIntegrations } from "./config/integrations.js";
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 {
@ -197,16 +189,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;
readonly licenses: LicenseService;
/** Raw license store (tenant ownership checks on single-license routes). */
readonly licenseStore: LicenseStore;
readonly files: FileDeliveryService;
// Authentication (account/session/magic-link) for the public /v1/auth routes.
@ -218,15 +204,6 @@ export interface AppContext {
// Integration clients (real when configured; null/in-memory otherwise).
readonly arcVerifier: PaymentVerifier | null;
/**
* On-chain payment verifiers per network. Payment confirm/observe FAIL
* CLOSED for a network with no verifier — a tx hash alone never settles.
*/
readonly verifiers: PaymentVerifiers;
/** Enabled EVM chain verifiers (boot asserts each RPC's chain id). */
readonly evmVerifiers: readonly EvmVerifier[];
/** Zcash quote/explorer services; null when ZCASH_ENABLED is unset. */
readonly zcash: ZcashRuntime | null;
/** Raw Arc client for verify / fee-estimate / confirmations. */
readonly arc: ArcClient | null;
readonly circle: CircleClient | null;
@ -303,12 +280,6 @@ export interface AppContext {
readonly payoutStore: PayoutStore;
/** Platform take-rate applied to merchant settlements (SettleKit revenue). */
readonly platformFeeSchedule: PlatformFeeSchedule;
/** x402 (every chain) + MPP (Tempo) agent payments; null when unconfigured. */
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. */
@ -420,11 +391,7 @@ 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"> = {
return {
db,
persistent: db !== null,
@ -440,14 +407,11 @@ export async function createContext(): Promise<AppContext> {
deliveryRuns: pick<EntityStore<DeliveryRun>>(db, (d) => new PgDeliveryRunStore(d), () => new InMemoryEntityStore<DeliveryRun>()),
deliveryRegistry: createDefaultRegistry(),
deliveryClients: integrations.deliveryClients,
webhookEndpoints: webhookEndpointStore,
webhookEvents: webhookEventStore,
webhookJobs,
webhookOutbox: createWebhookOutbox(db, webhookEndpointStore, webhookEventStore, webhookJobs),
webhookEndpoints: pick<EntityStore<WebhookEndpoint>>(db, (d) => new PgWebhookEndpointStore(d), () => new InMemoryEntityStore<WebhookEndpoint>()),
webhookEvents: pick<EntityStore<WebhookEvent>>(db, (d) => new PgWebhookEventStore(d), () => new InMemoryEntityStore<WebhookEvent>()),
apiKeys: new ApiKeyService(apiKeyStore),
licenses: new LicenseService(licenseStore, { tokenSecret: config.licenseTokenSecret }),
licenseStore,
files: new FileDeliveryService(grantStore, {
baseUrl: config.fileDelivery.baseUrl,
secret: config.fileDelivery.secret,
@ -482,9 +446,6 @@ export async function createContext(): Promise<AppContext> {
),
arcVerifier: integrations.arcVerifier,
verifiers: integrations.verifiers,
evmVerifiers: integrations.evmVerifiers,
zcash: integrations.zcash,
arc: integrations.arc,
circle: integrations.circle,
payoutExecutor: integrations.payoutExecutor,
@ -571,13 +532,7 @@ export async function createContext(): Promise<AppContext> {
payouts: new PayoutService(payoutStore, () => generateId("payoutWallet")),
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) };
}
/** Hono `Variables` binding: the context is attached to every request. */
@ -587,9 +542,5 @@ 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[];
};
}

View File

@ -1,77 +0,0 @@
/**
* 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

@ -1,74 +0,0 @@
/**
* 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,18 +47,9 @@ export function error(c: Context, err: unknown): Response {
err.httpStatus as ContentfulStatusCode,
);
}
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`,
);
const message = err instanceof Error ? err.message : "Unexpected error";
return c.json<ErrorEnvelope>(
{ error: { code: "internal_error", message: "Something went wrong on our side. Please try again." } },
{ error: { code: "internal_error", message } },
500,
);
}

View File

@ -10,7 +10,6 @@
* which the middleware binds explicitly.
*/
import type { Context } from "hono";
import { notFound, type Payment, type Subscription } from "@settlekit/common";
import { DEFAULT_ORG_ID } from "@settlekit/persistence";
import type { AppEnv } from "../context.js";
@ -18,65 +17,3 @@ import type { AppEnv } from "../context.js";
export function requireOrg(c: Context<AppEnv>): string {
return c.get("organizationId") ?? DEFAULT_ORG_ID;
}
/** Anything stamped with the tenant that owns it. */
export interface TenantOwned {
readonly organizationId: string;
}
/**
* Ownership guard for single-resource routes that load a record by an opaque
* id. Returns the record when it belongs to the authenticated org; otherwise
* throws `not_found` — deliberately 404, never 403, so a caller cannot probe
* which ids exist in other tenants.
*/
export function requireOwned<T extends TenantOwned>(
c: Context<AppEnv>,
resource: T | null | undefined,
label: string,
id: string,
): T {
if (!resource || resource.organizationId !== requireOrg(c)) {
throw notFound(`${label} not found`, { id });
}
return resource;
}
/** Whether `resource` belongs to the authenticated org (no throw). */
export function isOwned(c: Context<AppEnv>, resource: TenantOwned | null | undefined): boolean {
return resource !== null && resource !== undefined && resource.organizationId === requireOrg(c);
}
/**
* Load a payment by id and require it belongs to the caller's org. Used by the
* payment routes and by resources that hang off a payment (refunds, disputes).
*/
export async function requireOwnedPayment(c: Context<AppEnv>, paymentId: string): Promise<Payment> {
return requireOwned(c, await c.get("ctx").payments.findById(paymentId), "payment", paymentId);
}
/** Load a subscription by id, requiring it belongs to the caller's org. */
export async function ownedSubscription(c: Context<AppEnv>, subscriptionId: string): Promise<Subscription> {
return requireOwned(c, await c.get("ctx").subscriptions.findById(subscriptionId), "subscription", subscriptionId);
}
/** Ids of every payment owned by the caller's org (for scoping list reads). */
export async function ownedPaymentIds(c: Context<AppEnv>): Promise<Set<string>> {
const payments = await c.get("ctx").payments.listByOrganization(requireOrg(c));
return new Set(payments.map((p) => p.id));
}
/** Ids of every subscription owned by the caller's org (for scoping list reads). */
export async function ownedSubscriptionIds(c: Context<AppEnv>): Promise<Set<string>> {
const subs = await c.get("ctx").subscriptions.listByOrganization(requireOrg(c));
return new Set(subs.map((s) => s.id));
}
/** Keep only records stamped with the caller's org. */
export function scopeToOrg<T extends { readonly organizationId?: string | null }>(
c: Context<AppEnv>,
records: readonly T[],
): T[] {
const org = requireOrg(c);
return records.filter((r) => r.organizationId === org);
}

View File

@ -1,156 +0,0 @@
/**
* 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

@ -1,95 +0,0 @@
/**
* 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

@ -1,348 +0,0 @@
/**
* 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

@ -1,164 +0,0 @@
/**
* 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

@ -1,185 +0,0 @@
/**
* 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

@ -1,214 +0,0 @@
/**
* 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

@ -1,294 +0,0 @@
/**
* 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

@ -1,163 +0,0 @@
/**
* 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

@ -1,132 +0,0 @@
/**
* 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

@ -1,102 +0,0 @@
/**
* 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

@ -1,103 +0,0 @@
/**
* 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

@ -1,40 +0,0 @@
/**
* 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

@ -1,107 +0,0 @@
/**
* 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,58 +15,24 @@
* 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");
@ -79,23 +45,11 @@ 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;
}
@ -103,16 +57,6 @@ 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);
@ -132,22 +76,9 @@ 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

@ -1,73 +0,0 @@
/**
* Delivery for onchain subscriptions (API side): on the first successful
* charge and on reactivation, run the product's delivery actions (GitHub
* invite / team, Discord role, file grant, license / API key, ...) through the
* real handler registry — the same runner agent purchases use — and persist
* the run so POST /v1/delivery-runs/:id/retry can re-drive failed actions.
*
* Idempotent per charge: a run already recorded for the charge's payment id
* is never repeated.
*/
import { generateId, toIso, type DeliveryPlan, type Entitlement } from "@settlekit/common";
import { DeliveryRunner, deliveryActionsFor, type DeliveryContext } from "@settlekit/delivery";
import type { AccessDelivery } from "@settlekit/onchain-billing";
import type { AppContext } from "../context.js";
import { githubInstallationFor } from "../agent-payments/fulfil.js";
const INLINE_RETRY = { maxAttempts: 2, baseDelayMs: 250 } as const;
type DeliveryDeps = Omit<AppContext, "onchainBilling">;
/** The active entitlement for the subscription's product, granting one when missing. */
async function ensureEntitlement(ctx: DeliveryDeps, delivery: AccessDelivery): Promise<Entitlement | undefined> {
const sub = delivery.subscription;
const existing = (await ctx.entitlementRepo.listByCustomer(sub.customerId)).find(
(e) => e.productId === sub.productId && e.status === "active",
);
if (existing) return existing;
if (!sub.subscriptionId) return undefined;
const [subscription, product] = await Promise.all([ctx.subscriptions.findById(sub.subscriptionId), ctx.products.findById(sub.productId)]);
if (!subscription || !product) return undefined;
return ctx.entitlements.grantFromSubscription({ subscription, product });
}
export async function deliverOnchainSubscription(ctx: DeliveryDeps, delivery: AccessDelivery): Promise<void> {
const sub = delivery.subscription;
const product = await ctx.products.findById(sub.productId);
if (!product) return;
const actions = deliveryActionsFor(product);
if (actions.length === 0) return;
const already = await ctx.deliveryRuns.list((run) => run.paymentId === delivery.paymentId);
if (already.length > 0) return;
const entitlement = await ensureEntitlement(ctx, delivery);
if (!entitlement) throw new Error(`no entitlement to deliver against for ${sub.id}`);
const customer = await ctx.customers.findById(sub.customerId);
const needsGithub = actions.some((action) => action.type === "github_invite" || action.type === "github_team_add");
const githubInstallationId = needsGithub ? await githubInstallationFor(ctx, product) : undefined;
const email = customer?.email || sub.customerEmail;
const plan: DeliveryPlan = {
id: generateId("deliveryPlan"),
organizationId: sub.organizationId,
productId: product.id,
actions,
createdAt: toIso(new Date()),
};
const deliveryCtx: DeliveryContext = {
organizationId: sub.organizationId,
customerId: sub.customerId,
productId: product.id,
paymentId: delivery.paymentId,
entitlementId: entitlement.id,
...(githubInstallationId !== undefined ? { githubInstallationId } : {}),
...(customer?.githubUsername ? { githubUsername: customer.githubUsername } : {}),
...(customer?.discordUserId ? { discordUserId: customer.discordUserId } : {}),
...(email ? { customerEmail: email } : {}),
emailVariables: { reason: delivery.reason, onchainSubscriptionId: sub.id },
clients: ctx.deliveryClients,
};
const runner = new DeliveryRunner(ctx.deliveryRegistry, { retry: INLINE_RETRY });
const run = await runner.run(plan, deliveryCtx, { paymentId: delivery.paymentId, customerId: sub.customerId });
await ctx.deliveryRuns.save(run);
}

View File

@ -1,86 +0,0 @@
/**
* API-side onchain billing: the shared @settlekit/onchain-billing runtime over
* the API's stores (Postgres when DATABASE_URL is set — the SAME tables the
* worker's subscription-charge job reads), with access hooks writing the
* API's subscription / entitlement / payment repositories. The API charges
* period 0 right after a grant is accepted; the worker charges the rest.
*/
import { DunningService } from "@settlekit/dunning";
import {
InMemoryOnchainBillingStore,
buildOnchainBilling,
createAccessHooks,
type OnchainBillingRuntime,
} from "@settlekit/onchain-billing";
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";
export async function buildApiOnchainBilling(
ctx: Omit<AppContext, "onchainBilling">,
env: Readonly<Record<string, string | undefined>> = process.env,
): Promise<OnchainBillingRuntime | null> {
const hooks = createAccessHooks({
async getSubscription(id) {
return (await ctx.subscriptions.findById(id)) ?? undefined;
},
async saveSubscription(subscription) {
await ctx.subscriptions.save(subscription);
},
async entitlementsFor(customerId, productId) {
return (await ctx.entitlementRepo.listByCustomer(customerId)).filter((e) => e.productId === productId);
},
async saveEntitlement(entitlement) {
await ctx.entitlementRepo.save(entitlement);
},
async savePayment(payment) {
await ctx.payments.save(payment);
},
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),
});
const hypercoreRefunds = hyperCoreRefundSender(env);
return buildOnchainBilling({
env,
store: ctx.db ? new PgOnchainBillingStore(ctx.db) : new InMemoryOnchainBillingStore(),
dunning: new DunningService(ctx.dunningStore),
checkouts: ctx.checkouts,
email: ctx.email,
merchantId: DEFAULT_MERCHANT_ID,
hooks,
...(hypercoreRefunds ? { hypercoreRefunds } : {}),
});
}
/**
* HyperCore refunds: an operator-signed `usdSend` from the onchain billing
* operator key (HYPERCORE_REFUND_PRIVATE_KEY overrides it), when HyperCore is
* enabled. The account must hold USDC on HyperCore to refund from.
*/
function hyperCoreRefundSender(env: Readonly<Record<string, string | undefined>>): HyperCoreUsdSender | undefined {
const config = loadHyperCoreConfig(env);
const key = env.HYPERCORE_REFUND_PRIVATE_KEY?.trim() || env.ONCHAIN_BILLING_OPERATOR_PRIVATE_KEY?.trim();
if (!config || !key) return undefined;
if (!/^0x[0-9a-fA-F]{64}$/.test(key)) throw new Error("HYPERCORE_REFUND_PRIVATE_KEY must be a 0x-prefixed 32-byte hex key");
return createHyperCoreUsdSender({ client: createHyperCoreClient(config), privateKey: key as `0x${string}` });
}

View File

@ -1,123 +0,0 @@
/**
* 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

@ -1,109 +0,0 @@
/**
* 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

@ -1,29 +0,0 @@
/**
* 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

@ -1,131 +0,0 @@
/**
* 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

@ -1,339 +0,0 @@
/**
* 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

@ -1,48 +0,0 @@
/**
* 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

@ -9,14 +9,13 @@
* POST /v1/agent-services/:id/publish
* GET /v1/agent-services/:id/metadata.json — machine-readable metadata
*/
import { Hono, type Context } from "hono";
import type { AgentService } from "@settlekit/common";
import { Hono } from "hono";
import { z } from "zod";
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 } from "../http/tenant.js";
import { requireOrg } from "../http/tenant.js";
const createSchema = z.object({
// Derived from the authenticated org (tenant scope); ignored if supplied.
@ -39,12 +38,6 @@ const patchSchema = z.object({
price: z.string().regex(/^\d+(\.\d+)?$/).optional(),
});
/** Load an agent service by id, requiring it belongs to the caller's org (else 404). */
async function ownedService(c: Context<AppEnv>, id: string): Promise<AgentService> {
const found = await c.get("ctx").agentServices.get(id);
return requireOwned(c, found.ok ? found.value : undefined, "agent service", id);
}
export function agentServiceRoutes(): Hono<AppEnv> {
const app = new Hono<AppEnv>();
@ -74,13 +67,14 @@ export function agentServiceRoutes(): Hono<AppEnv> {
});
app.get("/:id", async (c) => {
return data(c, await ownedService(c, c.req.param("id")));
const svc = unwrapResult(await c.get("ctx").agentServices.get(c.req.param("id")));
return data(c, svc);
});
// Patch mutable fields, persisting through the store.
app.patch("/:id", async (c) => {
const ctx = c.get("ctx");
const current = await ownedService(c, c.req.param("id"));
const current = unwrapResult(await ctx.agentServices.get(c.req.param("id")));
const body = await parseBody(c, patchSchema);
const updated = {
...current,
@ -93,15 +87,13 @@ export function agentServiceRoutes(): Hono<AppEnv> {
});
app.post("/:id/publish", async (c) => {
const { id } = await ownedService(c, c.req.param("id"));
const svc = unwrapResult(await c.get("ctx").agentServices.publish(id));
const svc = unwrapResult(await c.get("ctx").agentServices.publish(c.req.param("id")));
return data(c, svc);
});
// Machine-readable metadata document (plan §11). Served as raw JSON, not enveloped.
app.get("/:id/metadata.json", async (c) => {
const { id } = await ownedService(c, c.req.param("id"));
const metadata = unwrapResult(await c.get("ctx").agentServices.metadata(id));
const metadata = unwrapResult(await c.get("ctx").agentServices.metadata(c.req.param("id")));
return c.json(metadata);
});

View File

@ -25,7 +25,6 @@ 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;
@ -114,34 +113,6 @@ 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,8 +8,6 @@
*/
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";
@ -34,70 +32,17 @@ 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 the organization's key records (never exposes plaintext).
// List all API key records (merchant-wide; never exposes plaintext).
app.get("/", async (c) => {
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))));
return data(c, await c.get("ctx").apiKeys.list());
});
// 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,11 +25,8 @@ 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";
@ -41,7 +38,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_KEY_PRODUCT;
const PLATFORM_SENTINEL = "__platform__";
const BEARER_RE = /^Bearer\s+(.+)$/i;
@ -81,13 +78,6 @@ 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(),
});
@ -131,11 +121,9 @@ 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.type === "merchant" ? generateId("organization") : body.organizationId;
body.organizationId ??
(body.type === "merchant" ? generateId("organization") : undefined);
const account: Account = unwrapResult(
await ctx.auth.registerWithPassword({
@ -289,62 +277,6 @@ 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

@ -1,67 +0,0 @@
/**
* 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

@ -9,14 +9,14 @@
* GET/PATCH /v1/bundles/:id
* POST /v1/bundles/:id/publish
*/
import { Hono, type Context } from "hono";
import { Hono } from "hono";
import { z } from "zod";
import { money, type Bundle, type Money } from "@settlekit/common";
import { money, type Money } from "@settlekit/common";
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 } from "../http/tenant.js";
import { requireOrg } from "../http/tenant.js";
const createSchema = z.object({
merchantId: z.string().min(1),
@ -35,12 +35,6 @@ const patchSchema = z.object({
status: z.enum(["draft", "active", "archived"]).optional(),
});
/** Load a bundle by id, requiring it belongs to the caller's org (else 404). */
async function ownedBundle(c: Context<AppEnv>, id: string): Promise<Bundle> {
const found = await c.get("ctx").bundles.getBundle(id);
return requireOwned(c, found.ok ? found.value : undefined, "bundle", id);
}
export function bundleRoutes(): Hono<AppEnv> {
const app = new Hono<AppEnv>();
@ -69,13 +63,14 @@ export function bundleRoutes(): Hono<AppEnv> {
});
app.get("/:id", async (c) => {
return data(c, await ownedBundle(c, c.req.param("id")));
const bundle = unwrapResult(await c.get("ctx").bundles.getBundle(c.req.param("id")));
return data(c, bundle);
});
// Patch mutable bundle fields (immutably persisted through the store).
app.patch("/:id", async (c) => {
const ctx = c.get("ctx");
const current = await ownedBundle(c, c.req.param("id"));
const current = unwrapResult(await ctx.bundles.getBundle(c.req.param("id")));
const body = await parseBody(c, patchSchema);
if (body.status === "archived") {
return data(c, unwrapResult(await ctx.bundles.archiveBundle(current.id)));
@ -92,7 +87,7 @@ export function bundleRoutes(): Hono<AppEnv> {
app.post("/:id/publish", async (c) => {
const ctx = c.get("ctx");
const current = await ownedBundle(c, c.req.param("id"));
const current = unwrapResult(await ctx.bundles.getBundle(c.req.param("id")));
const published = {
...current,
status: "active" as const,

View File

@ -7,10 +7,9 @@
* Buyer delivery fields can be merged with `collectFields`; sessions can be
* canceled/expired through the pure transition functions.
*/
import { Hono, type Context } from "hono";
import { Hono } from "hono";
import { z } from "zod";
import { validationError, PAYMENT_NETWORKS, type CheckoutSession, type PaymentNetwork } from "@settlekit/common";
import { checkPayTo } from "@settlekit/chains";
import { notFound, validationError, type PaymentNetwork } from "@settlekit/common";
import {
cancelSession,
collectFields,
@ -18,18 +17,12 @@ import {
expireSession,
type PricedLineItem,
} from "@settlekit/payments";
import { createReference } from "@settlekit/solana";
import type { AppContext, AppEnv } from "../context.js";
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 { 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";
import { requireOrg } from "../http/tenant.js";
const NETWORKS = PAYMENT_NETWORKS as unknown as readonly [PaymentNetwork, ...PaymentNetwork[]];
const NETWORKS = ["arc", "base", "ethereum"] as const;
const lineItemSchema = z.object({
priceId: z.string().min(1),
@ -38,104 +31,36 @@ const lineItemSchema = z.object({
quantity: z.number().int().positive().default(1),
});
const createSchema = z
.object({
// Derived from the authenticated org (tenant scope); ignored if supplied.
organizationId: z.string().min(1).optional(),
merchantId: z.string().min(1),
customerId: z.string().optional(),
items: z.array(lineItemSchema).min(1),
payToAddress: z.string().min(1),
network: z.enum(NETWORKS),
/** Networks the buyer may pick from; must include `network`. */
acceptedNetworks: z.array(z.enum(NETWORKS)).min(1).optional(),
/** Per-network payTo (e.g. a Solana wallet and an EVM wallet). */
payToByNetwork: z.record(z.enum(NETWORKS), z.string().min(1)).optional(),
/** Tempo: only accept transferWithMemo(keccak256(session id)) payments. */
requireMemo: z.boolean().optional(),
successUrl: z.string().url().optional(),
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
// sent to a malformed address are unrecoverable, and verification matches
// the recipient exactly.
const accepted = body.acceptedNetworks ?? [body.network];
if (!accepted.includes(body.network)) {
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["acceptedNetworks"], message: "must include network" });
}
if (new Set(accepted).size !== accepted.length) {
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["acceptedNetworks"], message: "must not repeat a network" });
}
for (const network of accepted) {
const payTo = body.payToByNetwork?.[network] ?? body.payToAddress;
const check = checkPayTo(network, payTo);
if (!check.ok) {
const path = body.payToByNetwork?.[network] !== undefined ? ["payToByNetwork", network] : ["payToAddress"];
ctx.addIssue({ code: z.ZodIssueCode.custom, path, message: check.reason });
}
}
if (body.requireMemo === true && !accepted.includes("tempo")) {
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["requireMemo"], message: "requireMemo applies to Tempo; accept tempo or drop it" });
}
for (const network of Object.keys(body.payToByNetwork ?? {}) as PaymentNetwork[]) {
if (!accepted.includes(network)) {
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["payToByNetwork", network], message: "network is not accepted" });
}
}
});
/**
* Attach per-network payment bindings: a Solana Pay reference when Solana is
* payable (the paying tx must include it) and a locked ZEC quote when Zcash
* is payable (the buyer owes exactly that many zatoshis).
*/
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;
const payTo = payToFor(withReference, "zcash");
const zcashNetwork = ctx.zcash?.network ?? "mainnet";
const check = checkPayTo("zcash", payTo, { zcashNetwork });
if (!check.ok) throw validationError(`invalid Zcash payTo: ${check.reason}`, { network: "zcash" });
const settlementQuote = await lockZcashQuoteFor(ctx, withReference);
return { ...withReference, settlementQuote };
}
const createSchema = z.object({
// Derived from the authenticated org (tenant scope); ignored if supplied.
organizationId: z.string().min(1).optional(),
merchantId: z.string().min(1),
customerId: z.string().optional(),
items: z.array(lineItemSchema).min(1),
payToAddress: z.string().min(1),
network: z.enum(NETWORKS),
successUrl: z.string().url().optional(),
cancelUrl: z.string().url().optional(),
collectedFields: z.record(z.string()).optional(),
ttlDays: z.number().int().positive().optional(),
});
const collectSchema = z.object({
fields: z.record(z.string()),
});
/** Load the `:id` checkout session, requiring it belongs to the caller's org. */
async function ownedSession(c: Context<AppEnv>): Promise<CheckoutSession> {
const id = c.req.param("id") ?? "";
return requireOwned(c, await c.get("ctx").checkouts.findById(id), "checkout session", id);
}
export function checkoutRoutes(): Hono<AppEnv> {
const app = new Hono<AppEnv>();
app.post("/", async (c) => {
const ctx = c.get("ctx");
const body = await parseBody(c, createSchema);
const org = requireOrg(c);
// Resolve each line item's Price from the price store for total math. A
// price is only usable by the org owning its product; another tenant's
// price is reported exactly like a missing one (no existence leak).
// Resolve each line item's Price from the price store for total math.
const priced: PricedLineItem[] = await Promise.all(
body.items.map(async (item) => {
const price = await ctx.prices.findById(item.priceId);
const product = price ? await ctx.products.findById(price.productId) : undefined;
if (!price || product?.organizationId !== org) {
if (!price) {
throw validationError(`price not found: ${item.priceId}`, { priceId: item.priceId });
}
return {
@ -150,13 +75,11 @@ 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,
const session = createCheckoutSession({
organizationId: requireOrg(c),
merchantId: body.merchantId,
...(body.customerId !== undefined ? { customerId: body.customerId } : {}),
items: fx.items,
items: priced,
payToAddress: body.payToAddress,
network: body.network as PaymentNetwork,
...(body.successUrl !== undefined ? { successUrl: body.successUrl } : {}),
@ -164,40 +87,22 @@ 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, {
...taxed,
...(body.acceptedNetworks !== undefined ? { acceptedNetworks: body.acceptedNetworks } : {}),
...(body.payToByNetwork !== undefined ? { payToByNetwork: body.payToByNetwork } : {}),
...(body.requireMemo === true ? { requireMemo: true } : {}),
});
// Zcash: the amount tag is chosen + saved atomically per payTo.
const saved =
session.settlementQuote !== undefined
? await saveZcashSession(ctx, { ...session, settlementQuote: session.settlementQuote }, payToFor(session, "zcash"))
: await ctx.checkouts.save(session);
const saved = await ctx.checkouts.save(session);
return created(c, saved);
});
// Single-session routes are owner-only (another org's id answers 404). The
// buyer-facing checkout app reads sessions straight from the store by their
// capability id and does not go through these merchant API routes.
app.get("/:id", async (c) => {
return data(c, await ownedSession(c));
const session = await c.get("ctx").checkouts.findById(c.req.param("id"));
if (!session) throw notFound("checkout session not found", { id: c.req.param("id") });
return data(c, session);
});
// Merge buyer-supplied delivery fields into an open session.
app.post("/:id/collect-fields", async (c) => {
const ctx = c.get("ctx");
const session = await ownedSession(c);
const session = await ctx.checkouts.findById(c.req.param("id"));
if (!session) throw notFound("checkout session not found", { id: c.req.param("id") });
const body = await parseBody(c, collectSchema);
const updated = await ctx.checkouts.save(collectFields(session, body.fields));
return data(c, updated);
@ -205,13 +110,15 @@ export function checkoutRoutes(): Hono<AppEnv> {
app.post("/:id/cancel", async (c) => {
const ctx = c.get("ctx");
const session = await ownedSession(c);
const session = await ctx.checkouts.findById(c.req.param("id"));
if (!session) throw notFound("checkout session not found", { id: c.req.param("id") });
return data(c, await ctx.checkouts.save(cancelSession(session)));
});
app.post("/:id/expire", async (c) => {
const ctx = c.get("ctx");
const session = await ownedSession(c);
const session = await ctx.checkouts.findById(c.req.param("id"));
if (!session) throw notFound("checkout session not found", { id: c.req.param("id") });
return data(c, await ctx.checkouts.save(expireSession(session)));
});

View File

@ -10,14 +10,12 @@
*/
import { Hono } from "hono";
import { z } from "zod";
import { money, notFound, type Money } from "@settlekit/common";
import { normalizeCouponCode, type Coupon, type CouponDiscount } from "@settlekit/coupons";
import type { Context } from "hono";
import { money, type Money } from "@settlekit/common";
import type { CouponDiscount } from "@settlekit/coupons";
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 } from "../http/tenant.js";
const amount = z.string().regex(/^\d+(\.\d+)?$/);
@ -51,18 +49,6 @@ function toDiscount(input: z.infer<typeof discountSchema>): CouponDiscount {
return { type: "free-trial-days", days: input.days };
}
/**
* Load a coupon by code, requiring it belongs to the caller's org. Legacy
* coupons with no owner and other tenants' coupons answer 404.
*/
async function ownedCoupon(c: Context<AppEnv>, code: string): Promise<Coupon> {
const coupon = unwrapResult(await c.get("ctx").coupons.get(code));
if (!coupon.organizationId || coupon.organizationId !== requireOrg(c)) {
throw notFound(`Coupon ${normalizeCouponCode(code)} not found`);
}
return coupon;
}
export function couponRoutes(): Hono<AppEnv> {
const app = new Hono<AppEnv>();
@ -72,7 +58,6 @@ export function couponRoutes(): Hono<AppEnv> {
const coupon = unwrapResult(
await c.get("ctx").coupons.create({
code: body.code,
organizationId: requireOrg(c),
...(body.name !== undefined ? { name: body.name } : {}),
discount: toDiscount(body.discount),
...(body.status !== undefined ? { status: body.status } : {}),
@ -88,18 +73,17 @@ export function couponRoutes(): Hono<AppEnv> {
});
app.get("/", async (c) => {
const org = requireOrg(c);
const coupons = await c.get("ctx").coupons.list((co) => co.organizationId === org);
const coupons = await c.get("ctx").coupons.list();
return data(c, coupons);
});
app.get("/:code", async (c) => {
return data(c, await ownedCoupon(c, c.req.param("code")));
const coupon = unwrapResult(await c.get("ctx").coupons.get(c.req.param("code")));
return data(c, coupon);
});
app.post("/:code/validate", async (c) => {
const body = await parseBody(c, applySchema);
await ownedCoupon(c, c.req.param("code"));
const result = unwrapResult(
await c.get("ctx").coupons.validate(c.req.param("code"), money(body.subtotal), {
...(body.customerId !== undefined ? { customerId: body.customerId } : {}),
@ -110,7 +94,6 @@ export function couponRoutes(): Hono<AppEnv> {
app.post("/:code/redeem", async (c) => {
const body = await parseBody(c, applySchema);
await ownedCoupon(c, c.req.param("code"));
const outcome = unwrapResult(
await c.get("ctx").coupons.redeem(c.req.param("code"), money(body.subtotal), {
...(body.customerId !== undefined ? { customerId: body.customerId } : {}),

View File

@ -6,11 +6,11 @@
*/
import { Hono } from "hono";
import { z } from "zod";
import { generateId, type Customer } from "@settlekit/common";
import { generateId, notFound, type Customer } from "@settlekit/common";
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 { requireOrg } from "../http/tenant.js";
const createCustomerSchema = z.object({
// Derived from the authenticated org (tenant scope); ignored if supplied.
@ -49,8 +49,9 @@ export function customerRoutes(): Hono<AppEnv> {
});
app.get("/:id", async (c) => {
const id = c.req.param("id");
return data(c, requireOwned(c, await c.get("ctx").customers.findById(id), "customer", id));
const customer = await c.get("ctx").customers.findById(c.req.param("id"));
if (!customer) throw notFound("customer not found", { id: c.req.param("id") });
return data(c, customer);
});
return app;

View File

@ -24,7 +24,7 @@ import type { DeliveryContext as RunnerContext } from "@settlekit/delivery";
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 { requireOrg } from "../http/tenant.js";
// Zod schema for the discriminated DeliveryAction union (plan §15).
const actionSchema = z.discriminatedUnion("type", [
@ -69,15 +69,16 @@ export function deliveryRunRoutes(): Hono<AppEnv> {
});
app.get("/:id", async (c) => {
const id = c.req.param("id");
return data(c, requireOwned(c, await c.get("ctx").deliveryRuns.findById(id), "delivery run", id));
const run = await c.get("ctx").deliveryRuns.findById(c.req.param("id"));
if (!run) throw notFound("delivery run not found", { id: c.req.param("id") });
return data(c, run);
});
// Retry the failed actions of a run by marking them pending again.
app.post("/:id/retry", async (c) => {
const ctx = c.get("ctx");
const id = c.req.param("id");
const run = requireOwned(c, await ctx.deliveryRuns.findById(id), "delivery run", id);
const run = await ctx.deliveryRuns.findById(c.req.param("id"));
if (!run) throw notFound("delivery run not found", { id: c.req.param("id") });
const actionRuns: DeliveryActionRun[] = run.actionRuns.map((ar) =>
ar.status === "failed" ? { ...ar, status: "pending", attempts: ar.attempts } : ar,
);

View File

@ -15,9 +15,6 @@ 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 { isOwned, ownedPaymentIds, requireOwnedPayment } from "../http/tenant.js";
import type { Context } from "hono";
import type { Dispute } from "@settlekit/disputes";
const openSchema = z.object({
paymentId: z.string().min(1),
@ -35,26 +32,11 @@ const resolveSchema = z.object({
outcome: z.enum(["won", "lost", "refunded"]),
});
/**
* Load a dispute by id, requiring its payment belongs to the caller's org. A
* foreign dispute answers 404 exactly like a missing one.
*/
async function ownedDispute(c: Context<AppEnv>, id: string): Promise<Dispute> {
const ctx = c.get("ctx");
const dispute = await ctx.disputes.get(id);
if (!dispute || !isOwned(c, await ctx.payments.findById(dispute.paymentId))) {
throw notFound(`dispute ${id} not found`, { id });
}
return dispute;
}
export function disputeRoutes(): Hono<AppEnv> {
const app = new Hono<AppEnv>();
app.post("/", async (c) => {
const body = await parseBody(c, openSchema);
// Tenant-scoped: disputes can only be opened on the caller's own payments.
await requireOwnedPayment(c, body.paymentId);
const dispute = unwrapResult(
await c.get("ctx").disputes.open({
paymentId: body.paymentId,
@ -68,28 +50,28 @@ export function disputeRoutes(): Hono<AppEnv> {
app.get("/", async (c) => {
const ctx = c.get("ctx");
const status = c.req.query("status");
// Tenant-scoped: a dispute is visible only when its payment is ours.
const owned = await ownedPaymentIds(c);
const source =
status === "open" || status === "under_review"
? await ctx.disputes.listOpen()
: await ctx.disputeStore.listAll();
const mine = source.filter((d) => owned.has(d.paymentId));
if (status && status !== "open" && status !== "under_review") {
return data(c, mine.filter((d) => d.status === status));
if (status === "open" || status === "under_review") {
return data(c, await ctx.disputes.listOpen());
}
return data(c, mine);
const all = await ctx.disputeStore.listAll();
if (status) {
return data(c, all.filter((d) => d.status === status));
}
return data(c, all);
});
app.get("/:id", async (c) => {
return data(c, await ownedDispute(c, c.req.param("id")));
const dispute = await c.get("ctx").disputes.get(c.req.param("id"));
if (!dispute) {
throw notFound(`dispute ${c.req.param("id")} not found`);
}
return data(c, dispute);
});
app.post("/:id/evidence", async (c) => {
const { id } = await ownedDispute(c, c.req.param("id"));
const body = await parseBody(c, evidenceSchema);
const dispute = unwrapResult(
await c.get("ctx").disputes.submitEvidence(id, {
await c.get("ctx").disputes.submitEvidence(c.req.param("id"), {
kind: body.kind,
description: body.description,
value: body.value,
@ -99,9 +81,8 @@ export function disputeRoutes(): Hono<AppEnv> {
});
app.post("/:id/resolve", async (c) => {
const { id } = await ownedDispute(c, c.req.param("id"));
const body = await parseBody(c, resolveSchema);
const dispute = unwrapResult(await c.get("ctx").disputes.resolve(id, body.outcome));
const dispute = unwrapResult(await c.get("ctx").disputes.resolve(c.req.param("id"), body.outcome));
return data(c, dispute);
});

View File

@ -13,7 +13,6 @@ 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 { ownedSubscription, ownedSubscriptionIds } from "../http/tenant.js";
const startSchema = z.object({
subscriptionId: z.string().min(1),
@ -29,8 +28,6 @@ export function dunningRoutes(): Hono<AppEnv> {
app.post("/", async (c) => {
const body = await parseBody(c, startSchema);
// Tenant-scoped: only the caller's own subscriptions can enter dunning.
await ownedSubscription(c, body.subscriptionId);
const state = unwrapResult(await c.get("ctx").dunning.start(body.subscriptionId));
return created(c, state);
});
@ -38,15 +35,13 @@ export function dunningRoutes(): Hono<AppEnv> {
app.get("/", async (c) => {
const ctx = c.get("ctx");
const due = c.req.query("due");
// Tenant-scoped: only campaigns for the caller's own subscriptions.
const owned = await ownedSubscriptionIds(c);
const campaigns =
due === "true" || due === "1" ? await ctx.dunning.listDue() : await ctx.dunning.listActive();
return data(c, campaigns.filter((d) => owned.has(d.subscriptionId)));
if (due === "true" || due === "1") {
return data(c, await ctx.dunning.listDue());
}
return data(c, await ctx.dunning.listActive());
});
app.post("/:subscriptionId/attempt", async (c) => {
await ownedSubscription(c, c.req.param("subscriptionId"));
const body = await parseBody(c, attemptSchema);
// A "recovered" outcome closes the campaign; "failed" advances/exhausts it.
const ctx = c.get("ctx");
@ -62,7 +57,6 @@ export function dunningRoutes(): Hono<AppEnv> {
});
app.post("/:subscriptionId/recover", async (c) => {
await ownedSubscription(c, c.req.param("subscriptionId"));
const state = unwrapResult(await c.get("ctx").dunning.recover(c.req.param("subscriptionId")));
return data(c, state);
});

View File

@ -8,32 +8,19 @@
import { Hono } from "hono";
import type { Context } from "hono";
import { z } from "zod";
import { notFound, type Entitlement } from "@settlekit/common";
import { notFound } from "@settlekit/common";
import type { AppEnv } from "../context.js";
import { data } from "../http/respond.js";
import { parseBody, validate } from "../http/validate.js";
import { requireOrg, requireOwned, scopeToOrg } from "../http/tenant.js";
const verifySchema = z
.object({
customerId: z.string().min(1).optional(),
/** Check by the buyer's checkout email instead of a customer id. */
email: z.string().email().optional(),
customerId: z.string().min(1),
productId: z.string().optional(),
feature: z.string().optional(),
requiredCredits: z.number().int().positive().optional(),
})
.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);
}
.strict();
const spendSchema = z.object({
customerId: z.string().min(1),
@ -52,30 +39,20 @@ export function entitlementRoutes(): Hono<AppEnv> {
app.get("/", async (c) => {
const ctx = c.get("ctx");
const customerId = c.req.query("customerId");
const email = c.req.query("email");
if (!customerId && !email) throw notFound("customerId or email query param is required");
if (!customerId) throw notFound("customerId query param is required");
const activeOnly = c.req.query("activeOnly") === "true";
const productId = c.req.query("productId");
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()));
const list = await ctx.entitlementRepo.listByCustomer(customerId, {
activeOnly,
...(productId !== undefined ? { productId } : {}),
});
return data(c, list);
});
// Verify access (feature / credits / product), scoped to the caller's org.
// Verify access (feature / credits / product).
app.post("/verify", async (c) => {
const body = await parseBody(c, verifySchema);
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;
}
const result = await c.get("ctx").entitlements.verify(body);
return data(c, result);
});
@ -92,26 +69,22 @@ export function entitlementRoutes(): Hono<AppEnv> {
});
app.get("/:id", async (c) => {
return data(c, await ownedEntitlement(c, c.req.param("id")));
const ent = await c.get("ctx").entitlementRepo.findById(c.req.param("id"));
if (!ent) throw notFound("entitlement not found", { id: c.req.param("id") });
return data(c, ent);
});
// Revoke an entitlement.
app.post("/:id/revoke", async (c) => {
const ctx = c.get("ctx");
const entitlement = await ownedEntitlement(c, c.req.param("id"));
const body = validate(revokeSchema, await safeJson(c));
const revoked = await ctx.entitlements.revoke(entitlement.id, body.reason);
const revoked = await ctx.entitlements.revoke(c.req.param("id"), body.reason);
return data(c, revoked);
});
return app;
}
/** Load an entitlement by id, requiring it belongs to the caller's org (else 404). */
async function ownedEntitlement(c: Context<AppEnv>, id: string): Promise<Entitlement> {
return requireOwned(c, await c.get("ctx").entitlementRepo.findById(id), "entitlement", id);
}
/** Read a JSON body that may be empty, returning `{}` when absent. */
async function safeJson(c: Context<AppEnv>): Promise<unknown> {
try {
@ -120,4 +93,3 @@ async function safeJson(c: Context<AppEnv>): Promise<unknown> {
return {};
}
}

View File

@ -12,17 +12,15 @@
*
* (assign / release / dispute are also exposed for a complete lifecycle.)
*/
import { Hono, type Context } from "hono";
import { Hono } from "hono";
import { z } from "zod";
import type { EscrowTask } from "@settlekit/common";
import { notFound } from "@settlekit/common";
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";
const createSchema = z.object({
// Derived from the authenticated org (tenant scope); ignored if supplied.
organizationId: z.string().min(1).optional(),
organizationId: z.string().min(1),
buyerCustomerId: z.string().min(1),
title: z.string().min(1),
description: z.string().min(1),
@ -36,19 +34,13 @@ const submitSchema = z.object({ content: z.string().min(1) });
const releaseSchema = z.object({ releaseTxHash: z.string().min(1) });
const refundSchema = z.object({ reason: z.string().min(1).default("refunded via API") });
/** Load the `:id` escrow task, requiring it belongs to the caller's org (else 404). */
async function ownedTask(c: Context<AppEnv>): Promise<EscrowTask> {
const id = c.req.param("id") ?? "";
return requireOwned(c, await c.get("ctx").escrow.getTask(id), "escrow task", id);
}
export function escrowRoutes(): Hono<AppEnv> {
const app = new Hono<AppEnv>();
app.post("/tasks", async (c) => {
const body = await parseBody(c, createSchema);
const task = await c.get("ctx").escrow.createTask({
organizationId: requireOrg(c),
organizationId: body.organizationId,
buyerCustomerId: body.buyerCustomerId,
title: body.title,
description: body.description,
@ -58,49 +50,45 @@ export function escrowRoutes(): Hono<AppEnv> {
return created(c, task);
});
// Tenant-scoped: only the authenticated org's tasks (any organizationId
// query param is ignored).
app.get("/tasks", async (c) => {
return data(c, await c.get("ctx").escrow.listTasks(requireOrg(c)));
const orgId = c.req.query("organizationId");
if (!orgId) throw notFound("organizationId query param is required");
return data(c, await c.get("ctx").escrow.listTasks(orgId));
});
app.get("/tasks/:id", async (c) => {
return data(c, await ownedTask(c));
const task = await c.get("ctx").escrow.getTask(c.req.param("id"));
if (!task) throw notFound("escrow task not found", { id: c.req.param("id") });
return data(c, task);
});
app.post("/tasks/:id/fund", async (c) => {
const { id } = await ownedTask(c);
const body = await parseBody(c, fundSchema);
return data(c, await c.get("ctx").escrow.fundTask(id, body.fundingTxHash));
return data(c, await c.get("ctx").escrow.fundTask(c.req.param("id"), body.fundingTxHash));
});
app.post("/tasks/:id/assign", async (c) => {
const { id } = await ownedTask(c);
const body = await parseBody(c, assignSchema);
return data(c, await c.get("ctx").escrow.assignWorker(id, body.workerCustomerId));
return data(c, await c.get("ctx").escrow.assignWorker(c.req.param("id"), body.workerCustomerId));
});
app.post("/tasks/:id/submit", async (c) => {
const { id } = await ownedTask(c);
const body = await parseBody(c, submitSchema);
return data(c, await c.get("ctx").escrow.submitWork(id, body.content));
return data(c, await c.get("ctx").escrow.submitWork(c.req.param("id"), body.content));
});
app.post("/tasks/:id/approve", async (c) => {
const { id } = await ownedTask(c);
return data(c, await c.get("ctx").escrow.approve(id));
return data(c, await c.get("ctx").escrow.approve(c.req.param("id")));
});
app.post("/tasks/:id/release", async (c) => {
const { id } = await ownedTask(c);
const body = await parseBody(c, releaseSchema);
return data(c, await c.get("ctx").escrow.release(id, body.releaseTxHash));
return data(c, await c.get("ctx").escrow.release(c.req.param("id"), body.releaseTxHash));
});
app.post("/tasks/:id/refund", async (c) => {
const { id } = await ownedTask(c);
const body = await parseBody(c, refundSchema);
return data(c, await c.get("ctx").escrow.refund(id, body.reason));
return data(c, await c.get("ctx").escrow.refund(c.req.param("id"), body.reason));
});
return app;

View File

@ -1,262 +0,0 @@
/**
* 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,31 +9,16 @@
* 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 { Hono } from "hono";
import { z } from "zod";
import { generateId, money, validationError } from "@settlekit/common";
import { renderInvoicePdf } from "@settlekit/invoices";
import type { Invoice, InvoiceLineItem } from "@settlekit/invoices";
import { money } from "@settlekit/common";
import type { 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";
import { requireOrg } from "../http/tenant.js";
const amount = z.string().regex(/^\d+(\.\d+)?$/);
@ -60,51 +45,10 @@ 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) };
}
/** 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);
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> {
const app = new Hono<AppEnv>();
@ -126,100 +70,42 @@ export function invoiceRoutes(): Hono<AppEnv> {
}
: {}),
...(body.dueAt !== undefined ? { dueAt: body.dueAt } : {}),
...(body.metadata !== undefined ? { metadata: withoutReservedMetadata(body.metadata) } : {}),
...(body.metadata !== undefined ? { metadata: 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 = 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"`,
});
const invoices = await c.get("ctx").invoices.list(customerId ?? undefined);
return data(c, invoices);
});
// `:id.html` must be matched before the bare `:id` route below.
app.get("/:id{.+\\.html}", async (c) => {
const { id } = await ownedInvoice(c, c.req.param("id").replace(/\.html$/, ""));
const id = c.req.param("id").replace(/\.html$/, "");
const html = unwrapResult(await c.get("ctx").invoices.renderHtml(id, c.get("ctx").merchant));
return c.html(html);
});
app.get("/:id", async (c) => {
return data(c, await ownedInvoice(c, c.req.param("id")));
const invoice = unwrapResult(await c.get("ctx").invoices.get(c.req.param("id")));
return data(c, invoice);
});
app.post("/:id/finalize", async (c) => {
const { id } = await ownedInvoice(c, c.req.param("id"));
const invoice = unwrapResult(await c.get("ctx").invoices.finalize(id));
const invoice = unwrapResult(await c.get("ctx").invoices.finalize(c.req.param("id")));
return data(c, invoice);
});
app.post("/:id/pay", async (c) => {
const { id } = await ownedInvoice(c, c.req.param("id"));
const invoice = unwrapResult(await c.get("ctx").invoices.markPaid(id));
const invoice = unwrapResult(await c.get("ctx").invoices.markPaid(c.req.param("id")));
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 ctx.invoices.void(id));
await closeInvoiceSessions(ctx, invoice);
const invoice = unwrapResult(await c.get("ctx").invoices.void(c.req.param("id")));
return data(c, invoice);
});

View File

@ -6,13 +6,12 @@
* and verifies a presented key for a product + machine (activating the machine
* when new and within capacity).
*/
import { Hono, type Context } from "hono";
import type { LicenseKey } from "@settlekit/common";
import { Hono } from "hono";
import { z } from "zod";
import type { AppEnv } from "../context.js";
import { created, data } from "../http/respond.js";
import { parseBody } from "../http/validate.js";
import { requireOrg, requireOwned, scopeToOrg } from "../http/tenant.js";
import { requireOrg } from "../http/tenant.js";
const issueSchema = z.object({
// Derived from the authenticated org (tenant scope); ignored if supplied.
@ -31,17 +30,12 @@ const verifySchema = z.object({
machineId: z.string().min(1),
});
/** Load a license by id, requiring it belongs to the caller's org (else 404). */
async function ownedLicense(c: Context<AppEnv>, id: string): Promise<LicenseKey> {
return requireOwned(c, await c.get("ctx").licenseStore.findById(id), "license", id);
}
export function licenseRoutes(): Hono<AppEnv> {
const app = new Hono<AppEnv>();
// List the caller's issued license keys (tenant-scoped).
// List all issued license keys (merchant-wide).
app.get("/", async (c) => {
return data(c, scopeToOrg(c, await c.get("ctx").licenses.list()));
return data(c, await c.get("ctx").licenses.list());
});
// Issue a license key.
@ -72,15 +66,13 @@ export function licenseRoutes(): Hono<AppEnv> {
// Mint an offline validation token for an existing license.
app.post("/:id/token", async (c) => {
const { id } = await ownedLicense(c, c.req.param("id"));
const token = await c.get("ctx").licenses.issueToken(id);
const token = await c.get("ctx").licenses.issueToken(c.req.param("id"));
return data(c, { token });
});
// Revoke a license.
app.post("/:id/revoke", async (c) => {
const { id } = await ownedLicense(c, c.req.param("id"));
const revoked = await c.get("ctx").licenses.revoke(id);
const revoked = await c.get("ctx").licenses.revoke(c.req.param("id"));
return data(c, revoked);
});

View File

@ -11,14 +11,14 @@
* POST /v1/marketplace/listings/:id/rate add a 1–5 star rating
* GET /v1/marketplace/sellers/:merchantId aggregate seller profile
*/
import { Hono, type Context } from "hono";
import { Hono } from "hono";
import { z } from "zod";
import { notFound, type MarketplaceListing } from "@settlekit/common";
import { notFound } from "@settlekit/common";
import type { ListingSort } from "@settlekit/marketplace-core";
import type { AppEnv } from "../context.js";
import { created, data } from "../http/respond.js";
import { parseBody } from "../http/validate.js";
import { isOwned, requireOrg, requireOwned } from "../http/tenant.js";
import { requireOrg } from "../http/tenant.js";
const createSchema = z.object({
// Derived from the authenticated org (tenant scope); ignored if supplied.
@ -36,23 +36,6 @@ const rateSchema = z.object({
const SORTS: ReadonlyArray<ListingSort> = ["top", "new", "price"];
/** Load a listing the caller may manage (its own org), else 404. */
async function ownedListing(c: Context<AppEnv>, id: string): Promise<MarketplaceListing> {
return requireOwned(c, await c.get("ctx").marketplace.getListing(id), "marketplace listing", id);
}
/**
* Load a listing the caller may SEE: published listings are public discovery
* (any tenant), drafts only to their owner. Hidden listings answer 404.
*/
async function visibleListing(c: Context<AppEnv>, id: string): Promise<MarketplaceListing> {
const listing = await c.get("ctx").marketplace.getListing(id);
if (!listing || (!listing.published && !isOwned(c, listing))) {
throw notFound("marketplace listing not found", { id });
}
return listing;
}
export function marketplaceRoutes(): Hono<AppEnv> {
const app = new Hono<AppEnv>();
@ -85,25 +68,24 @@ export function marketplaceRoutes(): Hono<AppEnv> {
});
app.get("/listings/:id", async (c) => {
return data(c, await visibleListing(c, c.req.param("id")));
const listing = await c.get("ctx").marketplace.getListing(c.req.param("id"));
if (!listing) throw notFound("marketplace listing not found", { id: c.req.param("id") });
return data(c, listing);
});
app.post("/listings/:id/publish", async (c) => {
const { id } = await ownedListing(c, c.req.param("id"));
const listing = await c.get("ctx").marketplace.publish(id);
const listing = await c.get("ctx").marketplace.publish(c.req.param("id"));
return data(c, listing);
});
app.post("/listings/:id/unpublish", async (c) => {
const { id } = await ownedListing(c, c.req.param("id"));
const listing = await c.get("ctx").marketplace.unpublish(id);
const listing = await c.get("ctx").marketplace.unpublish(c.req.param("id"));
return data(c, listing);
});
app.post("/listings/:id/rate", async (c) => {
const { id } = await visibleListing(c, c.req.param("id"));
const body = await parseBody(c, rateSchema);
const listing = await c.get("ctx").marketplace.addRating(id, body.stars);
const listing = await c.get("ctx").marketplace.addRating(c.req.param("id"), body.stars);
return data(c, listing);
});

View File

@ -1,316 +0,0 @@
/**
* 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

@ -1,122 +0,0 @@
/**
* Agent payments on Tempo over the Machine Payments Protocol (`mppx`, wevm,
* MIT). PUBLIC: the payment is the authorization.
*
* GET /v1/mpp/research sample paid resource (mppx/hono middleware)
* POST /v1/mpp/products/:productId/buy buy a product: the mppx charge is verified
* on-chain first, then the Payment is recorded
* (unique tx hash), the entitlement granted and
* delivery run inline; the artifact is returned
* with the Payment-Receipt header
*
* Challenges ride on `WWW-Authenticate: Payment ...`, credentials on
* `Authorization: Payment ...` (HTTP Payment auth scheme).
*/
import { Hono, type Context, type MiddlewareHandler } from "hono";
import { Credential, Receipt } from "mppx";
import { Mppx as MppxHono } from "mppx/hono";
import { Mppx } from "mppx/server";
import type { AppEnv } from "../context.js";
import type { AgentPaymentsRuntime } from "../agent-payments/config.js";
import type { MppRuntime } from "../agent-payments/mpp.js";
import { fulfilAgentPurchase } from "../agent-payments/fulfil.js";
import { fulfilmentError } from "../agent-payments/unfulfilled.js";
import { readBuyer, resolvePurchasable } from "../agent-payments/purchasable.js";
import { data, error } from "../http/respond.js";
const CHARGE_KEY = "tempo/charge";
/** `did:pkh:eip155:<chain>:<address>` -> address, when the credential names its payer. */
function payerFromCredential(request: Request): string | undefined {
try {
const source = Credential.fromRequest(request).source;
const match = source ? /^did:pkh:eip155:\d+:(0x[0-9a-fA-F]{40})$/.exec(source) : null;
return match?.[1];
} catch {
return undefined;
}
}
function unavailable(c: Context): Response {
return c.json(
{ error: { code: "mpp_unavailable", message: "MPP on Tempo is not configured (set MPP_SECRET_KEY and MPP_TEMPO_RECIPIENT)" } },
503,
);
}
type ChargeFn = (options: Record<string, unknown>) => (request: Request) => Promise<
{ status: 402; challenge: Response } | { status: 200; withReceipt: (response?: Response) => Response }
>;
function chargeOf(instance: unknown): ChargeFn | undefined {
return (instance as Record<string, ChargeFn | undefined>)[CHARGE_KEY];
}
/** Mount under `/v1/mpp`. */
export function mppTempoRoutes(runtime: AgentPaymentsRuntime | null): Hono<AppEnv> {
const app = new Hono<AppEnv>();
const mpp: MppRuntime | null = runtime?.mpp ?? null;
if (!mpp) {
app.all("*", unavailable);
return app;
}
const config = { methods: [mpp.charge], secretKey: mpp.secretKey, realm: mpp.realm };
const core = Mppx.create(config);
const buyCharge = chargeOf(core);
if (!buyCharge) throw new Error("mppx did not expose the tempo/charge intent on the server instance");
const honoMppx = MppxHono.create(config);
const researchCharge = (honoMppx as unknown as Record<string, (options: Record<string, unknown>) => MiddlewareHandler>)[CHARGE_KEY];
if (!researchCharge) throw new Error("mppx did not expose the tempo/charge intent");
app.get("/research", researchCharge({ amount: runtime?.researchPrice ?? "0.01", description: "SettleKit sample paid research resource" }), (c) =>
data(c, {
answer: "Paid research result: settled on Tempo through the Machine Payments Protocol.",
generatedAt: new Date().toISOString(),
}),
);
app.post("/products/:productId/buy", async (c) => {
try {
const ctx = c.get("ctx");
const buyer = await readBuyer(c.req.raw);
const purchase = await resolvePurchasable(ctx, c.req.param("productId"), buyer);
const result = await buyCharge({
amount: purchase.price.amount,
description: `SettleKit: ${purchase.product.name}`,
externalId: purchase.product.id,
})(c.req.raw);
if (result.status === 402) return result.challenge;
const receipt = Receipt.fromResponse(result.withReceipt(new Response(null)));
const payer = payerFromCredential(c.req.raw);
try {
const outcome = await fulfilAgentPurchase(ctx, {
product: purchase.product,
price: purchase.price,
rail: "mpp",
network: "tempo",
txHash: receipt.reference,
...(payer ? { payer } : {}),
assetSymbol: mpp.symbol,
buyer: purchase.buyer,
});
return result.withReceipt(data(c, outcome, 201));
} catch (err) {
return result.withReceipt(
fulfilmentError(c, err, {
rail: "mpp",
network: "tempo",
txHash: receipt.reference,
productId: purchase.product.id,
...(payer ? { payer } : {}),
}),
);
}
} catch (err) {
return error(c, err);
}
});
return app;
}

View File

@ -16,7 +16,6 @@ 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 {
@ -43,7 +42,7 @@ async function computeOnboarding(
ctx: AppContext,
organizationId: string,
): Promise<OnboardingStatus> {
const products = await ctx.products.list((p) => p.organizationId === organizationId && !isInvoiceProduct(p));
const products = await ctx.products.list((p) => p.organizationId === organizationId);
const productIds = new Set(products.map((p) => p.id));
const [prices, confirmedPayments, payouts] = await Promise.all([

View File

@ -1,589 +0,0 @@
/**
* Onchain billing routes (API-key guarded; the checkout calls these server-side):
*
* 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=&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
* POST /v1/onchain-billing/escrow Base escrow intent (commerce-payments)
* GET /v1/onchain-billing/escrow/:id escrow payment record
* 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
* 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";
import {
SettleKitError,
fromBaseUnits,
generateId,
money,
notFound,
toBaseUnits,
validationError,
type Customer,
type Payment,
} from "@settlekit/common";
import { checkPayTo, type Hex } from "@settlekit/chains";
import { completeSession, createCheckoutSession, refundPayment } from "@settlekit/payments";
import { refundSucceededWebhook, subscriptionCanceledWebhook } from "@settlekit/persistence";
import {
BILLING_METHODS,
ChargeDeclinedError,
RefundUnsupportedError,
chargeIdForPayment,
paymentInfoFromJson,
type BillingNetwork,
type OnchainBillingRuntime,
} from "@settlekit/onchain-billing";
import { DEFAULT_MERCHANT_ID } from "@settlekit/persistence";
import type { AppContext, AppEnv } from "../context.js";
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");
const createSchema = z.object({
network: z.enum(BILLING_NETWORKS),
method: z.enum(BILLING_METHODS as unknown as [string, ...string[]]),
customerId: z.string().min(1),
productId: z.string().min(1),
priceId: z.string().min(1),
payTo: z.string().min(1),
payer: z.string().min(1).optional(),
email: z.string().email().optional(),
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({
signature: z.string().regex(/^0x[0-9a-fA-F]+$/).optional(),
approveSignature: z.string().min(32).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}$/),
receiver: z.string().regex(/^0x[0-9a-fA-F]{40}$/),
amount,
collector: z.enum(["erc3009", "permit2", "pre_approval"]),
autoCapture: z.boolean().optional(),
customerId: z.string().min(1),
authorizationTtlSeconds: z.number().int().min(60).max(30 * 86_400).optional(),
refundTtlSeconds: z.number().int().min(60).max(365 * 86_400).optional(),
});
const captureSchema = z.object({ amount: amount.optional() });
const refundSchema = z
.object({
paymentId: z.string().min(1).optional(),
escrowPaymentId: z.string().min(1).optional(),
amount,
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" });
/** JSON-safe payloads: bigints (typed data, amounts) become decimal strings. */
function jsonSafe<T>(value: T): unknown {
return JSON.parse(JSON.stringify(value, (_key, v: unknown) => (typeof v === "bigint" ? v.toString() : v)));
}
function billing(c: Context<AppEnv>): OnchainBillingRuntime {
const runtime = c.get("ctx").onchainBilling;
if (!runtime) throw notFound("onchain billing is not configured (set ONCHAIN_BILLING_OPERATOR_PRIVATE_KEY / ONCHAIN_BILLING_CHECKOUT_URL)");
return runtime;
}
/** Map domain errors onto the API's error envelope. */
async function guard<T>(fn: () => Promise<T>): Promise<T> {
try {
return await fn();
} catch (error) {
if (SettleKitError.is(error)) throw error;
if (error instanceof ChargeDeclinedError || error instanceof RangeError || error instanceof RefundUnsupportedError) {
throw validationError(error.message);
}
if (error instanceof Error && /not found/.test(error.message)) throw notFound(error.message);
throw error;
}
}
async function ownedSubscription(c: Context<AppEnv>, id: string) {
return requireOwned(c, await billing(c).subscriptions.get(id), "onchain subscription", id);
}
async function ownedEscrow(c: Context<AppEnv>, id: string) {
return requireOwned(c, await billing(c).store.getEscrowPayment(id), "escrow payment", id);
}
/** A customer id stamped by another tenant is refused (unknown ids are allowed: checkout creates them). */
async function assertCustomerNotForeign(c: Context<AppEnv>, customerId: string): Promise<void> {
const customer = await c.get("ctx").customers.findById(customerId);
if (customer) requireOwned(c, customer, "customer", customerId);
}
/** A checkout-session record for the purchase, so charges' Payments reference it. */
async function recordSession(ctx: AppContext, input: { organizationId: string; customerId?: string; productId?: string; priceId: string; amount: string; network: BillingNetwork; payTo: string }): Promise<string | undefined> {
const session = createCheckoutSession({
organizationId: input.organizationId,
merchantId: DEFAULT_MERCHANT_ID,
...(input.customerId ? { customerId: input.customerId } : {}),
items: [
{
lineItem: { ...(input.productId ? { productId: input.productId } : {}), priceId: input.priceId, quantity: 1 },
price: { id: input.priceId, productId: input.productId ?? "", amount: input.amount, currency: "USDC", interval: "monthly", usageBased: false, active: true, createdAt: new Date().toISOString() },
},
],
payToAddress: input.payTo,
network: input.network,
collectedFields: { source: "onchain_billing" },
});
return (await ctx.checkouts.save(session)).id;
}
async function completeRecordedSession(ctx: AppContext, sessionId: string | undefined): Promise<void> {
if (!sessionId) return;
const session = await ctx.checkouts.findById(sessionId);
if (session && session.status === "open") await ctx.checkouts.save(completeSession(session));
}
export function onchainBillingRoutes(): Hono<AppEnv> {
const app = new Hono<AppEnv>();
app.get("/networks", (c) => {
const runtime = billing(c);
const networks = Object.values(runtime.assets).map((asset) => ({
...asset,
methods: runtime.subscriptions.methodsFor(asset.network),
}));
return data(c, {
networks,
operator: runtime.operatorAddress,
solanaDelegate: runtime.solanaDelegate,
escrow: runtime.escrow !== null,
notes: runtime.notes,
});
});
app.post("/subscriptions", async (c) => {
const ctx = c.get("ctx");
const body = await parseBody(c, createSchema);
const runtime = billing(c);
requireOwned(c, await ctx.products.findById(body.productId), "product", body.productId);
const price = await ctx.prices.findById(body.priceId);
if (!price) throw notFound("price not found", { id: body.priceId });
if (price.interval !== "monthly" && price.interval !== "yearly") {
throw validationError("onchain subscriptions need a monthly or yearly price", { priceId: price.id });
}
if (price.productId !== body.productId) throw validationError("price does not belong to product", { priceId: price.id });
const check = checkPayTo(body.network, body.payTo);
if (!check.ok) throw validationError(`payTo ${check.reason}`);
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,
productId: body.productId,
priceId: price.id,
amount: price.amount,
network: body.network,
payTo: body.payTo,
});
const intent = await guard(() =>
runtime.subscriptions.createIntent({
id: `osub_${generateId("subscription").replace(/^[a-z]+_/, "")}`,
organizationId,
customerId: body.customerId,
productId: body.productId,
priceId: price.id,
...(body.subscriptionId ? { subscriptionId: body.subscriptionId } : { subscriptionId: generateId("subscription") }),
...(checkoutSessionId ? { checkoutSessionId } : {}),
network: body.network,
method: body.method as never,
...(body.payer ? { payer: body.payer } : {}),
payTo: body.payTo,
amount: price.amount,
interval: price.interval as "monthly" | "yearly",
...(body.periods ? { periods: body.periods } : {}),
...(body.email ? { email: body.email } : {}),
}),
);
return created(c, jsonSafe(intent));
});
app.get("/subscriptions", async (c) => {
const runtime = billing(c);
const customerId = c.req.query("customerId");
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 runtime.store.listCharges(sub.id),
view: await onchainSubscriptionView(c.get("ctx"), runtime, sub),
});
});
app.post("/subscriptions/:id/grant", 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, grantSchema);
const active = await guard(() =>
runtime.subscriptions.submitGrant(sub.id, {
...(body.signature ? { signature: body.signature } : {}),
...(body.approveSignature ? { approveSignature: body.approveSignature } : {}),
}),
);
await completeRecordedSession(ctx, active.checkoutSessionId);
const outcome = await runtime.engine.chargeSubscription(active.id);
if (outcome === "succeeded") await grantAccess(ctx, active.subscriptionId, active.productId);
return data(c, {
subscription: await runtime.subscriptions.get(active.id),
firstCharge: { outcome, charge: await runtime.store.getCharge(active.id, 0) },
});
});
app.post("/subscriptions/:id/charge", async (c) => {
const runtime = billing(c);
const sub = await ownedSubscription(c, c.req.param("id"));
const outcome = await runtime.engine.chargeSubscription(sub.id);
return data(c, { outcome, subscription: await runtime.subscriptions.get(sub.id), charges: await runtime.store.listCharges(sub.id) });
});
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 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) => {
const ctx = c.get("ctx");
const runtime = billing(c);
if (!runtime.escrow) throw notFound("Base escrow is not configured (enable base with ONCHAIN_BILLING_OPERATOR_PRIVATE_KEY)");
const escrow = runtime.escrow;
const body = await parseBody(c, escrowSchema);
await assertCustomerNotForeign(c, body.customerId);
const base = runtime.assets.base;
if (!base?.chainId) throw validationError("base is not an enabled network");
const organizationId = requireOrg(c);
const id = `esc_${generateId("payment").replace(/^[a-z]+_/, "")}`;
const checkoutSessionId = await recordSession(ctx, {
organizationId,
customerId: body.customerId,
priceId: `escrow:${id}`,
amount: body.amount,
network: "base",
payTo: body.receiver,
});
const intent = await guard(() =>
escrow.createIntent({
id,
organizationId,
customerId: body.customerId,
...(checkoutSessionId ? { checkoutSessionId } : {}),
payer: body.payer as Hex,
receiver: body.receiver as Hex,
token: base.token as Hex,
amount: toBaseUnits(body.amount),
collector: body.collector,
...(body.autoCapture !== undefined ? { autoCapture: body.autoCapture } : {}),
...(body.authorizationTtlSeconds ? { authorizationTtlSeconds: body.authorizationTtlSeconds } : {}),
...(body.refundTtlSeconds ? { refundTtlSeconds: body.refundTtlSeconds } : {}),
tokenDomain: base.chainId === 8453 ? { name: "USD Coin", version: "2" } : { name: "USDC", version: "2" },
}),
);
return created(c, jsonSafe(intent));
});
app.get("/escrow/:id", async (c) => data(c, await ownedEscrow(c, c.req.param("id"))));
app.post("/escrow/:id/authorize", async (c) => {
const ctx = c.get("ctx");
const record = await ownedEscrow(c, c.req.param("id"));
const body = await parseBody(c, z.object({ signature: z.string().regex(/^0x[0-9a-fA-F]*$/) }));
const runtime = billing(c);
const chainId = record.chainId;
const updated = await guard(() =>
(runtime.escrow as NonNullable<typeof runtime.escrow>).submitSignature(
record.id,
body.signature as Hex,
chainId === 8453 ? { name: "USD Coin", version: "2" } : { name: "USDC", version: "2" },
),
);
if (updated.status === "captured") await recordEscrowPayment(ctx, updated.id);
return data(c, updated);
});
app.post("/escrow/:id/capture", async (c) => {
const ctx = c.get("ctx");
const record = await ownedEscrow(c, c.req.param("id"));
const body = await parseBody(c, captureSchema);
const runtime = billing(c);
const updated = await guard(() =>
(runtime.escrow as NonNullable<typeof runtime.escrow>).capture(record.id, body.amount ? toBaseUnits(body.amount) : undefined),
);
await recordEscrowPayment(ctx, updated.id);
return data(c, updated);
});
app.post("/escrow/:id/void", async (c) => {
const record = await ownedEscrow(c, c.req.param("id"));
const runtime = billing(c);
return data(c, await guard(() => (runtime.escrow as NonNullable<typeof runtime.escrow>).void(record.id)));
});
app.get("/escrow/:id/reclaim", async (c) => {
const record = await ownedEscrow(c, c.req.param("id"));
const runtime = billing(c);
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 }),
);
try {
const execution = await guard(() =>
runtime.refunds.refund({
network: target.network,
to: target.to,
amount: toBaseUnits(body.amount),
reference: refund.id,
...(target.escrowPaymentId ? { escrowPaymentId: target.escrowPaymentId } : {}),
}),
);
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);
throw error;
}
});
return app;
}
/** First paid period: grant the product entitlement for the new core subscription. */
async function grantAccess(ctx: AppContext, subscriptionId: string | undefined, productId: string): Promise<void> {
if (!subscriptionId) return;
const subscription = await ctx.subscriptions.findById(subscriptionId);
const product = await ctx.products.findById(productId);
if (!subscription || !product) return;
const existing = await ctx.entitlementRepo.listByCustomer(subscription.customerId);
if (existing.some((e) => e.productId === productId && e.status === "active")) return;
await ctx.entitlements.grantFromSubscription({ subscription, product });
}
interface RefundTarget {
payment: Payment;
network: BillingNetwork;
to: string;
escrowPaymentId?: string;
}
function escrowPaymentId(escrowId: string): string {
return `pay_${escrowId}`;
}
/** Record the captured escrow amount as a confirmed core Payment (refunds need one). */
async function recordEscrowPayment(ctx: AppContext, escrowId: string): Promise<void> {
const runtime = ctx.onchainBilling;
const record = runtime ? await runtime.store.getEscrowPayment(escrowId) : undefined;
if (!record || BigInt(record.capturedAmount) === 0n) return;
const capture = [...record.txs].reverse().find((t) => t.action === "capture" || t.action === "charge");
if (!record.checkoutSessionId || !record.customerId) return;
const existing = await ctx.payments.findById(escrowPaymentId(escrowId));
await completeRecordedSession(ctx, record.checkoutSessionId);
const checkoutSessionId = record.checkoutSessionId;
await ctx.payments.save({
id: escrowPaymentId(escrowId),
organizationId: record.organizationId,
checkoutSessionId,
customerId: record.customerId,
amount: money(fromBaseUnits(BigInt(record.capturedAmount))),
network: "base",
...(existing?.txHash ?? capture?.txHash ? { txHash: (existing?.txHash ?? capture?.txHash) as string } : {}),
confirmations: 1,
status: "confirmed",
createdAt: existing?.createdAt ?? record.createdAt,
confirmedAt: new Date().toISOString(),
});
}
async function resolveRefundTarget(
c: Context<AppEnv>,
body: { paymentId?: string | undefined; escrowPaymentId?: string | undefined; to?: string | undefined },
): Promise<RefundTarget> {
const ctx = c.get("ctx");
const runtime = billing(c);
const escrowId = body.escrowPaymentId ?? (body.paymentId?.startsWith("pay_esc_") ? body.paymentId.slice("pay_".length) : undefined);
if (escrowId) {
const record = await ownedEscrow(c, escrowId);
const payment = await ctx.payments.findById(escrowPaymentId(escrowId));
if (!payment) throw validationError("escrow payment has not been captured yet");
return { payment, network: "base", to: paymentInfoFromJson(record.paymentInfo).payer, escrowPaymentId: escrowId };
}
const payment = await requireOwnedPayment(c, body.paymentId as string);
const chargeId = chargeIdForPayment(payment.id);
if (chargeId) {
const charge = await runtime.store.getChargeById(chargeId);
const sub = charge ? await runtime.store.getSubscription(charge.onchainSubscriptionId) : undefined;
if (!sub) throw notFound("onchain charge for payment not found", { id: payment.id });
return { payment, network: sub.network, to: sub.payer };
}
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 };
}
/** 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

@ -1,202 +0,0 @@
/**
* 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

@ -1,150 +0,0 @@
/**
* Shared on-chain verification rules for the payment routes.
*
* Invariants enforced here (both confirm and observe go through them):
* - FAIL CLOSED: a network with no registered verifier can never confirm a
* payment. A tx hash alone is never evidence of payment.
* - A transaction hash settles at most ONE payment (global uniqueness), so a
* single on-chain transfer cannot be replayed across sessions or orgs.
* - Tx ids are validated and normalized per network (@settlekit/chains):
* EVM and Zcash lowercase, Solana signatures verbatim.
* - Session bindings travel to the verifier: payTo for the network, the
* session creation time (block time must not predate it), the declared
* payer, the session id (Tempo memo) and the locked Zcash quote.
*/
import {
conflict,
validationError,
type CheckoutSession,
type Payment,
type PaymentNetwork,
type SettlementQuote,
} from "@settlekit/common";
import { normalizeTxHash as normalizeFill, parseTxHash, txHashFormatHint, type SettlementVerifier } from "@settlekit/chains";
import { X402_SCHEME } from "@settlekit/x402";
import type { AppContext } from "../context.js";
export { normalizeTxHash } from "@settlekit/chains";
/** Validate + normalize `txHash` for `network`, or throw a 400. */
export function requireTxHash(network: PaymentNetwork, txHash: string): string {
const parsed = parseTxHash(network, txHash);
if (parsed === null) {
throw validationError(`txHash must be ${txHashFormatHint(network)} for network ${network}`, { network });
}
return parsed;
}
/** The verifier for `network`, or a validation error (fail closed). */
export function requireVerifier(ctx: AppContext, network: PaymentNetwork): SettlementVerifier {
const verifier = ctx.verifiers[network];
if (!verifier) {
throw validationError(
`on-chain verification is not configured for network "${network}"; payments on it cannot be confirmed`,
{ network },
);
}
return verifier;
}
/**
* Throw 409 when `txHash` already backs a different payment. Returns the
* existing payment when it is `self` (idempotent re-confirm) or null.
*/
export async function assertTxHashUnused(
ctx: AppContext,
txHash: string,
selfPaymentId?: string,
): Promise<Payment | null> {
const existing = await ctx.payments.findByTxHash(txHash);
if (existing === null) return null;
if (selfPaymentId !== undefined && existing.id === selfPaymentId) return existing;
throw conflict("transaction hash already used by another payment", {
txHash,
paymentId: existing.id,
});
}
export interface OnChainCheck {
network: PaymentNetwork;
txHash: string;
/** Decimal major-unit amount that must have been received. */
amount: string;
asset: string;
payTo: string;
/** Solana Pay reference the transaction must include (Solana only). */
reference?: string;
from?: string;
resource: string;
/** ISO time the payment must not predate (session createdAt). */
notBefore?: string;
/** Declared payer address (payer binding). */
payer?: string;
/** Checkout session id (Tempo memo binding). */
sessionId?: string;
/** Tempo: only transferWithMemo carrying keccak256(sessionId) settles. */
requireMemo?: boolean;
/** Locked Zcash quote. */
settlementQuote?: SettlementQuote;
/** Route-provider destination fill (no Solana Pay reference / payer / memo binding). */
routedFill?: boolean;
}
/** The address `session` must be paid at on `network`. */
export function payToFor(session: CheckoutSession, network: PaymentNetwork): string {
return session.payToByNetwork?.[network] ?? session.payToAddress;
}
/**
* True when `txHash` is the destination fill an any-token route provider
* reported for `session` (stored server-side by the checkout): the solver
* sent it, so the payer and memo bindings do not apply.
*/
export function isRoutedFill(session: CheckoutSession, network: PaymentNetwork, txHash: string): boolean {
const fill = session.route?.destinationTxHash;
if (fill === undefined || session.route?.network !== network) return false;
return normalizeFill(network, fill) === normalizeFill(network, txHash);
}
/** Build the verification check binding `txHash` to `session` on `network`. */
export function sessionCheck(session: CheckoutSession, network: PaymentNetwork, txHash: string): OnChainCheck {
const routed = isRoutedFill(session, network, txHash);
return {
network,
txHash,
amount: session.amount.amount,
asset: session.amount.currency,
payTo: payToFor(session, network),
resource: `checkout_session:${session.id}`,
notBefore: session.createdAt,
sessionId: session.id,
...(session.paymentReference !== undefined && !routed ? { reference: session.paymentReference } : {}),
...(session.payerAddress !== undefined && !routed ? { payer: session.payerAddress } : {}),
...(session.requireMemo === true && !routed ? { requireMemo: true } : {}),
...(session.settlementQuote !== undefined ? { settlementQuote: session.settlementQuote } : {}),
...(routed ? { routedFill: true } : {}),
};
}
/** Verify a transfer on-chain through the network's verifier; throws on failure. */
export async function verifyOnChainOrThrow(ctx: AppContext, check: OnChainCheck): Promise<void> {
const verifier = requireVerifier(ctx, check.network);
const { network, txHash, from, ...rest } = check;
const verification = await verifier(
{ txHash, from: from ?? "", amount: check.amount, network, nonce: "" },
{ ...rest, scheme: X402_SCHEME, network, productId: "", nonce: "" },
);
if (verification.ok) return;
const reason = verification.reason ?? "unverified";
const prefix = verification.late
? "payment requires manual review"
: verification.retryable
? "payment not yet verifiable on-chain (retry later)"
: "on-chain payment verification failed";
throw validationError(`${prefix}: ${reason}`, {
network,
txHash,
...(verification.retryable ? { retryable: true } : {}),
...(verification.late ? { manualReview: true } : {}),
});
}

View File

@ -13,7 +13,7 @@
*/
import { Hono } from "hono";
import { z } from "zod";
import { conflict, money, validationError, type Entitlement, type Money } from "@settlekit/common";
import { conflict, money, notFound, validationError, type Entitlement, type Money } from "@settlekit/common";
import {
confirmPayment,
failPayment,
@ -21,21 +21,12 @@ import {
refundPayment,
} from "@settlekit/payments";
import { completeSession } from "@settlekit/payments";
import { paymentConfirmedWebhook, redeemSessionCoupon } from "@settlekit/persistence";
import { X402_SCHEME } from "@settlekit/x402";
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";
import { requireOrg } from "../http/tenant.js";
import { screenAddressOrThrow } from "../compliance/screen.js";
import { checkPayTo, isValidTxHash, txHashFormatHint } from "@settlekit/chains";
import {
assertTxHashUnused,
requireTxHash,
requireVerifier,
sessionCheck,
verifyOnChainOrThrow,
} from "./payment-verification.js";
const recordSchema = z.object({
checkoutSessionId: z.string().min(1),
@ -48,49 +39,21 @@ const confirmSchema = z.object({
minConfirmations: z.number().int().positive().optional(),
});
/**
* Networks a direct deposit can be observed on. Zcash is excluded: its
* amount is only meaningful against a checkout session's locked quote.
*/
const OBSERVABLE_NETWORKS = [
"solana",
"arc",
"base",
"ethereum",
"arbitrum",
"robinhood",
"hyperevm",
"hypercore",
"tempo",
] as const;
const observeSchema = z
.object({
// Derived from the authenticated org (tenant scope); ignored if supplied.
organizationId: z.string().min(1).optional(),
txHash: z.string().min(1),
/** The watched (recipient) address the transfer landed at. */
to: z.string().min(1),
amount: z.string().regex(/^\d+(\.\d+)?$/, "must be a decimal amount"),
asset: z.enum(["USDC", "EURC", "USYC"]).default("USDC"),
network: z.enum(OBSERVABLE_NETWORKS).default("arc"),
/** Sender, if the indexer decoded it; screened when present. */
from: z.string().optional(),
/** Optional customer attribution; defaults to a synthetic direct-payment id. */
customerId: z.string().optional(),
confirmations: z.number().int().nonnegative().default(0),
})
.superRefine((body, ctx) => {
// Hash/address formats depend on the chain (@settlekit/chains rules).
if (!isValidTxHash(body.network, body.txHash)) {
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["txHash"], message: `must be ${txHashFormatHint(body.network)}` });
}
const to = checkPayTo(body.network, body.to);
if (!to.ok) ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["to"], message: to.reason });
if (body.from !== undefined && !checkPayTo(body.network, body.from).ok) {
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["from"], message: `must be a valid ${body.network} address` });
}
});
const observeSchema = z.object({
// Derived from the authenticated org (tenant scope); ignored if supplied.
organizationId: z.string().min(1).optional(),
txHash: z.string().regex(/^0x[a-fA-F0-9]{64}$/, "must be a 0x tx hash"),
/** The watched (recipient) address the transfer landed at. */
to: z.string().regex(/^0x[a-fA-F0-9]{40}$/, "must be a 0x address"),
amount: z.string().regex(/^\d+(\.\d+)?$/, "must be a decimal amount"),
asset: z.enum(["USDC", "EURC", "USYC"]).default("USDC"),
network: z.enum(["arc", "base", "ethereum"]).default("arc"),
/** Sender, if the indexer decoded it; screened when present. */
from: z.string().regex(/^0x[a-fA-F0-9]{40}$/).optional(),
/** Optional customer attribution; defaults to a synthetic direct-payment id. */
customerId: z.string().optional(),
confirmations: z.number().int().nonnegative().default(0),
});
export function paymentRoutes(): Hono<AppEnv> {
const app = new Hono<AppEnv>();
@ -99,29 +62,21 @@ export function paymentRoutes(): Hono<AppEnv> {
app.post("/", async (c) => {
const ctx = c.get("ctx");
const body = await parseBody(c, recordSchema);
// Tenant-scoped: only the caller's own sessions can be paid against.
const session = requireOwned(
c,
await ctx.checkouts.findById(body.checkoutSessionId),
"checkout session",
body.checkoutSessionId,
);
const session = await ctx.checkouts.findById(body.checkoutSessionId);
if (!session) throw notFound("checkout session not found", { id: body.checkoutSessionId });
if (session.customerId === undefined) {
throw validationError("checkout session has no customer; set customerId before paying", {
sessionId: session.id,
});
}
const txHash = body.txHash !== undefined ? requireTxHash(session.network, body.txHash) : undefined;
if (txHash !== undefined) await assertTxHashUnused(ctx, txHash);
const payment = recordPendingPayment({
organizationId: session.organizationId,
checkoutSessionId: session.id,
customerId: session.customerId,
amount: session.amount,
network: session.network,
...(txHash !== undefined ? { txHash } : {}),
...(body.txHash !== undefined ? { txHash: body.txHash } : {}),
});
return created(c, await ctx.payments.save(payment));
});
@ -131,38 +86,60 @@ export function paymentRoutes(): Hono<AppEnv> {
return data(c, await c.get("ctx").payments.listByOrganization(requireOrg(c)));
});
// Single-payment routes: owner-only; another org's id answers 404.
app.get("/:id", async (c) => {
return data(c, await requireOwnedPayment(c, c.req.param("id")));
const payment = await c.get("ctx").payments.findById(c.req.param("id"));
if (!payment) throw notFound("payment not found", { id: c.req.param("id") });
return data(c, payment);
});
// Confirm a payment: completes the session and grants entitlements.
app.post("/:id/confirm", async (c) => {
const ctx = c.get("ctx");
const payment = await requireOwnedPayment(c, c.req.param("id"));
const id = c.req.param("id");
const payment = await ctx.payments.findById(id);
if (!payment) throw notFound("payment not found", { id });
const body = await parseBody(c, confirmSchema);
const session = await ctx.checkouts.findById(payment.checkoutSessionId);
if (!session) throw conflict("checkout session vanished", { id: payment.checkoutSessionId });
// Verify the transfer ON-CHAIN before confirming, on EVERY network: the tx
// must have paid the session's payTo for this network at least the
// invoiced amount (Zcash: exactly the locked quote), no earlier than the
// session, from the declared payer, carrying the session's Solana
// reference / Tempo memo where applicable (a route provider's destination
// fill stored on the session is bound by payTo, amount and block time
// instead, matching the checkout and worker). No verifier for the network
// means the payment cannot be confirmed (fail closed), and a tx hash can
// back only one payment, so one transfer never settles two sessions.
requireVerifier(ctx, payment.network);
const txHash = requireTxHash(payment.network, body.txHash);
await assertTxHashUnused(ctx, txHash, payment.id);
await verifyOnChainOrThrow(ctx, sessionCheck(session, payment.network, txHash));
// When Arc settlement is configured, verify the transfer ON-CHAIN before
// confirming an Arc-network payment: the tx must have moved at least the
// invoiced USDC to the session's payTo address with enough confirmations.
// This prevents a caller from settling a session with an arbitrary hash.
// (Non-Arc networks / unconfigured Arc fall through to the recorded count.)
if (ctx.arcVerifier && payment.network === "arc") {
const verification = await ctx.arcVerifier(
{
txHash: body.txHash,
from: "",
amount: session.amount.amount,
network: payment.network,
nonce: "",
},
{
scheme: X402_SCHEME,
amount: session.amount.amount,
asset: session.amount.currency,
network: payment.network,
payTo: session.payToAddress,
productId: "",
resource: `checkout_session:${session.id}`,
nonce: "",
},
);
if (!verification.ok) {
throw validationError(`on-chain payment verification failed: ${verification.reason ?? "unverified"}`, {
paymentId: id,
txHash: body.txHash,
});
}
}
const confirmed = confirmPayment(
payment,
txHash,
body.txHash,
body.confirmations,
body.minConfirmations,
);
@ -170,34 +147,26 @@ export function paymentRoutes(): Hono<AppEnv> {
// Complete the session (idempotent) and grant entitlements for each product.
if (session.status === "open") {
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);
await ctx.checkouts.save(completeSession(session));
}
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 });
});
// Fail a pending payment.
app.post("/:id/fail", async (c) => {
const ctx = c.get("ctx");
const payment = await requireOwnedPayment(c, c.req.param("id"));
const payment = await ctx.payments.findById(c.req.param("id"));
if (!payment) throw notFound("payment not found", { id: c.req.param("id") });
return data(c, await ctx.payments.save(failPayment(payment)));
});
// Refund a confirmed payment.
app.post("/:id/refund", async (c) => {
const ctx = c.get("ctx");
const payment = await requireOwnedPayment(c, c.req.param("id"));
const payment = await ctx.payments.findById(c.req.param("id"));
if (!payment) throw notFound("payment not found", { id: c.req.param("id") });
return data(c, await ctx.payments.save(refundPayment(payment)));
});
@ -212,55 +181,60 @@ export function paymentRoutes(): Hono<AppEnv> {
// Tenant-scoped: credit the authenticated org, never a client-supplied one.
const organizationId = requireOrg(c);
// Fail closed: without a verifier for the network nothing can be credited.
requireVerifier(ctx, body.network);
const txHash = requireTxHash(body.network, body.txHash);
// Idempotency: this org already recorded the transfer -> return it. A hash
// recorded by ANY other payment (another org/session) is a replay -> 409.
const existing = await ctx.payments.findByTxHash(txHash);
if (existing) {
if (existing.organizationId === organizationId && existing.status === "confirmed") {
return data(c, { payment: existing, deduped: true });
}
throw conflict("transaction hash already used by another payment", { txHash, paymentId: existing.id });
if (!ctx.arcVerifier) {
throw validationError(
"Arc is not configured; observed transfers cannot be verified (set ARC_CHAIN_ID)",
);
}
// Independently re-verify the transfer on-chain via the network's verifier
// (the same one the checkout-confirm path uses). This enforces recipient +
// amount (+ confirmations on EVM) against the chain, so a spoofed
// `observe` body is rejected.
await verifyOnChainOrThrow(ctx, {
network: body.network,
txHash,
amount: body.amount,
asset: body.asset,
payTo: body.to,
resource: `observe:${txHash}`,
...(body.from !== undefined ? { from: body.from } : {}),
});
// Idempotency: a confirmed payment for this txHash already exists?
const confirmed = await ctx.payments.findConfirmedByOrganization(organizationId);
const dupe = confirmed.find((p) => p.txHash === body.txHash);
if (dupe) return data(c, { payment: dupe, deduped: true });
// Independently re-verify the transfer on-chain via the same Arc verifier
// the checkout-confirm path uses. This enforces recipient + amount +
// confirmations against the chain, so a spoofed `observe` body is rejected.
const verification = await ctx.arcVerifier(
{ txHash: body.txHash, from: body.from ?? "", amount: body.amount, network: body.network, nonce: "" },
{
scheme: X402_SCHEME,
amount: body.amount,
// The verifier widens asset to string at runtime to resolve EURC/USYC.
asset: body.asset as "USDC",
network: body.network,
payTo: body.to,
productId: "",
resource: `observe:${body.txHash}`,
nonce: "",
},
);
if (!verification.ok) {
throw validationError(`on-chain verification failed: ${verification.reason ?? "unverified"}`, {
txHash: body.txHash,
});
}
// Screen the sender (when decoded) before crediting the merchant.
if (body.from) {
await screenAddressOrThrow(
{ screening: ctx.screening, defaultChain: ctx.complianceDefaultChain },
{ address: body.from, network: body.network, context: `observe:${txHash}` },
{ address: body.from, network: body.network, context: `observe:${body.txHash}` },
);
}
const amount = { amount: money(body.amount).amount, currency: body.asset } as unknown as Money;
const pending = recordPendingPayment({
organizationId,
checkoutSessionId: `direct:${txHash}`,
checkoutSessionId: `direct:${body.txHash}`,
customerId: body.customerId ?? `direct:${body.from ?? "unknown"}`,
amount,
network: body.network,
txHash,
txHash: body.txHash,
});
// The on-chain verifier already enforced confirmations; mark confirmed.
const settled = confirmPayment(pending, txHash, Math.max(body.confirmations, 1), 1);
const settled = confirmPayment(pending, body.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

@ -20,7 +20,7 @@ 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 } from "../http/tenant.js";
import { requireOrg } from "../http/tenant.js";
import { screenAddressOrThrow } from "../compliance/screen.js";
const amount = z.string().regex(/^\d+(\.\d+)?$/);
@ -106,7 +106,8 @@ export function payoutRoutes(): Hono<AppEnv> {
{ id },
);
}
const payout = requireOwned(c, await ctx.payoutStore.findById(id), "payout", id);
const payout = await ctx.payoutStore.findById(id);
if (!payout) throw notFound("payout not found", { id });
if (payout.status !== "pending") {
throw conflict(`payout is ${payout.status}, only pending payouts can be executed`, { id });
}
@ -143,7 +144,8 @@ export function payoutRoutes(): Hono<AppEnv> {
if (!ctx.payoutExecutor) {
throw validationError("payout execution is not configured", { id });
}
const payout = requireOwned(c, await ctx.payoutStore.findById(id), "payout", id);
const payout = await ctx.payoutStore.findById(id);
if (!payout) throw notFound("payout not found", { id });
if (!payout.providerRef) {
throw conflict("payout has not been executed; nothing to reconcile", { id });
}
@ -165,19 +167,15 @@ export function payoutRoutes(): Hono<AppEnv> {
});
app.post("/:id/paid", async (c) => {
const id = c.req.param("id");
requireOwned(c, await c.get("ctx").payoutStore.findById(id), "payout", id);
const body = await parseBody(c, paidSchema);
const payout = unwrapResult(await c.get("ctx").payouts.markPaid(id, body.txHash));
const payout = unwrapResult(await c.get("ctx").payouts.markPaid(c.req.param("id"), body.txHash));
return data(c, payout);
});
app.post("/:id/fail", async (c) => {
const id = c.req.param("id");
requireOwned(c, await c.get("ctx").payoutStore.findById(id), "payout", id);
const body = await parseBody(c, failSchema);
const payout = unwrapResult(
await c.get("ctx").payouts.markFailed(id, body.reason ?? "payout failed"),
await c.get("ctx").payouts.markFailed(c.req.param("id"), body.reason ?? "payout failed"),
);
return data(c, payout);
});

View File

@ -5,16 +5,14 @@
* domain functions; persistence uses the in-memory product store on the context.
* Prices attach to a product and feed checkout total math downstream.
*/
import { Hono, type Context } from "hono";
import { Hono } from "hono";
import { z } from "zod";
import { FIAT_CURRENCIES, fiatToUsdc, generateId, type Price, type Product } from "@settlekit/common";
import { generateId, notFound, type Price } 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";
import { requireOrg } from "../http/tenant.js";
const PRODUCT_TYPES = [
"saas_plan",
@ -61,39 +59,14 @@ const createProductSchema = z.object({
metadata: z.record(z.unknown()).default({}),
});
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> {
return requireOwned(c, await c.get("ctx").products.findById(id), "product", id);
}
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(),
});
export function productRoutes(): Hono<AppEnv> {
const app = new Hono<AppEnv>();
@ -123,21 +96,23 @@ 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 && !isInvoiceProduct(p));
const products = await c.get("ctx").products.list((p) => p.organizationId === org);
return data(c, products);
});
// Get a product.
app.get("/:id", async (c) => {
return data(c, await ownedProduct(c, c.req.param("id")));
const product = await c.get("ctx").products.findById(c.req.param("id"));
if (!product) throw notFound("product not found", { id: c.req.param("id") });
return data(c, product);
});
// Publish a product (requires an active price).
app.post("/:id/publish", async (c) => {
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 product = await ctx.products.findById(id);
if (!product) throw notFound("product not found", { id });
const prices = await ctx.prices.list((p) => p.productId === id);
const published = publishProduct(product, prices);
return data(c, await ctx.products.save(published));
@ -147,19 +122,14 @@ export function productRoutes(): Hono<AppEnv> {
app.post("/:id/prices", async (c) => {
const ctx = c.get("ctx");
const productId = c.req.param("id");
await ownedProduct(c, productId);
const product = await ctx.products.findById(productId);
if (!product) throw notFound("product not found", { id: 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,
...(fiat ? { displayCurrency: body.displayCurrency!, displayAmount: body.displayAmount! } : {}),
amount: body.amount,
currency: body.currency,
interval: body.interval,
usageBased: body.usageBased,
@ -174,7 +144,6 @@ export function productRoutes(): Hono<AppEnv> {
// List prices for a product.
app.get("/:id/prices", async (c) => {
const productId = c.req.param("id");
await ownedProduct(c, productId);
const prices = await c.get("ctx").prices.list((p) => p.productId === productId);
return data(c, prices);
});

View File

@ -1,121 +0,0 @@
/**
* 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

@ -17,9 +17,6 @@ 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 { isOwned, ownedPaymentIds, requireOwnedPayment } from "../http/tenant.js";
import type { Context } from "hono";
import type { Refund } from "@settlekit/refunds";
const amount = z.string().regex(/^\d+(\.\d+)?$/);
@ -38,27 +35,16 @@ const failSchema = z.object({
reason: z.string().min(1).optional(),
});
/**
* Load a refund by id, requiring its payment belongs to the caller's org. A
* foreign refund answers 404 exactly like a missing one.
*/
async function ownedRefund(c: Context<AppEnv>, id: string): Promise<Refund> {
const ctx = c.get("ctx");
const refund = await ctx.refundStore.findById(id);
if (!refund || !isOwned(c, await ctx.payments.findById(refund.paymentId))) {
throw notFound("refund not found", { id });
}
return refund;
}
export function refundRoutes(): Hono<AppEnv> {
const app = new Hono<AppEnv>();
app.post("/", async (c) => {
const body = await parseBody(c, createSchema);
const ctx = c.get("ctx");
// Tenant-scoped: only the caller's own payments can be refunded.
const payment = await requireOwnedPayment(c, body.paymentId);
const payment = await ctx.payments.findById(body.paymentId);
if (!payment) {
throw notFound(`payment ${body.paymentId} not found`);
}
const refund = unwrapResult(
await ctx.refunds.create({
payment,
@ -74,27 +60,24 @@ export function refundRoutes(): Hono<AppEnv> {
const ctx = c.get("ctx");
const paymentId = c.req.query("paymentId");
const customerId = c.req.query("customerId");
// Tenant-scoped: a refund is visible only when its payment is ours.
const owned = await ownedPaymentIds(c);
const all = paymentId
? await ctx.refunds.listByPayment(paymentId)
: customerId
? await ctx.refunds.listByCustomer(customerId)
: await ctx.refundStore.listAll();
return data(c, all.filter((r) => owned.has(r.paymentId)));
if (paymentId) {
return data(c, await ctx.refunds.listByPayment(paymentId));
}
if (customerId) {
return data(c, await ctx.refunds.listByCustomer(customerId));
}
return data(c, await ctx.refundStore.listAll());
});
app.post("/:id/succeed", async (c) => {
const { id } = await ownedRefund(c, c.req.param("id"));
const refund = unwrapResult(await c.get("ctx").refunds.markSucceeded(id));
const refund = unwrapResult(await c.get("ctx").refunds.markSucceeded(c.req.param("id")));
return data(c, refund);
});
app.post("/:id/fail", async (c) => {
const { id } = await ownedRefund(c, c.req.param("id"));
const body = await parseBody(c, failSchema);
const refund = unwrapResult(
await c.get("ctx").refunds.markFailed(id, body.reason ?? "refund failed"),
await c.get("ctx").refunds.markFailed(c.req.param("id"), body.reason ?? "refund failed"),
);
return data(c, refund);
});

View File

@ -9,10 +9,7 @@
*/
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";
@ -24,32 +21,6 @@ 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> {
@ -64,21 +35,8 @@ 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, 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()))] } : {}),
};
const { organizationId, ...patch } = body;
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);
});

View File

@ -17,7 +17,7 @@ import {
import type { AppEnv } from "../context.js";
import { created, data } from "../http/respond.js";
import { parseBody } from "../http/validate.js";
import { requireOrg, requireOwned, ownedSubscription } from "../http/tenant.js";
import { requireOrg } from "../http/tenant.js";
const createSchema = z.object({
// Derived from the authenticated org (tenant scope); ignored if supplied.
@ -34,16 +34,16 @@ export function subscriptionRoutes(): Hono<AppEnv> {
app.post("/", async (c) => {
const ctx = c.get("ctx");
const body = await parseBody(c, createSchema);
// Tenant-scoped: the product (and the price hanging off it) must be the
// caller's own; another org's ids answer 404 like missing ones.
const product = requireOwned(c, await ctx.products.findById(body.productId), "product", body.productId);
const price = await ctx.prices.findById(body.priceId);
if (!price || price.productId !== product.id) throw notFound("price not found", { id: body.priceId });
if (!price) throw notFound("price not found", { id: body.priceId });
if (price.interval === "one_time") {
throw validationError("subscriptions require a recurring price interval", {
priceId: price.id,
});
}
const product = await ctx.products.findById(body.productId);
if (!product) throw notFound("product not found", { id: body.productId });
const subscription = createSubscription({
organizationId: requireOrg(c),
customerId: body.customerId,
@ -66,12 +66,15 @@ export function subscriptionRoutes(): Hono<AppEnv> {
});
app.get("/:id", async (c) => {
return data(c, await ownedSubscription(c, c.req.param("id")));
const sub = await c.get("ctx").subscriptions.findById(c.req.param("id"));
if (!sub) throw notFound("subscription not found", { id: c.req.param("id") });
return data(c, sub);
});
app.post("/:id/renew", async (c) => {
const ctx = c.get("ctx");
const sub = await ownedSubscription(c, c.req.param("id"));
const sub = await ctx.subscriptions.findById(c.req.param("id"));
if (!sub) throw notFound("subscription not found", { id: c.req.param("id") });
const price = await ctx.prices.findById(sub.priceId);
if (!price) throw notFound("price not found", { id: sub.priceId });
const interval = price.interval === "yearly" ? "yearly" : "monthly";
@ -80,7 +83,8 @@ export function subscriptionRoutes(): Hono<AppEnv> {
app.post("/:id/cancel", async (c) => {
const ctx = c.get("ctx");
const sub = await ownedSubscription(c, c.req.param("id"));
const sub = await ctx.subscriptions.findById(c.req.param("id"));
if (!sub) throw notFound("subscription not found", { id: c.req.param("id") });
return data(c, await ctx.subscriptions.save(cancelSubscription(sub)));
});

View File

@ -1,209 +0,0 @@
/**
* 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,35 +9,23 @@
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, validate } from "../http/validate.js";
import { requireOrg, requireOwned } from "../http/tenant.js";
import { parseBody } from "../http/validate.js";
import { requireOrg } 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({
@ -54,29 +42,6 @@ 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>();
@ -148,92 +113,9 @@ export function webhookRoutes(): Hono<AppEnv> {
});
app.get("/events/:id", async (c) => {
const id = c.req.param("id");
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))));
const event = await c.get("ctx").webhookEvents.findById(c.req.param("id"));
if (!event) throw notFound("webhook event not found", { id: c.req.param("id") });
return data(c, event);
});
return app;

View File

@ -1,197 +0,0 @@
/**
* Agent payments over x402 v2 (x402-foundation `@x402/*` 2.27) on every chain.
* PUBLIC: the payment is the authorization.
*
* GET /v1/x402/networks what an agent can pay with (no payment)
* GET /v1/x402/research sample paid resource (@x402/hono paymentMiddleware)
* POST /v1/x402/products/:productId/buy buy a product: settle FIRST, then record the
* Payment (unique tx hash), grant the entitlement,
* run delivery inline and return the artifact
* * /v1/x402/facilitator/* self-hosted facilitator (see ./x402-evm.ts)
*
* One 402 challenge lists every configured network (Solana / Base / Arbitrum
* via PayAI; Ethereum / HyperEVM / Robinhood via the local facilitator); the
* agent picks one. Buy body (optional JSON): { email?, githubUsername?, discordUserId? }.
*/
import { Hono, type Context } from "hono";
import type { HTTPRequestContext, PaymentOption, RoutesConfig } from "@x402/core/http";
import { decodePaymentSignatureHeader } from "@x402/core/http";
import type { AssetAmount } from "@x402/core/types";
import { paymentMiddleware, x402HTTPResourceServer, x402ResourceServer } from "@x402/hono";
import { toAtomicAmount } from "@settlekit/x402-facilitator";
import type { AppEnv } from "../context.js";
import type { AgentPaymentNetwork, AgentPaymentsRuntime } from "../agent-payments/config.js";
import { fulfilAgentPurchase } from "../agent-payments/fulfil.js";
import { fulfilmentError } from "../agent-payments/unfulfilled.js";
import { readBuyer, resolvePurchasable, type Purchasable } from "../agent-payments/purchasable.js";
import { ContextAdapter, settleFirstPayment, type SettleFirstVariables } from "../agent-payments/settle-first.js";
import { data, error } from "../http/respond.js";
import { localFacilitatorRoutes, registerEvmSchemes } from "./x402-evm.js";
import { registerSvmSchemes } from "./x402-svm.js";
interface AgentVariables extends SettleFirstVariables {
x402Purchase?: Purchasable;
}
type AgentEnv = { Variables: AppEnv["Variables"] & AgentVariables };
const RESEARCH_PATTERN = "GET /research";
const BUY_PATTERN = "POST /products/:productId/buy";
function priceFor(entry: AgentPaymentNetwork, decimalAmount: string): AssetAmount {
return { asset: entry.asset, amount: toAtomicAmount(decimalAmount, entry.decimals), extra: entry.extra };
}
function staticOption(entry: AgentPaymentNetwork, amount: string, maxTimeoutSeconds: number): PaymentOption {
return { scheme: "exact", network: entry.caip2, payTo: entry.payTo, price: priceFor(entry, amount), maxTimeoutSeconds };
}
/** Buy options: price resolved per request from the product; settle before delivery. */
function purchaseOption(entry: AgentPaymentNetwork, maxTimeoutSeconds: number): PaymentOption {
return {
scheme: "exact",
network: entry.caip2,
payTo: entry.payTo,
maxTimeoutSeconds,
extra: { paymentFlow: "upfront" },
price: (context: HTTPRequestContext) => {
const purchase = (context.adapter as ContextAdapter).context.get("x402Purchase") as Purchasable | undefined;
if (!purchase) throw new Error("purchase was not resolved before the payment challenge");
return priceFor(entry, purchase.price.amount);
},
};
}
function payerOf(c: Context): string | undefined {
const header = c.req.header("payment-signature") ?? c.req.header("x-payment");
if (!header) return undefined;
try {
const payload = decodePaymentSignatureHeader(header).payload as Record<string, { from?: unknown } | undefined>;
const from = payload.authorization?.from ?? payload.permit2Authorization?.from;
return typeof from === "string" ? from : undefined;
} catch {
return undefined;
}
}
function unavailable(c: Context, runtime: AgentPaymentsRuntime | null): Response {
return c.json(
{
error: {
code: "agent_payments_unavailable",
message: "no x402 network is configured on this deployment",
details: { notes: runtime?.notes ?? [] },
},
},
503,
);
}
/** Mount under `/v1/x402`. `runtime` null serves the discovery + 503s only. */
export function x402AgentRoutes(runtime: AgentPaymentsRuntime | null): Hono<AgentEnv> {
const app = new Hono<AgentEnv>();
app.get("/networks", (c) =>
data(c, {
networks: (runtime?.networks ?? []).map(({ network, caip2, env, symbol, asset, decimals, payTo, facilitator, experimental }) => ({
network,
caip2,
env,
symbol,
asset,
decimals,
payTo,
facilitator,
experimental,
})),
mpp: runtime?.mpp
? { network: "tempo", env: runtime.mpp.env, chainId: runtime.mpp.chainId, currency: runtime.mpp.currency, symbol: runtime.mpp.symbol }
: null,
notes: runtime?.notes ?? [],
}),
);
app.route("/facilitator", localFacilitatorRoutes(runtime));
if (!runtime || runtime.networks.length === 0) {
app.get("/research", (c) => unavailable(c, runtime));
app.post("/products/:productId/buy", (c) => unavailable(c, runtime));
return app;
}
const server = new x402ResourceServer([...runtime.facilitators]);
registerEvmSchemes(server, runtime.networks);
registerSvmSchemes(server, runtime.networks);
const researchRoutes: RoutesConfig = {
[RESEARCH_PATTERN]: {
accepts: runtime.networks.map((entry) => staticOption(entry, runtime.researchPrice, runtime.maxTimeoutSeconds)),
description: "SettleKit sample paid research resource",
mimeType: "application/json",
},
};
app.get("/research", paymentMiddleware(researchRoutes, server), async (c) => {
const ctx = c.get("ctx");
await ctx.usage.record(
{ organizationId: runtime.organizationId, customerId: payerOf(c) ?? "x402_agent", productId: "prod_x402_research", metric: "paid_calls" },
1,
new Date(),
);
return data(c, {
answer: "Paid research result: SettleKit settles agent payments on Solana, Base, Arbitrum, Ethereum, HyperEVM and Robinhood.",
generatedAt: new Date().toISOString(),
});
});
const buyServer = new x402HTTPResourceServer(server, {
[BUY_PATTERN]: {
accepts: runtime.networks.map((entry) => purchaseOption(entry, runtime.maxTimeoutSeconds)),
description: "Buy a SettleKit product (settles before delivery)",
mimeType: "application/json",
},
});
app.post(
"/products/:productId/buy",
async (c, next) => {
try {
const buyer = await readBuyer(c.req.raw);
c.set("x402Purchase", await resolvePurchasable(c.get("ctx"), c.req.param("productId"), buyer));
} catch (err) {
return error(c, err);
}
await next();
},
settleFirstPayment(buyServer),
async (c) => {
const settled = c.get("x402Settled");
const purchase = c.get("x402Purchase");
const entry = runtime.networks.find((candidate) => candidate.caip2 === settled?.requirements.network);
if (!settled || !purchase || !entry) {
return c.json({ error: { code: "internal_error", message: "settled payment missing" } }, 500);
}
try {
const result = await fulfilAgentPurchase(c.get("ctx"), {
product: purchase.product,
price: purchase.price,
rail: "x402",
network: entry.network,
txHash: settled.settlement.transaction,
...(settled.settlement.payer ? { payer: settled.settlement.payer } : {}),
assetSymbol: entry.symbol,
buyer: purchase.buyer,
});
return data(c, result, 201);
} catch (err) {
return fulfilmentError(c, err, {
rail: "x402",
network: entry.network,
txHash: settled.settlement.transaction,
productId: purchase.product.id,
...(settled.settlement.payer ? { payer: settled.settlement.payer } : {}),
});
}
},
);
return app;
}

View File

@ -1,46 +0,0 @@
/**
* x402 on EVM chains: spec-compliant `exact` payments (EIP-3009
* `transferWithAuthorization`, or Permit2 via the x402 proxy for tokens
* without it). Base and Arbitrum settle through the remote facilitator
* (PayAI); Ethereum, HyperEVM and Robinhood (and Tempo when explicitly
* enabled) through SettleKit's self-hosted facilitator, whose standard
* facilitator endpoints are also exposed here:
*
* GET /v1/x402/facilitator/supported public
* GET /v1/x402/facilitator/assets public
* POST /v1/x402/facilitator/verify Bearer X402_FACILITATOR_TOKEN
* POST /v1/x402/facilitator/settle Bearer X402_FACILITATOR_TOKEN
*/
import { Hono } from "hono";
import type { x402ResourceServer } from "@x402/core/server";
import { ExactEvmScheme } from "@x402/evm/exact/server";
import { createFacilitatorHttpHandler } from "@settlekit/x402-facilitator";
import type { AgentPaymentNetwork, AgentPaymentsRuntime } from "../agent-payments/config.js";
/** EVM networks among the offered ones. */
export function evmNetworks(networks: readonly AgentPaymentNetwork[]): AgentPaymentNetwork[] {
return networks.filter((entry) => entry.caip2.startsWith("eip155:"));
}
/** Register the `exact` EVM server scheme for every offered EVM network. */
export function registerEvmSchemes(server: x402ResourceServer, networks: readonly AgentPaymentNetwork[]): void {
for (const entry of evmNetworks(networks)) server.register(entry.caip2, new ExactEvmScheme());
}
/** The self-hosted facilitator's HTTP surface, or 404s when it is not configured. */
export function localFacilitatorRoutes(runtime: AgentPaymentsRuntime | null): Hono {
const app = new Hono();
const local = runtime?.localFacilitator ?? null;
if (!local) {
app.all("*", (c) =>
c.json({ error: { code: "not_found", message: "self-hosted x402 facilitator is not configured" } }, 404),
);
return app;
}
const handle = createFacilitatorHttpHandler(local, {
...(runtime?.facilitatorToken ? { authToken: runtime.facilitatorToken } : {}),
basePath: "/v1/x402/facilitator",
});
app.all("*", (c) => handle(c.req.raw));
return app;
}

View File

@ -1,19 +0,0 @@
/**
* x402 on Solana (SOLANA-PLAN section D): spec-compliant `exact` SVM payments
* (a partially-signed SPL USDC transfer the facilitator co-signs as fee payer
* and submits). Facilitated remotely by PayAI; mounted into the shared agent
* router in ./x402-evm.ts so one 402 challenge offers every network.
*/
import type { x402ResourceServer } from "@x402/core/server";
import { ExactSvmScheme } from "@x402/svm/exact/server";
import type { AgentPaymentNetwork } from "../agent-payments/config.js";
/** Solana networks among the offered ones. */
export function svmNetworks(networks: readonly AgentPaymentNetwork[]): AgentPaymentNetwork[] {
return networks.filter((entry) => entry.network === "solana");
}
/** Register the `exact` SVM server scheme for every offered Solana network. */
export function registerSvmSchemes(server: x402ResourceServer, networks: readonly AgentPaymentNetwork[]): void {
for (const entry of svmNetworks(networks)) server.register(entry.caip2, new ExactSvmScheme());
}

View File

@ -1,108 +0,0 @@
/**
* Lock a ZEC quote for a new Zcash checkout session.
*
* The amount carries a per-session zatoshi tag (transparent addresses have
* no memo), kept unique among the OPEN sessions paying the same address so
* an incoming payment matches exactly one session. The tag is assigned and
* the session saved atomically per payTo (Postgres advisory lock across
* instances, in-process mutex otherwise) — see `saveWithUniqueTag`.
*/
import {
SettleKitError,
validationError,
type CheckoutSession,
type SettlementQuote,
} from "@settlekit/common";
import { withAdvisoryLock } from "@settlekit/database";
import {
createInMemoryTagLock,
lockQuote,
QuoteError,
saveWithUniqueTag,
usdToZats,
type TagLock,
} from "@settlekit/zcash";
import type { AppContext } from "../context.js";
import { payToFor } from "./payment-verification.js";
/** The tag embedded in a session's locked quote (amount minus the USD conversion). */
function tagOf(session: CheckoutSession): number | null {
const quote = session.settlementQuote;
if (quote === undefined) return null;
const tag = BigInt(quote.amountBase) - usdToZats(session.amount.amount, quote.rate);
return tag >= 0n ? Number(tag) : null;
}
/** Tags held by OTHER open Zcash sessions with a live quote on `payTo`. */
async function takenTags(ctx: AppContext, sessionId: string, payTo: string, now: Date): Promise<Set<number>> {
const open = await ctx.checkouts.findOpen();
const tags = open
.filter((session) => session.id !== sessionId && payToFor(session, "zcash") === payTo)
.filter((session) => session.settlementQuote !== undefined && Date.parse(session.settlementQuote.expiresAt) > now.getTime())
.map(tagOf)
.filter((tag): tag is number => tag !== null);
return new Set(tags);
}
/** One in-process lock shared by every in-memory context in this process. */
const inMemoryTagLock = createInMemoryTagLock();
/** Per-payTo lock: Postgres advisory lock when a database is wired, else in-process. */
function tagLockFor(ctx: AppContext): TagLock {
const db = ctx.db;
if (!db) return inMemoryTagLock;
return { withLock: (key, fn) => withAdvisoryLock(db, `zcash-tag:${key}`, fn) };
}
/**
* Save `session` (whose `settlementQuote` was locked with tag 0 by
* {@link lockZcashQuoteFor}) with a tag unique on `payTo`, atomically.
*/
export async function saveZcashSession(
ctx: AppContext,
session: CheckoutSession & { settlementQuote: SettlementQuote },
payTo: string,
now: Date = new Date(),
): Promise<CheckoutSession> {
return saveWithUniqueTag({
lock: tagLockFor(ctx),
payTo,
sessionId: session.id,
baseQuote: session.settlementQuote,
takenTags: () => takenTags(ctx, session.id, payTo, now),
save: (settlementQuote) => ctx.checkouts.save({ ...session, settlementQuote }),
});
}
/**
* Lock the base (tag 0) quote for `session` paying `payTo`; the unique tag is
* added when the session is saved via {@link saveZcashSession}. 400 when
* Zcash is disabled, 502 when prices fail.
*/
export async function lockZcashQuoteFor(
ctx: AppContext,
session: CheckoutSession,
now: Date = new Date(),
): Promise<SettlementQuote> {
if (ctx.zcash === null) {
throw validationError('zcash payments are not enabled on this deployment (set ZCASH_ENABLED)', { network: "zcash" });
}
try {
return await lockQuote({
usdAmount: session.amount.amount,
tag: 0,
sources: ctx.zcash.priceSources,
now,
ttlSec: ctx.zcash.quoteTtlSec,
});
} catch (error) {
if (error instanceof QuoteError) {
throw new SettleKitError({
code: "integration_error",
message: `could not lock a ZEC price: ${error.message}`,
retryable: true,
});
}
throw error;
}
}

View File

@ -5,8 +5,6 @@
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() {
@ -23,10 +21,7 @@ function log(message: string, fields: Record<string, unknown> = {}): void {
/** Start listening. Returns the running server handle. */
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 app = await createServer();
const server = serve({ fetch: app.fetch, port }, (info) => {
log("api listening", { port: info.port, url: `http://localhost:${info.port}` });
});
@ -40,7 +35,6 @@ 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

@ -1,115 +0,0 @@
/**
* 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. */
export function buildDiscordClient(deps: Pick<DeliveryWiringDeps, "discordApi" | "grants">): DiscordRoleClient {
function buildDiscordClient(deps: DeliveryWiringDeps): DiscordRoleClient {
return {
async addRole(input) {
const grant = await grantDiscordRole(deps.discordApi, {

View File

@ -11,28 +11,12 @@ import { describe, it, expect, beforeEach } from "vitest";
import type { Hono } from "hono";
import { createApp } from "../src/app.js";
import { createContext, type AppEnv } from "../src/context.js";
import { randomBytes } from "node:crypto";
import type { SettlementVerifier } from "@settlekit/chains";
const BOOTSTRAP = "test-bootstrap-key";
/**
* Stand-in for the Base chain: payment confirmation now fails closed without
* an on-chain verifier, so these flow tests register one that accepts any
* proof whose network matches the challenged session.
*/
const baseChainDouble: SettlementVerifier = async (proof, requirements) =>
proof.network === requirements.network ? { ok: true } : { ok: false, reason: "network mismatch" };
/** A fresh, well-formed EVM transaction hash (each settles one payment). */
function evmTxHash(): string {
return `0x${randomBytes(32).toString("hex")}`;
}
async function authedApp(): Promise<Hono<AppEnv>> {
process.env.API_BOOTSTRAP_KEY = BOOTSTRAP;
const ctx = await createContext();
return createApp({ ...ctx, verifiers: { ...ctx.verifiers, base: baseChainDouble } });
return createApp(await createContext());
}
interface Json {
@ -90,7 +74,7 @@ async function makeConfirmedPayment(
merchantId: "mch_1",
customerId,
items: [{ priceId, productId, quantity: 1 }],
payToAddress: "0x1111111111111111111111111111111111111111",
payToAddress: "0xMerchantWallet",
network: "base",
});
const sessionId = checkout.json.data.id as string;
@ -99,7 +83,7 @@ async function makeConfirmedPayment(
});
const paymentId = payment.json.data.id as string;
await call(app, "POST", `/v1/payments/${paymentId}/confirm`, {
txHash: evmTxHash(),
txHash: "0xdeadbeef",
confirmations: 3,
});
return { paymentId, customerId };
@ -161,7 +145,7 @@ describe("SettleKit API", () => {
merchantId: "mch_1",
customerId,
items: [{ priceId, productId, quantity: 1 }],
payToAddress: "0x1111111111111111111111111111111111111111",
payToAddress: "0xMerchantWallet",
network: "base",
});
expect(checkout.status).toBe(201);
@ -178,7 +162,7 @@ describe("SettleKit API", () => {
// 6. Confirm the payment -> session completed + entitlement granted.
const confirmed = await call(app, "POST", `/v1/payments/${paymentId}/confirm`, {
txHash: evmTxHash(),
txHash: "0xabc123",
confirmations: 3,
});
expect(confirmed.status).toBe(200);
@ -633,27 +617,13 @@ describe("SettleKit API", () => {
});
it("starts a dunning campaign and records a recovery", async () => {
// Dunning is tenant-scoped: it needs a real subscription owned by the caller.
const product = await call(app, "POST", "/v1/products", {
merchantId: "mch_1",
name: "Dunning Plan",
type: "saas_plan",
deliveryMode: "saas_entitlement",
const started = await call(app, "POST", "/v1/dunning", {
subscriptionId: "sub_dun_1",
});
const productId = product.json.data.id as string;
const price = await call(app, "POST", `/v1/products/${productId}/prices`, { amount: "9", interval: "monthly" });
const sub = await call(app, "POST", "/v1/subscriptions", {
customerId: "cus_dun",
productId,
priceId: price.json.data.id,
});
const subscriptionId = sub.json.data.subscription.id as string;
const started = await call(app, "POST", "/v1/dunning", { subscriptionId });
expect(started.status).toBe(201);
expect(started.json.data.status).toBe("active");
const recovered = await call(app, "POST", `/v1/dunning/${subscriptionId}/attempt`, {
const recovered = await call(app, "POST", "/v1/dunning/sub_dun_1/attempt", {
outcome: "recovered",
});
expect(recovered.json.data.status).toBe("recovered");
@ -829,24 +799,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 1%, no fixed fee:
// fee = 0.40 ; net = 39.60.
// Settle a 40.00 USDC payment. Default take-rate is 2.5% + 0.30:
// fee = 1.00 + 0.30 = 1.30 ; net = 38.70.
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("0.4");
expect(balance.json.data.netToMerchant.amount).toBe("39.6");
expect(balance.json.data.platformFees.amount).toBe("1.3");
expect(balance.json.data.netToMerchant.amount).toBe("38.7");
// Withdrawable is net of the platform fee (no prior payouts yet).
expect(balance.json.data.available.amount).toBe("39.6");
expect(balance.json.data.feeSchedule.bps).toBe(100);
expect(balance.json.data.available.amount).toBe("38.7");
expect(balance.json.data.feeSchedule.bps).toBe(250);
// 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: "39.60",
amount: "38.70",
network: "arc",
});
expect(ok.status).toBe(201);

View File

@ -1,109 +0,0 @@
/**
* 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

@ -1,151 +0,0 @@
/**
* Checkout-session network bindings (acceptedNetworks, payToByNetwork, Zcash
* quote locking with unique amount tags), the multi-chain verifier registry
* and chain env loading.
*/
import { describe, expect, it } from "vitest";
import type { Hono } from "hono";
import { usdToZats } from "@settlekit/zcash";
import { createApp } from "../src/app.js";
import { createContext, type AppEnv } from "../src/context.js";
import { loadConfig } from "../src/config/env.js";
import { buildIntegrations } from "../src/config/integrations.js";
import { buildVerifierRegistry } from "../src/config/verifier-registry.js";
import { assertChainIdsAtBoot } from "../src/config/boot-checks.js";
import { evmLedger, zcashLedger } from "./support/multichain-fakes.js";
const BOOTSTRAP = "test-bootstrap-key";
const EVM = "0x1111111111111111111111111111111111111111";
const SOL = "mvines9iiHiQTysrwkJjGf2gb9Ex9jXJX8ns3qwf2kN";
const ZEC = "t1Ne88F8ouCV92brDXNBB47a85brvnEHE8g";
async function zcashApp(): Promise<Hono<AppEnv>> {
process.env.API_BOOTSTRAP_KEY = BOOTSTRAP;
const registry = buildVerifierRegistry(loadConfig({ ZCASH_ENABLED: "true" }), { fetch: zcashLedger().fetch });
const ctx = await createContext();
return createApp({ ...ctx, verifiers: registry.verifiers, zcash: registry.zcash });
}
async function call(app: Hono<AppEnv>, 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 } } };
}
async function session(app: Hono<AppEnv>, body: Record<string, unknown>) {
const product = await call(app, "POST", "/v1/products", {
merchantId: "mch_1", organizationId: "org_1", name: "Repo", description: "Source", type: "github_repo_access", deliveryMode: "github_invite",
});
const price = await call(app, "POST", `/v1/products/${product.json.data.id}/prices`, { amount: "25.00", interval: "one_time" });
return call(app, "POST", "/v1/checkout-sessions", {
merchantId: "mch_1", items: [{ priceId: price.json.data.id, productId: product.json.data.id, quantity: 1 }], ...body,
});
}
describe("checkout session network bindings", () => {
it("accepts several networks with per-network payTo and binds each", async () => {
const app = await zcashApp();
const res = await session(app, {
payToAddress: EVM,
network: "base",
acceptedNetworks: ["base", "tempo", "solana", "zcash"],
payToByNetwork: { solana: SOL, zcash: ZEC },
});
expect(res.status).toBe(201);
expect(res.json.data.acceptedNetworks).toEqual(["base", "tempo", "solana", "zcash"]);
expect(res.json.data.paymentReference).toBeDefined();
expect(res.json.data.settlementQuote).toMatchObject({ asset: "ZEC", decimals: 8, rate: "1438.25", source: "coinbase" });
});
it("validates every accepted network's payTo and the network list", async () => {
const app = await zcashApp();
const badSolana = await session(app, { payToAddress: EVM, network: "base", acceptedNetworks: ["base", "solana"] });
expect(badSolana.status).toBe(400);
const missingPrimary = await session(app, { payToAddress: EVM, network: "base", acceptedNetworks: ["arbitrum"] });
expect(missingPrimary.status).toBe(400);
const stray = await session(app, { payToAddress: EVM, network: "base", payToByNetwork: { solana: SOL } });
expect(stray.status).toBe(400);
const zeroAddress = await session(app, { payToAddress: "0x0000000000000000000000000000000000000000", network: "arbitrum" });
expect(zeroAddress.status).toBe(400);
const shielded = await session(app, { payToAddress: "zs1z7rejlpsa98s2rrrfkwmaxu53e4ue0ulcrw0h4x5g8jl04tak0d3mm47vdtahatqrlkngh9sly", network: "zcash" });
expect(shielded.status).toBe(400);
expect(JSON.stringify(shielded.json.error)).toMatch(/shielded/);
});
it("gives concurrent Zcash sessions on one address distinct amounts", async () => {
const app = await zcashApp();
const amounts = new Set<string>();
for (let i = 0; i < 5; i += 1) {
const res = await session(app, { payToAddress: ZEC, network: "zcash" });
expect(res.status).toBe(201);
const quote = res.json.data.settlementQuote;
expect(BigInt(quote.amountBase) - usdToZats("25", quote.rate)).toBeLessThan(10_000n);
amounts.add(quote.amountBase);
}
expect(amounts.size).toBe(5);
});
it("returns 502 when no ZEC price can be obtained", async () => {
process.env.API_BOOTSTRAP_KEY = BOOTSTRAP;
const down = async () => ({ ok: false, status: 503, json: async () => ({}) });
const registry = buildVerifierRegistry(loadConfig({ ZCASH_ENABLED: "true" }), { fetch: down });
const app = createApp({ ...(await createContext()), verifiers: registry.verifiers, zcash: registry.zcash });
const res = await session(app, { payToAddress: ZEC, network: "zcash" });
expect(res.status).toBe(502);
expect(res.json.error?.code).toBe("integration_error");
});
});
describe("verifier registry", () => {
it("registers exactly the enabled networks", () => {
const { verifiers } = buildIntegrations(
loadConfig({ ENABLED_EVM_CHAINS: "tempo,robinhood", ZCASH_ENABLED: "true", SOLANA_CLUSTER: "devnet" }),
);
expect(Object.keys(verifiers).sort()).toEqual(["robinhood", "solana", "tempo", "zcash"]);
});
it("exposes the zcash runtime only when enabled", () => {
expect(buildIntegrations(loadConfig({})).zcash).toBeNull();
expect(buildIntegrations(loadConfig({ ZCASH_ENABLED: "1" })).zcash).toMatchObject({ network: "mainnet", quoteTtlSec: 900, minConfirmations: 3 });
});
});
describe("boot chain-id assertion", () => {
const config = loadConfig({ ENABLED_EVM_CHAINS: "base", SETTLEKIT_CHAIN_ENV: "mainnet" });
const logs: string[] = [];
const log = (message: string) => logs.push(message);
it("passes when every RPC serves its chain", async () => {
const { evmVerifiers } = buildVerifierRegistry(config, { evmRpcs: { base: evmLedger(8453).rpc } });
await expect(assertChainIdsAtBoot(evmVerifiers, log)).resolves.toBeUndefined();
});
it("refuses to boot on a chain-id mismatch", async () => {
const { evmVerifiers } = buildVerifierRegistry(config, { evmRpcs: { base: evmLedger(84532).rpc } });
await expect(assertChainIdsAtBoot(evmVerifiers, log)).rejects.toThrow(/Refusing to boot/);
});
it("only warns when an RPC is unreachable", async () => {
const rpc = { ...evmLedger(8453).rpc, getChainId: async () => Promise.reject(new Error("ECONNREFUSED")) };
const { evmVerifiers } = buildVerifierRegistry(config, { evmRpcs: { base: rpc } });
await expect(assertChainIdsAtBoot(evmVerifiers, log)).resolves.toBeUndefined();
expect(logs.some((line) => line.includes("unreachable"))).toBe(true);
});
});
describe("loadConfig chain groups", () => {
it("defaults to testnet with no chains and Zcash off", () => {
const cfg = loadConfig({});
expect(cfg.evm).toEqual({ env: "testnet", enabled: {}, notes: [] });
expect(cfg.zcash).toBeNull();
expect(cfg.hasZcash).toBe(false);
});
it("surfaces chain misconfiguration as a ConfigError", () => {
expect(() => loadConfig({ ENABLED_EVM_CHAINS: "dogechain" })).toThrow(/unknown chain/);
expect(() => loadConfig({ ENABLED_EVM_CHAINS: "base", BASE_TOKEN_ADDRESS: "0x1111111111111111111111111111111111111111", NODE_ENV: "production", DATABASE_URL: "postgres://x", LICENSE_TOKEN_SECRET: "a", WEBHOOK_SIGNING_SECRET: "b", AUTH_COOKIE_SECRET: "c" })).toThrow(/refused in production/);
});
});

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