Compare commits
No commits in common. "main" and "feat/x402-multichain" have entirely different histories.
main
...
feat/x402-
142
.env.example
142
.env.example
@ -151,15 +151,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 +186,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
|
||||
@ -325,14 +287,6 @@ X402_PAY_TO=0x0000000000000000000000000000000000000000
|
||||
# ONCHAIN_BILLING_OPERATOR_PRIVATE_KEY=0x... # EVM operator (pull spender, escrow operator, refund sender)
|
||||
# ONCHAIN_BILLING_SOLANA_SECRET= # Solana SPL delegate + refund sender
|
||||
# ONCHAIN_BILLING_CHECKOUT_URL=https://pay.example.com # renewal-invoice links
|
||||
# ONCHAIN_BILLING_NETWORKS=base,arbitrum,solana,hypercore,zcash # default: every enabled network
|
||||
# ONCHAIN_BILLING_ESCROW=off # disable Base commerce-payments escrow
|
||||
# The hosted checkout calls /v1/onchain-billing server-side with this token
|
||||
# (same value on the API and the checkout; 32+ chars, e.g. openssl rand -hex 32).
|
||||
# Accepted ONLY under /v1/onchain-billing, with X-SettleKit-Organization.
|
||||
# SETTLEKIT_SERVICE_TOKEN=
|
||||
# Checkout: signs buyer "manage subscription" links (/s/<token>).
|
||||
# CHECKOUT_MANAGE_SECRET=
|
||||
# HYPERCORE_ENABLED=true # also enables HyperCore refunds (operator usdSend)
|
||||
# HYPERCORE_REFUND_PRIVATE_KEY=0x... # optional: HyperCore refund account (default: operator key)
|
||||
|
||||
@ -449,97 +403,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
|
||||
|
||||
82
.github/workflows/release-sdks.yml
vendored
82
.github/workflows/release-sdks.yml
vendored
@ -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 }}
|
||||
37
.github/workflows/render-keepwarm.yml
vendored
37
.github/workflows/render-keepwarm.yml
vendored
@ -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
|
||||
21
LICENSE
21
LICENSE
@ -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.
|
||||
137
README.md
137
README.md
@ -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).
|
||||
|
||||
---
|
||||
|
||||
@ -320,15 +232,10 @@ closed per network. Full matrix with finality notes:
|
||||
| Solana | USDC | mainnet, devnet | |
|
||||
| Base, Ethereum, Arbitrum, HyperEVM | USDC | mainnet, testnet | |
|
||||
| Robinhood Chain | USDG (mainnet), Mock USDC (testnet) | mainnet, testnet | no native USDC |
|
||||
| Robinhood Chain ($wif) | $wif, 18 decimals | mainnet only | experimental, Permit2-only — see `docs/worldisflat/SUBMISSION.md` |
|
||||
| Tempo | USDC.e (mainnet), pathUSD (testnet) | mainnet, testnet | bridged |
|
||||
| Arc | USDC | testnet only | testnet |
|
||||
| Zcash | ZEC at a locked USD quote | mainnet only | transparent, not shielded |
|
||||
|
||||
**World is Flat hackathon** (Robinhood Chain, $wif): full writeup, real on-chain proofs and an
|
||||
honest demo video at [docs/worldisflat/SUBMISSION.md](./docs/worldisflat/SUBMISSION.md) —
|
||||
[docs/worldisflat/media/settlekit-wif-demo.mp4](./docs/worldisflat/media/settlekit-wif-demo.mp4).
|
||||
|
||||
---
|
||||
|
||||
## Architecture overview
|
||||
@ -416,8 +323,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)
|
||||
|
||||
141
TAMEION.md
141
TAMEION.md
@ -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.
|
||||
@ -187,7 +187,6 @@ const KNOWN_EVENT_TYPES = new Set<WebhookEventType>([
|
||||
"entitlement.revoked",
|
||||
"delivery.succeeded",
|
||||
"delivery.failed",
|
||||
"invoice.paid",
|
||||
]);
|
||||
|
||||
function asEventType(value: string): WebhookEventType {
|
||||
|
||||
@ -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 -------------------------------------
|
||||
# ---- Base: Node 20 + pnpm via Corepack -------------------------------------
|
||||
FROM node:22-alpine AS base
|
||||
ENV PNPM_HOME=/pnpm
|
||||
ENV PATH=$PNPM_HOME:$PATH
|
||||
# Non-interactive build: lets the prod-deps `pnpm install --prod` purge the
|
||||
# modules dir without a TTY prompt (ERR_PNPM_ABORTED_REMOVE_MODULES_DIR_NO_TTY).
|
||||
ENV CI=true
|
||||
RUN corepack enable
|
||||
WORKDIR /app
|
||||
|
||||
# ---- Dependencies: install 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"]
|
||||
|
||||
@ -46,26 +46,22 @@
|
||||
"@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:*",
|
||||
|
||||
@ -30,9 +30,7 @@ import {
|
||||
} from "@settlekit/common";
|
||||
import { DeliveryRunner, type DeliveryContext } from "@settlekit/delivery";
|
||||
import { confirmPayment, recordPendingPayment } from "@settlekit/payments";
|
||||
import { paymentConfirmedWebhook } from "@settlekit/persistence";
|
||||
import type { AppContext } from "../context.js";
|
||||
import { emitWebhook } from "../webhooks/outbox.js";
|
||||
import { assertTxHashUnused, requireTxHash } from "../routes/payment-verification.js";
|
||||
import { deliveryActionsFor } from "./delivery-action.js";
|
||||
|
||||
@ -198,10 +196,6 @@ export async function fulfilAgentPurchase(ctx: AppContext, input: AgentPurchaseI
|
||||
...(input.price.creditsGranted !== undefined ? { creditsRemaining: input.price.creditsGranted } : {}),
|
||||
});
|
||||
const delivery = await runDelivery(ctx, input, payment, entitlement);
|
||||
await emitWebhook(
|
||||
ctx.webhookOutbox,
|
||||
paymentConfirmedWebhook(payment, { productIds: [input.product.id], ...(customer.email ? { customerEmail: customer.email } : {}) }),
|
||||
);
|
||||
return {
|
||||
payment,
|
||||
entitlement,
|
||||
|
||||
@ -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,
|
||||
},
|
||||
};
|
||||
}
|
||||
@ -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,9 @@ 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> {
|
||||
@ -140,11 +134,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 +186,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 +195,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());
|
||||
|
||||
@ -43,7 +43,6 @@ import {
|
||||
|
||||
export type { PaymentVerifiers, ZcashRuntime } from "./verifier-registry.js";
|
||||
import {
|
||||
buildDiscordClient,
|
||||
createDeliveryClients,
|
||||
type DeliveryGrantSink,
|
||||
} from "../wiring/delivery-clients.js";
|
||||
@ -181,15 +180,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
|
||||
|
||||
@ -170,9 +170,6 @@ 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,10 +194,6 @@ 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;
|
||||
@ -307,8 +300,6 @@ export interface AppContext {
|
||||
readonly agentPayments: AgentPaymentsRuntime | null;
|
||||
/** Onchain subscriptions, Base escrow and per-network refunds; null when unconfigured. */
|
||||
readonly onchainBilling: OnchainBillingRuntime | null;
|
||||
/** Live FX rates for fiat-priced products (frankfurter, ECB rates). */
|
||||
readonly fxRates: FxRateSource;
|
||||
}
|
||||
|
||||
/** Pick the Postgres implementation when `db` is set, else the in-memory one. */
|
||||
@ -420,10 +411,6 @@ export async function createContext(): Promise<AppContext> {
|
||||
...(process.env.MERCHANT_WEBSITE ? { website: process.env.MERCHANT_WEBSITE } : {}),
|
||||
};
|
||||
|
||||
const webhookEndpointStore = pick<EntityStore<WebhookEndpoint>>(db, (d) => new PgWebhookEndpointStore(d), () => new InMemoryEntityStore<WebhookEndpoint>());
|
||||
const webhookEventStore = pick<EntityStore<WebhookEvent>>(db, (d) => new PgWebhookEventStore(d), () => new InMemoryEntityStore<WebhookEvent>());
|
||||
const webhookJobs = createWebhookJobStore(db);
|
||||
|
||||
const base: Omit<AppContext, "onchainBilling"> = {
|
||||
db,
|
||||
persistent: db !== null,
|
||||
@ -440,10 +427,8 @@ 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 }),
|
||||
@ -572,10 +557,6 @@ export async function createContext(): Promise<AppContext> {
|
||||
payoutStore,
|
||||
platformFeeSchedule,
|
||||
agentPayments: loadAgentPayments(process.env, db ? { nonceStore: new PgX402NonceStore(db) } : {}),
|
||||
fxRates: createFrankfurterSource({
|
||||
...(process.env.FX_RATES_URL ? { baseUrl: process.env.FX_RATES_URL } : {}),
|
||||
...(process.env.FX_RATES_TTL_SECONDS ? { ttlMs: Number(process.env.FX_RATES_TTL_SECONDS) * 1000 } : {}),
|
||||
}),
|
||||
};
|
||||
return { ...base, onchainBilling: await buildApiOnchainBilling(base) };
|
||||
}
|
||||
@ -587,9 +568,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[];
|
||||
};
|
||||
}
|
||||
|
||||
@ -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;
|
||||
},
|
||||
};
|
||||
}
|
||||
@ -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;
|
||||
}
|
||||
@ -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,
|
||||
);
|
||||
}
|
||||
|
||||
@ -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" };
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
@ -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));
|
||||
}
|
||||
@ -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("&", "&")
|
||||
.replaceAll("<", "<")
|
||||
.replaceAll(">", ">")
|
||||
.replaceAll('"', """);
|
||||
}
|
||||
|
||||
/** 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;
|
||||
}
|
||||
@ -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,
|
||||
},
|
||||
};
|
||||
}
|
||||
@ -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);
|
||||
}
|
||||
@ -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 })),
|
||||
};
|
||||
}
|
||||
@ -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;
|
||||
}
|
||||
@ -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 });
|
||||
}
|
||||
@ -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;
|
||||
}
|
||||
@ -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` };
|
||||
}
|
||||
@ -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";
|
||||
}
|
||||
@ -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);
|
||||
}
|
||||
@ -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,
|
||||
};
|
||||
}
|
||||
@ -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();
|
||||
|
||||
@ -12,13 +12,7 @@ import {
|
||||
createAccessHooks,
|
||||
type OnchainBillingRuntime,
|
||||
} from "@settlekit/onchain-billing";
|
||||
import {
|
||||
DEFAULT_MERCHANT_ID,
|
||||
PgOnchainBillingStore,
|
||||
emitWebhookSafely,
|
||||
paymentConfirmedWebhook,
|
||||
subscriptionChargedWebhook,
|
||||
} from "@settlekit/persistence";
|
||||
import { DEFAULT_MERCHANT_ID, PgOnchainBillingStore } from "@settlekit/persistence";
|
||||
import { createHyperCoreClient, createHyperCoreUsdSender, loadHyperCoreConfig, type HyperCoreUsdSender } from "@settlekit/hyperliquid";
|
||||
import type { AppContext } from "../context.js";
|
||||
import { deliverOnchainSubscription } from "./delivery.js";
|
||||
@ -46,16 +40,6 @@ export async function buildApiOnchainBilling(
|
||||
async queueDelivery(delivery) {
|
||||
await deliverOnchainSubscription(ctx, delivery);
|
||||
},
|
||||
async onCharged(sub, charge, period, paymentId) {
|
||||
await emitWebhookSafely(ctx.webhookOutbox, subscriptionChargedWebhook(sub, charge, period, paymentId));
|
||||
const payment = paymentId ? await ctx.payments.findById(paymentId) : null;
|
||||
if (payment) {
|
||||
await emitWebhookSafely(
|
||||
ctx.webhookOutbox,
|
||||
paymentConfirmedWebhook(payment, { productIds: [sub.productId], ...(sub.customerEmail ? { customerEmail: sub.customerEmail } : {}) }),
|
||||
);
|
||||
}
|
||||
},
|
||||
}, {
|
||||
onError: (message, meta) => console.warn(`[onchain-billing] ${message}`, meta),
|
||||
});
|
||||
|
||||
@ -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,
|
||||
};
|
||||
}
|
||||
@ -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;
|
||||
}
|
||||
}
|
||||
@ -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;
|
||||
}
|
||||
@ -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);
|
||||
}
|
||||
@ -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 },
|
||||
});
|
||||
}
|
||||
@ -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);
|
||||
};
|
||||
}
|
||||
@ -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.
|
||||
|
||||
@ -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,
|
||||
|
||||
@ -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));
|
||||
|
||||
@ -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;
|
||||
}
|
||||
@ -25,9 +25,6 @@ import { parseBody } from "../http/validate.js";
|
||||
import { requireOrg, requireOwned } from "../http/tenant.js";
|
||||
import { payToFor } from "./payment-verification.js";
|
||||
import { lockZcashQuoteFor, saveZcashSession } from "./zcash-quote.js";
|
||||
import { applyPromo } from "../merchant/session-promo.js";
|
||||
import { lockFx, withFx } from "../fx/session-fx.js";
|
||||
import { withSessionTax } from "@settlekit/persistence";
|
||||
|
||||
const NETWORKS = PAYMENT_NETWORKS as unknown as readonly [PaymentNetwork, ...PaymentNetwork[]];
|
||||
|
||||
@ -57,12 +54,6 @@ const createSchema = z
|
||||
cancelUrl: z.string().url().optional(),
|
||||
collectedFields: z.record(z.string()).optional(),
|
||||
ttlDays: z.number().int().positive().optional(),
|
||||
/** Optional promo code; the session amount becomes the discounted total. */
|
||||
couponCode: z.string().trim().min(1).max(64).optional(),
|
||||
/** Buyer billing country (ISO alpha-2) for the seller's tax rate. */
|
||||
billingCountry: z.string().trim().length(2).optional(),
|
||||
/** Buyer VAT ID (EU B2B reverse charge when the seller enables it). */
|
||||
vatId: z.string().trim().min(4).max(20).optional(),
|
||||
})
|
||||
.superRefine((body, ctx) => {
|
||||
// Every payable network needs a valid destination for ITS chain: funds
|
||||
@ -98,7 +89,7 @@ const createSchema = z
|
||||
* payable (the paying tx must include it) and a locked ZEC quote when Zcash
|
||||
* is payable (the buyer owes exactly that many zatoshis).
|
||||
*/
|
||||
export async function withNetworkBindings(ctx: AppContext, session: CheckoutSession): Promise<CheckoutSession> {
|
||||
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;
|
||||
@ -150,13 +141,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,
|
||||
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,16 +153,8 @@ 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,
|
||||
...draft,
|
||||
...(body.acceptedNetworks !== undefined ? { acceptedNetworks: body.acceptedNetworks } : {}),
|
||||
...(body.payToByNetwork !== undefined ? { payToByNetwork: body.payToByNetwork } : {}),
|
||||
...(body.requireMemo === true ? { requireMemo: true } : {}),
|
||||
|
||||
@ -12,28 +12,16 @@ import { notFound, type Entitlement } from "@settlekit/common";
|
||||
import type { AppEnv } from "../context.js";
|
||||
import { data } from "../http/respond.js";
|
||||
import { parseBody, validate } from "../http/validate.js";
|
||||
import { requireOrg, requireOwned, scopeToOrg } from "../http/tenant.js";
|
||||
import { 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 +40,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, scopeToOrg(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);
|
||||
});
|
||||
|
||||
|
||||
@ -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;
|
||||
}
|
||||
@ -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 { z } from "zod";
|
||||
import { generateId, money, validationError } from "@settlekit/common";
|
||||
import { renderInvoicePdf } from "@settlekit/invoices";
|
||||
import { money } from "@settlekit/common";
|
||||
import type { Invoice, InvoiceLineItem } from "@settlekit/invoices";
|
||||
import type { AppEnv } from "../context.js";
|
||||
import { created, data } from "../http/respond.js";
|
||||
import { parseBody } from "../http/validate.js";
|
||||
import { unwrapResult } from "../http/internal.js";
|
||||
import { requireOrg, requireOwned, scopeToOrg } from "../http/tenant.js";
|
||||
import {
|
||||
closeInvoiceSessions,
|
||||
invoiceMerchant,
|
||||
payUrlFor,
|
||||
reconcileInvoiceWithPayments,
|
||||
sendInvoice,
|
||||
} from "../merchant/invoice-payments.js";
|
||||
import { payTokenOf, withoutReservedMetadata } from "@settlekit/invoices";
|
||||
|
||||
const amount = z.string().regex(/^\d+(\.\d+)?$/);
|
||||
|
||||
@ -60,23 +45,6 @@ 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) };
|
||||
}
|
||||
@ -84,25 +52,7 @@ function toLineItem(input: z.infer<typeof lineItemSchema>): InvoiceLineItem {
|
||||
/** Load an invoice by id, requiring it belongs to the caller's org (else 404). */
|
||||
async function ownedInvoice(c: Context<AppEnv>, id: string): Promise<Invoice> {
|
||||
const found = await c.get("ctx").invoices.get(id);
|
||||
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;
|
||||
return requireOwned(c, found.ok ? found.value : undefined, "invoice", id);
|
||||
}
|
||||
|
||||
export function invoiceRoutes(): Hono<AppEnv> {
|
||||
@ -126,61 +76,16 @@ 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, scopeToOrg(c, invoices));
|
||||
});
|
||||
|
||||
// `:id.html` must be matched before the bare `:id` route below.
|
||||
@ -206,20 +111,9 @@ export function invoiceRoutes(): Hono<AppEnv> {
|
||||
return data(c, invoice);
|
||||
});
|
||||
|
||||
app.post("/:id/send", async (c) => {
|
||||
const invoice = await ownedInvoice(c, c.req.param("id"));
|
||||
const raw = await c.req.json().catch(() => ({}));
|
||||
const body = sendSchema.safeParse(raw);
|
||||
if (!body.success) throw validationError("payerEmail must be an email address", { fields: ["payerEmail"] });
|
||||
const sent = await sendInvoice(c.get("ctx"), invoice, body.data.payerEmail ? { payerEmail: body.data.payerEmail } : {});
|
||||
return data(c, sent);
|
||||
});
|
||||
|
||||
app.post("/:id/void", async (c) => {
|
||||
const ctx = c.get("ctx");
|
||||
const { id } = await ownedInvoice(c, c.req.param("id"));
|
||||
const invoice = unwrapResult(await ctx.invoices.void(id));
|
||||
await closeInvoiceSessions(ctx, invoice);
|
||||
const invoice = unwrapResult(await c.get("ctx").invoices.void(id));
|
||||
return data(c, invoice);
|
||||
});
|
||||
|
||||
|
||||
@ -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;
|
||||
}
|
||||
@ -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([
|
||||
|
||||
@ -3,8 +3,8 @@
|
||||
*
|
||||
* GET /v1/onchain-billing/networks billable networks + methods
|
||||
* POST /v1/onchain-billing/subscriptions create intent -> what the buyer signs/sends
|
||||
* GET /v1/onchain-billing/subscriptions?customerId=&view=1 list (org-scoped; view=1 -> dashboard read model)
|
||||
* GET /v1/onchain-billing/subscriptions/:id one subscription + its charges + read model
|
||||
* GET /v1/onchain-billing/subscriptions?customerId= list (org-scoped)
|
||||
* GET /v1/onchain-billing/subscriptions/:id one subscription + its charges
|
||||
* POST /v1/onchain-billing/subscriptions/:id/grant submit the signed grant; charges period 0
|
||||
* POST /v1/onchain-billing/subscriptions/:id/charge charge the due period now (idempotent)
|
||||
* POST /v1/onchain-billing/subscriptions/:id/cancel cancel (at period end by default) + revoke actions
|
||||
@ -13,8 +13,7 @@
|
||||
* 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)
|
||||
* POST /v1/onchain-billing/refunds owner refund, dispatched per network
|
||||
*/
|
||||
import { Hono, type Context } from "hono";
|
||||
import { z } from "zod";
|
||||
@ -26,12 +25,10 @@ import {
|
||||
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 { completeSession, createCheckoutSession } from "@settlekit/payments";
|
||||
import {
|
||||
BILLING_METHODS,
|
||||
ChargeDeclinedError,
|
||||
@ -47,9 +44,6 @@ 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");
|
||||
@ -66,13 +60,6 @@ const createSchema = z.object({
|
||||
periods: z.number().int().min(1).max(120).optional(),
|
||||
/** Link to an existing core subscription (else one is created on first charge). */
|
||||
subscriptionId: z.string().min(1).optional(),
|
||||
/** Delivery identities collected at checkout (GitHub invite, Discord role). */
|
||||
buyer: z
|
||||
.object({
|
||||
githubUsername: z.string().trim().min(1).max(39).optional(),
|
||||
discordUserId: z.string().regex(/^\d{15,21}$/).optional(),
|
||||
})
|
||||
.optional(),
|
||||
});
|
||||
|
||||
const grantSchema = z.object({
|
||||
@ -80,11 +67,7 @@ const grantSchema = z.object({
|
||||
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 cancelSchema = z.object({ atPeriodEnd: z.boolean().optional() });
|
||||
|
||||
const escrowSchema = z.object({
|
||||
payer: z.string().regex(/^0x[0-9a-fA-F]{40}$/),
|
||||
@ -107,8 +90,6 @@ const refundSchema = z
|
||||
reason: z.enum(["duplicate", "fraudulent", "customer_request", "delivery_failed"]),
|
||||
/** Recipient for payments not made through onchain billing. */
|
||||
to: z.string().min(1).optional(),
|
||||
/** Revoke the access the payment granted (default true). */
|
||||
revokeAccess: z.boolean().optional(),
|
||||
})
|
||||
.refine((b) => b.paymentId !== undefined || b.escrowPaymentId !== undefined, { message: "paymentId or escrowPaymentId is required" });
|
||||
|
||||
@ -210,7 +191,6 @@ export function onchainBillingRoutes(): Hono<AppEnv> {
|
||||
await assertCustomerNotForeign(c, body.customerId);
|
||||
if (body.subscriptionId) await ownedCoreSubscription(c, body.subscriptionId);
|
||||
const organizationId = requireOrg(c);
|
||||
await upsertBuyer(ctx, organizationId, body);
|
||||
const checkoutSessionId = await recordSession(ctx, {
|
||||
organizationId,
|
||||
customerId: body.customerId,
|
||||
@ -243,24 +223,14 @@ export function onchainBillingRoutes(): Hono<AppEnv> {
|
||||
});
|
||||
|
||||
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)));
|
||||
const list = await billing(c).subscriptions.list({ organizationId: requireOrg(c), ...(customerId ? { customerId } : {}) });
|
||||
return data(c, list);
|
||||
});
|
||||
|
||||
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),
|
||||
});
|
||||
return data(c, { subscription: sub, charges: await billing(c).store.listCharges(sub.id) });
|
||||
});
|
||||
|
||||
app.post("/subscriptions/:id/grant", async (c) => {
|
||||
@ -291,15 +261,10 @@ export function onchainBillingRoutes(): Hono<AppEnv> {
|
||||
});
|
||||
|
||||
app.post("/subscriptions/:id/cancel", async (c) => {
|
||||
const ctx = c.get("ctx");
|
||||
const runtime = billing(c);
|
||||
const sub = await ownedSubscription(c, c.req.param("id"));
|
||||
const body = await parseBody(c, cancelSchema);
|
||||
const 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) });
|
||||
const result = await guard(() => billing(c).subscriptions.cancel(sub.id, body.atPeriodEnd ?? true));
|
||||
return data(c, jsonSafe(result));
|
||||
});
|
||||
|
||||
app.post("/escrow", async (c) => {
|
||||
@ -384,35 +349,11 @@ export function onchainBillingRoutes(): Hono<AppEnv> {
|
||||
return data(c, await guard(() => (runtime.escrow as NonNullable<typeof runtime.escrow>).reclaimCall(record.id)));
|
||||
});
|
||||
|
||||
app.get("/refunds/route", async (c) => {
|
||||
const runtime = billing(c);
|
||||
const paymentId = c.req.query("paymentId");
|
||||
if (!paymentId) throw validationError("paymentId query param is required");
|
||||
const payment = await requireOwnedPayment(c, paymentId);
|
||||
const escrow = paymentId.startsWith("pay_esc_");
|
||||
const route = runtime.refunds.routeFor(payment.network, escrow);
|
||||
const known = await knownPayer(c, payment.id);
|
||||
return data(c, {
|
||||
paymentId,
|
||||
network: payment.network,
|
||||
route,
|
||||
automated: route !== null,
|
||||
/** The payer's wallet when onchain billing recorded it; otherwise the seller supplies `to`. */
|
||||
to: known,
|
||||
needsRecipient: route !== null && !escrow && known === null,
|
||||
operator: runtime.operatorAddress,
|
||||
reason: route === null ? `The SettleKit operator wallet is not configured to send refunds on ${payment.network}.` : null,
|
||||
});
|
||||
});
|
||||
|
||||
app.post("/refunds", async (c) => {
|
||||
const ctx = c.get("ctx");
|
||||
const runtime = billing(c);
|
||||
const body = await parseBody(c, refundSchema);
|
||||
const target = await resolveRefundTarget(c, body);
|
||||
if (target.payment.status !== "confirmed") {
|
||||
throw validationError(`only confirmed payments can be refunded (payment is ${target.payment.status})`);
|
||||
}
|
||||
const refund = unwrapResult(
|
||||
await ctx.refunds.create({ payment: target.payment, customerId: target.payment.customerId, amount: body.amount, reason: body.reason }),
|
||||
);
|
||||
@ -426,24 +367,8 @@ export function onchainBillingRoutes(): Hono<AppEnv> {
|
||||
...(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) },
|
||||
});
|
||||
const succeeded = unwrapResult(await ctx.refunds.markSucceeded(refund.id));
|
||||
return created(c, { refund: succeeded, execution });
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.message : "refund failed";
|
||||
await ctx.refunds.markFailed(refund.id, reason);
|
||||
@ -522,68 +447,8 @@ async function resolveRefundTarget(
|
||||
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 (!body.to) throw validationError("`to` (the payer's address) is required for payments made outside onchain billing");
|
||||
const check = checkPayTo(payment.network, body.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);
|
||||
return { payment, network: payment.network, to: body.to };
|
||||
}
|
||||
|
||||
@ -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;
|
||||
}
|
||||
@ -21,9 +21,7 @@ import {
|
||||
refundPayment,
|
||||
} from "@settlekit/payments";
|
||||
import { completeSession } from "@settlekit/payments";
|
||||
import { paymentConfirmedWebhook, redeemSessionCoupon } from "@settlekit/persistence";
|
||||
import type { AppEnv, AppContext } from "../context.js";
|
||||
import { emitWebhook } from "../webhooks/outbox.js";
|
||||
import { created, data } from "../http/respond.js";
|
||||
import { parseBody } from "../http/validate.js";
|
||||
import { requireOrg, requireOwned, requireOwnedPayment } from "../http/tenant.js";
|
||||
@ -170,20 +168,10 @@ 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 });
|
||||
});
|
||||
|
||||
@ -260,7 +248,6 @@ export function paymentRoutes(): Hono<AppEnv> {
|
||||
// The on-chain verifier already enforced confirmations; mark confirmed.
|
||||
const settled = confirmPayment(pending, txHash, Math.max(body.confirmations, 1), 1);
|
||||
const saved = await ctx.payments.save(settled);
|
||||
await emitWebhook(ctx.webhookOutbox, paymentConfirmedWebhook(saved));
|
||||
return created(c, { payment: saved, deduped: false });
|
||||
});
|
||||
|
||||
|
||||
@ -7,14 +7,12 @@
|
||||
*/
|
||||
import { Hono, type Context } from "hono";
|
||||
import { z } from "zod";
|
||||
import { FIAT_CURRENCIES, fiatToUsdc, generateId, type Price, type Product } from "@settlekit/common";
|
||||
import { generateId, type Price, type Product } from "@settlekit/common";
|
||||
import { createProductDraft, publishProduct } from "@settlekit/product-catalog";
|
||||
import type { AppEnv } from "../context.js";
|
||||
import { created, data } from "../http/respond.js";
|
||||
import { parseBody } from "../http/validate.js";
|
||||
import { requireOrg, requireOwned } from "../http/tenant.js";
|
||||
import { isInvoiceProduct } from "../merchant/invoice-payments.js";
|
||||
import { assertCanCreateProduct } from "../platform/fee-statements.js";
|
||||
|
||||
const PRODUCT_TYPES = [
|
||||
"saas_plan",
|
||||
@ -61,34 +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" });
|
||||
}
|
||||
});
|
||||
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(),
|
||||
});
|
||||
|
||||
/** 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> {
|
||||
@ -123,7 +101,7 @@ export function productRoutes(): Hono<AppEnv> {
|
||||
app.get("/", async (c) => {
|
||||
// Tenant-scoped: only the authenticated organization's products.
|
||||
const org = requireOrg(c);
|
||||
const products = await c.get("ctx").products.list((p) => p.organizationId === org && !isInvoiceProduct(p));
|
||||
const products = await c.get("ctx").products.list((p) => p.organizationId === org);
|
||||
return data(c, products);
|
||||
});
|
||||
|
||||
@ -137,7 +115,6 @@ export function productRoutes(): Hono<AppEnv> {
|
||||
const ctx = c.get("ctx");
|
||||
const id = c.req.param("id");
|
||||
const product = await ownedProduct(c, id);
|
||||
if (product.status !== "active") await assertCanCreateProduct(ctx, product.organizationId);
|
||||
const prices = await ctx.prices.list((p) => p.productId === id);
|
||||
const published = publishProduct(product, prices);
|
||||
return data(c, await ctx.products.save(published));
|
||||
@ -150,16 +127,10 @@ export function productRoutes(): Hono<AppEnv> {
|
||||
await ownedProduct(c, productId);
|
||||
|
||||
const body = await parseBody(c, createPriceSchema);
|
||||
const fiat = body.displayCurrency !== undefined && body.displayAmount !== undefined;
|
||||
// USDC reference value at creation; each checkout re-converts at the live rate.
|
||||
const amount = fiat
|
||||
? fiatToUsdc(body.displayAmount!, (await ctx.fxRates.usdPer(body.displayCurrency!)).rate)
|
||||
: body.amount!;
|
||||
const price: Price = {
|
||||
id: generateId("price"),
|
||||
productId,
|
||||
amount,
|
||||
...(fiat ? { displayCurrency: body.displayCurrency!, displayAmount: body.displayAmount! } : {}),
|
||||
amount: body.amount,
|
||||
currency: body.currency,
|
||||
interval: body.interval,
|
||||
usageBased: body.usageBased,
|
||||
|
||||
@ -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;
|
||||
}
|
||||
@ -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);
|
||||
});
|
||||
|
||||
@ -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;
|
||||
}
|
||||
@ -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 { parseBody } from "../http/validate.js";
|
||||
import { requireOrg, requireOwned } from "../http/tenant.js";
|
||||
|
||||
const EVENT_TYPES = [
|
||||
"payment.confirmed",
|
||||
"payment.failed",
|
||||
"payment.refunded",
|
||||
"refund.succeeded",
|
||||
"subscription.created",
|
||||
"subscription.charged",
|
||||
"subscription.renewed",
|
||||
"subscription.canceled",
|
||||
"entitlement.granted",
|
||||
"entitlement.revoked",
|
||||
"delivery.succeeded",
|
||||
"delivery.failed",
|
||||
"invoice.paid",
|
||||
"webhook.test",
|
||||
] as const;
|
||||
|
||||
const createEndpointSchema = z.object({
|
||||
@ -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>();
|
||||
|
||||
@ -152,89 +117,5 @@ export function webhookRoutes(): Hono<AppEnv> {
|
||||
return data(c, requireOwned(c, await c.get("ctx").webhookEvents.findById(id), "webhook event", id));
|
||||
});
|
||||
|
||||
// Delivery log: one row per (event, endpoint) with every attempt.
|
||||
app.get("/deliveries", async (c) => {
|
||||
const ctx = c.get("ctx");
|
||||
const eventId = c.req.query("eventId");
|
||||
const endpointId = c.req.query("endpointId");
|
||||
const status = c.req.query("status");
|
||||
const limit = Math.min(Math.max(Number(c.req.query("limit") ?? 100) || 100, 1), 500);
|
||||
const jobs = (await ctx.webhookJobs.listByOrganization(requireOrg(c), 1_000))
|
||||
.filter((j) => (eventId ? j.event.id === eventId : true))
|
||||
.filter((j) => (endpointId ? j.endpoint.id === endpointId : true))
|
||||
.filter((j) => (status ? j.status === status : true))
|
||||
.slice(0, limit);
|
||||
return data(c, jobs.map(deliveryView));
|
||||
});
|
||||
|
||||
app.get("/deliveries/:id", async (c) => {
|
||||
const id = c.req.param("id");
|
||||
const job = await c.get("ctx").webhookJobs.findById(id);
|
||||
if (!job || job.event.organizationId !== requireOrg(c)) throw notFound("webhook delivery not found", { id });
|
||||
return data(c, deliveryView(job));
|
||||
});
|
||||
|
||||
// Resend an event (fresh delivery with a new signature and attempt log).
|
||||
app.post("/events/:id/resend", async (c) => {
|
||||
const ctx = c.get("ctx");
|
||||
const id = c.req.param("id");
|
||||
const event = requireOwned(c, await ctx.webhookEvents.findById(id), "webhook event", id);
|
||||
const raw = await c.req.json().catch(() => ({}));
|
||||
const body = validate(resendSchema, raw);
|
||||
const endpoints = body.endpointId
|
||||
? [await ownedEndpoint(c, body.endpointId)]
|
||||
: subscribedEndpoints(await ctx.webhookEndpoints.list(), event.organizationId, event.type);
|
||||
const jobs = [];
|
||||
for (const endpoint of endpoints) {
|
||||
jobs.push(await queueManualDelivery(ctx.db, ctx.webhookJobs, event, endpoint, "resend"));
|
||||
}
|
||||
return created(c, jobs.map(deliveryView));
|
||||
});
|
||||
|
||||
// Send a signed webhook.test event to one endpoint (ignores enabledEvents).
|
||||
app.post("/endpoints/:id/test", async (c) => {
|
||||
const ctx = c.get("ctx");
|
||||
const endpoint = await ownedEndpoint(c, c.req.param("id"));
|
||||
const event = await ctx.webhookEvents.save(
|
||||
buildWebhookEvent("webhook.test", { endpointId: endpoint.id, message: "Test event from SettleKit" }, {
|
||||
organizationId: endpoint.organizationId,
|
||||
}),
|
||||
);
|
||||
const job = await queueManualDelivery(ctx.db, ctx.webhookJobs, event, endpoint, "test");
|
||||
return created(c, deliveryView(job));
|
||||
});
|
||||
|
||||
// Rotate the signing secret; the old one keeps signing during the grace window.
|
||||
app.post("/endpoints/:id/rotate-secret", async (c) => {
|
||||
const ctx = c.get("ctx");
|
||||
const endpoint = await ownedEndpoint(c, c.req.param("id"));
|
||||
const raw = await c.req.json().catch(() => ({}));
|
||||
const body = validate(rotateSchema, raw);
|
||||
const rotated = await ctx.webhookEndpoints.save(rotateEndpointSecret(endpoint, new Date(), body.graceHours * 3_600_000));
|
||||
return data(c, {
|
||||
...publicEndpoint(rotated),
|
||||
signingSecret: rotated.signingSecret,
|
||||
previousSecretExpiresAt: rotated.previousSecretExpiresAt ?? null,
|
||||
});
|
||||
});
|
||||
|
||||
app.post("/endpoints/:id/disable", async (c) => {
|
||||
const ctx = c.get("ctx");
|
||||
const endpoint = await ownedEndpoint(c, c.req.param("id"));
|
||||
const saved = await ctx.webhookEndpoints.save({
|
||||
...endpoint,
|
||||
active: false,
|
||||
disabledAt: new Date().toISOString(),
|
||||
disabledReason: "disabled by the merchant",
|
||||
});
|
||||
return data(c, publicEndpoint(saved));
|
||||
});
|
||||
|
||||
app.post("/endpoints/:id/enable", async (c) => {
|
||||
const ctx = c.get("ctx");
|
||||
const endpoint = await ownedEndpoint(c, c.req.param("id"));
|
||||
return data(c, publicEndpoint(await ctx.webhookEndpoints.save(enableEndpoint(endpoint))));
|
||||
});
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
@ -6,7 +6,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() {
|
||||
@ -26,7 +25,6 @@ export async function startServer(port = Number(process.env.PORT ?? 8787)) {
|
||||
const ctx = await createContext();
|
||||
await assertChainIdsAtBoot(ctx.evmVerifiers, log);
|
||||
const app = createApp(ctx);
|
||||
const stopStatements = startStatementScheduler(ctx, log);
|
||||
const server = serve({ fetch: app.fetch, port }, (info) => {
|
||||
log("api listening", { port: info.port, url: `http://localhost:${info.port}` });
|
||||
});
|
||||
@ -40,7 +38,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", {});
|
||||
|
||||
@ -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);
|
||||
}
|
||||
@ -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, {
|
||||
|
||||
@ -829,24 +829,24 @@ describe("SettleKit API", () => {
|
||||
});
|
||||
|
||||
it("applies the platform take-rate to the merchant's withdrawable balance", async () => {
|
||||
// Settle a 40.00 USDC payment. Default take-rate is 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);
|
||||
|
||||
@ -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");
|
||||
});
|
||||
});
|
||||
@ -1,140 +0,0 @@
|
||||
/**
|
||||
* Checkout tax + tax-grade receipts: the seller's settings add tax on top of
|
||||
* the net price, the buyer's country / VAT ID pick the rate, onchain
|
||||
* verification expects the tax-inclusive total, and the receipt PDF is served
|
||||
* for the settled checkout.
|
||||
*/
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import type { Hono } from "hono";
|
||||
import type { SettlementVerifier } from "@settlekit/chains";
|
||||
import { createApp } from "../src/app.js";
|
||||
import { createContext, type AppContext, type AppEnv } from "../src/context.js";
|
||||
|
||||
const BOOTSTRAP = "test-bootstrap-key";
|
||||
const PAY_TO = "0x8888888888888888888888888888888888888888";
|
||||
|
||||
let app: Hono<AppEnv>;
|
||||
let ctx: AppContext;
|
||||
const verifiedAmounts: string[] = [];
|
||||
|
||||
const verifier: SettlementVerifier = async (proof, requirements) => {
|
||||
verifiedAmounts.push((requirements as unknown as { amount: string }).amount);
|
||||
return proof.network === requirements.network ? { ok: true } : { ok: false, reason: "network mismatch" };
|
||||
};
|
||||
|
||||
async function call(method: string, path: string, body?: unknown, auth = true) {
|
||||
const res = await app.request(path, {
|
||||
method,
|
||||
headers: { ...(auth ? { authorization: `Bearer ${BOOTSTRAP}` } : {}), "content-type": "application/json" },
|
||||
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
|
||||
});
|
||||
if ((res.headers.get("content-type") ?? "").includes("application/pdf")) {
|
||||
return { status: res.status, json: {} as { data?: any; error?: any }, pdf: Buffer.from(await res.arrayBuffer()) };
|
||||
}
|
||||
return { status: res.status, json: (await res.json()) as { data?: any; error?: { message: string } }, pdf: null };
|
||||
}
|
||||
|
||||
const TAX = {
|
||||
enabled: true,
|
||||
label: "VAT",
|
||||
sellerCountry: "de",
|
||||
taxId: "DE123456789",
|
||||
legalName: "Acme Software GmbH",
|
||||
defaultRateBps: 0,
|
||||
rates: { DE: 1900, FR: 2000 },
|
||||
reverseCharge: true,
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
process.env.API_BOOTSTRAP_KEY = BOOTSTRAP;
|
||||
const base = await createContext();
|
||||
ctx = { ...base, verifiers: { ...base.verifiers, base: verifier } };
|
||||
app = createApp(ctx);
|
||||
verifiedAmounts.length = 0;
|
||||
});
|
||||
|
||||
async function price(amount: string) {
|
||||
const product = await call("POST", "/v1/products", { merchantId: "mch_1", name: "Pro license", type: "license_key", deliveryMode: "license_key" });
|
||||
const p = await call("POST", `/v1/products/${product.json.data.id}/prices`, { amount });
|
||||
return { productId: product.json.data.id as string, priceId: p.json.data.id as string };
|
||||
}
|
||||
|
||||
describe("checkout tax", () => {
|
||||
it("validates and stores tax settings", async () => {
|
||||
const saved = await call("POST", "/v1/settings", { tax: TAX });
|
||||
expect(saved.status).toBe(200);
|
||||
expect(saved.json.data.tax).toMatchObject({ enabled: true, sellerCountry: "DE", rates: { DE: 1900, FR: 2000 } });
|
||||
const bad = await call("POST", "/v1/settings", { tax: { ...TAX, rates: { France: 2000 } } });
|
||||
expect(bad.status).toBe(400);
|
||||
});
|
||||
|
||||
it("charges the buyer's rate, verifies the taxed total and serves a tax-grade receipt", async () => {
|
||||
await call("POST", "/v1/settings", { tax: TAX });
|
||||
const { productId, priceId } = await price("100");
|
||||
const customer = await call("POST", "/v1/customers", { email: "ap@client.fr" });
|
||||
const base = { merchantId: "mch_1", customerId: customer.json.data.id, items: [{ priceId, productId, quantity: 1 }], payToAddress: PAY_TO, network: "base" };
|
||||
|
||||
const domestic = await call("POST", "/v1/checkout-sessions", base);
|
||||
expect(domestic.json.data.amount.amount).toBe("119");
|
||||
expect(domestic.json.data.tax).toMatchObject({ rateBps: 1900, jurisdiction: "DE", amount: { amount: "19" }, net: { amount: "100" } });
|
||||
|
||||
const b2b = await call("POST", "/v1/checkout-sessions", { ...base, billingCountry: "FR", vatId: "FR12345678901" });
|
||||
expect(b2b.json.data.amount.amount).toBe("100");
|
||||
expect(b2b.json.data.tax).toMatchObject({ reverseCharge: true, vatId: "FR12345678901" });
|
||||
|
||||
const consumer = await call("POST", "/v1/checkout-sessions", { ...base, billingCountry: "FR", collectedFields: { email: "ap@client.fr" } });
|
||||
expect(consumer.json.data.amount.amount).toBe("120");
|
||||
const sessionId = consumer.json.data.id as string;
|
||||
|
||||
// Receipt is only available once the checkout settled.
|
||||
expect((await call("GET", `/v1/public/receipts/${sessionId}/pdf`, undefined, false)).status).toBe(404);
|
||||
|
||||
const payment = await call("POST", "/v1/payments", { checkoutSessionId: sessionId });
|
||||
await call("POST", `/v1/payments/${payment.json.data.id}/confirm`, { txHash: `0x${randomBytes(32).toString("hex")}`, confirmations: 3 });
|
||||
expect(verifiedAmounts.at(-1)).toBe("120");
|
||||
|
||||
const receipt = await call("GET", `/v1/public/receipts/${sessionId}/pdf`, undefined, false);
|
||||
expect(receipt.status).toBe(200);
|
||||
expect(receipt.pdf?.subarray(0, 5).toString()).toBe("%PDF-");
|
||||
expect(receipt.pdf!.length).toBeGreaterThan(1500);
|
||||
});
|
||||
|
||||
it("combines a promo with tax without compounding", async () => {
|
||||
await call("POST", "/v1/settings", { tax: TAX });
|
||||
await call("POST", "/v1/coupons", { code: "TEN", discount: { type: "amount", amountOff: "10" } });
|
||||
const { productId, priceId } = await price("100");
|
||||
const s = await call("POST", "/v1/checkout-sessions", {
|
||||
merchantId: "mch_1",
|
||||
items: [{ priceId, productId, quantity: 1 }],
|
||||
payToAddress: PAY_TO,
|
||||
network: "base",
|
||||
couponCode: "TEN",
|
||||
});
|
||||
expect(s.json.data.tax.net.amount).toBe("90");
|
||||
expect(s.json.data.amount.amount).toBe("107.1");
|
||||
});
|
||||
|
||||
it("leaves checkout untaxed when the seller has no tax settings", async () => {
|
||||
const { productId, priceId } = await price("100");
|
||||
const s = await call("POST", "/v1/checkout-sessions", {
|
||||
merchantId: "mch_1",
|
||||
items: [{ priceId, productId, quantity: 1 }],
|
||||
payToAddress: PAY_TO,
|
||||
network: "base",
|
||||
billingCountry: "FR",
|
||||
});
|
||||
expect(s.json.data.amount.amount).toBe("100");
|
||||
expect(s.json.data.tax).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("embed origins setting", () => {
|
||||
it("stores exact https origins and rejects paths or plain http", async () => {
|
||||
const ok = await call("POST", "/v1/settings", { embedOrigins: ["https://Shop.Example.com", "https://shop.example.com", "http://localhost:3000"] });
|
||||
expect(ok.status).toBe(200);
|
||||
expect(ok.json.data.embedOrigins).toEqual(["https://shop.example.com", "http://localhost:3000"]);
|
||||
expect((await call("POST", "/v1/settings", { embedOrigins: ["https://shop.example.com/cart"] })).status).toBe(400);
|
||||
expect((await call("POST", "/v1/settings", { embedOrigins: ["http://shop.example.com"] })).status).toBe(400);
|
||||
});
|
||||
});
|
||||
@ -1,47 +0,0 @@
|
||||
import { Hono } from "hono";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { error } from "../src/http/respond.js";
|
||||
import { errorMiddleware } from "../src/middleware/error.js";
|
||||
|
||||
function appThatThrows(): Hono {
|
||||
const app = new Hono();
|
||||
app.use("*", errorMiddleware());
|
||||
app.get("/boom", () => {
|
||||
throw new Error('Failed query: insert into "prices" ... params: secret-value');
|
||||
});
|
||||
app.onError((err, c) => error(c, err));
|
||||
return app;
|
||||
}
|
||||
|
||||
describe("unhandled error envelope", () => {
|
||||
const originalEnv = process.env.NODE_ENV;
|
||||
afterEach(() => {
|
||||
process.env.NODE_ENV = originalEnv;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("hides internals from the caller in production and logs them server-side", async () => {
|
||||
process.env.NODE_ENV = "production";
|
||||
const writes: string[] = [];
|
||||
vi.spyOn(process.stderr, "write").mockImplementation((chunk: string | Uint8Array) => {
|
||||
writes.push(String(chunk));
|
||||
return true;
|
||||
});
|
||||
|
||||
const res = await appThatThrows().request("/boom");
|
||||
const body = (await res.json()) as { error: { code: string; message: string } };
|
||||
|
||||
expect(res.status).toBe(500);
|
||||
expect(body.error.code).toBe("internal_error");
|
||||
expect(body.error.message).not.toContain("Failed query");
|
||||
expect(body.error.message).not.toContain("secret-value");
|
||||
expect(writes.join("")).toContain("Failed query");
|
||||
});
|
||||
|
||||
it("keeps the detailed message outside production", async () => {
|
||||
process.env.NODE_ENV = "test";
|
||||
const res = await appThatThrows().request("/boom");
|
||||
const body = (await res.json()) as { error: { message: string } };
|
||||
expect(body.error.message).toContain("Failed query");
|
||||
});
|
||||
});
|
||||
@ -1,100 +0,0 @@
|
||||
/** Merchant accounting exports: tenant-scoped CSVs incl. Xero / QuickBooks imports. */
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import type { Hono } from "hono";
|
||||
import type { SettlementVerifier } from "@settlekit/chains";
|
||||
import { createApp } from "../src/app.js";
|
||||
import { createContext, type AppContext, type AppEnv } from "../src/context.js";
|
||||
|
||||
const BOOTSTRAP = "test-bootstrap-key";
|
||||
const PAY_TO = "0x9999999999999999999999999999999999999999";
|
||||
|
||||
let app: Hono<AppEnv>;
|
||||
let ctx: AppContext;
|
||||
let otherKey: string;
|
||||
|
||||
const verifier: SettlementVerifier = async (proof, req) =>
|
||||
proof.network === req.network ? { ok: true } : { ok: false, reason: "network mismatch" };
|
||||
|
||||
async function call(method: string, path: string, body?: unknown, key = BOOTSTRAP) {
|
||||
const res = await app.request(path, {
|
||||
method,
|
||||
headers: { authorization: `Bearer ${key}`, "content-type": "application/json" },
|
||||
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
|
||||
});
|
||||
const type = res.headers.get("content-type") ?? "";
|
||||
return {
|
||||
status: res.status,
|
||||
type,
|
||||
disposition: res.headers.get("content-disposition") ?? "",
|
||||
text: type.includes("text/csv") ? await res.text() : "",
|
||||
json: type.includes("json") ? ((await res.json()) as { data?: any; error?: { message: string } }) : {},
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
process.env.API_BOOTSTRAP_KEY = BOOTSTRAP;
|
||||
const base = await createContext();
|
||||
ctx = { ...base, verifiers: { ...base.verifiers, base: verifier } };
|
||||
app = createApp(ctx);
|
||||
otherKey = (
|
||||
await ctx.apiKeys.issue({ organizationId: "org_other", customerId: "c", productId: "__platform__", entitlementId: "e", scopes: ["*"], env: "live" })
|
||||
).plaintext;
|
||||
|
||||
const product = await call("POST", "/v1/products", { merchantId: "mch_1", name: "=cmd|' /C calc'!A0", type: "license_key", deliveryMode: "license_key" });
|
||||
const price = await call("POST", `/v1/products/${product.json.data.id}/prices`, { amount: "25" });
|
||||
const customer = await call("POST", "/v1/customers", { email: "buyer@example.com" });
|
||||
const session = await call("POST", "/v1/checkout-sessions", {
|
||||
merchantId: "mch_1",
|
||||
customerId: customer.json.data.id,
|
||||
items: [{ priceId: price.json.data.id, productId: product.json.data.id, quantity: 1 }],
|
||||
payToAddress: PAY_TO,
|
||||
network: "base",
|
||||
});
|
||||
const payment = await call("POST", "/v1/payments", { checkoutSessionId: session.json.data.id });
|
||||
await call("POST", `/v1/payments/${payment.json.data.id}/confirm`, { txHash: `0x${randomBytes(32).toString("hex")}`, confirmations: 3 });
|
||||
const refund = await call("POST", "/v1/refunds", { paymentId: payment.json.data.id, customerId: customer.json.data.id, amount: "5", reason: "customer_request" });
|
||||
await call("POST", `/v1/refunds/${refund.json.data.id}/succeed`, { txHash: `0x${randomBytes(32).toString("hex")}` });
|
||||
});
|
||||
|
||||
describe("accounting exports", () => {
|
||||
it("downloads payments as CSV with formula cells neutralized", async () => {
|
||||
const res = await call("GET", "/v1/exports/payments.csv");
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.type).toContain("text/csv");
|
||||
expect(res.disposition).toMatch(/attachment; filename="settlekit-.*-payments\.csv"/);
|
||||
const [header, row] = res.text.split("\n");
|
||||
expect(header).toContain('"id","created_at","confirmed_at","status","amount"');
|
||||
expect(row).toContain('"confirmed","25","USDC","base"');
|
||||
expect(row).toContain('"buyer@example.com"');
|
||||
expect(row).toContain(`"'=cmd|' /C calc'!A0"`);
|
||||
});
|
||||
|
||||
it("builds Xero and QuickBooks bank statements from payments and refunds", async () => {
|
||||
const xero = (await call("GET", "/v1/exports/xero.csv")).text.split("\n");
|
||||
expect(xero[0]).toBe('"*Date","*Amount","Payee","Description","Reference"');
|
||||
expect(xero).toHaveLength(3);
|
||||
expect(xero[1]).toContain('"25","buyer@example.com"');
|
||||
expect(xero.some((l) => l.includes('"-5"'))).toBe(true);
|
||||
const qb = (await call("GET", "/v1/exports/quickbooks.csv")).text.split("\n");
|
||||
expect(qb[0]).toBe('"Date","Description","Amount"');
|
||||
expect(qb).toHaveLength(3);
|
||||
expect((await call("GET", "/v1/exports/ledger.csv")).text).toContain('"refund","-5","USDC"');
|
||||
});
|
||||
|
||||
it("filters by date and rejects malformed dates", async () => {
|
||||
const future = await call("GET", "/v1/exports/ledger.csv?from=2999-01-01");
|
||||
expect(future.text.split("\n")).toHaveLength(1);
|
||||
expect((await call("GET", "/v1/exports/ledger.csv?from=yesterday")).status).toBe(400);
|
||||
});
|
||||
|
||||
it("exports refunds, invoices and payouts and never another tenant's data", async () => {
|
||||
expect((await call("GET", "/v1/exports/refunds.csv")).text.split("\n")).toHaveLength(2);
|
||||
expect((await call("GET", "/v1/exports/invoices.csv")).status).toBe(200);
|
||||
expect((await call("GET", "/v1/exports/payouts.csv")).status).toBe(200);
|
||||
const other = await call("GET", "/v1/exports/payments.csv", undefined, otherKey);
|
||||
expect(other.text.split("\n")).toHaveLength(1);
|
||||
expect((await call("GET", "/v1/exports/xero.csv", undefined, otherKey)).text.split("\n")).toHaveLength(1);
|
||||
expect((await call("GET", "/v1/exports/refunds.csv", undefined, otherKey)).text.split("\n")).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@ -1,179 +0,0 @@
|
||||
/**
|
||||
* Fiat pricing: prices set in EUR/GBP settle in USDC at a live rate
|
||||
* (frankfurter, ECB) locked on each checkout session.
|
||||
*/
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import type { Hono } from "hono";
|
||||
import type { SettlementVerifier } from "@settlekit/chains";
|
||||
import { createApp } from "../src/app.js";
|
||||
import { createContext, type AppContext, type AppEnv } from "../src/context.js";
|
||||
import { createFrankfurterSource, type FxRateSource } from "../src/fx/rates.js";
|
||||
|
||||
const BOOTSTRAP = "test-bootstrap-key";
|
||||
const PAY_TO = "0x1212121212121212121212121212121212121212";
|
||||
|
||||
let app: Hono<AppEnv>;
|
||||
let ctx: AppContext;
|
||||
let eurRate = "1.0834";
|
||||
const verified: string[] = [];
|
||||
|
||||
const fakeRates: FxRateSource = {
|
||||
async usdPer(currency) {
|
||||
if (currency === "USD") return { rate: "1", date: "2026-09-29", source: "USDC par" };
|
||||
if (currency === "EUR") return { rate: eurRate, date: "2026-09-29", source: "ECB via frankfurter" };
|
||||
if (currency === "GBP") return { rate: "1.27", date: "2026-09-29", source: "ECB via frankfurter" };
|
||||
throw new Error("unexpected currency");
|
||||
},
|
||||
};
|
||||
|
||||
const verifier: SettlementVerifier = async (proof, req) => {
|
||||
verified.push((req as unknown as { amount: string }).amount);
|
||||
return proof.network === req.network ? { ok: true } : { ok: false, reason: "network mismatch" };
|
||||
};
|
||||
|
||||
async function call(method: string, path: string, body?: unknown, auth = true) {
|
||||
const res = await app.request(path, {
|
||||
method,
|
||||
headers: { ...(auth ? { authorization: `Bearer ${BOOTSTRAP}` } : {}), "content-type": "application/json" },
|
||||
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
|
||||
});
|
||||
return { status: res.status, json: (await res.json()) as { data?: any; error?: { message: string } } };
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
process.env.API_BOOTSTRAP_KEY = BOOTSTRAP;
|
||||
eurRate = "1.0834";
|
||||
verified.length = 0;
|
||||
const base = await createContext();
|
||||
ctx = { ...base, fxRates: fakeRates, verifiers: { ...base.verifiers, base: verifier } };
|
||||
app = createApp(ctx);
|
||||
});
|
||||
|
||||
async function eurProduct(displayAmount = "29") {
|
||||
const product = await call("POST", "/v1/products", { merchantId: "mch_1", name: "Kurs", type: "license_key", deliveryMode: "license_key" });
|
||||
const price = await call("POST", `/v1/products/${product.json.data.id}/prices`, { displayCurrency: "EUR", displayAmount });
|
||||
return { productId: product.json.data.id as string, price: price };
|
||||
}
|
||||
|
||||
describe("frankfurter rate source", () => {
|
||||
it("parses, caches and sanity-checks rates", async () => {
|
||||
let calls = 0;
|
||||
let t = 0;
|
||||
const source = createFrankfurterSource({
|
||||
baseUrl: "https://fx.test/v1/",
|
||||
now: () => t,
|
||||
fetch: (async (url: string) => {
|
||||
calls += 1;
|
||||
expect(url).toBe("https://fx.test/v1/latest?base=EUR&symbols=USD");
|
||||
return new Response(JSON.stringify({ amount: 1, base: "EUR", date: "2026-09-29", rates: { USD: 1.0834 } }));
|
||||
}) as unknown as typeof fetch,
|
||||
});
|
||||
expect(await source.usdPer("EUR")).toEqual({ rate: "1.0834", date: "2026-09-29", source: "ECB via frankfurter" });
|
||||
await source.usdPer("EUR");
|
||||
expect(calls).toBe(1);
|
||||
t = 600_001;
|
||||
await source.usdPer("EUR");
|
||||
expect(calls).toBe(2);
|
||||
expect((await source.usdPer("USD")).rate).toBe("1");
|
||||
});
|
||||
|
||||
it("fails closed on errors and implausible rates", async () => {
|
||||
const down = createFrankfurterSource({ fetch: (async () => new Response("", { status: 502 })) as unknown as typeof fetch });
|
||||
await expect(down.usdPer("EUR")).rejects.toMatchObject({ code: "integration_error" });
|
||||
const junk = createFrankfurterSource({
|
||||
fetch: (async () => new Response(JSON.stringify({ date: "2026-09-29", rates: { USD: 0 } }))) as unknown as typeof fetch,
|
||||
});
|
||||
await expect(junk.usdPer("GBP")).rejects.toThrow(/temporarily unavailable/);
|
||||
const offline = createFrankfurterSource({
|
||||
fetch: (async () => {
|
||||
throw new TypeError("fetch failed");
|
||||
}) as unknown as typeof fetch,
|
||||
});
|
||||
await expect(offline.usdPer("EUR")).rejects.toThrow(/unreachable/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("fiat-priced checkout", () => {
|
||||
it("stores a EUR price with a USDC reference and refuses fiat subscriptions", async () => {
|
||||
const { price, productId } = await eurProduct("29");
|
||||
expect(price.status).toBe(201);
|
||||
expect(price.json.data).toMatchObject({ displayCurrency: "EUR", displayAmount: "29", amount: "31.42", currency: "USDC" });
|
||||
const sub = await call("POST", `/v1/products/${productId}/prices`, { displayCurrency: "EUR", displayAmount: "9", interval: "monthly" });
|
||||
expect(sub.status).toBe(400);
|
||||
const half = await call("POST", `/v1/products/${productId}/prices`, { displayCurrency: "EUR" });
|
||||
expect(half.status).toBe(400);
|
||||
});
|
||||
|
||||
it("locks today's rate on the session and verifies the converted USDC amount", async () => {
|
||||
const { price, productId } = await eurProduct("29");
|
||||
eurRate = "1.1"; // the rate moved since the price was created
|
||||
const session = await call("POST", "/v1/checkout-sessions", {
|
||||
merchantId: "mch_1",
|
||||
items: [{ priceId: price.json.data.id, productId, quantity: 2 }],
|
||||
payToAddress: PAY_TO,
|
||||
network: "base",
|
||||
customerId: (await call("POST", "/v1/customers", { email: "k@x.test" })).json.data.id,
|
||||
});
|
||||
expect(session.status).toBe(201);
|
||||
expect(session.json.data.amount.amount).toBe("63.8");
|
||||
expect(session.json.data.fxQuote).toMatchObject({ currency: "EUR", amount: "58", rate: "1.1", usdcAmount: "63.8", rateDate: "2026-09-29" });
|
||||
expect(session.json.data.fxQuote.expiresAt).toBe(session.json.data.expiresAt);
|
||||
|
||||
const payment = await call("POST", "/v1/payments", { checkoutSessionId: session.json.data.id });
|
||||
await call("POST", `/v1/payments/${payment.json.data.id}/confirm`, { txHash: `0x${randomBytes(32).toString("hex")}`, confirmations: 3 });
|
||||
expect(verified.at(-1)).toBe("63.8");
|
||||
});
|
||||
|
||||
it("refuses mixing two fiat currencies in one checkout", async () => {
|
||||
const eur = await eurProduct("10");
|
||||
const gbpProduct = await call("POST", "/v1/products", { merchantId: "mch_1", name: "UK", type: "license_key", deliveryMode: "license_key" });
|
||||
const gbp = await call("POST", `/v1/products/${gbpProduct.json.data.id}/prices`, { displayCurrency: "GBP", displayAmount: "10" });
|
||||
const res = await call("POST", "/v1/checkout-sessions", {
|
||||
merchantId: "mch_1",
|
||||
items: [
|
||||
{ priceId: eur.price.json.data.id, productId: eur.productId, quantity: 1 },
|
||||
{ priceId: gbp.json.data.id, productId: gbpProduct.json.data.id, quantity: 1 },
|
||||
],
|
||||
payToAddress: PAY_TO,
|
||||
network: "base",
|
||||
});
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it("prices a quick product in EUR, shows it on the link and discounts the converted amount", async () => {
|
||||
await call("POST", "/v1/merchant/profile", { orgName: "Shop", acceptedNetworks: ["base"], addresses: { evm: PAY_TO } });
|
||||
await call("POST", "/v1/coupons", { code: "HALF", discount: { type: "percent", percentOff: 50 } });
|
||||
const product = await call("POST", "/v1/merchant/products", {
|
||||
name: "Kurs",
|
||||
priceUsd: "29",
|
||||
currency: "EUR",
|
||||
delivery: { kind: "license_key", machineLimit: 1 },
|
||||
});
|
||||
expect(product.status).toBe(201);
|
||||
expect(product.json.data).toMatchObject({ displayCurrency: "EUR", displayAmount: "29" });
|
||||
const slug = product.json.data.slug as string;
|
||||
|
||||
eurRate = "1.2";
|
||||
const summary = await call("GET", `/v1/public/links/${slug}`, undefined, false);
|
||||
expect(summary.json.data).toMatchObject({ displayCurrency: "EUR", displayAmount: "29", priceUsd: "34.8" });
|
||||
|
||||
const opened = await call("POST", `/v1/public/links/${slug}/sessions`, { promo: "HALF" }, false);
|
||||
const session = await ctx.checkouts.findById(opened.json.data.sessionId);
|
||||
expect(session?.fxQuote).toMatchObject({ currency: "EUR", rate: "1.2" });
|
||||
expect(session?.amount.amount).toBe("17.4");
|
||||
|
||||
// Editing the price keeps the currency.
|
||||
const patched = await call("PATCH", `/v1/merchant/products/${product.json.data.id}`, { priceUsd: "39" });
|
||||
expect(patched.json.data).toMatchObject({ displayCurrency: "EUR", displayAmount: "39", priceUsd: "46.8" });
|
||||
|
||||
const monthly = await call("POST", "/v1/merchant/products", {
|
||||
name: "Sub",
|
||||
priceUsd: "9",
|
||||
currency: "EUR",
|
||||
interval: "monthly",
|
||||
delivery: { kind: "license_key", machineLimit: 1 },
|
||||
});
|
||||
expect(monthly.status).toBe(400);
|
||||
});
|
||||
});
|
||||
@ -1,130 +0,0 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { money, type CheckoutSession, type Payment, type Price, type Product, type Subscription } from "@settlekit/common";
|
||||
import type { SettlementVerifier } from "@settlekit/chains";
|
||||
import { computeGrowthMetrics } from "../src/analytics/metrics.js";
|
||||
import { createApp } from "../src/app.js";
|
||||
import { createContext } from "../src/context.js";
|
||||
|
||||
const NOW = new Date("2026-09-30T00:00:00.000Z");
|
||||
const day = (n: number) => new Date(NOW.getTime() - n * 86_400_000).toISOString();
|
||||
|
||||
function session(id: string, productId: string, createdDaysAgo: number, status: CheckoutSession["status"] = "open"): CheckoutSession {
|
||||
return {
|
||||
id,
|
||||
organizationId: "org_1",
|
||||
merchantId: "m",
|
||||
lineItems: [{ productId, priceId: `price_${productId}`, quantity: 1 }],
|
||||
amount: money("10"),
|
||||
status,
|
||||
payToAddress: "0x",
|
||||
network: "base",
|
||||
expiresAt: day(createdDaysAgo - 1),
|
||||
collectedFields: {},
|
||||
createdAt: day(createdDaysAgo),
|
||||
};
|
||||
}
|
||||
|
||||
function payment(id: string, sessionId: string, customerId: string, amount: string, daysAgo: number): Payment {
|
||||
return {
|
||||
id,
|
||||
organizationId: "org_1",
|
||||
checkoutSessionId: sessionId,
|
||||
customerId,
|
||||
amount: money(amount),
|
||||
network: "base",
|
||||
confirmations: 3,
|
||||
status: "confirmed",
|
||||
createdAt: day(daysAgo),
|
||||
confirmedAt: day(daysAgo),
|
||||
};
|
||||
}
|
||||
|
||||
function sub(id: string, status: Subscription["status"], periodEndDaysAgo: number): Subscription {
|
||||
return {
|
||||
id,
|
||||
organizationId: "org_1",
|
||||
customerId: "c",
|
||||
productId: "prod_sub",
|
||||
priceId: "price_sub",
|
||||
status,
|
||||
currentPeriodStart: day(periodEndDaysAgo + 30),
|
||||
currentPeriodEnd: day(periodEndDaysAgo),
|
||||
cancelAtPeriodEnd: false,
|
||||
createdAt: day(100),
|
||||
};
|
||||
}
|
||||
|
||||
describe("growth metrics", () => {
|
||||
it("computes conversion, per-link stats, repeat customers, churn and LTV", () => {
|
||||
const sessions = [
|
||||
session("s1", "prod_a", 3, "completed"),
|
||||
session("s2", "prod_a", 2),
|
||||
session("s3", "prod_a", 1, "completed"),
|
||||
session("s4", "prod_b", 5),
|
||||
session("s_old", "prod_a", 60, "completed"),
|
||||
{ ...session("s_inv", "prod_inv", 1, "completed"), invoiceId: "inv_1" },
|
||||
];
|
||||
const payments = [
|
||||
payment("p1", "s1", "cus_1", "10", 3),
|
||||
payment("p3", "s3", "cus_1", "10", 1),
|
||||
payment("p_old", "s_old", "cus_2", "20", 60),
|
||||
];
|
||||
const products = [
|
||||
{ id: "prod_a", name: "Course", metadata: { paymentLinkSlug: "course-1" } },
|
||||
{ id: "prod_b", name: "Kit", metadata: {} },
|
||||
] as unknown as Product[];
|
||||
const prices = [{ id: "price_sub", productId: "prod_sub", amount: "30", interval: "monthly" }] as unknown as Price[];
|
||||
const subscriptions = [sub("a1", "active", -10), sub("a2", "active", -5), sub("a3", "active", -3), sub("c1", "canceled", 5)];
|
||||
|
||||
const m = computeGrowthMetrics({ sessions, payments, subscriptions, products, prices, now: NOW, days: 30 });
|
||||
expect(m.checkouts).toEqual({ opened: 4, paid: 2, conversion: 0.5 });
|
||||
expect(m.links[0]).toEqual({ productId: "prod_a", name: "Course", slug: "course-1", opened: 3, paid: 2, conversion: 0.6667, revenue: "20" });
|
||||
expect(m.links[1]).toMatchObject({ productId: "prod_b", opened: 1, paid: 0, conversion: 0 });
|
||||
expect(m.revenue).toEqual({ window: "20", allTime: "40" });
|
||||
expect(m.customers).toEqual({ paying: 2, repeat: 1, repeatRate: 0.5 });
|
||||
expect(m.averageRevenuePerCustomer).toBe("20");
|
||||
expect(m.subscriptions).toMatchObject({ active: 3, churned: 1, churnRate: 0.25, arpu: "30" });
|
||||
expect(m.subscriptions.estimatedLifetimeValue).toBe("120");
|
||||
});
|
||||
|
||||
it("handles an empty account", () => {
|
||||
const m = computeGrowthMetrics({ sessions: [], payments: [], subscriptions: [], products: [], prices: [], now: NOW, days: 7 });
|
||||
expect(m.checkouts.conversion).toBe(0);
|
||||
expect(m.subscriptions.estimatedLifetimeValue).toBeNull();
|
||||
expect(m.averageRevenuePerCustomer).toBe("0");
|
||||
});
|
||||
|
||||
it("serves /v1/analytics/metrics from live data", async () => {
|
||||
process.env.API_BOOTSTRAP_KEY = "test-bootstrap-key";
|
||||
const base = await createContext();
|
||||
const ok: SettlementVerifier = async (proof, req) => (proof.network === req.network ? { ok: true } : { ok: false });
|
||||
const app = createApp({ ...base, verifiers: { ...base.verifiers, base: ok } });
|
||||
const call = async (method: string, path: string, body?: unknown) => {
|
||||
const res = await app.request(path, {
|
||||
method,
|
||||
headers: { authorization: "Bearer test-bootstrap-key", "content-type": "application/json" },
|
||||
...(body ? { body: JSON.stringify(body) } : {}),
|
||||
});
|
||||
return (await res.json()) as { data?: any };
|
||||
};
|
||||
const product = await call("POST", "/v1/products", { merchantId: "m", name: "Guide", type: "license_key", deliveryMode: "license_key" });
|
||||
const price = await call("POST", `/v1/products/${product.data.id}/prices`, { amount: "9" });
|
||||
const customer = await call("POST", "/v1/customers", { email: "a@b.test" });
|
||||
const open = async () =>
|
||||
call("POST", "/v1/checkout-sessions", {
|
||||
merchantId: "m",
|
||||
customerId: customer.data.id,
|
||||
items: [{ priceId: price.data.id, productId: product.data.id, quantity: 1 }],
|
||||
payToAddress: "0x1111111111111111111111111111111111111111",
|
||||
network: "base",
|
||||
});
|
||||
const s1 = await open();
|
||||
await open();
|
||||
const pay = await call("POST", "/v1/payments", { checkoutSessionId: s1.data.id });
|
||||
await call("POST", `/v1/payments/${pay.data.id}/confirm`, { txHash: `0x${randomBytes(32).toString("hex")}`, confirmations: 3 });
|
||||
const metrics = await call("GET", "/v1/analytics/metrics?days=7");
|
||||
expect(metrics.data.checkouts).toEqual({ opened: 2, paid: 1, conversion: 0.5 });
|
||||
expect(metrics.data.links[0]).toMatchObject({ name: "Guide", opened: 2, paid: 1, revenue: "9" });
|
||||
});
|
||||
});
|
||||
@ -1,335 +0,0 @@
|
||||
/**
|
||||
* Payable invoices + payment requests, end to end through the real routes:
|
||||
* send -> public pay page -> checkout session -> onchain-verified payment ->
|
||||
* the invoice flips to paid on the next read.
|
||||
*/
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import type { Hono } from "hono";
|
||||
import type { SettlementVerifier } from "@settlekit/chains";
|
||||
import { createEmailClient, type EmailPayload } from "@settlekit/notifications";
|
||||
import { createApp } from "../src/app.js";
|
||||
import { createContext, type AppContext, type AppEnv } from "../src/context.js";
|
||||
|
||||
const BOOTSTRAP = "test-bootstrap-key";
|
||||
const EVM_PAYTO = "0x2222222222222222222222222222222222222222";
|
||||
|
||||
const baseChainDouble: SettlementVerifier = async (proof, requirements) =>
|
||||
proof.network === requirements.network ? { ok: true } : { ok: false, reason: "network mismatch" };
|
||||
|
||||
interface Json {
|
||||
data?: any;
|
||||
error?: { code: string; message: string };
|
||||
}
|
||||
|
||||
interface Harness {
|
||||
app: Hono<AppEnv>;
|
||||
ctx: AppContext;
|
||||
sent: EmailPayload[];
|
||||
}
|
||||
|
||||
async function harness(withEmail = true): Promise<Harness> {
|
||||
process.env.API_BOOTSTRAP_KEY = BOOTSTRAP;
|
||||
process.env.CHECKOUT_PUBLIC_URL = "https://pay.test";
|
||||
const base = await createContext();
|
||||
const sent: EmailPayload[] = [];
|
||||
const email = withEmail
|
||||
? createEmailClient({
|
||||
from: "SettleKit <billing@settlekit.test>",
|
||||
transport: {
|
||||
async send(payload: EmailPayload) {
|
||||
sent.push(payload);
|
||||
return { id: `msg_${sent.length}` };
|
||||
},
|
||||
},
|
||||
})
|
||||
: null;
|
||||
const ctx: AppContext = { ...base, email, verifiers: { ...base.verifiers, base: baseChainDouble } };
|
||||
return { app: createApp(ctx), ctx, sent };
|
||||
}
|
||||
|
||||
async function call(app: Hono<AppEnv>, method: string, path: string, body?: unknown, auth = true) {
|
||||
const res = await app.request(path, {
|
||||
method,
|
||||
headers: {
|
||||
...(auth ? { authorization: `Bearer ${BOOTSTRAP}` } : {}),
|
||||
"content-type": "application/json",
|
||||
},
|
||||
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
|
||||
});
|
||||
const type = res.headers.get("content-type") ?? "";
|
||||
if (type.includes("application/pdf")) {
|
||||
return { status: res.status, json: {} as Json, pdf: Buffer.from(await res.arrayBuffer()) };
|
||||
}
|
||||
return { status: res.status, json: (await res.json()) as Json, pdf: null };
|
||||
}
|
||||
|
||||
async function onboard(app: Hono<AppEnv>): Promise<void> {
|
||||
const res = await call(app, "POST", "/v1/merchant/profile", {
|
||||
orgName: "Acme Studio",
|
||||
acceptedNetworks: ["base"],
|
||||
addresses: { evm: EVM_PAYTO },
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
}
|
||||
|
||||
async function customer(app: Hono<AppEnv>, email = "ap@client.test"): Promise<string> {
|
||||
const res = await call(app, "POST", "/v1/customers", { email });
|
||||
expect(res.status).toBe(201);
|
||||
return res.json.data.id as string;
|
||||
}
|
||||
|
||||
async function payOnchain(app: Hono<AppEnv>, sessionId: string): Promise<string> {
|
||||
const txHash = `0x${randomBytes(32).toString("hex")}`;
|
||||
const payment = await call(app, "POST", "/v1/payments", { checkoutSessionId: sessionId });
|
||||
expect(payment.status).toBe(201);
|
||||
const confirmed = await call(app, "POST", `/v1/payments/${payment.json.data.id}/confirm`, {
|
||||
txHash,
|
||||
confirmations: 3,
|
||||
});
|
||||
expect(confirmed.status).toBe(200);
|
||||
return txHash;
|
||||
}
|
||||
|
||||
function tokenOf(payUrl: string): string {
|
||||
return payUrl.split("/i/")[1]!;
|
||||
}
|
||||
|
||||
describe("payable invoices", () => {
|
||||
let h: Harness;
|
||||
beforeEach(async () => {
|
||||
h = await harness();
|
||||
});
|
||||
|
||||
it("sends an invoice, the client pays onchain, and it settles automatically", async () => {
|
||||
await onboard(h.app);
|
||||
const customerId = await customer(h.app);
|
||||
const created = await call(h.app, "POST", "/v1/invoices", {
|
||||
customerId,
|
||||
lineItems: [
|
||||
{ description: "Brand design", quantity: 1, unitAmount: "400" },
|
||||
{ description: "Revisions", quantity: 2, unitAmount: "50" },
|
||||
],
|
||||
dueAt: "2026-10-30T00:00:00.000Z",
|
||||
});
|
||||
expect(created.status).toBe(201);
|
||||
const id = created.json.data.id as string;
|
||||
|
||||
const sent = await call(h.app, "POST", `/v1/invoices/${id}/send`, {});
|
||||
expect(sent.status).toBe(200);
|
||||
const { invoice, payUrl, checkoutSessionId, emailedTo } = sent.json.data;
|
||||
expect(invoice.status).toBe("open");
|
||||
expect(payUrl).toMatch(/^https:\/\/pay\.test\/i\/[A-Za-z0-9_-]{16,}$/);
|
||||
expect(emailedTo).toBe("ap@client.test");
|
||||
expect(h.sent).toHaveLength(1);
|
||||
expect(h.sent[0]!.subject).toContain(invoice.number);
|
||||
expect(h.sent[0]!.html).toContain(payUrl);
|
||||
|
||||
// The session charges the invoice total to the merchant's wallet.
|
||||
const session = await h.ctx.checkouts.findById(checkoutSessionId);
|
||||
expect(session?.amount.amount).toBe("500");
|
||||
expect(session?.payToAddress).toBe(EVM_PAYTO);
|
||||
expect(session?.invoiceId).toBe(id);
|
||||
expect(session?.customerId).toBe(customerId);
|
||||
|
||||
// Re-sending keeps the same link and the same open session.
|
||||
const again = await call(h.app, "POST", `/v1/invoices/${id}/send`, {});
|
||||
expect(again.json.data.payUrl).toBe(payUrl);
|
||||
expect(again.json.data.checkoutSessionId).toBe(checkoutSessionId);
|
||||
|
||||
// Public pay page: no API key.
|
||||
const token = tokenOf(payUrl);
|
||||
const view = await call(h.app, "GET", `/v1/public/invoices/${token}`, undefined, false);
|
||||
expect(view.status).toBe(200);
|
||||
expect(view.json.data).toMatchObject({ number: invoice.number, total: "500", payable: true, merchantName: "Acme Studio" });
|
||||
expect(view.json.data.customerId).toBeUndefined();
|
||||
const opened = await call(h.app, "POST", `/v1/public/invoices/${token}/sessions`, {}, false);
|
||||
expect(opened.status).toBe(201);
|
||||
expect(opened.json.data.sessionId).toBe(checkoutSessionId);
|
||||
|
||||
const txHash = await payOnchain(h.app, checkoutSessionId);
|
||||
|
||||
const paid = await call(h.app, "GET", `/v1/invoices/${id}`);
|
||||
expect(paid.json.data.status).toBe("paid");
|
||||
expect(paid.json.data.metadata.paidTxHash).toBe(txHash);
|
||||
const publicPaid = await call(h.app, "GET", `/v1/public/invoices/${token}`, undefined, false);
|
||||
expect(publicPaid.json.data).toMatchObject({ status: "paid", payable: false, paidTxHash: txHash });
|
||||
const reopen = await call(h.app, "POST", `/v1/public/invoices/${token}/sessions`, {}, false);
|
||||
expect(reopen.status).toBe(400);
|
||||
|
||||
// The hidden invoice product never shows in the catalog.
|
||||
const products = await call(h.app, "GET", "/v1/merchant/products");
|
||||
expect(products.json.data).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("creates and sends an ad-hoc payment request to an email", async () => {
|
||||
await onboard(h.app);
|
||||
const res = await call(h.app, "POST", "/v1/invoices/requests", {
|
||||
amount: "75.50",
|
||||
description: "Consulting call, 1 hour",
|
||||
payerEmail: "founder@client.test",
|
||||
});
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.json.data.invoice).toMatchObject({ status: "open", total: { amount: "75.5" } });
|
||||
expect(res.json.data.invoice.metadata.kind).toBe("payment_request");
|
||||
expect(res.json.data.emailedTo).toBe("founder@client.test");
|
||||
const customerId = res.json.data.invoice.customerId as string;
|
||||
expect((await h.ctx.customers.findById(customerId))?.email).toBe("founder@client.test");
|
||||
|
||||
// A second request to the same email reuses the customer.
|
||||
const second = await call(h.app, "POST", "/v1/invoices/requests", {
|
||||
amount: "10",
|
||||
description: "Follow-up",
|
||||
payerEmail: "FOUNDER@client.test",
|
||||
});
|
||||
expect(second.json.data.invoice.customerId).toBe(customerId);
|
||||
|
||||
const missing = await call(h.app, "POST", "/v1/invoices/requests", { amount: "10", description: "x" });
|
||||
expect(missing.status).toBe(400);
|
||||
const zero = await call(h.app, "POST", "/v1/invoices/requests", {
|
||||
amount: "0",
|
||||
description: "x",
|
||||
payerEmail: "a@b.test",
|
||||
});
|
||||
expect(zero.status).toBe(400);
|
||||
});
|
||||
|
||||
it("refuses to send before a receiving wallet is configured", async () => {
|
||||
const customerId = await customer(h.app);
|
||||
const created = await call(h.app, "POST", "/v1/invoices", {
|
||||
customerId,
|
||||
lineItems: [{ description: "Work", quantity: 1, unitAmount: "10" }],
|
||||
});
|
||||
const sent = await call(h.app, "POST", `/v1/invoices/${created.json.data.id}/send`, {});
|
||||
expect(sent.status).toBe(400);
|
||||
expect(sent.json.error?.message).toMatch(/receiving wallet/);
|
||||
});
|
||||
|
||||
it("reports a skipped email when no transport is configured", async () => {
|
||||
const noEmail = await harness(false);
|
||||
await onboard(noEmail.app);
|
||||
const res = await call(noEmail.app, "POST", "/v1/invoices/requests", {
|
||||
amount: "5",
|
||||
description: "Tip",
|
||||
payerEmail: "x@y.test",
|
||||
});
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.json.data.emailedTo).toBeNull();
|
||||
expect(res.json.data.emailSkipped).toMatch(/not configured/);
|
||||
});
|
||||
|
||||
it("voiding cancels the open session so an old link cannot be paid", async () => {
|
||||
await onboard(h.app);
|
||||
const req = await call(h.app, "POST", "/v1/invoices/requests", {
|
||||
amount: "20",
|
||||
description: "Deposit",
|
||||
payerEmail: "p@q.test",
|
||||
});
|
||||
const { invoice, checkoutSessionId, payUrl } = req.json.data;
|
||||
const voided = await call(h.app, "POST", `/v1/invoices/${invoice.id}/void`);
|
||||
expect(voided.json.data.status).toBe("void");
|
||||
expect((await h.ctx.checkouts.findById(checkoutSessionId))?.status).toBe("canceled");
|
||||
const view = await call(h.app, "GET", `/v1/public/invoices/${tokenOf(payUrl)}`, undefined, false);
|
||||
expect(view.json.data).toMatchObject({ payable: false, status: "void" });
|
||||
});
|
||||
|
||||
it("serves invoice PDFs to the merchant and the pay-link holder", async () => {
|
||||
await onboard(h.app);
|
||||
const req = await call(h.app, "POST", "/v1/invoices/requests", {
|
||||
amount: "30",
|
||||
description: "Logo",
|
||||
payerEmail: "p@q.test",
|
||||
});
|
||||
const merchantPdf = await call(h.app, "GET", `/v1/invoices/${req.json.data.invoice.id}.pdf`);
|
||||
expect(merchantPdf.status).toBe(200);
|
||||
expect(merchantPdf.pdf?.subarray(0, 5).toString()).toBe("%PDF-");
|
||||
const publicPdf = await call(h.app, "GET", `/v1/public/invoices/${tokenOf(req.json.data.payUrl)}/pdf`, undefined, false);
|
||||
expect(publicPdf.status).toBe(200);
|
||||
expect(publicPdf.pdf?.subarray(0, 5).toString()).toBe("%PDF-");
|
||||
});
|
||||
|
||||
it("answers 404 for an unknown pay token and keeps invoices tenant-scoped", async () => {
|
||||
const unknown = await call(h.app, "GET", "/v1/public/invoices/unknown_token_abcdefghij", undefined, false);
|
||||
expect(unknown.status).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
describe("payment requests for plugins", () => {
|
||||
it("can skip the email and return the payer to the store after paying", async () => {
|
||||
const h = await harness();
|
||||
await onboard(h.app);
|
||||
const res = await call(h.app, "POST", "/v1/invoices/requests", {
|
||||
amount: "42.00",
|
||||
description: "Order #1001",
|
||||
payerEmail: "shopper@store.test",
|
||||
sendEmail: false,
|
||||
successUrl: "https://store.test/checkout/order-received/1001?key=wc_order_abc",
|
||||
metadata: { wc_order_id: "1001" },
|
||||
});
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.json.data.emailedTo).toBeNull();
|
||||
expect(h.sent).toHaveLength(0);
|
||||
const session = await h.ctx.checkouts.findById(res.json.data.checkoutSessionId);
|
||||
expect(session?.successUrl).toBe("https://store.test/checkout/order-received/1001?key=wc_order_abc");
|
||||
expect(res.json.data.invoice.metadata.wc_order_id).toBe("1001");
|
||||
|
||||
const insecure = await call(h.app, "POST", "/v1/invoices/requests", {
|
||||
amount: "1",
|
||||
description: "x",
|
||||
payerEmail: "a@b.test",
|
||||
successUrl: "http://evil.test/",
|
||||
});
|
||||
expect(insecure.status).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe("invoice settlement bindings cannot be forged", () => {
|
||||
it("ignores reserved metadata and never settles from another org's payment", async () => {
|
||||
const { app, ctx } = await harness(false);
|
||||
await onboard(app);
|
||||
const cus = await customer(app);
|
||||
// Another org's confirmed payment.
|
||||
await ctx.payments.save({
|
||||
id: "pay_foreign",
|
||||
organizationId: "org_someone_else",
|
||||
checkoutSessionId: "cs_foreign_paid",
|
||||
customerId: "cus_x",
|
||||
amount: { amount: "500", currency: "USDC" },
|
||||
network: "base",
|
||||
txHash: `0x${randomBytes(32).toString("hex")}`,
|
||||
confirmations: 3,
|
||||
status: "confirmed",
|
||||
createdAt: new Date().toISOString(),
|
||||
confirmedAt: new Date().toISOString(),
|
||||
} as never);
|
||||
const createdRes = await call(app, "POST", "/v1/invoices", {
|
||||
customerId: cus,
|
||||
lineItems: [{ description: "Work", quantity: 1, unitAmount: "100" }],
|
||||
metadata: { checkoutSessionIds: "cs_foreign_paid", payToken: "attackerChosenToken123", note: "kept" },
|
||||
});
|
||||
expect(createdRes.status).toBe(201);
|
||||
const inv = createdRes.json.data;
|
||||
expect(inv.metadata.checkoutSessionIds).toBeUndefined();
|
||||
expect(inv.metadata.payToken).toBeUndefined();
|
||||
expect(inv.metadata.note).toBe("kept");
|
||||
|
||||
// Even with a binding planted directly in storage, a foreign payment never settles it.
|
||||
const stored = await ctx.invoices.get(inv.id);
|
||||
if (!stored.ok) throw stored.error;
|
||||
await ctx.invoices.save({ ...stored.value, status: "open", metadata: { ...stored.value.metadata, checkoutSessionIds: "cs_foreign_paid" } });
|
||||
const read = await call(app, "GET", `/v1/invoices/${inv.id}`);
|
||||
expect(read.json.data.status).toBe("open");
|
||||
|
||||
const request = await call(app, "POST", "/v1/invoices/requests", {
|
||||
amount: "5",
|
||||
description: "Quick job",
|
||||
payerEmail: "p@client.test",
|
||||
sendEmail: false,
|
||||
metadata: { kind: "platform_fee", merchantOrgId: "org_victim", paidTxHash: "0xdead" },
|
||||
});
|
||||
expect(request.status).toBe(201);
|
||||
expect(request.json.data.invoice.metadata.kind).toBe("payment_request");
|
||||
expect(request.json.data.invoice.metadata.merchantOrgId).toBeUndefined();
|
||||
expect(request.json.data.invoice.metadata.paidTxHash).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@ -1,66 +0,0 @@
|
||||
/**
|
||||
* Postgres enforces prices.product_id -> products.id, so a quick product must
|
||||
* be stored before its price. The in-memory repositories do not enforce the
|
||||
* foreign key, so this test wraps the price repository to reject a price whose
|
||||
* product does not exist yet (as Postgres does).
|
||||
*/
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import type { Hono } from "hono";
|
||||
import { createApp } from "../src/app.js";
|
||||
import { createContext, type AppContext, type AppEnv } from "../src/context.js";
|
||||
|
||||
const BOOTSTRAP = "test-bootstrap-key";
|
||||
|
||||
let app: Hono<AppEnv>;
|
||||
|
||||
async function call(method: string, path: string, body?: unknown) {
|
||||
const res = await app.request(path, {
|
||||
method,
|
||||
headers: { authorization: `Bearer ${BOOTSTRAP}`, "content-type": "application/json" },
|
||||
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
|
||||
});
|
||||
return { status: res.status, json: (await res.json()) as { data?: any; error?: { code: string; message: string } } };
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
process.env.API_BOOTSTRAP_KEY = BOOTSTRAP;
|
||||
const base = await createContext();
|
||||
const prices = base.prices;
|
||||
const fkPrices = new Proxy(prices, {
|
||||
get(target, prop, receiver) {
|
||||
if (prop === "save") {
|
||||
return async (price: { productId: string }) => {
|
||||
if (!(await base.products.findById(price.productId))) {
|
||||
throw new Error(`foreign key violation: product ${price.productId} does not exist`);
|
||||
}
|
||||
return target.save(price as never);
|
||||
};
|
||||
}
|
||||
return Reflect.get(target, prop, receiver);
|
||||
},
|
||||
});
|
||||
const ctx: AppContext = { ...base, prices: fkPrices };
|
||||
app = createApp(ctx);
|
||||
});
|
||||
|
||||
describe("merchant quick product", () => {
|
||||
it("stores the product before its price and publishes it", async () => {
|
||||
expect(
|
||||
(
|
||||
await call("POST", "/v1/merchant/profile", {
|
||||
orgName: "Shop",
|
||||
acceptedNetworks: ["base"],
|
||||
addresses: { evm: "0x7777777777777777777777777777777777777777" },
|
||||
})
|
||||
).status,
|
||||
).toBe(200);
|
||||
const product = await call("POST", "/v1/merchant/products", {
|
||||
name: "Pass",
|
||||
priceUsd: "1",
|
||||
delivery: { kind: "license_key", machineLimit: 1 },
|
||||
});
|
||||
expect(product.status, JSON.stringify(product.json.error)).toBe(201);
|
||||
expect(product.json.data.status).toBe("active");
|
||||
expect(typeof product.json.data.slug).toBe("string");
|
||||
});
|
||||
});
|
||||
@ -1,48 +0,0 @@
|
||||
import { createHmac } from "node:crypto";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { configuredOfframps, offrampLinks } from "../src/payouts/offramp.js";
|
||||
|
||||
const WALLET = "0x7878787878787878787878787878787878787878";
|
||||
|
||||
describe("off-ramp hand-off", () => {
|
||||
it("offers nothing until a partner key is configured", () => {
|
||||
expect(offrampLinks({ network: "base", amount: "250", wallet: WALLET }, {})).toEqual([]);
|
||||
expect(configuredOfframps({})).toEqual([]);
|
||||
});
|
||||
|
||||
it("prefills amount, network and the merchant's own wallet per partner", () => {
|
||||
const env = { TRANSAK_API_KEY: "tk_pub", RAMP_HOST_API_KEY: "ramp_pub", MOONPAY_PUBLISHABLE_KEY: "pk_x", MOONPAY_SECRET_KEY: "sk_x" };
|
||||
const links = offrampLinks({ network: "base", amount: "250.5", wallet: WALLET, returnUrl: "https://dash.test/payouts" }, env);
|
||||
expect(links.map((l) => l.provider)).toEqual(["transak", "moonpay", "ramp"]);
|
||||
|
||||
const transak = new URL(links[0]!.url);
|
||||
expect(transak.origin).toBe("https://global.transak.com");
|
||||
expect(Object.fromEntries(transak.searchParams)).toMatchObject({
|
||||
apiKey: "tk_pub",
|
||||
productsAvailed: "SELL",
|
||||
cryptoCurrencyCode: "USDC",
|
||||
network: "base",
|
||||
cryptoAmount: "250.5",
|
||||
walletAddress: WALLET,
|
||||
});
|
||||
|
||||
const moonpay = new URL(links[1]!.url);
|
||||
expect(moonpay.searchParams.get("baseCurrencyCode")).toBe("usdc_base");
|
||||
const signed = links[1]!.url.slice(links[1]!.url.indexOf("?"), links[1]!.url.indexOf("&signature="));
|
||||
expect(moonpay.searchParams.get("signature")).toBe(createHmac("sha256", "sk_x").update(signed).digest("base64"));
|
||||
|
||||
const ramp = new URL(links[2]!.url);
|
||||
expect(Object.fromEntries(ramp.searchParams)).toMatchObject({ swapAsset: "BASE_USDC", swapAmount: "250500000", userAddress: WALLET, enabledFlows: "OFFRAMP" });
|
||||
});
|
||||
|
||||
it("skips partners that do not support the network and validates the amount", () => {
|
||||
const env = { TRANSAK_API_KEY: "tk", RAMP_HOST_API_KEY: "r" };
|
||||
expect(offrampLinks({ network: "zcash", amount: "1", wallet: "t1abc" }, env)).toEqual([]);
|
||||
expect(offrampLinks({ network: "solana", amount: "1", wallet: "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM" }, env).map((l) => l.provider)).toEqual(["transak", "ramp"]);
|
||||
expect(() => offrampLinks({ network: "base", amount: "0", wallet: WALLET }, env)).toThrow(/positive/);
|
||||
expect(() => offrampLinks({ network: "base", amount: "abc", wallet: WALLET }, env)).toThrow(/positive/);
|
||||
expect(new URL(offrampLinks({ network: "base", amount: "1", wallet: WALLET }, { ...env, TRANSAK_ENV: "staging" })[0]!.url).origin).toBe(
|
||||
"https://global-stg.transak.com",
|
||||
);
|
||||
});
|
||||
});
|
||||
@ -1,195 +0,0 @@
|
||||
/**
|
||||
* Operator routes over Hono's app.request(), with a real operator runtime
|
||||
* (in-memory store, LocalExecutor vault simulation, heuristic engine) and the
|
||||
* real API-key auth middleware. Mounted exactly as app.ts mounts them: before
|
||||
* the API-key-guarded v1 group.
|
||||
*/
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { Hono } from "hono";
|
||||
import { DEFAULT_ORG_ID } from "@settlekit/persistence";
|
||||
import { createOperatorRuntime, LocalExecutor, type OperatorRuntime } from "@settlekit/operator";
|
||||
import type { AppContext, AppEnv } from "../src/context.js";
|
||||
import { error } from "../src/http/respond.js";
|
||||
import { authMiddleware } from "../src/middleware/auth.js";
|
||||
import { operatorRoutes } from "../src/routes/operator.js";
|
||||
|
||||
const BOOTSTRAP = "operator-bootstrap";
|
||||
const AGENT_KEY = "sk_agent";
|
||||
const OTHER_ORG_KEY = "sk_other";
|
||||
const VENDOR = "0x00000000000000000000000000000000007e2d02";
|
||||
const STRANGER = "0x0000000000000000000000000000000000000bad";
|
||||
const U = 1_000_000n;
|
||||
const T0 = new Date("2026-10-04T12:00:00.000Z");
|
||||
|
||||
const fakeCtx = {
|
||||
apiKeys: {
|
||||
verify: async (key: string) =>
|
||||
key === AGENT_KEY
|
||||
? { valid: true, apiKey: { id: "key_agent", organizationId: DEFAULT_ORG_ID, scopes: ["platform:admin"], status: "active", productId: "__platform__" } }
|
||||
: key === OTHER_ORG_KEY
|
||||
? { valid: true, apiKey: { id: "key_other", organizationId: "org_other", scopes: ["platform:admin"], status: "active", productId: "__platform__" } }
|
||||
: { valid: false },
|
||||
recordUsage: async () => undefined,
|
||||
},
|
||||
auth: { authenticateSession: async () => ({ ok: false }) },
|
||||
} as unknown as AppContext;
|
||||
|
||||
interface Setup {
|
||||
readonly app: Hono<AppEnv>;
|
||||
readonly runtime: OperatorRuntime;
|
||||
readonly vault: LocalExecutor;
|
||||
}
|
||||
|
||||
function setup(): Setup {
|
||||
process.env.API_BOOTSTRAP_KEY = BOOTSTRAP;
|
||||
const vault = new LocalExecutor({ caps: { perTxCap: 1000n * U, dailyCap: 1500n * U, escalateAbove: 500n * U }, allowlist: [VENDOR], now: () => T0 });
|
||||
const runtime = createOperatorRuntime({ OPERATOR_ALLOWLIST: VENDOR }, DEFAULT_ORG_ID, { executor: vault, owner: vault, now: () => T0 });
|
||||
const app = new Hono<AppEnv>();
|
||||
app.use("*", async (c, next) => {
|
||||
c.set("ctx", fakeCtx);
|
||||
await next();
|
||||
});
|
||||
app.route("/", operatorRoutes({ runtime: () => runtime, proofTtlMs: 0 }));
|
||||
const v1 = new Hono<AppEnv>();
|
||||
v1.use("*", authMiddleware());
|
||||
v1.get("/anything", (c) => c.json({ data: "guarded" }));
|
||||
app.route("/v1", v1);
|
||||
app.onError((err, c) => error(c, err));
|
||||
return { app, runtime, vault };
|
||||
}
|
||||
|
||||
async function call(app: Hono<AppEnv>, method: string, path: string, body?: unknown, key: string | null = BOOTSTRAP) {
|
||||
const res = await app.request(path, {
|
||||
method,
|
||||
headers: { "content-type": "application/json", ...(key ? { authorization: `Bearer ${key}` } : {}) },
|
||||
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
|
||||
});
|
||||
return { status: res.status, json: (await res.json()) as { data?: any; error?: { code: string; message: string; details?: any } } };
|
||||
}
|
||||
|
||||
const sale = (id = "evt_sale_1", amount = 2000n * U) => ({ type: "revenue.received", id, at: T0.toISOString(), amount: amount.toString(), payer: "0x00000000000000000000000000000000000000aa", paymentRef: "0xpay" });
|
||||
|
||||
describe("operator routes", () => {
|
||||
let s: Setup;
|
||||
beforeEach(() => {
|
||||
s = setup();
|
||||
s.vault.deposit(2000n * U);
|
||||
});
|
||||
|
||||
it("requires a credential and scopes to the operator org", async () => {
|
||||
expect((await call(s.app, "GET", "/v1/operator/decisions", undefined, null)).status).toBe(401);
|
||||
expect((await call(s.app, "GET", "/v1/operator/decisions", undefined, OTHER_ORG_KEY)).status).toBe(403);
|
||||
expect((await call(s.app, "GET", "/v1/anything", undefined, null)).status).toBe(401);
|
||||
});
|
||||
|
||||
it("handles an event once, forcing the caller's org, and replays duplicates", async () => {
|
||||
const first = await call(s.app, "POST", "/v1/operator/events", { ...sale(), orgId: "org_attacker" }, AGENT_KEY);
|
||||
expect(first.status).toBe(201);
|
||||
expect(first.json.data).toMatchObject({ orgId: DEFAULT_ORG_ID, outcome: "executed", seq: 0 });
|
||||
const replay = await call(s.app, "POST", "/v1/operator/events", sale(), AGENT_KEY);
|
||||
expect(replay.status).toBe(200);
|
||||
expect(replay.json.data.id).toBe(first.json.data.id);
|
||||
const bad = await call(s.app, "POST", "/v1/operator/events", { type: "revenue.received", id: "x" }, AGENT_KEY);
|
||||
expect(bad.status).toBe(400);
|
||||
expect(bad.json.error?.details.issues.length).toBeGreaterThan(0);
|
||||
|
||||
const list = await call(s.app, "GET", "/v1/operator/decisions?limit=10");
|
||||
expect(list.json.data).toHaveLength(1);
|
||||
const one = await call(s.app, "GET", `/v1/operator/decisions/${first.json.data.id}`);
|
||||
expect(one.json.data.hash).toBe(first.json.data.hash);
|
||||
expect((await call(s.app, "GET", "/v1/operator/decisions/nope")).status).toBe(404);
|
||||
});
|
||||
|
||||
it("takes bills, escalates unknown payees, and lets only the owner approve or reject", async () => {
|
||||
await call(s.app, "POST", "/v1/operator/events", sale(), AGENT_KEY);
|
||||
const paid = await call(s.app, "POST", "/v1/operator/bills", { payee: VENDOR, amountUsdc: "120", dueAt: T0.toISOString(), description: "Hosting" }, AGENT_KEY);
|
||||
expect(paid.status).toBe(201);
|
||||
expect(paid.json.data.bill.status).toBe("paid");
|
||||
const unknown = await call(s.app, "POST", "/v1/operator/bills", { payee: STRANGER, amountUsdc: "75", dueAt: T0.toISOString(), description: "New contractor" }, AGENT_KEY);
|
||||
expect(unknown.json.data.decision.outcome).toBe("escalated");
|
||||
expect((await call(s.app, "POST", "/v1/operator/bills", { payee: "nope", amountUsdc: "x", dueAt: "y", description: "" })).status).toBe(400);
|
||||
expect((await call(s.app, "POST", "/v1/operator/bills", { invoiceText: "Invoice" })).json.error?.message).toMatch(/ANTHROPIC_API_KEY/);
|
||||
|
||||
const pending = await call(s.app, "GET", "/v1/operator/escalations?status=pending");
|
||||
const id = pending.json.data[0].id as string;
|
||||
expect((await call(s.app, "POST", `/v1/operator/escalations/${id}/reject`, { reason: "unknown" }, AGENT_KEY)).status).toBe(403);
|
||||
const rejected = await call(s.app, "POST", `/v1/operator/escalations/${id}/reject`, { reason: "not a vendor we use" });
|
||||
expect(rejected.json.data).toMatchObject({ model: "owner", outcome: "denied" });
|
||||
expect((await call(s.app, "POST", `/v1/operator/escalations/${id}/approve`)).status).toBe(409);
|
||||
expect((await call(s.app, "POST", `/v1/operator/escalations/missing/approve`)).status).toBe(404);
|
||||
expect((await call(s.app, "GET", "/v1/operator/bills?status=rejected")).json.data).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("approves a vault escalation above the threshold", async () => {
|
||||
await call(s.app, "POST", "/v1/operator/events", sale(), AGENT_KEY);
|
||||
const big = await call(s.app, "POST", "/v1/operator/bills", { payee: VENDOR, amountUsdc: "600", dueAt: T0.toISOString(), description: "Annual" }, AGENT_KEY);
|
||||
expect(big.json.data.decision.outcome).toBe("escalated");
|
||||
const [pending] = (await call(s.app, "GET", "/v1/operator/escalations?status=pending")).json.data;
|
||||
expect(pending.vaultEscalationId).toBe(1);
|
||||
const approved = await call(s.app, "POST", `/v1/operator/escalations/${pending.id}/approve`);
|
||||
expect(approved.json.data.outcome).toBe("executed");
|
||||
expect(s.vault.escalation(1)?.status).toBe("Approved");
|
||||
});
|
||||
|
||||
it("serves vault state: buckets, spend vs caps and pending escalations", async () => {
|
||||
await call(s.app, "POST", "/v1/operator/events", sale(), AGENT_KEY);
|
||||
await call(s.app, "POST", "/v1/operator/bills", { payee: VENDOR, amountUsdc: "120", dueAt: T0.toISOString(), description: "Hosting" }, AGENT_KEY);
|
||||
await call(s.app, "POST", "/v1/operator/bills", { payee: STRANGER, amountUsdc: "75", dueAt: T0.toISOString(), description: "New contractor" }, AGENT_KEY);
|
||||
const state = await call(s.app, "GET", "/v1/operator/state", undefined, AGENT_KEY);
|
||||
expect(state.status).toBe(200);
|
||||
expect(state.json.data).toMatchObject({
|
||||
orgId: DEFAULT_ORG_ID,
|
||||
executor: "local-simulation",
|
||||
vault: null,
|
||||
spentToday: "120",
|
||||
caps: { perTxCap: "1000", dailyCap: "1500", escalateAbove: "500" },
|
||||
pendingEscalations: 1,
|
||||
});
|
||||
expect(Object.keys(state.json.data.buckets)).toEqual(["OPERATING", "TAX", "YIELD", "REFUND"]);
|
||||
expect((await call(s.app, "GET", "/v1/operator/state", undefined, OTHER_ORG_KEY)).status).toBe(403);
|
||||
});
|
||||
|
||||
it("serves policy and refuses drift from the vault", async () => {
|
||||
const got = await call(s.app, "GET", "/v1/operator/policy", undefined, AGENT_KEY);
|
||||
expect(got.json.data).toMatchObject({ executor: "local-simulation", engine: "heuristic", drift: [] });
|
||||
expect(got.json.data.policy.perTxCap).toBe("1000");
|
||||
const body = { ...got.json.data.policy, minFloat: "50" };
|
||||
expect((await call(s.app, "PUT", "/v1/operator/policy", body, AGENT_KEY)).status).toBe(403);
|
||||
const drift = await call(s.app, "PUT", "/v1/operator/policy", { ...body, dailyCap: "9000" });
|
||||
expect(drift.status).toBe(409);
|
||||
expect(drift.json.error?.details.drift[0]).toMatch(/dailyCap/);
|
||||
expect((await call(s.app, "PUT", "/v1/operator/policy", { ...body, split: { OPERATING: 1 } })).status).toBe(400);
|
||||
const saved = await call(s.app, "PUT", "/v1/operator/policy", body);
|
||||
expect(saved.json.data.policy.minFloat).toBe("50");
|
||||
});
|
||||
|
||||
it("publishes proof and verification without a key", async () => {
|
||||
const decision = (await call(s.app, "POST", "/v1/operator/events", sale(), AGENT_KEY)).json.data;
|
||||
const proof = await call(s.app, "GET", "/v1/public/operator/proof", undefined, null);
|
||||
expect(proof.status).toBe(200);
|
||||
expect(proof.json.data).toMatchObject({ orgs: 1, usdcIn: expect.stringMatching(/^2000/), executor: "local-simulation", decisions: { total: 1, executed: 1 } });
|
||||
const verify = await call(s.app, "GET", `/v1/public/operator/verify/${decision.id}`, undefined, null);
|
||||
// Local simulation: the log verifies, but a decision that moved money is not
|
||||
// reported valid without an on-chain anchor check.
|
||||
expect(verify.json.data).toMatchObject({ valid: false, commitment: "match", chain: { valid: true }, onChain: "not_configured" });
|
||||
expect((await call(s.app, "GET", "/v1/public/operator/verify/nope", undefined, null)).status).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
describe("operator routes without configuration", () => {
|
||||
it("answers 503 instead of silently simulating", async () => {
|
||||
const saved = { vault: process.env.OPERATOR_VAULT_ADDRESS, sim: process.env.OPERATOR_SIMULATION };
|
||||
delete process.env.OPERATOR_VAULT_ADDRESS;
|
||||
delete process.env.OPERATOR_SIMULATION;
|
||||
try {
|
||||
const app = new Hono<AppEnv>();
|
||||
app.route("/", operatorRoutes());
|
||||
app.onError((err, c) => error(c, err));
|
||||
const res = await app.request("/v1/public/operator/proof");
|
||||
expect(res.status).toBe(503);
|
||||
} finally {
|
||||
if (saved.vault !== undefined) process.env.OPERATOR_VAULT_ADDRESS = saved.vault;
|
||||
if (saved.sim !== undefined) process.env.OPERATOR_SIMULATION = saved.sim;
|
||||
}
|
||||
});
|
||||
});
|
||||
@ -1,272 +0,0 @@
|
||||
/**
|
||||
* SettleKit's own revenue: monthly fee statements issued from the platform org,
|
||||
* paid through SettleKit's own checkout, with the free plan's product limit
|
||||
* applied after the grace period.
|
||||
*/
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { afterAll, beforeEach, describe, expect, it } from "vitest";
|
||||
import type { Hono } from "hono";
|
||||
import { money, type Payment } from "@settlekit/common";
|
||||
import type { SettlementVerifier } from "@settlekit/chains";
|
||||
import { DEFAULT_ORG_ID } from "@settlekit/persistence";
|
||||
import { createApp } from "../src/app.js";
|
||||
import { createContext, type AppContext, type AppEnv } from "../src/context.js";
|
||||
import { issueStatement, loadPlatformBillingConfig, runStatements } from "../src/platform/fee-statements.js";
|
||||
|
||||
const BOOTSTRAP = "test-bootstrap-key";
|
||||
const PLATFORM_ORG = "org_platform";
|
||||
const PLATFORM_WALLET = "0x5555555555555555555555555555555555555555";
|
||||
const MERCHANT_WALLET = "0x6666666666666666666666666666666666666666";
|
||||
|
||||
const baseChainDouble: SettlementVerifier = async (proof, requirements) =>
|
||||
proof.network === requirements.network ? { ok: true } : { ok: false, reason: "network mismatch" };
|
||||
|
||||
let app: Hono<AppEnv>;
|
||||
let ctx: AppContext;
|
||||
let platformKey: string;
|
||||
let otherKey: string;
|
||||
|
||||
async function callAs(key: string, method: string, path: string, body?: unknown) {
|
||||
const res = await app.request(path, {
|
||||
method,
|
||||
headers: { authorization: `Bearer ${key}`, "content-type": "application/json" },
|
||||
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
|
||||
});
|
||||
return { status: res.status, json: (await res.json()) as { data?: any; error?: { code: string; message: string } } };
|
||||
}
|
||||
|
||||
const merchant = (method: string, path: string, body?: unknown) => callAs(BOOTSTRAP, method, path, body);
|
||||
const platform = (method: string, path: string, body?: unknown) => callAs(platformKey, method, path, body);
|
||||
|
||||
let paySeq = 0;
|
||||
async function settledPayment(amount: string, confirmedAt: string, organizationId = DEFAULT_ORG_ID): Promise<void> {
|
||||
paySeq += 1;
|
||||
const payment: Payment = {
|
||||
id: `pay_fee_${paySeq}`,
|
||||
organizationId,
|
||||
checkoutSessionId: `cs_fee_${paySeq}`,
|
||||
customerId: "cus_buyer",
|
||||
amount: money(amount),
|
||||
network: "base",
|
||||
txHash: `0x${randomBytes(32).toString("hex")}`,
|
||||
confirmations: 3,
|
||||
status: "confirmed",
|
||||
createdAt: confirmedAt,
|
||||
confirmedAt,
|
||||
};
|
||||
await ctx.payments.save(payment);
|
||||
}
|
||||
|
||||
async function quickProduct(name: string) {
|
||||
return merchant("POST", "/v1/merchant/products", {
|
||||
name,
|
||||
description: `${name} description`,
|
||||
priceUsd: "10",
|
||||
interval: "one_time",
|
||||
delivery: { kind: "license_key", machineLimit: 1 },
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
process.env.API_BOOTSTRAP_KEY = BOOTSTRAP;
|
||||
process.env.PLATFORM_BILLING_ORG_ID = PLATFORM_ORG;
|
||||
process.env.PLATFORM_BILLING_DUE_DAYS = "14";
|
||||
process.env.PLATFORM_BILLING_GRACE_DAYS = "7";
|
||||
process.env.PLATFORM_BILLING_MIN_USD = "1";
|
||||
const base = await createContext();
|
||||
ctx = { ...base, email: null, verifiers: { ...base.verifiers, base: baseChainDouble } };
|
||||
app = createApp(ctx);
|
||||
platformKey = (
|
||||
await ctx.apiKeys.issue({
|
||||
organizationId: PLATFORM_ORG,
|
||||
customerId: "cus_platform",
|
||||
productId: "__platform__",
|
||||
entitlementId: "ent_platform",
|
||||
scopes: ["*"],
|
||||
env: "live",
|
||||
})
|
||||
).plaintext;
|
||||
otherKey = (
|
||||
await ctx.apiKeys.issue({
|
||||
organizationId: "org_other",
|
||||
customerId: "cus_other",
|
||||
productId: "__platform__",
|
||||
entitlementId: "ent_other",
|
||||
scopes: ["*"],
|
||||
env: "live",
|
||||
})
|
||||
).plaintext;
|
||||
expect(
|
||||
(await platform("POST", "/v1/merchant/profile", { orgName: "SettleKit", acceptedNetworks: ["base"], addresses: { evm: PLATFORM_WALLET } }))
|
||||
.status,
|
||||
).toBe(200);
|
||||
expect(
|
||||
(
|
||||
await merchant("POST", "/v1/merchant/profile", {
|
||||
orgName: "Merchant Co",
|
||||
supportEmail: "owner@merchant.test",
|
||||
acceptedNetworks: ["base"],
|
||||
addresses: { evm: MERCHANT_WALLET },
|
||||
})
|
||||
).status,
|
||||
).toBe(200);
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
for (const key of ["PLATFORM_BILLING_ORG_ID", "PLATFORM_BILLING_DUE_DAYS", "PLATFORM_BILLING_GRACE_DAYS", "PLATFORM_BILLING_MIN_USD"]) {
|
||||
delete process.env[key];
|
||||
}
|
||||
});
|
||||
|
||||
describe("platform fee statements", () => {
|
||||
it("reads the config from env and stays off when unset", () => {
|
||||
expect(loadPlatformBillingConfig({})).toBeNull();
|
||||
expect(loadPlatformBillingConfig({ PLATFORM_BILLING_ORG_ID: "org_x" })).toEqual({
|
||||
orgId: "org_x",
|
||||
dueDays: 14,
|
||||
graceDays: 14,
|
||||
minimum: "1",
|
||||
});
|
||||
expect(() => loadPlatformBillingConfig({ PLATFORM_BILLING_ORG_ID: "org_x", PLATFORM_BILLING_GRACE_DAYS: "-1" })).toThrow();
|
||||
});
|
||||
|
||||
it("bills a closed month, is paid through the platform checkout, and lifts the limit", async () => {
|
||||
// Four active products (over the free limit of 3), then volume in Jan 2025.
|
||||
for (const name of ["Alpha", "Beta", "Gamma"]) expect((await quickProduct(name)).status).toBe(201);
|
||||
await settledPayment("300", "2025-01-10T00:00:00.000Z");
|
||||
await settledPayment("200", "2025-01-31T23:00:00.000Z");
|
||||
await settledPayment("999", "2025-02-01T00:00:00.000Z");
|
||||
|
||||
const accrued = await merchant("GET", "/v1/billing/fees");
|
||||
expect(accrued.json.data).toMatchObject({ configured: true, standing: "good", schedule: { bps: 100 } });
|
||||
expect(accrued.json.data.accrued).toMatchObject({ paymentCount: 3, fees: "14.99" });
|
||||
|
||||
// Only the platform operator can run statements.
|
||||
expect((await callAs(otherKey, "POST", "/v1/billing/statements/run", { period: "2025-01" })).status).toBe(403);
|
||||
const run = await platform("POST", "/v1/billing/statements/run", { period: "2025-01" });
|
||||
expect(run.status).toBe(200);
|
||||
expect(run.json.data.results).toEqual([
|
||||
expect.objectContaining({ merchantOrgId: DEFAULT_ORG_ID, status: "issued" }),
|
||||
]);
|
||||
// Re-running is idempotent.
|
||||
const again = await platform("POST", "/v1/billing/statements/run", { period: "2025-01" });
|
||||
expect(again.json.data.results[0].status).toBe("exists");
|
||||
// A month that has not ended cannot be billed.
|
||||
expect((await platform("POST", "/v1/billing/statements/run", { period: "2999-01" })).json.data.results[0].status).toBe("error");
|
||||
|
||||
const fees = await merchant("GET", "/v1/billing/fees");
|
||||
const [statement] = fees.json.data.statements;
|
||||
expect(statement).toMatchObject({ period: "2025-01", status: "open", total: "5", paymentCount: 2, grossVolume: "500" });
|
||||
expect(statement.payUrl).toMatch(/\/i\/[A-Za-z0-9_-]{16,}$/);
|
||||
expect(statement.dueAt).toBe("2025-02-15T00:00:00.000Z");
|
||||
// Long past due + grace: restricted.
|
||||
expect(fees.json.data.standing).toBe("restricted");
|
||||
expect(fees.json.data.accrued).toMatchObject({ paymentCount: 1, fees: "9.99" });
|
||||
|
||||
// The statement is an invoice of SettleKit's own org, paid to its wallet.
|
||||
const invoice = await ctx.invoices.get(statement.id);
|
||||
if (!invoice.ok) throw new Error("statement invoice missing");
|
||||
expect(invoice.value.organizationId).toBe(PLATFORM_ORG);
|
||||
const sessionId = invoice.value.metadata.checkoutSessionIds!;
|
||||
const session = await ctx.checkouts.findById(sessionId);
|
||||
expect(session).toMatchObject({ organizationId: PLATFORM_ORG, payToAddress: PLATFORM_WALLET, amount: { amount: "5" } });
|
||||
// The merchant never sees the statement in their own invoices.
|
||||
expect((await merchant("GET", "/v1/invoices")).json.data).toHaveLength(0);
|
||||
|
||||
// Restricted: the 4th active product is refused with the pay link.
|
||||
const blocked = await quickProduct("Delta");
|
||||
expect(blocked.status).toBe(402);
|
||||
expect(blocked.json.error?.code).toBe("payment_required");
|
||||
expect(blocked.json.error?.message).toContain(statement.payUrl);
|
||||
|
||||
// Pay the statement onchain through the platform checkout.
|
||||
const payment = await platform("POST", "/v1/payments", { checkoutSessionId: sessionId });
|
||||
expect(payment.status).toBe(201);
|
||||
const confirmed = await platform("POST", `/v1/payments/${payment.json.data.id}/confirm`, {
|
||||
txHash: `0x${randomBytes(32).toString("hex")}`,
|
||||
confirmations: 3,
|
||||
});
|
||||
expect(confirmed.status).toBe(200);
|
||||
|
||||
const after = await merchant("GET", "/v1/billing/fees");
|
||||
expect(after.json.data.statements[0].status).toBe("paid");
|
||||
expect(after.json.data.standing).toBe("good");
|
||||
expect((await quickProduct("Delta")).status).toBe(201);
|
||||
});
|
||||
|
||||
it("issues one statement when runs overlap and sends a draft left by an interrupted run", async () => {
|
||||
expect((await quickProduct("Overlap")).status).toBe(201);
|
||||
await settledPayment("400", "2025-05-10T00:00:00.000Z");
|
||||
const cfg = loadPlatformBillingConfig()!;
|
||||
const now = new Date("2025-06-02T00:00:00.000Z");
|
||||
const outcomes = await Promise.all([
|
||||
runStatements(ctx, cfg, "2025-05", now),
|
||||
runStatements(ctx, cfg, "2025-05", now),
|
||||
runStatements(ctx, cfg, "2025-05", now),
|
||||
]);
|
||||
const statuses = outcomes.map((o) => o.results[0]!.status).sort();
|
||||
expect(statuses).toEqual(["exists", "exists", "issued"]);
|
||||
const open = (await ctx.invoices.list()).filter(
|
||||
(inv) => inv.metadata.kind === "platform_fee" && inv.metadata.period === "2025-05" && inv.status !== "void",
|
||||
);
|
||||
expect(open).toHaveLength(1);
|
||||
expect(open[0]!.status).toBe("open");
|
||||
|
||||
// A second instance raced in a duplicate draft: it loses to the sent one.
|
||||
const loser = await issueStatement(ctx, cfg, DEFAULT_ORG_ID, "2025-05", now);
|
||||
expect(loser.status).toBe("exists");
|
||||
|
||||
// A draft left by a crash between create and send is sent on the next run.
|
||||
await settledPayment("300", "2025-06-10T00:00:00.000Z");
|
||||
const [customer] = await ctx.customers.list((c) => c.organizationId === PLATFORM_ORG);
|
||||
const draft = await ctx.invoices.create({
|
||||
organizationId: PLATFORM_ORG,
|
||||
customerId: customer!.id,
|
||||
lineItems: [{ description: "June", quantity: 1, unitAmount: money("3") }],
|
||||
metadata: { kind: "platform_fee", merchantOrgId: DEFAULT_ORG_ID, period: "2025-06", coverageEnd: "2025-07-01T00:00:00.000Z" },
|
||||
});
|
||||
if (!draft.ok) throw draft.error;
|
||||
const resumed = await issueStatement(ctx, cfg, DEFAULT_ORG_ID, "2025-06", new Date("2025-07-02T00:00:00.000Z"));
|
||||
expect(resumed.status).toBe("issued");
|
||||
if (resumed.status !== "issued") throw new Error("not issued");
|
||||
expect(resumed.invoice.id).toBe(draft.value.id);
|
||||
expect(resumed.invoice.status).toBe("open");
|
||||
});
|
||||
|
||||
it("carries fees below the minimum into the next statement and skips test accounts", async () => {
|
||||
expect((await quickProduct("Solo")).status).toBe(201);
|
||||
await settledPayment("50", "2025-03-05T00:00:00.000Z"); // 0.50 fee: below the 1 USDC minimum
|
||||
const march = await platform("POST", "/v1/billing/statements/run", { period: "2025-03" });
|
||||
expect(march.json.data.results[0]).toMatchObject({ status: "below_minimum", fees: "0.5" });
|
||||
|
||||
await settledPayment("100", "2025-04-05T00:00:00.000Z");
|
||||
const april = await platform("POST", "/v1/billing/statements/run", { period: "2025-04" });
|
||||
expect(april.json.data.results[0].status).toBe("issued");
|
||||
const [statement] = (await merchant("GET", "/v1/billing/fees")).json.data.statements;
|
||||
expect(statement).toMatchObject({ period: "2025-04", total: "1.5", paymentCount: 2 });
|
||||
|
||||
await merchant("POST", "/v1/merchant/profile", {
|
||||
acceptedNetworks: ["base"],
|
||||
addresses: { evm: MERCHANT_WALLET },
|
||||
testAccount: true,
|
||||
});
|
||||
await settledPayment("500", "2025-05-05T00:00:00.000Z");
|
||||
const may = await platform("POST", "/v1/billing/statements/run", { period: "2025-05" });
|
||||
expect(may.json.data.results).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("statement scheduler", () => {
|
||||
it("bills the previous month on a tick and is disabled without config", async () => {
|
||||
const { statementTick, startStatementScheduler } = await import("../src/platform/statement-scheduler.js");
|
||||
expect((await quickProduct("Tick")).status).toBe(201);
|
||||
await settledPayment("400", "2025-06-15T00:00:00.000Z");
|
||||
const result = await statementTick(ctx, new Date("2025-07-02T00:00:00.000Z"));
|
||||
expect(result?.period).toBe("2025-06");
|
||||
expect(result?.results[0]).toMatchObject({ status: "issued" });
|
||||
const stop = startStatementScheduler(ctx, () => {}, {});
|
||||
stop();
|
||||
delete process.env.PLATFORM_BILLING_ORG_ID;
|
||||
expect(await statementTick(ctx)).toBeNull();
|
||||
});
|
||||
});
|
||||
@ -1,131 +0,0 @@
|
||||
/**
|
||||
* Refund to payer: SettleKit prepares the transfer back to the buyer, the
|
||||
* merchant signs it, and the refund settles only after onchain verification.
|
||||
*/
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import type { Hono } from "hono";
|
||||
import type { SettlementVerifier } from "@settlekit/chains";
|
||||
import { parseSolanaPayUrl } from "@settlekit/solana";
|
||||
import { createApp } from "../src/app.js";
|
||||
import { createContext, type AppContext, type AppEnv } from "../src/context.js";
|
||||
import { erc20TransferData } from "../src/merchant/refund-to-payer.js";
|
||||
|
||||
const BOOTSTRAP = "test-bootstrap-key";
|
||||
const MERCHANT = "0x3434343434343434343434343434343434343434";
|
||||
const BUYER = "0x5656565656565656565656565656565656565656";
|
||||
const SOL_BUYER = "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM";
|
||||
|
||||
let app: Hono<AppEnv>;
|
||||
let ctx: AppContext;
|
||||
let verifyOk = true;
|
||||
const checks: { payTo: string; amount: string; reference?: string }[] = [];
|
||||
|
||||
const verifier: SettlementVerifier = async (proof, req) => {
|
||||
const r = req as unknown as { payTo: string; amount: string; reference?: string };
|
||||
checks.push({ payTo: r.payTo, amount: r.amount, ...(r.reference ? { reference: r.reference } : {}) });
|
||||
if (proof.network !== req.network) return { ok: false, reason: "network mismatch" };
|
||||
return verifyOk ? { ok: true } : { ok: false, reason: "no matching transfer" };
|
||||
};
|
||||
|
||||
const tx = () => `0x${randomBytes(32).toString("hex")}`;
|
||||
|
||||
async function call(method: string, path: string, body?: unknown) {
|
||||
const res = await app.request(path, {
|
||||
method,
|
||||
headers: { authorization: `Bearer ${BOOTSTRAP}`, "content-type": "application/json" },
|
||||
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
|
||||
});
|
||||
return { status: res.status, json: (await res.json()) as { data?: any; error?: { message: string } } };
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
process.env.API_BOOTSTRAP_KEY = BOOTSTRAP;
|
||||
verifyOk = true;
|
||||
checks.length = 0;
|
||||
const base = await createContext();
|
||||
ctx = { ...base, verifiers: { ...base.verifiers, base: verifier, solana: verifier } };
|
||||
app = createApp(ctx);
|
||||
});
|
||||
|
||||
async function paidPayment(network: "base" | "solana", amount = "40", payer: string | null = BUYER): Promise<string> {
|
||||
const product = await call("POST", "/v1/products", { merchantId: "mch_1", name: "Course", type: "license_key", deliveryMode: "license_key" });
|
||||
const price = await call("POST", `/v1/products/${product.json.data.id}/prices`, { amount });
|
||||
const customer = await call("POST", "/v1/customers", { email: "buyer@x.test" });
|
||||
const session = await call("POST", "/v1/checkout-sessions", {
|
||||
merchantId: "mch_1",
|
||||
customerId: customer.json.data.id,
|
||||
items: [{ priceId: price.json.data.id, productId: product.json.data.id, quantity: 1 }],
|
||||
payToAddress: network === "base" ? MERCHANT : "7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU",
|
||||
network,
|
||||
});
|
||||
const stored = await ctx.checkouts.findById(session.json.data.id);
|
||||
if (payer) await ctx.checkouts.save({ ...stored!, payerAddress: payer });
|
||||
const payment = await call("POST", "/v1/payments", { checkoutSessionId: session.json.data.id });
|
||||
const hash = network === "base" ? tx() : "5".repeat(88);
|
||||
const confirmed = await call("POST", `/v1/payments/${payment.json.data.id}/confirm`, { txHash: hash, confirmations: 3 });
|
||||
expect(confirmed.status).toBe(200);
|
||||
checks.length = 0;
|
||||
return payment.json.data.id as string;
|
||||
}
|
||||
|
||||
describe("refund to payer", () => {
|
||||
it("prepares an ERC-20 transfer to the paying wallet and settles after onchain verification", async () => {
|
||||
const paymentId = await paidPayment("base");
|
||||
const prepared = await call("POST", `/v1/merchant/payments/${paymentId}/refund/prepare`, { amountUsd: "15" });
|
||||
expect(prepared.status).toBe(201);
|
||||
const { refund, plan } = prepared.json.data;
|
||||
expect(refund).toMatchObject({ status: "pending", destination: BUYER, network: "base", source: "wallet" });
|
||||
expect(plan.evm.data).toBe(erc20TransferData(BUYER, 15_000_000n));
|
||||
expect(plan.evm.eip681).toContain(`/transfer?address=${BUYER}&uint256=15000000`);
|
||||
|
||||
verifyOk = false;
|
||||
const failed = await call("POST", `/v1/merchant/refunds/${refund.id}/confirm`, { txHash: tx() });
|
||||
expect(failed.status).toBe(400);
|
||||
expect((await ctx.refundStore.findById(refund.id))?.status).toBe("pending");
|
||||
|
||||
verifyOk = true;
|
||||
const hash = tx();
|
||||
const done = await call("POST", `/v1/merchant/refunds/${refund.id}/confirm`, { txHash: hash });
|
||||
expect(done.status).toBe(200);
|
||||
expect(done.json.data.refund).toMatchObject({ status: "succeeded", txHash: hash });
|
||||
expect(checks.at(-1)).toMatchObject({ payTo: BUYER, amount: "15" });
|
||||
// Partial refund: the payment stays confirmed.
|
||||
expect((await ctx.payments.findById(paymentId))?.status).toBe("confirmed");
|
||||
|
||||
// The same transaction cannot settle a second refund.
|
||||
const second = (await call("POST", `/v1/merchant/payments/${paymentId}/refund/prepare`, {})).json.data.refund;
|
||||
expect(second.amount.amount).toBe("25");
|
||||
expect((await call("POST", `/v1/merchant/refunds/${second.id}/confirm`, { txHash: hash })).status).toBe(409);
|
||||
const rest = await call("POST", `/v1/merchant/refunds/${second.id}/confirm`, { txHash: tx() });
|
||||
expect(rest.status).toBe(200);
|
||||
expect((await ctx.payments.findById(paymentId))?.status).toBe("refunded");
|
||||
});
|
||||
|
||||
it("prepares a Solana Pay transfer request bound to a reference", async () => {
|
||||
const paymentId = await paidPayment("solana", "12", SOL_BUYER);
|
||||
const prepared = await call("POST", `/v1/merchant/payments/${paymentId}/refund/prepare`, {});
|
||||
const { refund, plan } = prepared.json.data;
|
||||
const parsed = parseSolanaPayUrl(plan.solana.url) as { recipient: string; amount?: string; references?: string[] };
|
||||
expect(parsed.recipient).toBe(SOL_BUYER);
|
||||
expect(parsed.amount).toBe("12");
|
||||
expect(parsed.references).toEqual([plan.solana.reference]);
|
||||
const done = await call("POST", `/v1/merchant/refunds/${refund.id}/confirm`, { txHash: "4".repeat(88) });
|
||||
expect(done.status).toBe(200);
|
||||
expect(checks.at(-1)).toMatchObject({ payTo: SOL_BUYER, reference: plan.solana.reference });
|
||||
});
|
||||
|
||||
it("asks for an address when the payer is unknown and validates it", async () => {
|
||||
const paymentId = await paidPayment("base", "10", null);
|
||||
const missing = await call("POST", `/v1/merchant/payments/${paymentId}/refund/prepare`, {});
|
||||
expect(missing.status).toBe(400);
|
||||
expect(missing.json.error?.message).toMatch(/enter the address/);
|
||||
expect((await call("POST", `/v1/merchant/payments/${paymentId}/refund/prepare`, { to: "not-an-address" })).status).toBe(400);
|
||||
const ok = await call("POST", `/v1/merchant/payments/${paymentId}/refund/prepare`, { to: BUYER });
|
||||
expect(ok.status).toBe(201);
|
||||
const canceled = await call("POST", `/v1/merchant/refunds/${ok.json.data.refund.id}/cancel`);
|
||||
expect(canceled.json.data.status).toBe("failed");
|
||||
// Canceled refunds free the amount again.
|
||||
expect((await call("POST", `/v1/merchant/payments/${paymentId}/refund/prepare`, { to: BUYER })).json.data.refund.amount.amount).toBe("10");
|
||||
});
|
||||
});
|
||||
@ -1,85 +0,0 @@
|
||||
/** Hosted storefront: settings validation and the public store view. */
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import type { Hono } from "hono";
|
||||
import { createApp } from "../src/app.js";
|
||||
import { createContext, type AppContext, type AppEnv } from "../src/context.js";
|
||||
|
||||
const BOOTSTRAP = "test-bootstrap-key";
|
||||
let app: Hono<AppEnv>;
|
||||
let ctx: AppContext;
|
||||
let otherKey: string;
|
||||
|
||||
async function call(method: string, path: string, body?: unknown, key: string | null = BOOTSTRAP) {
|
||||
const res = await app.request(path, {
|
||||
method,
|
||||
headers: { ...(key ? { authorization: `Bearer ${key}` } : {}), "content-type": "application/json" },
|
||||
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
|
||||
});
|
||||
return { status: res.status, json: (await res.json()) as { data?: any; error?: { message: string } } };
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
process.env.API_BOOTSTRAP_KEY = BOOTSTRAP;
|
||||
ctx = await createContext();
|
||||
app = createApp(ctx);
|
||||
otherKey = (
|
||||
await ctx.apiKeys.issue({ organizationId: "org_other", customerId: "x", productId: "__platform__", entitlementId: "__platform__", scopes: ["*"], env: "live" })
|
||||
).plaintext;
|
||||
await call("POST", "/v1/merchant/profile", { orgName: "Pixel Tools", acceptedNetworks: ["base"], addresses: { evm: "0x9191919191919191919191919191919191919191" } });
|
||||
});
|
||||
|
||||
const STORE = {
|
||||
enabled: true,
|
||||
slug: "pixel-tools",
|
||||
title: "Pixel Tools",
|
||||
tagline: "Icons and UI kits",
|
||||
logoUrl: "https://cdn.pixel.test/logo.png",
|
||||
accentColor: "#ff5500",
|
||||
seoDescription: "Icon packs and UI kits paid in USDC.",
|
||||
customDomain: "shop.pixel.test",
|
||||
};
|
||||
|
||||
describe("hosted storefront", () => {
|
||||
it("lists active products with branding by slug and custom domain", async () => {
|
||||
expect((await call("POST", "/v1/settings", { store: STORE })).status).toBe(200);
|
||||
await call("POST", "/v1/merchant/products", { name: "Icon pack", description: "2,000 icons", priceUsd: "29", delivery: { kind: "license_key", machineLimit: 1 } });
|
||||
const archived = await call("POST", "/v1/merchant/products", { name: "Old", priceUsd: "5", delivery: { kind: "license_key", machineLimit: 1 } });
|
||||
await call("PATCH", `/v1/merchant/products/${archived.json.data.id}`, { status: "archived" });
|
||||
// A sent invoice creates a hidden product that must not appear.
|
||||
await call("POST", "/v1/invoices/requests", { amount: "50", description: "Custom work", payerEmail: "c@x.test" });
|
||||
|
||||
const store = await call("GET", "/v1/public/stores/pixel-tools", undefined, null);
|
||||
expect(store.status).toBe(200);
|
||||
expect(store.json.data).toMatchObject({
|
||||
title: "Pixel Tools",
|
||||
tagline: "Icons and UI kits",
|
||||
accentColor: "#ff5500",
|
||||
merchantName: "Pixel Tools",
|
||||
acceptingPayments: true,
|
||||
});
|
||||
const names = store.json.data.products.map((p: { name: string }) => p.name);
|
||||
expect(names).toContain("Icon pack");
|
||||
expect(names).not.toContain("Old");
|
||||
expect(names.some((n: string) => n.startsWith("Invoice"))).toBe(false);
|
||||
expect(store.json.data.products[0].slug).toMatch(/^icon-pack-/);
|
||||
|
||||
const byDomain = await call("GET", "/v1/public/stores/by-domain/shop.pixel.test", undefined, null);
|
||||
expect(byDomain.json.data.slug).toBe("pixel-tools");
|
||||
});
|
||||
|
||||
it("keeps slugs and domains unique and validates branding", async () => {
|
||||
await call("POST", "/v1/settings", { store: STORE });
|
||||
expect((await call("POST", "/v1/settings", { store: { ...STORE, customDomain: undefined } }, otherKey)).status).toBe(409);
|
||||
expect((await call("POST", "/v1/settings", { store: { ...STORE, slug: "other-shop" } }, otherKey)).status).toBe(409);
|
||||
expect((await call("POST", "/v1/settings", { store: { enabled: true, slug: "api" } }, otherKey)).status).toBe(400);
|
||||
expect((await call("POST", "/v1/settings", { store: { enabled: true, slug: "ok-shop", logoUrl: "http://insecure.test/x.png" } }, otherKey)).status).toBe(400);
|
||||
expect((await call("POST", "/v1/settings", { store: { enabled: true, slug: "ok-shop", accentColor: "red" } }, otherKey)).status).toBe(400);
|
||||
expect((await call("POST", "/v1/settings", { store: { enabled: true, slug: "ok-shop" } }, otherKey)).status).toBe(200);
|
||||
});
|
||||
|
||||
it("hides a disabled or unknown store", async () => {
|
||||
await call("POST", "/v1/settings", { store: { ...STORE, enabled: false } });
|
||||
expect((await call("GET", "/v1/public/stores/pixel-tools", undefined, null)).status).toBe(404);
|
||||
expect((await call("GET", "/v1/public/stores/nope-nope", undefined, null)).status).toBe(404);
|
||||
});
|
||||
});
|
||||
@ -1,147 +0,0 @@
|
||||
/**
|
||||
* Team roles and API key scopes: buyer access keys can never act as the
|
||||
* merchant, restricted platform keys only reach their scopes, keys cannot
|
||||
* mint broader keys, and invited teammates get their role's permissions.
|
||||
*/
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import type { Hono } from "hono";
|
||||
import { createApp } from "../src/app.js";
|
||||
import { createContext, type AppContext, type AppEnv } from "../src/context.js";
|
||||
|
||||
const BOOTSTRAP = "test-bootstrap-key";
|
||||
let app: Hono<AppEnv>;
|
||||
let ctx: AppContext;
|
||||
|
||||
async function call(method: string, path: string, body?: unknown, key: string | null = BOOTSTRAP) {
|
||||
const res = await app.request(path, {
|
||||
method,
|
||||
headers: { ...(key ? { authorization: `Bearer ${key}` } : {}), "content-type": "application/json" },
|
||||
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
|
||||
});
|
||||
return { status: res.status, json: (await res.json()) as { data?: any; error?: { code: string; message: string; details?: any } } };
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
process.env.API_BOOTSTRAP_KEY = BOOTSTRAP;
|
||||
ctx = { ...(await createContext()), email: null };
|
||||
app = createApp(ctx);
|
||||
});
|
||||
|
||||
describe("API key scopes", () => {
|
||||
it("refuses buyer access keys on the management API, whatever their scopes", async () => {
|
||||
for (const scopes of [["read"], ["*"], ["payments:read"]]) {
|
||||
const buyerKey = await ctx.apiKeys.issue({
|
||||
organizationId: "org_settlekit_default",
|
||||
customerId: "cus_buyer",
|
||||
productId: "prod_api_access",
|
||||
entitlementId: "ent_1",
|
||||
scopes,
|
||||
env: "live",
|
||||
});
|
||||
const res = await call("GET", "/v1/payments", undefined, buyerKey.plaintext);
|
||||
expect(res.status).toBe(403);
|
||||
expect(res.json.error?.message).toMatch(/customer access key/);
|
||||
}
|
||||
});
|
||||
|
||||
it("limits a restricted platform key to its scopes", async () => {
|
||||
const issued = await call("POST", "/v1/api-keys/platform", { scopes: ["payments:read", "access:read"], label: "reporting" });
|
||||
expect(issued.status).toBe(201);
|
||||
expect(issued.json.data.apiKey.kind).toBe("platform");
|
||||
const key = issued.json.data.plaintext as string;
|
||||
expect((await call("GET", "/v1/payments", undefined, key)).status).toBe(200);
|
||||
const denied = await call("POST", "/v1/products", { merchantId: "m", name: "x", type: "license_key", deliveryMode: "license_key" }, key);
|
||||
expect(denied.status).toBe(403);
|
||||
expect(denied.json.error?.details?.requiredScope).toBe("products:write");
|
||||
expect((await call("POST", "/v1/entitlements/verify", { customerId: "c", productId: "p" }, key)).status).toBe(200);
|
||||
expect((await call("GET", "/v1/exports/payments.csv", undefined, key)).status).toBe(403);
|
||||
});
|
||||
|
||||
it("cannot mint a key broader than itself and customer keys cannot carry management scopes", async () => {
|
||||
const limited = (await call("POST", "/v1/api-keys/platform", { scopes: ["api_keys:write"] })).json.data.plaintext as string;
|
||||
const escalate = await call("POST", "/v1/api-keys/platform", { scopes: ["platform:admin"] }, limited);
|
||||
expect(escalate.status).toBe(403);
|
||||
expect((await call("POST", "/v1/api-keys/platform", { scopes: ["payments:read"] }, limited)).status).toBe(403);
|
||||
expect((await call("POST", "/v1/api-keys/platform", { scopes: ["api_keys:read"] }, limited)).status).toBe(201);
|
||||
|
||||
const customerStar = await call("POST", "/v1/api-keys", { customerId: "c", productId: "p", entitlementId: "e", scopes: ["*"] });
|
||||
expect(customerStar.status).toBe(400);
|
||||
});
|
||||
|
||||
it("lists and revokes only the organization's keys", async () => {
|
||||
const other = await ctx.apiKeys.issue({ organizationId: "org_other", customerId: "x", productId: "__platform__", entitlementId: "__platform__", scopes: ["*"], env: "live" });
|
||||
const mine = await call("POST", "/v1/api-keys/platform", { scopes: ["reports:read"] });
|
||||
const list = await call("GET", "/v1/api-keys");
|
||||
expect(list.json.data.map((k: { id: string }) => k.id)).toContain(mine.json.data.apiKey.id);
|
||||
expect(list.json.data.map((k: { id: string }) => k.id)).not.toContain(other.apiKey.id);
|
||||
expect((await call("POST", `/v1/api-keys/${other.apiKey.id}/revoke`)).status).toBe(404);
|
||||
const revoked = await call("POST", `/v1/api-keys/${mine.json.data.apiKey.id}/revoke`);
|
||||
expect(revoked.json.data.status).toBe("revoked");
|
||||
expect((await call("GET", "/v1/payments", undefined, mine.json.data.plaintext)).status).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
describe("team roles", () => {
|
||||
async function registerOwner(): Promise<string> {
|
||||
const res = await call("POST", "/v1/auth/register", { type: "merchant", email: "owner@acme.test", password: "correct horse 1" }, null);
|
||||
expect(res.status).toBe(201);
|
||||
return res.json.data.sessionToken as string;
|
||||
}
|
||||
|
||||
async function invite(owner: string, email: string, role: string): Promise<string> {
|
||||
const res = await call("POST", "/v1/team/invitations", { email, role }, owner);
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.json.data.invitation.tokenHash).toBeUndefined();
|
||||
return (res.json.data.inviteUrl as string).split("/invite/")[1]!;
|
||||
}
|
||||
|
||||
it("invites a developer who gets exactly the developer permissions", async () => {
|
||||
const owner = await registerOwner();
|
||||
const token = decodeURIComponent(await invite(owner, "dev@acme.test", "developer"));
|
||||
const team = await call("GET", "/v1/team", undefined, owner);
|
||||
expect(team.json.data.members).toEqual([expect.objectContaining({ email: "owner@acme.test", role: "owner" })]);
|
||||
expect(team.json.data.invitations).toEqual([expect.objectContaining({ email: "dev@acme.test", role: "developer", status: "pending" })]);
|
||||
|
||||
expect((await call("POST", "/v1/auth/invitations/accept", { token }, null)).status).toBe(400);
|
||||
const accepted = await call("POST", "/v1/auth/invitations/accept", { token, password: "dev password 1" }, null);
|
||||
expect(accepted.status).toBe(200);
|
||||
const dev = accepted.json.data.sessionToken as string;
|
||||
expect(accepted.json.data.account.organizationId).toBe(team.json.data.members[0] ? (await call("GET", "/v1/auth/session", undefined, owner)).json.data.account.organizationId : "");
|
||||
// Token is single use.
|
||||
expect((await call("POST", "/v1/auth/invitations/accept", { token, password: "again password" }, null)).status).toBe(404);
|
||||
|
||||
expect((await call("GET", "/v1/payments", undefined, dev)).status).toBe(200);
|
||||
expect((await call("POST", "/v1/merchant/products", { name: "X", priceUsd: "5", delivery: { kind: "license_key", machineLimit: 1 } }, dev)).status).not.toBe(403);
|
||||
const settings = await call("POST", "/v1/settings", { orgName: "Hijack" }, dev);
|
||||
expect(settings.status).toBe(403);
|
||||
expect((await call("POST", "/v1/team/invitations", { email: "x@acme.test", role: "viewer" }, dev)).status).toBe(403);
|
||||
});
|
||||
|
||||
it("protects the owner role and removes members", async () => {
|
||||
const owner = await registerOwner();
|
||||
const token = decodeURIComponent(await invite(owner, "admin@acme.test", "admin"));
|
||||
const admin = (await call("POST", "/v1/auth/invitations/accept", { token, password: "admin password" }, null)).json.data.sessionToken as string;
|
||||
// An admin cannot mint owners.
|
||||
expect((await call("POST", "/v1/team/invitations", { email: "o2@acme.test", role: "owner" }, admin)).status).toBe(403);
|
||||
|
||||
const members = (await call("GET", "/v1/team", undefined, owner)).json.data.members as { accountId: string; role: string }[];
|
||||
const ownerId = members.find((m) => m.role === "owner")!.accountId;
|
||||
const adminId = members.find((m) => m.role === "admin")!.accountId;
|
||||
expect((await call("PATCH", `/v1/team/members/${ownerId}`, { role: "viewer" }, owner)).status).toBe(400);
|
||||
expect((await call("PATCH", `/v1/team/members/${adminId}`, { role: "viewer" }, owner)).json.data.role).toBe("viewer");
|
||||
// Viewer now: reads only.
|
||||
expect((await call("GET", "/v1/payments", undefined, admin)).status).toBe(200);
|
||||
expect((await call("POST", "/v1/coupons", { code: "X", discount: { type: "percent", percentOff: 5 } }, admin)).status).toBe(403);
|
||||
|
||||
expect((await call("DELETE", `/v1/team/members/${adminId}`, undefined, owner)).status).toBe(200);
|
||||
expect((await call("GET", "/v1/payments", undefined, admin)).status).toBe(401);
|
||||
});
|
||||
|
||||
it("revokes invitations", async () => {
|
||||
const owner = await registerOwner();
|
||||
const token = decodeURIComponent(await invite(owner, "late@acme.test", "viewer"));
|
||||
const inv = (await call("GET", "/v1/team", undefined, owner)).json.data.invitations[0];
|
||||
expect((await call("POST", `/v1/team/invitations/${inv.id}/revoke`, undefined, owner)).json.data.status).toBe("revoked");
|
||||
expect((await call("POST", "/v1/auth/invitations/accept", { token, password: "late password" }, null)).status).toBe(404);
|
||||
});
|
||||
});
|
||||
@ -214,7 +214,7 @@ beforeAll(async () => {
|
||||
const issued = await ctx.apiKeys.issue({
|
||||
organizationId: "org_intruder",
|
||||
customerId: "cus_intruder",
|
||||
productId: "__platform__",
|
||||
productId: "prod_intruder",
|
||||
entitlementId: "ent_intruder",
|
||||
scopes: ["*"],
|
||||
env: "live",
|
||||
|
||||
@ -1,85 +0,0 @@
|
||||
/**
|
||||
* Registration can never join an existing merchant organization: a merchant
|
||||
* always gets a fresh org, and a customer account (portal buyers, who do
|
||||
* carry the seller's org id) never gets management access through its
|
||||
* session.
|
||||
*/
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import type { Hono } from "hono";
|
||||
import { createApp } from "../src/app.js";
|
||||
import { createContext, type AppContext, type AppEnv } from "../src/context.js";
|
||||
|
||||
let app: Hono<AppEnv>;
|
||||
let ctx: AppContext;
|
||||
|
||||
async function call(method: string, path: string, body?: unknown, key: string | null = null) {
|
||||
const res = await app.request(path, {
|
||||
method,
|
||||
headers: { ...(key ? { authorization: `Bearer ${key}` } : {}), "content-type": "application/json" },
|
||||
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
|
||||
});
|
||||
return { status: res.status, json: (await res.json()) as { data?: any; error?: { code: string; message: string } } };
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
delete process.env.API_BOOTSTRAP_KEY;
|
||||
ctx = { ...(await createContext()), email: null };
|
||||
app = createApp(ctx);
|
||||
});
|
||||
|
||||
describe("registration tenant boundary", () => {
|
||||
async function victim(): Promise<{ org: string; key: string }> {
|
||||
const res = await call("POST", "/v1/auth/register", { type: "merchant", email: "victim@shop.test", password: "victim password 1" });
|
||||
expect(res.status).toBe(201);
|
||||
return { org: res.json.data.account.organizationId as string, key: res.json.data.apiKey as string };
|
||||
}
|
||||
|
||||
it("gives a merchant who names another org its own fresh org and key", async () => {
|
||||
const v = await victim();
|
||||
const product = await call("POST", "/v1/merchant/products", {
|
||||
name: "Secret",
|
||||
priceUsd: "10",
|
||||
delivery: { kind: "access", accessUrl: "https://example.com/x" },
|
||||
}, v.key);
|
||||
expect(product.status).toBe(201);
|
||||
|
||||
const attacker = await call("POST", "/v1/auth/register", {
|
||||
type: "merchant",
|
||||
email: "attacker@evil.test",
|
||||
password: "attacker password 1",
|
||||
organizationId: v.org,
|
||||
});
|
||||
expect(attacker.status).toBe(201);
|
||||
expect(attacker.json.data.account.organizationId).not.toBe(v.org);
|
||||
const listed = await call("GET", "/v1/merchant/products", undefined, attacker.json.data.apiKey);
|
||||
expect(listed.status).toBe(200);
|
||||
expect(listed.json.data).toEqual([]);
|
||||
const viaSession = await call("GET", "/v1/merchant/products", undefined, attacker.json.data.sessionToken);
|
||||
expect(viaSession.json.data).toEqual([]);
|
||||
});
|
||||
|
||||
it("refuses the management API to customer sessions that carry the seller's org", async () => {
|
||||
const v = await victim();
|
||||
const buyer = await call("POST", "/v1/auth/register", {
|
||||
type: "customer",
|
||||
email: "buyer@mail.test",
|
||||
password: "buyer password 1",
|
||||
organizationId: v.org,
|
||||
});
|
||||
expect(buyer.status).toBe(201);
|
||||
expect(buyer.json.data.apiKey).toBeUndefined();
|
||||
const token = buyer.json.data.sessionToken as string;
|
||||
// The session itself still works for the customer portal.
|
||||
expect((await call("GET", "/v1/auth/session", undefined, token)).status).toBe(200);
|
||||
for (const [method, path] of [
|
||||
["GET", "/v1/payments"],
|
||||
["GET", "/v1/merchant/products"],
|
||||
["GET", "/v1/api-keys"],
|
||||
["POST", "/v1/api-keys/platform"],
|
||||
] as const) {
|
||||
const res = await call(method, path, method === "POST" ? { scopes: ["platform:admin"] } : undefined, token);
|
||||
expect(res.status, `${method} ${path}`).toBeGreaterThanOrEqual(401);
|
||||
expect(res.status, `${method} ${path}`).toBeLessThanOrEqual(403);
|
||||
}
|
||||
});
|
||||
});
|
||||
@ -1,124 +0,0 @@
|
||||
/**
|
||||
* Webhook event log: per-attempt delivery records, resend, test events,
|
||||
* secret rotation with a grace window, and enable/disable. No database, so
|
||||
* deliveries run in-process against a stubbed fetch.
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { Hono } from "hono";
|
||||
import { verifySignature } from "@settlekit/webhooks";
|
||||
import { createApp } from "../src/app.js";
|
||||
import { createContext, type AppContext, type AppEnv } from "../src/context.js";
|
||||
|
||||
const BOOTSTRAP = "test-bootstrap-key";
|
||||
let app: Hono<AppEnv>;
|
||||
let ctx: AppContext;
|
||||
let otherKey: string;
|
||||
const received: { url: string; body: string; signature: string }[] = [];
|
||||
let respondWith = 200;
|
||||
|
||||
async function call(method: string, path: string, body?: unknown, key = BOOTSTRAP) {
|
||||
const res = await app.request(path, {
|
||||
method,
|
||||
headers: { authorization: `Bearer ${key}`, "content-type": "application/json" },
|
||||
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
|
||||
});
|
||||
return { status: res.status, json: (await res.json()) as { data?: any; error?: { message: string } } };
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
process.env.API_BOOTSTRAP_KEY = BOOTSTRAP;
|
||||
received.length = 0;
|
||||
respondWith = 200;
|
||||
vi.stubGlobal("fetch", async (url: string, init: RequestInit) => {
|
||||
const headers = init.headers as Record<string, string>;
|
||||
received.push({ url, body: String(init.body), signature: headers["SettleKit-Signature"] ?? "" });
|
||||
return new Response("", { status: respondWith });
|
||||
});
|
||||
ctx = await createContext();
|
||||
app = createApp(ctx);
|
||||
otherKey = (
|
||||
await ctx.apiKeys.issue({ organizationId: "org_other", customerId: "c", productId: "__platform__", entitlementId: "e", scopes: ["*"], env: "live" })
|
||||
).plaintext;
|
||||
});
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
async function endpoint(events = ["payment.confirmed"]) {
|
||||
const res = await call("POST", "/v1/webhooks/endpoints", { url: "https://hooks.test/settlekit", enabledEvents: events });
|
||||
expect(res.status).toBe(201);
|
||||
return res.json.data as { id: string; signingSecret: string };
|
||||
}
|
||||
|
||||
async function settle(): Promise<void> {
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
}
|
||||
|
||||
describe("webhook event log", () => {
|
||||
it("sends a signed test event and logs the attempt", async () => {
|
||||
const ep = await endpoint();
|
||||
const test = await call("POST", `/v1/webhooks/endpoints/${ep.id}/test`);
|
||||
expect(test.status).toBe(201);
|
||||
expect(test.json.data).toMatchObject({ eventType: "webhook.test", status: "delivered", attempts: 1, lastStatus: 200, manual: "test" });
|
||||
expect(received).toHaveLength(1);
|
||||
expect(verifySignature(ep.signingSecret, received[0]!.body, received[0]!.signature, 300)).toBe(true);
|
||||
const log = await call("GET", `/v1/webhooks/deliveries?endpointId=${ep.id}`);
|
||||
expect(log.json.data).toHaveLength(1);
|
||||
expect(JSON.stringify(log.json.data)).not.toContain(ep.signingSecret);
|
||||
});
|
||||
|
||||
it("records failures with status codes and resends an event", async () => {
|
||||
const ep = await endpoint();
|
||||
respondWith = 500;
|
||||
const failed = await call("POST", `/v1/webhooks/endpoints/${ep.id}/test`);
|
||||
expect(failed.json.data).toMatchObject({ status: "failed", lastStatus: 500, lastError: "HTTP 500" });
|
||||
expect(failed.json.data.nextAttemptAt).toBeTruthy();
|
||||
|
||||
// A real event emitted by the outbox lands in the log too.
|
||||
await ctx.webhookOutbox.enqueue({ organizationId: "org_settlekit_default", type: "payment.confirmed", key: "pay_1", data: { paymentId: "pay_1" } });
|
||||
await settle();
|
||||
const events = await call("GET", "/v1/webhooks/deliveries");
|
||||
const eventId = events.json.data.find((d: { eventType: string }) => d.eventType === "payment.confirmed").eventId;
|
||||
|
||||
respondWith = 200;
|
||||
const resent = await call("POST", `/v1/webhooks/events/${eventId}/resend`, {});
|
||||
expect(resent.status).toBe(201);
|
||||
expect(resent.json.data).toHaveLength(1);
|
||||
expect(resent.json.data[0]).toMatchObject({ status: "delivered", manual: "resend", eventId });
|
||||
const single = await call("GET", `/v1/webhooks/deliveries/${resent.json.data[0].id}`);
|
||||
expect(single.json.data.history).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("rotates the secret with a grace window so both secrets verify", async () => {
|
||||
const ep = await endpoint();
|
||||
const rotated = await call("POST", `/v1/webhooks/endpoints/${ep.id}/rotate-secret`, { graceHours: 24 });
|
||||
expect(rotated.status).toBe(200);
|
||||
const next = rotated.json.data.signingSecret as string;
|
||||
expect(next).not.toBe(ep.signingSecret);
|
||||
expect(rotated.json.data.previousSigningSecret).toBeUndefined();
|
||||
await call("POST", `/v1/webhooks/endpoints/${ep.id}/test`);
|
||||
const { body, signature } = received.at(-1)!;
|
||||
expect(verifySignature(next, body, signature, 300)).toBe(true);
|
||||
expect(verifySignature(ep.signingSecret, body, signature, 300)).toBe(true);
|
||||
|
||||
await call("POST", `/v1/webhooks/endpoints/${ep.id}/rotate-secret`, { graceHours: 0 });
|
||||
await call("POST", `/v1/webhooks/endpoints/${ep.id}/test`);
|
||||
const last = received.at(-1)!;
|
||||
expect(verifySignature(next, last.body, last.signature, 300)).toBe(false);
|
||||
expect((await call("POST", `/v1/webhooks/endpoints/${ep.id}/rotate-secret`, { graceHours: 500 })).status).toBe(400);
|
||||
});
|
||||
|
||||
it("disables and re-enables an endpoint and keeps other tenants out", async () => {
|
||||
const ep = await endpoint();
|
||||
const off = await call("POST", `/v1/webhooks/endpoints/${ep.id}/disable`);
|
||||
expect(off.json.data).toMatchObject({ active: false, disabledReason: "disabled by the merchant" });
|
||||
expect(off.json.data.signingSecret).toBeUndefined();
|
||||
await ctx.webhookOutbox.enqueue({ organizationId: "org_settlekit_default", type: "payment.confirmed", key: "pay_2", data: {} });
|
||||
await settle();
|
||||
expect(received).toHaveLength(0);
|
||||
const on = await call("POST", `/v1/webhooks/endpoints/${ep.id}/enable`);
|
||||
expect(on.json.data).toMatchObject({ active: true, consecutiveFailures: 0 });
|
||||
|
||||
expect((await call("POST", `/v1/webhooks/endpoints/${ep.id}/test`, undefined, otherKey)).status).toBe(404);
|
||||
expect((await call("GET", "/v1/webhooks/deliveries", undefined, otherKey)).json.data).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@ -9,14 +9,10 @@
|
||||
"references": [
|
||||
{ "path": "../../packages/onchain-billing" },
|
||||
{ "path": "../../packages/common" },
|
||||
{ "path": "../../packages/pricing" },
|
||||
{ "path": "../../packages/exports" },
|
||||
{ "path": "../../packages/invitations" },
|
||||
{ "path": "../../packages/solana" },
|
||||
{ "path": "../../packages/zcash" },
|
||||
{ "path": "../../packages/chains" },
|
||||
{ "path": "../../packages/hyperliquid" },
|
||||
{ "path": "../../packages/operator" },
|
||||
{ "path": "../../packages/auth" },
|
||||
{ "path": "../../packages/database" },
|
||||
{ "path": "../../packages/persistence" },
|
||||
@ -50,7 +46,6 @@
|
||||
{ "path": "../../packages/disputes" },
|
||||
{ "path": "../../packages/payouts" },
|
||||
{ "path": "../../packages/platform-billing" },
|
||||
{ "path": "../../packages/circle" },
|
||||
{ "path": "../../packages/circle-wallets" },
|
||||
{ "path": "../../packages/compliance" },
|
||||
{ "path": "../../packages/cctp" },
|
||||
|
||||
@ -17,25 +17,6 @@
|
||||
# CHECKOUT_DELIVERY_SECRET=
|
||||
# CHECKOUT_DOWNLOAD_BASE=
|
||||
|
||||
# --- Subscriptions (onchain billing through the SettleKit API) --------------------
|
||||
# Recurring products offer "Subscribe" (spend permission / Permit2 / SPL delegate /
|
||||
# renewal invoices). The checkout calls the API's /v1/onchain-billing server-side
|
||||
# with a platform service token; the API must have the SAME SETTLEKIT_SERVICE_TOKEN
|
||||
# (32+ chars, e.g. `openssl rand -hex 32`) and onchain billing configured.
|
||||
# SETTLEKIT_API_URL=https://api.example.com
|
||||
# SETTLEKIT_SERVICE_TOKEN=
|
||||
# Signs buyer "manage subscription" links (/s/<token>); defaults to CHECKOUT_DELIVERY_SECRET.
|
||||
# CHECKOUT_MANAGE_SECRET=
|
||||
|
||||
# --- Discord role delivery ----------------------------------------------------------
|
||||
# Buyers connect Discord (OAuth2 identify) at checkout; the bot adds the product's
|
||||
# role. Without DISCORD_BOT_TOKEN, Discord purchases show "pending setup" and the
|
||||
# worker grants the role once the bot is configured. Redirect URI to register in
|
||||
# the Discord developer portal: <CHECKOUT_PUBLIC_URL>/api/discord/callback
|
||||
# DISCORD_BOT_TOKEN=
|
||||
# DISCORD_CLIENT_ID=
|
||||
# DISCORD_CLIENT_SECRET=
|
||||
|
||||
# --- EVM chains (USD stablecoins, 6 decimals) -------------------------------------
|
||||
# mainnet | testnet for every EVM chain (default testnet); per-chain <KEY>_NETWORK.
|
||||
SETTLEKIT_CHAIN_ENV=testnet
|
||||
|
||||
@ -1,25 +0,0 @@
|
||||
/**
|
||||
* GET /api/discord/authorize?session=<checkoutSessionId>
|
||||
*
|
||||
* Starts "Connect Discord" for a checkout whose product grants a Discord role.
|
||||
*/
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import { authorizeUrl, discordOAuthSetup } from "@/lib/discord-connect";
|
||||
import { publicOrigin } from "@/lib/origin";
|
||||
import { getResolvedSession } from "@/lib/store";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const runtime = "nodejs";
|
||||
|
||||
export async function GET(request: Request): Promise<NextResponse> {
|
||||
const sessionId = new URL(request.url).searchParams.get("session") ?? "";
|
||||
const origin = publicOrigin(request);
|
||||
const setup = discordOAuthSetup();
|
||||
const resolved = sessionId ? await getResolvedSession(sessionId) : undefined;
|
||||
if (!resolved) return NextResponse.json({ error: "Checkout session not found." }, { status: 404 });
|
||||
if (!setup || resolved.deliveryAction.type !== "discord_role_add") {
|
||||
return NextResponse.redirect(`${origin}/c/${encodeURIComponent(sessionId)}?discord=unavailable`);
|
||||
}
|
||||
return NextResponse.redirect(authorizeUrl(setup, origin, sessionId));
|
||||
}
|
||||
@ -1,42 +0,0 @@
|
||||
/**
|
||||
* GET /api/discord/callback?code=&state=
|
||||
*
|
||||
* Saves the buyer's Discord id on the checkout session that started the flow
|
||||
* and adds them to the product's server (no paid role until payment settles).
|
||||
*/
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import { discordOAuthSetup, identify, readState } from "@/lib/discord-connect";
|
||||
import { getDiscordDelivery, joinGuild, resolveDiscordTarget } from "@/lib/discord-delivery";
|
||||
import { publicOrigin } from "@/lib/origin";
|
||||
import { getResolvedSession, saveCollectedFields } from "@/lib/store";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const runtime = "nodejs";
|
||||
|
||||
export async function GET(request: Request): Promise<NextResponse> {
|
||||
const url = new URL(request.url);
|
||||
const origin = publicOrigin(request);
|
||||
const sessionId = readState(url.searchParams.get("state") ?? "");
|
||||
if (!sessionId) return NextResponse.json({ error: "This Discord link expired. Go back to the checkout and connect again." }, { status: 400 });
|
||||
const back = (status: string) => NextResponse.redirect(`${origin}/c/${encodeURIComponent(sessionId)}?discord=${status}`);
|
||||
const code = url.searchParams.get("code");
|
||||
const setup = discordOAuthSetup();
|
||||
if (!code || !setup) return back("canceled");
|
||||
|
||||
const resolved = await getResolvedSession(sessionId);
|
||||
if (!resolved || resolved.session.status !== "open") return back("closed");
|
||||
try {
|
||||
const identity = await identify(setup, origin, code);
|
||||
await saveCollectedFields(sessionId, { discordUserId: identity.userId, discordUsername: identity.username });
|
||||
const action = resolved.deliveryAction;
|
||||
if (action.type === "discord_role_add") {
|
||||
const target = resolveDiscordTarget(action, resolved.product);
|
||||
if (target) await joinGuild(getDiscordDelivery(), target.guildId, identity.userId, identity.accessToken);
|
||||
}
|
||||
return back("connected");
|
||||
} catch (error) {
|
||||
console.error("[checkout] discord connect failed:", error);
|
||||
return back("failed");
|
||||
}
|
||||
}
|
||||
@ -1,28 +0,0 @@
|
||||
/**
|
||||
* POST /api/subscriptions/:token/cancel
|
||||
*
|
||||
* Buyer cancel from the manage page. Stops charges at the end of the paid
|
||||
* period and returns the wallet action that revokes the on-chain allowance
|
||||
* (the operator stops pulling either way).
|
||||
*/
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import { cancelManagedSubscription } from "@/lib/manage-subscription";
|
||||
import { errorReply } from "@/lib/route-helpers";
|
||||
import { assertSameOrigin } from "@/lib/same-origin";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const runtime = "nodejs";
|
||||
|
||||
interface RouteContext {
|
||||
params: { token: string };
|
||||
}
|
||||
|
||||
export async function POST(request: Request, context: RouteContext): Promise<NextResponse> {
|
||||
try {
|
||||
assertSameOrigin(request);
|
||||
return NextResponse.json(await cancelManagedSubscription(context.params.token));
|
||||
} catch (error) {
|
||||
return errorReply(error, "Could not cancel the subscription.", "subscription cancel");
|
||||
}
|
||||
}
|
||||
@ -1,36 +0,0 @@
|
||||
/**
|
||||
* POST /api/v1/checkout-sessions/:sessionId/promo
|
||||
*
|
||||
* Body: { code: string }
|
||||
*
|
||||
* Applies a seller promo code while the session is open and unpaid; the
|
||||
* discounted total becomes the amount due. 400 with the reason when the code
|
||||
* is refused, 409 when the session can no longer change.
|
||||
*/
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import { applyPromoCode } from "@/lib/promo";
|
||||
import { errorReply, readJsonObject } from "@/lib/route-helpers";
|
||||
import { assertSameOrigin } from "@/lib/same-origin";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const runtime = "nodejs";
|
||||
|
||||
interface RouteContext {
|
||||
params: { sessionId: string };
|
||||
}
|
||||
|
||||
export async function POST(request: Request, context: RouteContext): Promise<NextResponse> {
|
||||
try {
|
||||
assertSameOrigin(request);
|
||||
const body = await readJsonObject(request);
|
||||
const session = await applyPromoCode(context.params.sessionId, body.code);
|
||||
return NextResponse.json({
|
||||
amount: session.amount,
|
||||
discount: session.discount ?? null,
|
||||
settlementQuote: session.settlementQuote ?? null,
|
||||
});
|
||||
} catch (error) {
|
||||
return errorReply(error, "Could not apply the promo code.", "promo");
|
||||
}
|
||||
}
|
||||
@ -1,34 +0,0 @@
|
||||
/**
|
||||
* POST /api/v1/checkout-sessions/:sessionId/subscription/grant
|
||||
*
|
||||
* Body: { subscriptionId, signature? (EIP-712), approveSignature? (Solana) }
|
||||
* Forwards the buyer's signed authorization; the API registers it, charges
|
||||
* the first period and delivers access. Returns the buyer's manage link.
|
||||
*/
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import { errorReply, readJsonObject } from "@/lib/route-helpers";
|
||||
import { assertSameOrigin } from "@/lib/same-origin";
|
||||
import { completeSubscription } from "@/lib/subscription-checkout";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const runtime = "nodejs";
|
||||
|
||||
interface RouteContext {
|
||||
params: { sessionId: string };
|
||||
}
|
||||
|
||||
export async function POST(request: Request, context: RouteContext): Promise<NextResponse> {
|
||||
try {
|
||||
assertSameOrigin(request);
|
||||
const body = await readJsonObject(request);
|
||||
const result = await completeSubscription(context.params.sessionId, {
|
||||
subscriptionId: body.subscriptionId,
|
||||
signature: body.signature,
|
||||
approveSignature: body.approveSignature,
|
||||
});
|
||||
return NextResponse.json(result);
|
||||
} catch (error) {
|
||||
return errorReply(error, "Could not activate the subscription.", "subscription grant");
|
||||
}
|
||||
}
|
||||
@ -1,41 +0,0 @@
|
||||
/**
|
||||
* GET /api/v1/checkout-sessions/:sessionId/subscription
|
||||
* What subscribing looks like on the session's network (methods, cap, expiry).
|
||||
* POST /api/v1/checkout-sessions/:sessionId/subscription
|
||||
* Body: { method, payer?, fields } -> the intent the buyer's wallet signs/sends.
|
||||
*/
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import { errorReply, fieldsOf, readJsonObject } from "@/lib/route-helpers";
|
||||
import { assertSameOrigin } from "@/lib/same-origin";
|
||||
import { getSubscriptionOffer, startSubscription } from "@/lib/subscription-checkout";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const runtime = "nodejs";
|
||||
|
||||
interface RouteContext {
|
||||
params: { sessionId: string };
|
||||
}
|
||||
|
||||
export async function GET(_request: Request, context: RouteContext): Promise<NextResponse> {
|
||||
try {
|
||||
return NextResponse.json(await getSubscriptionOffer(context.params.sessionId));
|
||||
} catch (error) {
|
||||
return errorReply(error, "Could not load subscription options.", "subscription offer");
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: Request, context: RouteContext): Promise<NextResponse> {
|
||||
try {
|
||||
assertSameOrigin(request);
|
||||
const body = await readJsonObject(request);
|
||||
const result = await startSubscription(context.params.sessionId, {
|
||||
method: body.method,
|
||||
payer: body.payer,
|
||||
fields: fieldsOf(body),
|
||||
});
|
||||
return NextResponse.json(result);
|
||||
} catch (error) {
|
||||
return errorReply(error, "Could not start the subscription.", "subscription start");
|
||||
}
|
||||
}
|
||||
@ -1,31 +0,0 @@
|
||||
/**
|
||||
* POST /api/v1/checkout-sessions/:sessionId/tax
|
||||
*
|
||||
* Body: { country: "FR", vatId?: "FR12345678901" }
|
||||
*
|
||||
* Sets the buyer's billing country (and optional VAT ID) and recomputes the
|
||||
* tax-inclusive amount due while the session is open and unpaid.
|
||||
*/
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import { applyBuyerTax } from "@/lib/buyer-tax";
|
||||
import { errorReply, readJsonObject } from "@/lib/route-helpers";
|
||||
import { assertSameOrigin } from "@/lib/same-origin";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const runtime = "nodejs";
|
||||
|
||||
interface RouteContext {
|
||||
params: { sessionId: string };
|
||||
}
|
||||
|
||||
export async function POST(request: Request, context: RouteContext): Promise<NextResponse> {
|
||||
try {
|
||||
assertSameOrigin(request);
|
||||
const body = await readJsonObject(request);
|
||||
const session = await applyBuyerTax(context.params.sessionId, { country: body.country, vatId: body.vatId });
|
||||
return NextResponse.json({ amount: session.amount, tax: session.tax ?? null });
|
||||
} catch (error) {
|
||||
return errorReply(error, "Could not update the billing details.", "tax");
|
||||
}
|
||||
}
|
||||
@ -3,26 +3,15 @@ import { notFound, redirect } from "next/navigation";
|
||||
import { getCheckoutSession, ApiClientError } from "@/lib/api";
|
||||
import { badgeDescription, badgeText, formatAmount, formatExpiry, formatMoney } from "@/lib/format";
|
||||
import { OrderSummary } from "@/components/OrderSummary";
|
||||
import { PromoCode } from "@/components/PromoCode";
|
||||
import { TaxDetails } from "@/components/TaxDetails";
|
||||
import { orderLabels, promoLabels, serverT, taxLabels } from "@/lib/i18n";
|
||||
import { NetworkPicker } from "@/components/NetworkPicker";
|
||||
import { AnyTokenPay, EvmPay, HyperCorePay, SolanaPay, SubscribePay, WalletPay, ZcashPay } from "@/components/LazyPay";
|
||||
import { AnyTokenPay, EvmPay, HyperCorePay, SolanaPay, WalletPay, ZcashPay } from "@/components/LazyPay";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
interface PageProps {
|
||||
params: { sessionId: string };
|
||||
searchParams: { discord?: string; promo?: string; lang?: string };
|
||||
}
|
||||
|
||||
const DISCORD_NOTICE: Record<string, { ok: boolean; text: string }> = {
|
||||
connected: { ok: true, text: "Discord connected. Your role is added as soon as the payment settles." },
|
||||
failed: { ok: false, text: "Discord did not connect. Try again, or enter your user ID manually." },
|
||||
canceled: { ok: false, text: "Discord connection was canceled." },
|
||||
unavailable: { ok: false, text: "Connecting Discord is not available on this checkout; enter your user ID instead." },
|
||||
};
|
||||
|
||||
/**
|
||||
* Hosted checkout page. Server-fetches the checkout session from the SettleKit
|
||||
* API, renders the order summary, a network picker (accepted networks this
|
||||
@ -32,7 +21,7 @@ const DISCORD_NOTICE: Record<string, { ok: boolean; text: string }> = {
|
||||
* the network. Expired sessions redirect to the
|
||||
* /expired page; completed sessions redirect to /success.
|
||||
*/
|
||||
export default async function CheckoutPage({ params, searchParams }: PageProps) {
|
||||
export default async function CheckoutPage({ params }: PageProps) {
|
||||
const { sessionId } = params;
|
||||
|
||||
let session;
|
||||
@ -59,70 +48,26 @@ export default async function CheckoutPage({ params, searchParams }: PageProps)
|
||||
// The Arc demo wallet (offline simulation) only applies to Arc sessions.
|
||||
const isArc = session.network === "arc";
|
||||
|
||||
const discordNotice = searchParams.discord ? DISCORD_NOTICE[searchParams.discord] : undefined;
|
||||
const t = serverT(searchParams.lang);
|
||||
|
||||
return (
|
||||
<div>
|
||||
{discordNotice ? (
|
||||
<div className={`alert ${discordNotice.ok ? "alert-success" : "alert-error"}`} role="status">
|
||||
{discordNotice.text}
|
||||
</div>
|
||||
) : null}
|
||||
<div className="card">
|
||||
<h2>{t("order.title")}</h2>
|
||||
<p className="merchant">{t("order.soldBy", { merchant: session.merchantName })}</p>
|
||||
<OrderSummary lines={session.lines} total={session.amount} discount={session.discount} tax={session.tax} labels={orderLabels(t)} />
|
||||
{session.fx ? (
|
||||
<p className="muted" style={{ marginTop: 6 }}>
|
||||
{t("fx.note", {
|
||||
amount: session.fx.amount,
|
||||
currency: session.fx.currency,
|
||||
rate: session.fx.rate,
|
||||
source: session.fx.source,
|
||||
date: session.fx.rateDate,
|
||||
})}
|
||||
</p>
|
||||
) : null}
|
||||
{searchParams.promo === "refused" && !session.discount ? (
|
||||
<p className="field-error" role="status">
|
||||
{t("promo.refused")}
|
||||
</p>
|
||||
) : null}
|
||||
{session.promoAllowed ? <PromoCode sessionId={session.id} labels={promoLabels(t)} /> : null}
|
||||
{session.tax && session.taxEditable ? (
|
||||
<TaxDetails sessionId={session.id} country={session.tax.country} vatId={session.tax.vatId} labels={taxLabels(t)} />
|
||||
) : null}
|
||||
<h2>Order summary</h2>
|
||||
<p className="merchant">Sold by {session.merchantName}</p>
|
||||
<OrderSummary lines={session.lines} total={session.amount} />
|
||||
</div>
|
||||
|
||||
{session.recurring && option.available ? (
|
||||
<div className="card">
|
||||
<h2>{t("pay.subscribe")}</h2>
|
||||
<SubscribePay
|
||||
key={session.network}
|
||||
sessionId={session.id}
|
||||
requiredFields={session.requiredFields}
|
||||
initialValues={session.collectedFields}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="card">
|
||||
<h2>
|
||||
{session.recurring
|
||||
? t("pay.oneOff", { period: t(session.recurring === "yearly" ? "pay.year" : "pay.month") })
|
||||
: t("pay.title")}
|
||||
</h2>
|
||||
<h2>Payment</h2>
|
||||
<NetworkPicker sessionId={session.id} current={session.network} options={session.networkOptions} />
|
||||
<div className="payto">
|
||||
<div className="payto-row">
|
||||
<span className="label">{t("pay.amountDue")}</span>
|
||||
<span className="label">Amount due</span>
|
||||
<span className="line-amount">
|
||||
{family === "zcash" ? `${formatMoney(session.amount)} in ZEC` : amountLabel}
|
||||
</span>
|
||||
</div>
|
||||
<div className="payto-row">
|
||||
<span className="label">{t("pay.network")}</span>
|
||||
<span className="label">Network</span>
|
||||
<span className="network-badges">
|
||||
<span className="badge badge-network">{option.name}</span>
|
||||
{option.badges.map((badge) => (
|
||||
@ -133,7 +78,7 @@ export default async function CheckoutPage({ params, searchParams }: PageProps)
|
||||
</span>
|
||||
</div>
|
||||
<div className="payto-row">
|
||||
<span className="label">{t("pay.window")}</span>
|
||||
<span className="label">Window</span>
|
||||
<span className="badge badge-expiry">
|
||||
{formatExpiry(session.expiresAt)}
|
||||
</span>
|
||||
@ -187,7 +132,7 @@ export default async function CheckoutPage({ params, searchParams }: PageProps)
|
||||
|
||||
{option.available && session.anyToken.available ? (
|
||||
<div className="card">
|
||||
<h2>{t("pay.anyToken")}</h2>
|
||||
<h2>Pay with any token</h2>
|
||||
<AnyTokenPay
|
||||
key={session.network}
|
||||
sessionId={session.id}
|
||||
|
||||
@ -1,26 +0,0 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import { apiBaseUrl } from "@/lib/payment-link";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const SESSION_RE = /^[A-Za-z0-9_-]{8,100}$/;
|
||||
|
||||
/** GET /c/:sessionId/receipt: the tax-grade receipt PDF of a settled checkout. */
|
||||
export async function GET(_request: Request, { params }: { params: { sessionId: string } }) {
|
||||
if (!SESSION_RE.test(params.sessionId)) return NextResponse.json({ error: "not found" }, { status: 404 });
|
||||
const upstream = await fetch(`${apiBaseUrl()}/v1/public/receipts/${encodeURIComponent(params.sessionId)}/pdf`, {
|
||||
cache: "no-store",
|
||||
});
|
||||
if (!upstream.ok || !upstream.body) {
|
||||
return NextResponse.json({ error: "receipt unavailable" }, { status: upstream.status === 404 ? 404 : 502 });
|
||||
}
|
||||
return new NextResponse(upstream.body, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"content-type": "application/pdf",
|
||||
"content-disposition": upstream.headers.get("content-disposition") ?? "inline",
|
||||
"cache-control": "private, no-store",
|
||||
},
|
||||
});
|
||||
}
|
||||
@ -8,9 +8,6 @@ import {
|
||||
} from "@/lib/format";
|
||||
import { OrderSummary } from "@/components/OrderSummary";
|
||||
import { AccessList } from "@/components/AccessList";
|
||||
import { EmbedSuccess } from "@/components/EmbedSuccess";
|
||||
import { embedOriginsForSession } from "@/lib/embed";
|
||||
import { orderLabels, serverT } from "@/lib/i18n";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
@ -38,31 +35,24 @@ export default async function SuccessPage({ params }: PageProps) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
const embedOrigins = await embedOriginsForSession(sessionId).catch(() => []);
|
||||
const t = serverT();
|
||||
// The receipt amount is the authoritative settled total.
|
||||
const total = receipt.amount;
|
||||
const INTERNAL_FIELDS = new Set(["subscribeIntentId", "onchainSubscriptionId", "periodIndex"]);
|
||||
const buyerEntries = Object.entries(receipt.buyer).filter(([key]) => !INTERNAL_FIELDS.has(key));
|
||||
const buyerEntries = Object.entries(receipt.buyer);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<EmbedSuccess sessionId={sessionId} paymentId={receipt.paymentId} allowedOrigins={embedOrigins} />
|
||||
<div className="card center">
|
||||
<div className="big-status">{t("success.title")}</div>
|
||||
<div className="big-status">Payment confirmed</div>
|
||||
<p className="muted">
|
||||
{receipt.access.some((item) => item.pending) ? t("success.pending") : t("success.delivered")}
|
||||
{receipt.access.some((item) => item.pending)
|
||||
? "Your USDC payment settled. Some access is still pending; details below."
|
||||
: "Your USDC payment settled and access has been delivered."}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="card">
|
||||
<h2>{t("success.receipt")}</h2>
|
||||
<OrderSummary lines={receipt.lines} total={total} discount={receipt.discount} tax={receipt.tax} labels={orderLabels(t)} />
|
||||
<p style={{ marginTop: 8 }}>
|
||||
<a className="link" href={`/c/${encodeURIComponent(sessionId)}/receipt`} target="_blank" rel="noreferrer">
|
||||
{t("success.downloadReceipt")}
|
||||
</a>
|
||||
</p>
|
||||
<h2>Receipt</h2>
|
||||
<OrderSummary lines={receipt.lines} total={total} />
|
||||
<div className="divider" />
|
||||
<div className="payto-row">
|
||||
<span className="label">Paid</span>
|
||||
@ -119,15 +109,9 @@ export default async function SuccessPage({ params }: PageProps) {
|
||||
</div>
|
||||
|
||||
<div className="center">
|
||||
{receipt.returnUrl ? (
|
||||
<a className="btn btn-primary" href={receipt.returnUrl}>
|
||||
Continue to {new URL(receipt.returnUrl).host}
|
||||
</a>
|
||||
) : (
|
||||
<Link className="link" href="/">
|
||||
Back to checkout
|
||||
</Link>
|
||||
)}
|
||||
<Link className="link" href="/">
|
||||
Back to checkout
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@ -276,19 +276,19 @@ body {
|
||||
.alert-error {
|
||||
background: rgba(239, 93, 107, 0.12);
|
||||
border: 1px solid rgba(239, 93, 107, 0.4);
|
||||
color: var(--danger);
|
||||
color: #ffc6cc;
|
||||
}
|
||||
|
||||
.alert-info {
|
||||
background: rgba(79, 140, 255, 0.1);
|
||||
border: 1px solid rgba(79, 140, 255, 0.35);
|
||||
color: var(--accent-2);
|
||||
color: #cfe0ff;
|
||||
}
|
||||
|
||||
.alert-success {
|
||||
background: rgba(41, 192, 138, 0.12);
|
||||
border: 1px solid rgba(41, 192, 138, 0.4);
|
||||
color: var(--success);
|
||||
color: #b7f3dc;
|
||||
}
|
||||
|
||||
.badge {
|
||||
@ -642,119 +642,3 @@ a.link:hover {
|
||||
align-items: center;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
/* --- Subscriptions (SubscribePay, ManageSubscription) --------------------- */
|
||||
.plain-list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
.sub-headline {
|
||||
margin: 0 0 14px;
|
||||
}
|
||||
.sub-methods {
|
||||
border: 0;
|
||||
margin: 0 0 16px;
|
||||
padding: 0;
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
}
|
||||
.sub-method {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
align-items: flex-start;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
background: var(--panel);
|
||||
cursor: pointer;
|
||||
}
|
||||
.sub-method.selected {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
.sub-method .help {
|
||||
display: block;
|
||||
margin-top: 2px;
|
||||
}
|
||||
.sub-authorize {
|
||||
margin-bottom: 18px;
|
||||
}
|
||||
.sub-terms li {
|
||||
padding: 4px 0;
|
||||
font-size: 14px;
|
||||
}
|
||||
.sub-spender {
|
||||
font-size: 12px;
|
||||
margin: 8px 0 0;
|
||||
word-break: break-all;
|
||||
}
|
||||
.sub-grid {
|
||||
display: grid;
|
||||
grid-template-columns: max-content 1fr;
|
||||
gap: 8px 16px;
|
||||
margin: 12px 0 18px;
|
||||
}
|
||||
.sub-grid dt {
|
||||
color: var(--muted);
|
||||
}
|
||||
.sub-grid dd {
|
||||
margin: 0;
|
||||
word-break: break-word;
|
||||
}
|
||||
.badge-status-active {
|
||||
background: var(--success);
|
||||
color: #fff;
|
||||
}
|
||||
.badge-status-past_due,
|
||||
.badge-status-pending_grant {
|
||||
background: var(--warn);
|
||||
color: #fff;
|
||||
}
|
||||
.badge-status-suspended,
|
||||
.badge-status-canceled {
|
||||
background: var(--panel-2);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
/* --- Connect Discord ------------------------------------------------------- */
|
||||
.connect-row {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.connect-manual {
|
||||
margin-top: 8px;
|
||||
}
|
||||
.connect-manual summary {
|
||||
cursor: pointer;
|
||||
font-size: 13px;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
/* ---------- Promo code ---------- */
|
||||
.link-button {
|
||||
background: none;
|
||||
border: 0;
|
||||
padding: 0;
|
||||
margin-top: 12px;
|
||||
color: inherit;
|
||||
text-decoration: underline;
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
opacity: 0.8;
|
||||
}
|
||||
.promo {
|
||||
margin-top: 12px;
|
||||
}
|
||||
.field-error {
|
||||
color: #d64545;
|
||||
font-size: 13px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
.line-discount {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
opacity: 0.85;
|
||||
padding: 6px 0;
|
||||
}
|
||||
|
||||
@ -1,105 +0,0 @@
|
||||
import { notFound } from "next/navigation";
|
||||
|
||||
import { InvoiceLinkError, getInvoice } from "@/lib/invoice-link";
|
||||
import { serverT } from "@/lib/i18n";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
interface PageProps {
|
||||
params: { token: string };
|
||||
searchParams: { error?: string; lang?: string };
|
||||
}
|
||||
|
||||
function day(iso: string | null): string | null {
|
||||
return iso ? iso.slice(0, 10) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Public invoice / payment request page. Shows what is owed and one action:
|
||||
* pay in USDC (opens the invoice's checkout session) or, once paid, the
|
||||
* receipt with the settlement transaction.
|
||||
*/
|
||||
export default async function InvoicePage({ params, searchParams }: PageProps) {
|
||||
let invoice;
|
||||
try {
|
||||
invoice = await getInvoice(params.token);
|
||||
} catch (error) {
|
||||
if (error instanceof InvoiceLinkError && error.status === 404) notFound();
|
||||
return (
|
||||
<div className="card">
|
||||
<h2>Invoice unavailable</h2>
|
||||
<p className="muted">
|
||||
{error instanceof Error ? error.message : "This invoice could not be loaded."} Try again in a minute.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const pdfHref = `/i/${encodeURIComponent(params.token)}/pdf`;
|
||||
const t = serverT(searchParams.lang);
|
||||
return (
|
||||
<div>
|
||||
<div className="card">
|
||||
<p className="merchant">{t("invoice.from", { merchant: invoice.merchantName })}</p>
|
||||
<h2>{invoice.number}</h2>
|
||||
{invoice.dueAt && invoice.status === "open" ? <p className="muted">{t("invoice.due", { date: day(invoice.dueAt) ?? "" })}</p> : null}
|
||||
<ul className="line-items">
|
||||
{invoice.lineItems.map((line, i) => (
|
||||
<li key={i} className="line-desc">
|
||||
{line.quantity > 1 ? `${line.quantity} x ` : ""}
|
||||
{line.description}: {line.unitAmount} {invoice.currency}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{invoice.discount ? (
|
||||
<div className="total">
|
||||
<span>{t("invoice.discount")}</span>
|
||||
<span>-{invoice.discount} {invoice.currency}</span>
|
||||
</div>
|
||||
) : null}
|
||||
{invoice.tax ? (
|
||||
<div className="total">
|
||||
<span>{t("invoice.tax")}</span>
|
||||
<span>
|
||||
{invoice.tax} {invoice.currency}
|
||||
</span>
|
||||
</div>
|
||||
) : null}
|
||||
<div className="total">
|
||||
<span>{t("order.total")}</span>
|
||||
<span>
|
||||
{invoice.total} {invoice.currency}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="card">
|
||||
{searchParams.error ? (
|
||||
<div className="alert alert-error" role="alert">
|
||||
We could not open the payment just now. Please try again.
|
||||
</div>
|
||||
) : null}
|
||||
{invoice.status === "paid" ? (
|
||||
<div>
|
||||
<h3>{t("invoice.paid")}</h3>
|
||||
<p className="muted">
|
||||
{t("invoice.paidOn", { date: day(invoice.paidAt) ?? "" })}
|
||||
{invoice.paidNetwork ? ` on ${invoice.paidNetwork}` : ""}.
|
||||
</p>
|
||||
{invoice.paidTxHash ? <p className="mono">{invoice.paidTxHash}</p> : null}
|
||||
</div>
|
||||
) : invoice.payable ? (
|
||||
<form method="post" action={`/i/${encodeURIComponent(params.token)}/start`}>
|
||||
<button type="submit" className="btn btn-primary">
|
||||
{t("invoice.pay", { amount: invoice.total, currency: invoice.currency })}
|
||||
</button>
|
||||
</form>
|
||||
) : (
|
||||
<p className="muted">{invoice.unpayableReason}</p>
|
||||
)}
|
||||
<p style={{ marginTop: 12 }}>
|
||||
<a href={pdfHref}>{invoice.status === "paid" ? t("invoice.downloadReceipt") : t("invoice.downloadInvoice")}</a>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -1,22 +0,0 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import { invoicePdfApiUrl, isInvoiceToken } from "@/lib/invoice-link";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** GET /i/:token/pdf: stream the invoice (or receipt, once paid) PDF. */
|
||||
export async function GET(_request: Request, { params }: { params: { token: string } }) {
|
||||
if (!isInvoiceToken(params.token)) return NextResponse.json({ error: "not found" }, { status: 404 });
|
||||
const upstream = await fetch(invoicePdfApiUrl(params.token), { cache: "no-store" });
|
||||
if (!upstream.ok || !upstream.body) {
|
||||
return NextResponse.json({ error: "invoice unavailable" }, { status: upstream.status === 404 ? 404 : 502 });
|
||||
}
|
||||
return new NextResponse(upstream.body, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"content-type": "application/pdf",
|
||||
"content-disposition": upstream.headers.get("content-disposition") ?? "inline",
|
||||
"cache-control": "private, no-store",
|
||||
},
|
||||
});
|
||||
}
|
||||
@ -1,20 +0,0 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import { InvoiceLinkError, startInvoicePayment } from "@/lib/invoice-link";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/**
|
||||
* POST /i/:token/start: open (or reuse) the invoice's checkout session and
|
||||
* move the payer to it. A plain form POST works without JavaScript.
|
||||
*/
|
||||
export async function POST(request: Request, { params }: { params: { token: string } }) {
|
||||
try {
|
||||
const sessionId = await startInvoicePayment(params.token);
|
||||
return NextResponse.redirect(new URL(`/c/${encodeURIComponent(sessionId)}`, request.url), 303);
|
||||
} catch (error) {
|
||||
const status = error instanceof InvoiceLinkError ? error.status : 502;
|
||||
const target = status === 404 ? "/not-found" : `/i/${encodeURIComponent(params.token)}?error=1`;
|
||||
return NextResponse.redirect(new URL(target, request.url), 303);
|
||||
}
|
||||
}
|
||||
@ -1,93 +0,0 @@
|
||||
import { notFound } from "next/navigation";
|
||||
|
||||
import { PaymentLinkError, getPaymentLink } from "@/lib/payment-link";
|
||||
import { StartCheckout } from "@/components/StartCheckout";
|
||||
import { serverT, startLabels } from "@/lib/i18n";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
interface PageProps {
|
||||
params: { slug: string };
|
||||
searchParams: { error?: string; promo?: string; lang?: string };
|
||||
}
|
||||
|
||||
/** A promo code from the URL, or undefined when absent or malformed. */
|
||||
function cleanPromo(raw: string | undefined): string | undefined {
|
||||
const code = raw?.trim();
|
||||
return code && /^[A-Za-z0-9_-]{1,64}$/.test(code) ? code : undefined;
|
||||
}
|
||||
|
||||
const INTERVAL_LABEL: Record<string, string> = { monthly: " / month", yearly: " / year" };
|
||||
|
||||
/**
|
||||
* Reusable payment link landing. Shows what the buyer is paying for, then
|
||||
* opens a fresh checkout session (client-side, so link unfurlers and
|
||||
* crawlers never create sessions) and moves the buyer to it.
|
||||
*/
|
||||
export default async function PaymentLinkPage({ params, searchParams }: PageProps) {
|
||||
let link;
|
||||
try {
|
||||
link = await getPaymentLink(params.slug);
|
||||
} catch (error) {
|
||||
if (error instanceof PaymentLinkError && error.status === 404) notFound();
|
||||
return (
|
||||
<div className="card">
|
||||
<h2>Checkout unavailable</h2>
|
||||
<p className="muted">
|
||||
{error instanceof Error ? error.message : "This payment link could not be loaded."} Try again in a minute.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const promo = cleanPromo(searchParams.promo);
|
||||
const t = serverT(searchParams.lang);
|
||||
return (
|
||||
<div>
|
||||
<div className="card">
|
||||
<p className="merchant">{t("order.soldBy", { merchant: link.merchantName })}</p>
|
||||
<h2>{link.name}</h2>
|
||||
{link.description ? <p className="line-desc">{link.description}</p> : null}
|
||||
<div className="total">
|
||||
<span>{t("link.price")}</span>
|
||||
<span>
|
||||
{link.displayCurrency && link.displayAmount ? `${link.displayAmount} ${link.displayCurrency}` : `$${link.priceUsd}`}
|
||||
{INTERVAL_LABEL[link.interval] ?? ""}
|
||||
</span>
|
||||
</div>
|
||||
{link.displayCurrency ? (
|
||||
<p className="muted" style={{ marginTop: 8 }}>
|
||||
Paid in USDC at the live exchange rate, about {link.priceUsd} USDC now.
|
||||
</p>
|
||||
) : null}
|
||||
{INTERVAL_LABEL[link.interval] ? (
|
||||
<p className="muted" style={{ marginTop: 8 }}>
|
||||
Subscribe with one wallet approval capped at the price per period (or renewal invoices by email). Cancel any
|
||||
time from your manage link.
|
||||
</p>
|
||||
) : null}
|
||||
<div className="network-badges" style={{ marginTop: 12 }}>
|
||||
{link.networks.map((n) => (
|
||||
<span key={n.network} className="badge badge-network" title={`${n.asset} on ${n.name}`}>
|
||||
{n.name} {n.asset}
|
||||
{n.env === "testnet" ? " (testnet)" : ""}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="card">
|
||||
{searchParams.error ? (
|
||||
<div className="alert alert-error" role="alert">
|
||||
We could not open a checkout just now. Please try again.
|
||||
</div>
|
||||
) : null}
|
||||
{promo ? (
|
||||
<p className="muted" style={{ marginBottom: 10 }}>
|
||||
{t("link.promo", { code: promo })}
|
||||
</p>
|
||||
) : null}
|
||||
<StartCheckout slug={link.slug} auto={!searchParams.error} labels={startLabels(t)} {...(promo ? { promo } : {})} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -1,26 +0,0 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import { PaymentLinkError, startPaymentLinkWithPromo } from "@/lib/payment-link";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/**
|
||||
* POST /l/:slug/start — open a fresh checkout session for this visit.
|
||||
* JSON callers get `{ url }`; a plain form POST (no JavaScript) is
|
||||
* redirected straight to the checkout.
|
||||
*/
|
||||
export async function POST(request: Request, { params }: { params: { slug: string } }) {
|
||||
const wantsJson = request.headers.get("accept")?.includes("application/json") ?? false;
|
||||
try {
|
||||
const promo = new URL(request.url).searchParams.get("promo") ?? undefined;
|
||||
const started = await startPaymentLinkWithPromo(params.slug, promo);
|
||||
const url = `/c/${encodeURIComponent(started.sessionId)}${started.promo === "refused" ? "?promo=refused" : ""}`;
|
||||
if (wantsJson) return NextResponse.json({ url });
|
||||
return NextResponse.redirect(new URL(url, request.url), 303);
|
||||
} catch (error) {
|
||||
const status = error instanceof PaymentLinkError ? error.status : 502;
|
||||
const message = error instanceof Error ? error.message : "Could not open checkout";
|
||||
if (wantsJson) return NextResponse.json({ error: message }, { status: status >= 400 ? status : 502 });
|
||||
return NextResponse.redirect(new URL(`/l/${encodeURIComponent(params.slug)}?error=1`, request.url), 303);
|
||||
}
|
||||
}
|
||||
@ -3,8 +3,6 @@ import type { ReactNode } from "react";
|
||||
import { Archivo, IBM_Plex_Mono } from "next/font/google";
|
||||
|
||||
import "./globals.css";
|
||||
import { EmbedBridge } from "@/components/EmbedBridge";
|
||||
import { checkoutLocale, serverT } from "@/lib/i18n";
|
||||
|
||||
const archivo = Archivo({
|
||||
subsets: ["latin"],
|
||||
@ -32,9 +30,8 @@ export default function RootLayout({
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<html lang={checkoutLocale()} className={`${archivo.variable} ${plexMono.variable}`}>
|
||||
<html lang="en" className={`${archivo.variable} ${plexMono.variable}`}>
|
||||
<body>
|
||||
<EmbedBridge />
|
||||
<div className="page">
|
||||
<header className="topbar">
|
||||
<span className="brand">SettleKit</span>
|
||||
@ -42,7 +39,9 @@ export default function RootLayout({
|
||||
</header>
|
||||
<main className="content">{children}</main>
|
||||
<footer className="footer">
|
||||
<span>{serverT()("footer.note")}</span>
|
||||
<span>
|
||||
Payments settle in USDC. Access is delivered automatically.
|
||||
</span>
|
||||
</footer>
|
||||
</div>
|
||||
</body>
|
||||
|
||||
@ -1,35 +0,0 @@
|
||||
import { notFound } from "next/navigation";
|
||||
|
||||
import { ManageSubscription } from "@/components/ManageSubscription";
|
||||
import { CheckoutError } from "@/lib/errors";
|
||||
import { getManagedSubscription } from "@/lib/manage-subscription";
|
||||
import { verifyManageToken } from "@/lib/manage-token";
|
||||
import { configuredSolanaCluster } from "@/lib/solana";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
interface PageProps {
|
||||
params: { token: string };
|
||||
}
|
||||
|
||||
/**
|
||||
* Buyer "manage subscription" page. The signed link (shown after subscribing)
|
||||
* is the credential: it shows the status, next charge, what the wallet
|
||||
* authorized and every charge, and lets the buyer cancel and revoke.
|
||||
*/
|
||||
export default async function ManageSubscriptionPage({ params }: PageProps) {
|
||||
if (!verifyManageToken(params.token)) notFound();
|
||||
let managed;
|
||||
try {
|
||||
managed = await getManagedSubscription(params.token);
|
||||
} catch (error) {
|
||||
if (error instanceof CheckoutError && error.code === "session_not_found") notFound();
|
||||
return (
|
||||
<div className="card">
|
||||
<h2>Subscription</h2>
|
||||
<p className="muted">{error instanceof Error ? error.message : "This subscription could not be loaded."} Try again in a minute.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return <ManageSubscription token={params.token} initial={managed.view} solanaCluster={configuredSolanaCluster()} />;
|
||||
}
|
||||
@ -1,29 +0,0 @@
|
||||
import type { Metadata } from "next";
|
||||
import { notFound } from "next/navigation";
|
||||
|
||||
import { StorefrontView } from "@/components/StorefrontView";
|
||||
import { getStorefront } from "@/lib/storefront";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
interface PageProps {
|
||||
params: { slug: string };
|
||||
}
|
||||
|
||||
export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
|
||||
const store = await getStorefront({ slug: params.slug }).catch(() => null);
|
||||
if (!store) return { title: "Store not found" };
|
||||
const description = store.seoDescription ?? store.tagline ?? `Products from ${store.merchantName}, paid in USDC.`;
|
||||
return {
|
||||
title: store.title,
|
||||
description,
|
||||
openGraph: { title: store.title, description, ...(store.logoUrl ? { images: [store.logoUrl] } : {}) },
|
||||
};
|
||||
}
|
||||
|
||||
/** Hosted storefront: the merchant's branded product list. */
|
||||
export default async function StorePage({ params }: PageProps) {
|
||||
const store = await getStorefront({ slug: params.slug });
|
||||
if (!store) notFound();
|
||||
return <StorefrontView store={store} />;
|
||||
}
|
||||
@ -1,25 +0,0 @@
|
||||
import type { Metadata } from "next";
|
||||
import { notFound } from "next/navigation";
|
||||
|
||||
import { StorefrontView } from "@/components/StorefrontView";
|
||||
import { getStorefront } from "@/lib/storefront";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
interface PageProps {
|
||||
params: { domain: string };
|
||||
}
|
||||
|
||||
export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
|
||||
const store = await getStorefront({ domain: decodeURIComponent(params.domain) }).catch(() => null);
|
||||
if (!store) return { title: "Store not found" };
|
||||
const description = store.seoDescription ?? store.tagline ?? `Products from ${store.merchantName}, paid in USDC.`;
|
||||
return { title: store.title, description };
|
||||
}
|
||||
|
||||
/** Storefront served on a merchant's custom domain (see middleware.ts). */
|
||||
export default async function DomainStorePage({ params }: PageProps) {
|
||||
const store = await getStorefront({ domain: decodeURIComponent(params.domain) });
|
||||
if (!store) notFound();
|
||||
return <StorefrontView store={store} />;
|
||||
}
|
||||
@ -3,7 +3,6 @@
|
||||
import { useCallback, useState } from "react";
|
||||
|
||||
import type { CollectedFieldSpec } from "@/lib/types";
|
||||
import { ConnectField } from "./ConnectField";
|
||||
|
||||
/** Controlled state for the buyer's delivery fields. */
|
||||
export function useBuyerFields(requiredFields: CollectedFieldSpec[], initialValues: Record<string, string>) {
|
||||
@ -30,18 +29,6 @@ export function BuyerFields({ idPrefix, requiredFields, fields, onChange, disabl
|
||||
<>
|
||||
{requiredFields.map((spec) => {
|
||||
const id = `${idPrefix}-field-${spec.key}`;
|
||||
if (spec.connect) {
|
||||
return (
|
||||
<ConnectField
|
||||
key={spec.key}
|
||||
id={id}
|
||||
spec={{ ...spec, connect: spec.connect }}
|
||||
value={fields[spec.key] ?? ""}
|
||||
onChange={(value) => onChange(spec.key, value)}
|
||||
{...(disabled !== undefined ? { disabled } : {})}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className="field" key={spec.key}>
|
||||
<label htmlFor={id}>{spec.label}</label>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user