Compare commits
2 Commits
main
...
feat/state
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d3f7b80ccf | ||
|
|
269992b8f3 |
238
.env.example
238
.env.example
@ -32,56 +32,6 @@ ARC_CHAIN_ID=5042002
|
||||
# Required only for an unknown ARC_CHAIN_ID.
|
||||
# ARC_USDC_ADDRESS=0x3600000000000000000000000000000000000000
|
||||
|
||||
# --- Multi-chain payments (EVM stablecoins, Solana, Zcash) -------------------
|
||||
#
|
||||
# Every network FAILS CLOSED until enabled: a payment on a disabled network can
|
||||
# never be confirmed. Chain ids, RPCs and token addresses come from the verified
|
||||
# @settlekit/chains registry (see docs/colosseum/MULTICHAIN-PLAN.md).
|
||||
#
|
||||
# mainnet | testnet for every EVM chain (default testnet). Per-chain override:
|
||||
# <KEY>_NETWORK. Keys: ethereum, base, arbitrum, robinhood, hyperevm, tempo, arc.
|
||||
# SETTLEKIT_CHAIN_ENV=testnet
|
||||
# Comma list of EVM chains to verify (BASE_RPC_URL / ARC_CHAIN_ID also enable
|
||||
# Base / Arc for backwards compatibility).
|
||||
# ENABLED_EVM_CHAINS=base,arbitrum,tempo
|
||||
# Per-chain RPC (defaults to the registry's public RPC; use your own in prod,
|
||||
# the public HyperEVM RPC is limited to 100 req/min/IP) and confirmation depth
|
||||
# (defaults: ethereum 12, base/arbitrum/robinhood/arc 3, hyperevm/tempo 1).
|
||||
# ETHEREUM_RPC_URL=
|
||||
# ETHEREUM_NETWORK=
|
||||
# ETHEREUM_MIN_CONFIRMATIONS=
|
||||
# BASE_RPC_URL=
|
||||
# BASE_NETWORK=
|
||||
# BASE_MIN_CONFIRMATIONS=
|
||||
# ARBITRUM_RPC_URL=
|
||||
# ARBITRUM_NETWORK=
|
||||
# ARBITRUM_MIN_CONFIRMATIONS=
|
||||
# ROBINHOOD_RPC_URL=
|
||||
# ROBINHOOD_NETWORK=
|
||||
# ROBINHOOD_MIN_CONFIRMATIONS=
|
||||
# HYPEREVM_RPC_URL=
|
||||
# HYPEREVM_NETWORK=
|
||||
# HYPEREVM_MIN_CONFIRMATIONS=
|
||||
# TEMPO_RPC_URL=
|
||||
# TEMPO_NETWORK=
|
||||
# TEMPO_MIN_CONFIRMATIONS=
|
||||
# <KEY>_TOKEN_ADDRESS overrides a token for local testing only; production
|
||||
# refuses any value other than the registry address.
|
||||
#
|
||||
# Solana (mainnet | devnet); RPC and USDC mint default from the cluster.
|
||||
# SOLANA_CLUSTER=devnet
|
||||
# SOLANA_RPC_URL=
|
||||
#
|
||||
# Zcash: transparent t-addresses only, mainnet, verified via Blockchair
|
||||
# (keyless tier: 1000 requests/day, 30/min). Quotes lock for ZCASH_QUOTE_TTL_SEC.
|
||||
# ZCASH_ENABLED=false
|
||||
# ZCASH_EXPLORER_URL=https://api.blockchair.com/zcash
|
||||
# BLOCKCHAIR_API_KEY=
|
||||
# ZCASH_MIN_CONFIRMATIONS=3
|
||||
# ZCASH_QUOTE_TTL_SEC=900
|
||||
# Worker: how often open Zcash sessions' addresses are polled (ms).
|
||||
# WORKER_ZCASH_WATCH_INTERVAL_MS=90000
|
||||
|
||||
# --- Circle (Gateway / x402 payment rails) ------------------------------------
|
||||
|
||||
# Circle API key for Gateway and x402 paid-API settlement.
|
||||
@ -151,15 +101,8 @@ GITHUB_WEBHOOK_SECRET=replace_with_github_webhook_secret
|
||||
|
||||
# --- Discord (community / role access delivery) -------------------------------
|
||||
|
||||
# Bot token used to add/remove Discord roles on purchase (API, worker, checkout).
|
||||
# Unset = Discord purchases show "pending setup"; roles are granted once set.
|
||||
# Bot token used to add/remove Discord roles on purchase.
|
||||
DISCORD_BOT_TOKEN=replace_with_discord_bot_token
|
||||
# Checkout "Connect Discord" (OAuth2 identify + guilds.join). Register the
|
||||
# redirect <CHECKOUT_PUBLIC_URL>/api/discord/callback in the Discord portal.
|
||||
# DISCORD_CLIENT_ID=
|
||||
# DISCORD_CLIENT_SECRET=
|
||||
# Dashboard: shows the "add the bot to your server" link.
|
||||
# NEXT_PUBLIC_DISCORD_CLIENT_ID=
|
||||
|
||||
# --- Email (transactional, via Resend) ----------------------------------------
|
||||
|
||||
@ -193,37 +136,6 @@ WEBHOOK_SIGNING_SECRET=replace_with_webhook_signing_secret
|
||||
|
||||
# Public base URL of the SettleKit API, read by the browser-facing Next apps.
|
||||
NEXT_PUBLIC_API_URL=http://localhost:8787
|
||||
# Dashboard: hosted checkout base URL; payment links are <url>/l/<slug>.
|
||||
NEXT_PUBLIC_CHECKOUT_URL=http://localhost:3000
|
||||
# --- Platform fee (single source of truth) --------------------------------------
|
||||
# Default: 1% per successful payment, no fixed fee. Defined once as
|
||||
# DEFAULT_FEE_SCHEDULE in packages/platform-billing/src/fees.ts ({ bps: 100,
|
||||
# fixed: "0" }). The API uses it unless PLATFORM_FEE_BPS / PLATFORM_FEE_FIXED
|
||||
# are set; the landing/pricing pages (apps/web) default to the same values via
|
||||
# NEXT_PUBLIC_PLATFORM_FEE_*. To change the fee, change the constant and set
|
||||
# all four variables to the new values so the page matches what is charged.
|
||||
# PLATFORM_FEE_BPS=100
|
||||
# PLATFORM_FEE_FIXED=0
|
||||
#
|
||||
# --- Platform fee statements (SettleKit's own revenue) ---------------------------
|
||||
# Buyers pay merchants' wallets directly, so the fee above is billed monthly: a
|
||||
# statement invoice from SettleKit's own organization, paid through SettleKit's
|
||||
# own checkout. Off (and nothing enforced) until PLATFORM_BILLING_ORG_ID is set.
|
||||
# That org must finish payment setup (receiving wallets) in the dashboard.
|
||||
# PLATFORM_BILLING_ORG_ID=org_settlekit
|
||||
# PLATFORM_BILLING_DUE_DAYS=14 # due N days after the month ends
|
||||
# PLATFORM_BILLING_GRACE_DAYS=14 # then free-plan product limits apply
|
||||
# PLATFORM_BILLING_MIN_USD=1 # smaller totals roll into next month
|
||||
# PLATFORM_BILLING_AUTORUN=1 # 0 = only POST /v1/billing/statements/run
|
||||
#
|
||||
# Public URL of the hosted checkout (invoice pay pages /i/<token>, receipt PDF
|
||||
# links in receipt emails; API and worker). Falls back to NEXT_PUBLIC_CHECKOUT_URL.
|
||||
# CHECKOUT_PUBLIC_URL=https://pay.example.com
|
||||
NEXT_PUBLIC_PLATFORM_FEE_BPS=100
|
||||
NEXT_PUBLIC_PLATFORM_FEE_FIXED=0
|
||||
# API: extra organization ids hidden from the public /proof page (demo/test
|
||||
# sellers; the bootstrap org and orgs flagged testAccount are always hidden).
|
||||
# PROOF_EXCLUDED_ORGS=org_demo1,org_demo2
|
||||
|
||||
# =============================================================================
|
||||
# Everything below is OPTIONAL for local dev — the API boots with none of it
|
||||
@ -241,6 +153,12 @@ LICENSE_TOKEN_SECRET=settlekit-dev-license-secret
|
||||
# Dev default: settlekit-dev-auth-cookie-secret
|
||||
AUTH_COOKIE_SECRET=settlekit-dev-auth-cookie-secret
|
||||
|
||||
# HMAC secret used to sign proof-of-citation tokens (creator-dashboard +
|
||||
# citation-toll sidecar). MUST be set in production — if unset, the dashboard
|
||||
# falls back to a per-process random secret so a known constant is never shipped,
|
||||
# but proofs then won't verify across instances. Dev default: dev-citation-proof-secret
|
||||
CITATION_PROOF_SECRET=dev-citation-proof-secret
|
||||
|
||||
# --- API: runtime / identity --------------------------------------------------
|
||||
|
||||
# Static bootstrap Bearer key so the first authenticated call can mint real API
|
||||
@ -270,10 +188,6 @@ ARC_MIN_CONFIRMATIONS=3
|
||||
# Default installation id the API/worker authenticate as (required with the
|
||||
# GITHUB_APP_* group above).
|
||||
GITHUB_INSTALLATION_ID=12345678
|
||||
# The checkout app reads GITHUB_APP_INSTALLATION_ID; the worker accepts either.
|
||||
# Worker: how often pending GitHub entitlements from checkout are re-delivered
|
||||
# once an installation id is configured (ms).
|
||||
# WORKER_GITHUB_RETRY_INTERVAL_MS=120000
|
||||
|
||||
# --- File delivery: API process (FILE_DOWNLOAD_*) -----------------------------
|
||||
|
||||
@ -292,50 +206,6 @@ FILE_DOWNLOAD_MAX_DOWNLOADS=3
|
||||
# Set to your real wallet to actually receive payment. (read in routes/x402.ts)
|
||||
X402_PAY_TO=0x0000000000000000000000000000000000000000
|
||||
|
||||
# --- Agent payments: x402 v2 on every chain + MPP on Tempo (/v1/x402, /v1/mpp) -
|
||||
# A network is offered only with a payTo + a facilitator. Remote (PayAI, no key)
|
||||
# serves Solana/Base/Arbitrum; the self-hosted facilitator (relayer hot key)
|
||||
# serves Ethereum/HyperEVM/Robinhood. Chain env follows SETTLEKIT_CHAIN_ENV,
|
||||
# <KEY>_NETWORK and SOLANA_CLUSTER. See apps/api/src/agent-payments/config.ts.
|
||||
# X402_EVM_PAY_TO=0x...
|
||||
# X402_SOLANA_PAY_TO=
|
||||
# X402_PAY_TO_HYPEREVM=0x... # per-network override
|
||||
# X402_NETWORKS=solana,base,arbitrum,ethereum,hyperevm,robinhood
|
||||
# X402_REMOTE_FACILITATOR_URL=https://facilitator.payai.network
|
||||
# X402_REMOTE_FACILITATOR_API_KEY= # only for keyed facilitators (e.g. CDP)
|
||||
# X402_RESEARCH_PRICE=0.01
|
||||
# Self-hosted facilitator (@settlekit/x402-facilitator). Unset key = off.
|
||||
# X402_RELAYER_PRIVATE_KEY=0x... # hot key: fund with gas only
|
||||
# X402_FACILITATOR_NETWORKS=ethereum,hyperevm,robinhood
|
||||
# X402_FACILITATOR_MAX_AMOUNT=100 # USD per settlement
|
||||
# X402_FACILITATOR_ALLOWED_PAY_TO=0x... # recipients the relayer will settle to (default: X402_EVM_PAY_TO +
|
||||
# # X402_PAY_TO_<CHAIN>; "*" = any recipient; empty = refuse all)
|
||||
# Replay protection uses the x402_nonces table when DATABASE_URL is set (in-memory otherwise, dev only).
|
||||
# X402_FACILITATOR_KILL=0 # 1 = refuse every verify/settle
|
||||
# X402_FACILITATOR_TOKEN= # bearer for POST /v1/x402/facilitator/*
|
||||
# X402_FACILITATOR_ALLOW_EXPERIMENTAL=0 # 1 = Tempo Permit2 / Robinhood testnet
|
||||
# X402_GAS_MAX_FEE_ETHEREUM=3000000000000000 # native base units per settlement
|
||||
# X402_GAS_DAILY_BUDGET_ETHEREUM=50000000000000000
|
||||
# MPP on Tempo (mppx): USDC.e on mainnet, pathUSD on Moderato.
|
||||
# MPP_SECRET_KEY= # >= 32 bytes, e.g. openssl rand -base64 32
|
||||
# MPP_TEMPO_RECIPIENT=0x...
|
||||
# TEMPO_NETWORK=mainnet
|
||||
|
||||
# --- Onchain billing (subscriptions, Base escrow, refunds) --------------------
|
||||
# ONCHAIN_BILLING_OPERATOR_PRIVATE_KEY=0x... # EVM operator (pull spender, escrow operator, refund sender)
|
||||
# ONCHAIN_BILLING_SOLANA_SECRET= # Solana SPL delegate + refund sender
|
||||
# ONCHAIN_BILLING_CHECKOUT_URL=https://pay.example.com # renewal-invoice links
|
||||
# ONCHAIN_BILLING_NETWORKS=base,arbitrum,solana,hypercore,zcash # default: every enabled network
|
||||
# ONCHAIN_BILLING_ESCROW=off # disable Base commerce-payments escrow
|
||||
# The hosted checkout calls /v1/onchain-billing server-side with this token
|
||||
# (same value on the API and the checkout; 32+ chars, e.g. openssl rand -hex 32).
|
||||
# Accepted ONLY under /v1/onchain-billing, with X-SettleKit-Organization.
|
||||
# SETTLEKIT_SERVICE_TOKEN=
|
||||
# Checkout: signs buyer "manage subscription" links (/s/<token>).
|
||||
# CHECKOUT_MANAGE_SECRET=
|
||||
# HYPERCORE_ENABLED=true # also enables HyperCore refunds (operator usdSend)
|
||||
# HYPERCORE_REFUND_PRIVATE_KEY=0x... # optional: HyperCore refund account (default: operator key)
|
||||
|
||||
# =============================================================================
|
||||
# Worker (apps/worker) — background jobs. Required integrations fail boot if
|
||||
# missing. File-delivery uses FILE_DELIVERY_* (note: different prefix from API).
|
||||
@ -449,97 +319,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
|
||||
@ -1 +0,0 @@
|
||||
22
|
||||
@ -15,7 +15,7 @@
|
||||
ARG APP_PORT=3000
|
||||
|
||||
# ---- Base: Node 20 + pnpm via Corepack -------------------------------------
|
||||
FROM node:22-alpine AS base
|
||||
FROM node:20-alpine AS base
|
||||
ENV PNPM_HOME=/pnpm
|
||||
ENV PATH=$PNPM_HOME:$PATH
|
||||
ENV NEXT_TELEMETRY_DISABLED=1
|
||||
|
||||
@ -43,26 +43,7 @@ Also done (RFB 6.01): **`@settlekit/attribution`** — the reuse-detection / pro
|
||||
- **`LeptonStreamSettlement.sol`** — per-second on-chain stream: deposit reserve, accrue by `block.timestamp`, proof-of-flow `pause`/`resume`, `settle`, `close` (settle tail + refund unused reserve). RFB 4.
|
||||
- **`AgentReputationBond.sol`** — ERC-8004-style: broker posts a USDC bond; `release` (good outcome) or `slash` to the client (bad outcome), arbiter-resolvable. RFB 3.
|
||||
|
||||
### Live testnet runbook (needs creds + running instances)
|
||||
|
||||
1. **Auth.** Install the ARC + Circle CLIs and authenticate (interactive):
|
||||
```sh
|
||||
uv tool install git+https://github.com/the-canteen-dev/ARC-cli && arc-canteen login
|
||||
npm install -g @circle-fin/cli
|
||||
```
|
||||
2. **Deploy the Lepton contracts to Arc.** A faucet-funded deployer key (USDC is
|
||||
the gas token) drives the bundled Foundry script:
|
||||
```sh
|
||||
cd contracts && forge script script/DeployLepton.s.sol \
|
||||
--rpc-url https://rpc.testnet.arc.network --private-key $DEPLOYER_KEY --broadcast
|
||||
```
|
||||
Dry-run first with no flags (`forge script script/DeployLepton.s.sol`) — it
|
||||
simulates all three deploys and prints their addresses. `script/Deploy.s.sol`
|
||||
deploys the Escrow + CCTP hook the same way.
|
||||
3. **Flip the sidecars to real settlement.** Point them at running
|
||||
RSSHub/Navidrome/Owncast and set `SETTLEMENT_PROVIDER=circle` (or a Gateway
|
||||
port) plus the Arc-indexer verifier (`ARC_INDEXER_URL`). No code change — the
|
||||
provider and verifier are injected by config.
|
||||
Remaining for a live testnet run (needs creds + running instances): point the sidecars at real RSSHub/Navidrome/Owncast with `SETTLEMENT_PROVIDER=circle` (or a Gateway port) and the Arc-indexer verifier, and deploy the contracts via `contracts/script`.
|
||||
|
||||
## Directory map (new work, by top-level folder)
|
||||
|
||||
|
||||
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.
|
||||
172
README.md
172
README.md
@ -1,140 +1,38 @@
|
||||
# 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)
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/caelum0x/settlekit/releases/download/demo-2026-06-22/settlekit-demo.mp4">
|
||||
<img src="https://github.com/caelum0x/settlekit/releases/download/demo-2026-06-22/settlekit-demo.gif" alt="SettleKit product walkthrough" width="900">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/caelum0x/settlekit/releases/download/demo-2026-06-22/settlekit-demo.mp4"><b>▶ Watch the full-quality video (MP4)</b></a>
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
## 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).
|
||||
|
||||
---
|
||||
|
||||
@ -166,7 +64,6 @@ settlekit/
|
||||
│ ├── api/ HTTP API (Hono on Node) — /v1 resources
|
||||
│ ├── worker/ Background worker — delivery, confirmation, sweeps, retries
|
||||
│ ├── dashboard/ Merchant dashboard (Next.js 14)
|
||||
│ ├── creator-dashboard/ Creator earnings + attribution view (Next.js 14, Lepton)
|
||||
│ ├── checkout/ Hosted USDC checkout (Next.js 14)
|
||||
│ ├── marketplace/ Public marketplace (Next.js 14)
|
||||
│ ├── admin/ Internal admin + risk console (Next.js 14)
|
||||
@ -202,12 +99,7 @@ settlekit/
|
||||
├── agent-services/ AI agent service listings
|
||||
├── escrow/ Escrow tasks
|
||||
├── arc/ Arc settlement + USDC chain reads
|
||||
├── arc-chains/ Arc/Circle chain · token · contract constants (one source of truth)
|
||||
├── app-kit/ Circle App Kit on Arc — Send/Bridge/Swap/Unified Balance + settlement bridge
|
||||
├── erc8004/ ERC-8004 agent identity · reputation · validation on Arc
|
||||
├── erc8183/ ERC-8183 autonomous-agent job lifecycle (escrow create→settle)
|
||||
├── circle/ Circle Gateway / x402 payment rails
|
||||
├── circle-wallets/ Circle Developer-Controlled Wallets (transfers + contract execution)
|
||||
├── x402/ x402 paid-API middleware
|
||||
├── database/ drizzle schema, migrations, doc codec
|
||||
├── persistence/ Shared Postgres stores (used by api · worker · checkout)
|
||||
@ -262,7 +154,7 @@ cp .env.example .env
|
||||
| API | `pnpm --filter @settlekit/api dev` | `8787` | http://localhost:8787 |
|
||||
| Worker | `pnpm --filter @settlekit/worker dev` | — | (no HTTP port) |
|
||||
| Dashboard | `pnpm --filter @settlekit/dashboard dev` | `3001` | http://localhost:3001 |
|
||||
| Marketplace | `pnpm --filter @settlekit/marketplace dev` | `3011` | http://localhost:3011 |
|
||||
| Marketplace | `pnpm --filter @settlekit/marketplace dev` | `3002` | http://localhost:3002 |
|
||||
| Checkout | `pnpm --filter @settlekit/checkout-app dev`| `3003` | http://localhost:3003 |
|
||||
| Admin | `pnpm --filter @settlekit/admin dev` | `3004` | http://localhost:3004 |
|
||||
| Docs | `pnpm --filter @settlekit/docs-app dev` | `3005` | http://localhost:3005 |
|
||||
@ -309,26 +201,6 @@ Every variable the system reads is documented in
|
||||
Validate that required secrets are present at startup; never commit a real
|
||||
`.env`.
|
||||
|
||||
### Chain support
|
||||
|
||||
Checkout, API and worker share one registry (`@settlekit/chains`) and fail
|
||||
closed per network. Full matrix with finality notes:
|
||||
[apps/checkout/README.md](./apps/checkout/README.md#chain-support).
|
||||
|
||||
| Network | Asset | Environments | Label |
|
||||
| --- | --- | --- | --- |
|
||||
| Solana | USDC | mainnet, devnet | |
|
||||
| Base, Ethereum, Arbitrum, HyperEVM | USDC | mainnet, testnet | |
|
||||
| Robinhood Chain | USDG (mainnet), Mock USDC (testnet) | mainnet, testnet | no native USDC |
|
||||
| Robinhood Chain ($wif) | $wif, 18 decimals | mainnet only | experimental, Permit2-only — see `docs/worldisflat/SUBMISSION.md` |
|
||||
| Tempo | USDC.e (mainnet), pathUSD (testnet) | mainnet, testnet | bridged |
|
||||
| Arc | USDC | testnet only | testnet |
|
||||
| Zcash | ZEC at a locked USD quote | mainnet only | transparent, not shielded |
|
||||
|
||||
**World is Flat hackathon** (Robinhood Chain, $wif): full writeup, real on-chain proofs and an
|
||||
honest demo video at [docs/worldisflat/SUBMISSION.md](./docs/worldisflat/SUBMISSION.md) —
|
||||
[docs/worldisflat/media/settlekit-wif-demo.mp4](./docs/worldisflat/media/settlekit-wif-demo.mp4).
|
||||
|
||||
---
|
||||
|
||||
## Architecture overview
|
||||
@ -416,8 +288,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.
|
||||
@ -1 +0,0 @@
|
||||
22
|
||||
@ -1,156 +0,0 @@
|
||||
import { api } from "@/lib/api";
|
||||
import { formatMoney } from "@/lib/format";
|
||||
import {
|
||||
bucketByDay,
|
||||
countBy,
|
||||
sumSettledVolume,
|
||||
type BarDatum,
|
||||
} from "@/lib/analytics";
|
||||
import { MetricCard } from "../components/ui";
|
||||
import { BarChart } from "../components/BarChart";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/**
|
||||
* Analytics / reporting console. A server component that fetches the raw lists
|
||||
* in parallel and aggregates them in-process (there are no pre-bucketed totals
|
||||
* in the API beyond overview()). Everything degrades to a labelled empty state
|
||||
* when a list is empty, and money is summed with addMoney/money — never with
|
||||
* floating point. Bars are CSS divs (no chart dependency).
|
||||
*
|
||||
* The feature brief mentions "agents" and "jobs" totals; those entities do not
|
||||
* exist in this admin's domain model, so they are surfaced as explicit "n/a"
|
||||
* cards rather than invented endpoints.
|
||||
*/
|
||||
|
||||
const DECISION_TONES = ["ok", "warn", "danger"] as const;
|
||||
|
||||
export default async function AnalyticsPage() {
|
||||
let overview;
|
||||
let settlements;
|
||||
let webhooks;
|
||||
let risk;
|
||||
try {
|
||||
[overview, settlements, webhooks, risk] = await Promise.all([
|
||||
api.overview(),
|
||||
api.settlements(),
|
||||
api.webhookEvents(),
|
||||
api.riskProfiles(),
|
||||
]);
|
||||
} catch (e) {
|
||||
return (
|
||||
<>
|
||||
<h1>Analytics</h1>
|
||||
<div className="error">
|
||||
Failed to load analytics: {e instanceof Error ? e.message : "unknown"}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const settledVolume = sumSettledVolume(settlements);
|
||||
|
||||
// Settlements created per day (last 14 days, zero-filled).
|
||||
const settlementSeries: BarDatum[] = bucketByDay(
|
||||
settlements,
|
||||
(s) => s.createdAt,
|
||||
).map((b) => ({ label: b.date.slice(5), value: b.count }));
|
||||
|
||||
// Webhook events created per day.
|
||||
const webhookSeries: BarDatum[] = bucketByDay(
|
||||
webhooks,
|
||||
(w) => w.createdAt,
|
||||
).map((b) => ({ label: b.date.slice(5), value: b.count }));
|
||||
|
||||
// Risk decision distribution (allow / review / block).
|
||||
const decisionCounts = countBy(risk, (r) => r.decision);
|
||||
const decisionSeries: BarDatum[] = [
|
||||
{ label: "allow", value: decisionCounts.get("allow") ?? 0 },
|
||||
{ label: "review", value: decisionCounts.get("review") ?? 0 },
|
||||
{ label: "block", value: decisionCounts.get("block") ?? 0 },
|
||||
];
|
||||
|
||||
const deliveredCount = webhooks.filter((w) => w.delivered).length;
|
||||
const pendingCount = webhooks.length - deliveredCount;
|
||||
const deliverySeries: BarDatum[] = [
|
||||
{ label: "delivered", value: deliveredCount },
|
||||
{ label: "pending", value: pendingCount },
|
||||
];
|
||||
|
||||
return (
|
||||
<>
|
||||
<h1>Analytics</h1>
|
||||
<p className="subtitle">
|
||||
Aggregated reporting across settlements, payments, webhooks, and risk.
|
||||
Settlements and webhook activity are bucketed by day; risk reflects the
|
||||
admin-owned review store.
|
||||
</p>
|
||||
|
||||
<div className="cards">
|
||||
<MetricCard
|
||||
label="Settled volume"
|
||||
value={formatMoney(settledVolume)}
|
||||
/>
|
||||
<MetricCard label="GMV (confirmed)" value={formatMoney(overview.gmv)} />
|
||||
<MetricCard label="Settlements" value={settlements.length} />
|
||||
<MetricCard
|
||||
label="Confirmed payments"
|
||||
value={overview.confirmedPaymentCount}
|
||||
/>
|
||||
<MetricCard label="Webhook events" value={webhooks.length} />
|
||||
<MetricCard label="Risk review queue" value={overview.riskReviewQueue} />
|
||||
<MetricCard
|
||||
label="Undelivered webhooks"
|
||||
value={overview.undeliveredWebhooks}
|
||||
/>
|
||||
<MetricCard label="Agents" value="n/a" />
|
||||
<MetricCard label="Jobs" value="n/a" />
|
||||
</div>
|
||||
|
||||
<div className="analytics-actions">
|
||||
<a className="btn" href="/api/export/settlements" download>
|
||||
Export settlements CSV
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<h2>Settlements per day</h2>
|
||||
<div className="panel chart-panel">
|
||||
<BarChart
|
||||
data={settlementSeries}
|
||||
tone="accent"
|
||||
emptyText="No settlements in the last 14 days."
|
||||
/>
|
||||
</div>
|
||||
|
||||
<h2>Webhook events per day</h2>
|
||||
<div className="panel chart-panel">
|
||||
<BarChart
|
||||
data={webhookSeries}
|
||||
tone="muted"
|
||||
emptyText="No webhook events in the last 14 days."
|
||||
/>
|
||||
</div>
|
||||
|
||||
<h2>Risk decision distribution</h2>
|
||||
<div className="panel chart-panel">
|
||||
{risk.length === 0 ? (
|
||||
<div className="empty">No risk profiles.</div>
|
||||
) : (
|
||||
<BarChart data={decisionSeries} tones={DECISION_TONES} />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<h2>Webhook delivery status</h2>
|
||||
<div className="panel chart-panel">
|
||||
{webhooks.length === 0 ? (
|
||||
<div className="empty">No webhook events.</div>
|
||||
) : (
|
||||
<BarChart
|
||||
data={deliverySeries}
|
||||
tones={["ok", "warn"]}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@ -1,61 +0,0 @@
|
||||
import { listSettlements } from "@/lib/service";
|
||||
import { fail } from "@/lib/respond";
|
||||
import { toCsv, type CsvColumn } from "@/lib/analytics";
|
||||
import type { AdminSettlement } from "@/lib/types";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/**
|
||||
* CSV export for admin reports.
|
||||
*
|
||||
* This route intentionally lives OUTSIDE /api/v1 and does NOT use the
|
||||
* {ok,data,error} envelope on its success path — it returns a raw text/csv
|
||||
* Response so browsers download a file. The error path still uses fail() (JSON)
|
||||
* since there is nothing to download. It reads the service layer directly
|
||||
* (server-only) rather than going back through the HTTP api.ts client.
|
||||
*/
|
||||
|
||||
const SETTLEMENT_COLUMNS: ReadonlyArray<CsvColumn<AdminSettlement>> = [
|
||||
{ header: "id", value: (s) => s.id },
|
||||
{ header: "organizationId", value: (s) => s.organizationId },
|
||||
{ header: "status", value: (s) => s.status },
|
||||
{ header: "amount", value: (s) => s.amount.amount },
|
||||
{ header: "currency", value: (s) => s.amount.currency },
|
||||
{ header: "network", value: (s) => s.network },
|
||||
{ header: "reference", value: (s) => s.reference },
|
||||
{ header: "txHash", value: (s) => s.txHash ?? "" },
|
||||
{ header: "createdAt", value: (s) => s.createdAt },
|
||||
{ header: "updatedAt", value: (s) => s.updatedAt },
|
||||
];
|
||||
|
||||
async function settlementsCsv(): Promise<string> {
|
||||
const settlements = await listSettlements();
|
||||
const sorted = [...settlements].sort((a, b) =>
|
||||
b.createdAt.localeCompare(a.createdAt),
|
||||
);
|
||||
return toCsv(sorted, SETTLEMENT_COLUMNS);
|
||||
}
|
||||
|
||||
export async function GET(
|
||||
_request: Request,
|
||||
{ params }: { params: { report: string } },
|
||||
) {
|
||||
const report = params.report;
|
||||
if (report !== "settlements") {
|
||||
return fail(`unknown report: ${report}`, 404);
|
||||
}
|
||||
|
||||
try {
|
||||
const csv = await settlementsCsv();
|
||||
return new Response(csv, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"content-type": "text/csv; charset=utf-8",
|
||||
"content-disposition": 'attachment; filename="settlements.csv"',
|
||||
"cache-control": "no-store",
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
return fail(e instanceof Error ? e.message : "export failed", 500);
|
||||
}
|
||||
}
|
||||
@ -1,17 +0,0 @@
|
||||
import { listSettlements } from "@/lib/service";
|
||||
import { ok, fail } from "@/lib/respond";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const settlements = await listSettlements();
|
||||
// Newest first so the most recent settlement activity surfaces at the top.
|
||||
const sorted = [...settlements].sort((a, b) =>
|
||||
b.createdAt.localeCompare(a.createdAt),
|
||||
);
|
||||
return ok(sorted);
|
||||
} catch (e) {
|
||||
return fail(e instanceof Error ? e.message : "settlement list failed", 500);
|
||||
}
|
||||
}
|
||||
@ -1,61 +0,0 @@
|
||||
import type { BarDatum } from "@/lib/analytics";
|
||||
|
||||
/**
|
||||
* A dependency-free bar chart rendered with CSS divs (no chart library, no
|
||||
* client JS). Heights are computed as a percentage of the largest value, with
|
||||
* a guard against divide-by-zero so an all-zero series renders flat tracks
|
||||
* rather than NaN heights. Colors come from the greenbar console CSS vars.
|
||||
*/
|
||||
|
||||
type BarTone = "accent" | "ok" | "warn" | "danger" | "muted";
|
||||
|
||||
const TONE_VAR: Record<BarTone, string> = {
|
||||
accent: "var(--accent)",
|
||||
ok: "var(--ok)",
|
||||
warn: "var(--warn)",
|
||||
danger: "var(--danger)",
|
||||
muted: "var(--muted)",
|
||||
};
|
||||
|
||||
interface BarChartProps {
|
||||
readonly data: readonly BarDatum[];
|
||||
/** Optional per-bar tone; falls back to `tone` then "accent". */
|
||||
readonly tones?: readonly BarTone[];
|
||||
readonly tone?: BarTone;
|
||||
/** Label shown when there is no data to plot. */
|
||||
readonly emptyText?: string;
|
||||
}
|
||||
|
||||
export function BarChart({
|
||||
data,
|
||||
tones,
|
||||
tone = "accent",
|
||||
emptyText = "No data for this period.",
|
||||
}: BarChartProps) {
|
||||
if (data.length === 0) {
|
||||
return <div className="empty">{emptyText}</div>;
|
||||
}
|
||||
|
||||
const max = data.reduce((m, d) => (d.value > m ? d.value : m), 0);
|
||||
|
||||
return (
|
||||
<div className="bars" role="img" aria-label="Bar chart">
|
||||
{data.map((d, i) => {
|
||||
const heightPct = max > 0 ? Math.round((d.value / max) * 100) : 0;
|
||||
const color = TONE_VAR[tones?.[i] ?? tone];
|
||||
return (
|
||||
<div className="bar-col" key={`${d.label}-${i}`} title={`${d.label}: ${d.value}`}>
|
||||
<div className="bar-value">{d.value}</div>
|
||||
<div className="bar-track">
|
||||
<div
|
||||
className="bar-fill"
|
||||
style={{ height: `${heightPct}%`, background: color }}
|
||||
/>
|
||||
</div>
|
||||
<div className="bar-label">{d.label}</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -237,76 +237,6 @@ button.btn.danger {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
/* Analytics page: export action + dependency-free CSS bar charts. */
|
||||
.analytics-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin: 18px 0 4px;
|
||||
}
|
||||
a.btn {
|
||||
display: inline-block;
|
||||
font-size: 12px;
|
||||
border: 1px solid var(--border);
|
||||
background: var(--panel-2);
|
||||
color: var(--text);
|
||||
padding: 6px 12px;
|
||||
border-radius: 8px;
|
||||
}
|
||||
a.btn:hover {
|
||||
border-color: var(--accent);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.chart-panel {
|
||||
padding: 18px 20px;
|
||||
}
|
||||
.bars {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
gap: 10px;
|
||||
height: 200px;
|
||||
width: 100%;
|
||||
}
|
||||
.bar-col {
|
||||
flex: 1 1 0;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
height: 100%;
|
||||
}
|
||||
.bar-value {
|
||||
font-size: 11px;
|
||||
color: var(--muted);
|
||||
margin-bottom: 4px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.bar-track {
|
||||
flex: 1;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
background: var(--panel-2);
|
||||
border-radius: 6px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.bar-fill {
|
||||
width: 100%;
|
||||
min-height: 2px;
|
||||
background: var(--accent);
|
||||
border-radius: 6px 6px 0 0;
|
||||
}
|
||||
.bar-label {
|
||||
margin-top: 6px;
|
||||
font-size: 11px;
|
||||
color: var(--muted);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
max-width: 100%;
|
||||
font-family: var(--font-mono);
|
||||
}
|
||||
|
||||
.empty {
|
||||
padding: 28px;
|
||||
color: var(--muted);
|
||||
|
||||
@ -25,10 +25,8 @@ export const metadata: Metadata = {
|
||||
|
||||
const NAV: ReadonlyArray<{ href: string; label: string }> = [
|
||||
{ href: "/", label: "Overview" },
|
||||
{ href: "/analytics", label: "Analytics" },
|
||||
{ href: "/risk", label: "Risk queue" },
|
||||
{ href: "/organizations", label: "Organizations" },
|
||||
{ href: "/settlements", label: "Settlements" },
|
||||
{ href: "/deliveries", label: "Failed deliveries" },
|
||||
{ href: "/webhooks", label: "Webhooks" },
|
||||
];
|
||||
|
||||
@ -1,93 +0,0 @@
|
||||
import Link from "next/link";
|
||||
import { api } from "@/lib/api";
|
||||
import { formatMoney, formatRelative } from "@/lib/format";
|
||||
import type { SettlementStatus } from "@/lib/types";
|
||||
import { Pill, EmptyRow } from "../components/ui";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/**
|
||||
* statusTone() has no cases for `settled` / `submitted` (they fall through to
|
||||
* `muted`), so a local map is used with <Pill> rather than <Badge> — mirroring
|
||||
* the risk page's REVIEW_TONE — to avoid touching the shared helper.
|
||||
*/
|
||||
const SETTLEMENT_TONE: Record<SettlementStatus, "ok" | "warn" | "danger" | "muted"> = {
|
||||
settled: "ok",
|
||||
submitted: "warn",
|
||||
pending: "muted",
|
||||
failed: "danger",
|
||||
};
|
||||
|
||||
/** Shorten a tx hash to a 0x-prefixed head…tail for the table cell. */
|
||||
function shortHash(hash: string): string {
|
||||
if (hash.length <= 16) return hash;
|
||||
return `${hash.slice(0, 10)}…${hash.slice(-6)}`;
|
||||
}
|
||||
|
||||
export default async function SettlementsPage() {
|
||||
let settlements;
|
||||
try {
|
||||
settlements = await api.settlements();
|
||||
} catch (e) {
|
||||
return (
|
||||
<>
|
||||
<h1>Settlements</h1>
|
||||
<div className="error">
|
||||
Failed to load settlements:{" "}
|
||||
{e instanceof Error ? e.message : "unknown"}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<h1>Settlements</h1>
|
||||
<p className="subtitle">
|
||||
Merchant payouts settled to external wallets. Each row tracks the
|
||||
on-chain network, settlement reference, and transaction hash.
|
||||
</p>
|
||||
|
||||
<div className="panel">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Settlement</th>
|
||||
<th>Org</th>
|
||||
<th>Status</th>
|
||||
<th>Amount</th>
|
||||
<th>Network</th>
|
||||
<th>Reference</th>
|
||||
<th>Tx hash</th>
|
||||
<th>Updated</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{settlements.length === 0 ? (
|
||||
<EmptyRow colSpan={8} text="No settlements." />
|
||||
) : (
|
||||
settlements.map((s) => (
|
||||
<tr key={s.id}>
|
||||
<td className="mono">{s.id}</td>
|
||||
<td>
|
||||
<Link href={`/organizations/${s.organizationId}`}>
|
||||
{s.organizationId}
|
||||
</Link>
|
||||
</td>
|
||||
<td>
|
||||
<Pill label={s.status} tone={SETTLEMENT_TONE[s.status]} />
|
||||
</td>
|
||||
<td>{formatMoney(s.amount)}</td>
|
||||
<td>{s.network}</td>
|
||||
<td className="mono">{s.reference}</td>
|
||||
<td className="mono">{s.txHash ? shortHash(s.txHash) : "—"}</td>
|
||||
<td>{formatRelative(s.updatedAt)}</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@ -1,108 +0,0 @@
|
||||
import { addMoney, money, type Money } from "@settlekit/common";
|
||||
import type { AdminSettlement } from "./types";
|
||||
|
||||
/**
|
||||
* Pure aggregation helpers for the analytics page. No React, no I/O — kept
|
||||
* separate so the math (Money summation, day-bucketing, CSV escaping) stays
|
||||
* unit-testable and the page component stays thin.
|
||||
*
|
||||
* NOTE on freshness: settlements/webhooks may be served from Postgres when
|
||||
* DATABASE_URL is set, while risk profiles are always served from the in-memory
|
||||
* store (admin-owned review state). Mixing them in one view is fine, but the
|
||||
* counts can have slightly different freshness.
|
||||
*/
|
||||
|
||||
/** A single time-series bucket: an ISO date (YYYY-MM-DD) and a count. */
|
||||
export interface DayBucket {
|
||||
readonly date: string;
|
||||
readonly count: number;
|
||||
}
|
||||
|
||||
/** A generic labelled value used by the bar chart. */
|
||||
export interface BarDatum {
|
||||
readonly label: string;
|
||||
readonly value: number;
|
||||
}
|
||||
|
||||
/** Extract the YYYY-MM-DD (UTC) prefix from an ISO timestamp, or null if invalid. */
|
||||
function isoDay(iso: string): string | null {
|
||||
const d = new Date(iso);
|
||||
if (Number.isNaN(d.getTime())) return null;
|
||||
const pad = (n: number) => String(n).padStart(2, "0");
|
||||
return `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Group items into per-day counts using an ISO-timestamp selector.
|
||||
*
|
||||
* Returns the last `days` calendar days (UTC), oldest first, with zero-filled
|
||||
* gaps so the chart always renders a continuous axis even when activity is
|
||||
* sparse. `anchor` defaults to the current time but is injectable for testing
|
||||
* (no hidden Date.now() in callers).
|
||||
*/
|
||||
export function bucketByDay<T>(
|
||||
items: readonly T[],
|
||||
isoSelector: (item: T) => string,
|
||||
days = 14,
|
||||
anchor: number = Date.now(),
|
||||
): DayBucket[] {
|
||||
const counts = new Map<string, number>();
|
||||
for (const item of items) {
|
||||
const day = isoDay(isoSelector(item));
|
||||
if (day === null) continue;
|
||||
counts.set(day, (counts.get(day) ?? 0) + 1);
|
||||
}
|
||||
|
||||
const buckets: DayBucket[] = [];
|
||||
const dayMs = 86_400_000;
|
||||
for (let i = days - 1; i >= 0; i -= 1) {
|
||||
const date = isoDay(new Date(anchor - i * dayMs).toISOString());
|
||||
if (date === null) continue;
|
||||
buckets.push({ date, count: counts.get(date) ?? 0 });
|
||||
}
|
||||
return buckets;
|
||||
}
|
||||
|
||||
/** Sum the amounts of settlements with status `settled`, immutably. */
|
||||
export function sumSettledVolume(settlements: readonly AdminSettlement[]): Money {
|
||||
return settlements
|
||||
.filter((s) => s.status === "settled")
|
||||
.reduce<Money>((sum, s) => addMoney(sum, s.amount), money("0"));
|
||||
}
|
||||
|
||||
/** Count occurrences of each value produced by `selector`. */
|
||||
export function countBy<T>(
|
||||
items: readonly T[],
|
||||
selector: (item: T) => string,
|
||||
): Map<string, number> {
|
||||
const counts = new Map<string, number>();
|
||||
for (const item of items) {
|
||||
const key = selector(item);
|
||||
counts.set(key, (counts.get(key) ?? 0) + 1);
|
||||
}
|
||||
return counts;
|
||||
}
|
||||
|
||||
/** Escape a single CSV field per RFC 4180 (quote when it contains , " or newline). */
|
||||
export function csvField(value: unknown): string {
|
||||
const str = value === null || value === undefined ? "" : String(value);
|
||||
if (/[",\r\n]/.test(str)) {
|
||||
return `"${str.replace(/"/g, '""')}"`;
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
/** A CSV column: a header label and an extractor for a row. */
|
||||
export interface CsvColumn<T> {
|
||||
readonly header: string;
|
||||
readonly value: (row: T) => unknown;
|
||||
}
|
||||
|
||||
/** Build an RFC-4180 CSV string (CRLF line endings) from rows + columns. */
|
||||
export function toCsv<T>(rows: readonly T[], columns: readonly CsvColumn<T>[]): string {
|
||||
const header = columns.map((c) => csvField(c.header)).join(",");
|
||||
const body = rows.map((row) =>
|
||||
columns.map((c) => csvField(c.value(row))).join(","),
|
||||
);
|
||||
return [header, ...body].join("\r\n");
|
||||
}
|
||||
@ -5,7 +5,6 @@ import type {
|
||||
AdminOrganization,
|
||||
AdminPayment,
|
||||
AdminRiskProfile,
|
||||
AdminSettlement,
|
||||
AdminWebhookEvent,
|
||||
} from "./types";
|
||||
import type { PlatformOverview } from "./service";
|
||||
@ -55,7 +54,6 @@ export const api = {
|
||||
deliveryRuns: AdminDeliveryRun[];
|
||||
}>(`/api/v1/organizations/${encodeURIComponent(id)}`),
|
||||
riskProfiles: () => getJson<AdminRiskProfile[]>("/api/v1/risk"),
|
||||
settlements: () => getJson<AdminSettlement[]>("/api/v1/settlements"),
|
||||
failedDeliveries: () =>
|
||||
getJson<AdminDeliveryRun[]>("/api/v1/delivery-runs?status=failed"),
|
||||
webhookEvents: () => getJson<AdminWebhookEvent[]>("/api/v1/webhooks"),
|
||||
|
||||
@ -11,7 +11,6 @@ import type {
|
||||
AdminEntitlement,
|
||||
AdminOrganization,
|
||||
AdminPayment,
|
||||
AdminSettlement,
|
||||
AdminWebhookEvent,
|
||||
} from "./types";
|
||||
|
||||
@ -107,23 +106,6 @@ export async function dbDeliveryRuns(): Promise<AdminDeliveryRun[]> {
|
||||
});
|
||||
}
|
||||
|
||||
export async function dbSettlements(): Promise<AdminSettlement[]> {
|
||||
const repo = createRepository(db(), schema.payouts);
|
||||
const rows = await repo.findMany();
|
||||
return rows.map((r) => ({
|
||||
id: r.id,
|
||||
organizationId: r.organizationId,
|
||||
status: (r.status as AdminSettlement["status"]) ?? "pending",
|
||||
amount: money(r.amount, (r.currency as "USDC") ?? "USDC"),
|
||||
network: r.network,
|
||||
// payouts has no reference column; derive a stable, non-empty value.
|
||||
reference: `stl_${r.id}`,
|
||||
txHash: r.txHash ?? undefined,
|
||||
createdAt: toIso(r.createdAt, new Date(0).toISOString()),
|
||||
updatedAt: toIso(r.updatedAt, new Date(0).toISOString()),
|
||||
}));
|
||||
}
|
||||
|
||||
export async function dbWebhookEvents(): Promise<AdminWebhookEvent[]> {
|
||||
const repo = createRepository(db(), schema.webhookEvents);
|
||||
const rows = await repo.findMany();
|
||||
|
||||
@ -6,7 +6,6 @@ import type {
|
||||
AdminOrganization,
|
||||
AdminPayment,
|
||||
AdminRiskProfile,
|
||||
AdminSettlement,
|
||||
AdminWebhookEvent,
|
||||
} from "./types";
|
||||
|
||||
@ -108,37 +107,6 @@ export const seedWebhookEvents: AdminWebhookEvent[] = [
|
||||
},
|
||||
];
|
||||
|
||||
export const seedSettlements: AdminSettlement[] = [
|
||||
{
|
||||
id: "po_2001", organizationId: "org_acme", status: "settled",
|
||||
amount: money("129.00"), network: "base", reference: "stl_po_2001",
|
||||
txHash: "0x9f1a3c7e2b4d6f8a0c1e2d3b4a5f6e7d8c9b0a1f2e3d4c5b6a7f8e9d0c1b2a3f",
|
||||
createdAt: iso(6 * HOUR), updatedAt: iso(6 * HOUR + 12 * 60_000),
|
||||
},
|
||||
{
|
||||
id: "po_2002", organizationId: "org_globex", status: "settled",
|
||||
amount: money("999.00"), network: "arbitrum", reference: "stl_po_2002",
|
||||
txHash: "0x1b2c3d4e5f60718293a4b5c6d7e8f90112233445566778899aabbccddeeff001",
|
||||
createdAt: iso(DAY + 3 * HOUR), updatedAt: iso(DAY + 3 * HOUR + 9 * 60_000),
|
||||
},
|
||||
{
|
||||
id: "po_2003", organizationId: "org_initech", status: "submitted",
|
||||
amount: money("2500.00"), network: "arc", reference: "stl_po_2003",
|
||||
txHash: "0xaabb00ff11223344556677889900aabbccddeeff00112233445566778899aabb",
|
||||
createdAt: iso(2 * DAY + 2 * HOUR), updatedAt: iso(2 * DAY + 2 * HOUR + 90_000),
|
||||
},
|
||||
{
|
||||
id: "po_2004", organizationId: "org_acme", status: "pending",
|
||||
amount: money("49.00"), network: "base", reference: "stl_po_2004",
|
||||
createdAt: iso(4 * DAY), updatedAt: iso(4 * DAY),
|
||||
},
|
||||
{
|
||||
id: "po_2005", organizationId: "org_umbrella", status: "failed",
|
||||
amount: money("750.00"), network: "polygon", reference: "stl_po_2005",
|
||||
createdAt: iso(3 * DAY + 4 * HOUR), updatedAt: iso(3 * DAY + 4 * HOUR + 6 * 60_000),
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* Build risk profiles by running real contexts through the @settlekit/risk
|
||||
* RuleEngine, so score/flags/decision are derived, not invented.
|
||||
|
||||
@ -13,7 +13,6 @@ import type {
|
||||
AdminOrganization,
|
||||
AdminPayment,
|
||||
AdminRiskProfile,
|
||||
AdminSettlement,
|
||||
AdminWebhookEvent,
|
||||
} from "./types";
|
||||
import { getStore, replaceById } from "./store";
|
||||
@ -22,7 +21,6 @@ import {
|
||||
dbEntitlements,
|
||||
dbOrganizations,
|
||||
dbPayments,
|
||||
dbSettlements,
|
||||
dbWebhookEvents,
|
||||
isDbEnabled,
|
||||
} from "./db";
|
||||
@ -62,10 +60,6 @@ export async function listWebhookEvents(): Promise<AdminWebhookEvent[]> {
|
||||
return isDbEnabled() ? dbWebhookEvents() : getStore().webhookEvents;
|
||||
}
|
||||
|
||||
export async function listSettlements(): Promise<AdminSettlement[]> {
|
||||
return isDbEnabled() ? dbSettlements() : getStore().settlements;
|
||||
}
|
||||
|
||||
export async function listRiskProfiles(): Promise<AdminRiskProfile[]> {
|
||||
// Risk review state is admin-owned; always served from the store.
|
||||
return getStore().riskProfiles;
|
||||
@ -187,7 +181,6 @@ const KNOWN_EVENT_TYPES = new Set<WebhookEventType>([
|
||||
"entitlement.revoked",
|
||||
"delivery.succeeded",
|
||||
"delivery.failed",
|
||||
"invoice.paid",
|
||||
]);
|
||||
|
||||
function asEventType(value: string): WebhookEventType {
|
||||
|
||||
@ -5,7 +5,6 @@ import type {
|
||||
AdminPayment,
|
||||
AdminEntitlement,
|
||||
AdminRiskProfile,
|
||||
AdminSettlement,
|
||||
AdminWebhookEvent,
|
||||
} from "./types";
|
||||
import {
|
||||
@ -14,7 +13,6 @@ import {
|
||||
seedOrganizations,
|
||||
seedPayments,
|
||||
seedRiskProfiles,
|
||||
seedSettlements,
|
||||
seedWebhookEvents,
|
||||
} from "./seed";
|
||||
|
||||
@ -36,7 +34,6 @@ export interface AdminStore {
|
||||
deliveryRuns: AdminDeliveryRun[];
|
||||
webhookEvents: AdminWebhookEvent[];
|
||||
riskProfiles: AdminRiskProfile[];
|
||||
settlements: AdminSettlement[];
|
||||
}
|
||||
|
||||
const GLOBAL_KEY = "__settlekit_admin_store__";
|
||||
@ -51,7 +48,6 @@ function createStore(): AdminStore {
|
||||
deliveryRuns: [...seedDeliveryRuns],
|
||||
webhookEvents: [...seedWebhookEvents],
|
||||
riskProfiles: [...seedRiskProfiles],
|
||||
settlements: [...seedSettlements],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@ -74,26 +74,6 @@ export interface AdminWebhookEvent {
|
||||
readonly deliveredAt?: string;
|
||||
}
|
||||
|
||||
export type SettlementStatus = "settled" | "submitted" | "failed" | "pending";
|
||||
|
||||
/**
|
||||
* A settlement (merchant payout) flattened for the console. Modeled on the
|
||||
* `payouts` table in @settlekit/database (status, amount, currency, network,
|
||||
* tx_hash). `reference` is derived deterministically since payouts has no
|
||||
* dedicated reference column; `txHash` is absent for pending/failed rows.
|
||||
*/
|
||||
export interface AdminSettlement {
|
||||
readonly id: string;
|
||||
readonly organizationId: string;
|
||||
readonly status: SettlementStatus;
|
||||
readonly amount: Money;
|
||||
readonly network: string;
|
||||
readonly reference: string;
|
||||
readonly txHash?: string;
|
||||
readonly createdAt: string;
|
||||
readonly updatedAt: string;
|
||||
}
|
||||
|
||||
/** A risk profile enriched with the live engine decision + manual override. */
|
||||
export interface AdminRiskProfile {
|
||||
readonly id: string;
|
||||
|
||||
@ -1,6 +0,0 @@
|
||||
{
|
||||
"$schema": "https://openapi.vercel.sh/vercel.json",
|
||||
"framework": "nextjs",
|
||||
"installCommand": "corepack enable && pnpm install --frozen-lockfile",
|
||||
"buildCommand": "pnpm --filter @settlekit/admin... build"
|
||||
}
|
||||
1
apps/agent-console/.gitignore
vendored
1
apps/agent-console/.gitignore
vendored
@ -1 +0,0 @@
|
||||
.vercel
|
||||
@ -1 +0,0 @@
|
||||
22
|
||||
@ -1,62 +0,0 @@
|
||||
# SettleKit — Agent Console
|
||||
|
||||
The **Agentic + Innovation** surface: a window into autonomous agents doing
|
||||
commerce. It shows agents discovering published **agent-services**, paying for
|
||||
each call via **x402**, citing the sources they were grounded in, and presenting
|
||||
signed **proofs-of-citation**.
|
||||
|
||||
## Real domain logic, not mocked JSON
|
||||
|
||||
`lib/data.ts` is deterministic but **drives the real SettleKit spine** — it never
|
||||
ships hand-written JSON:
|
||||
|
||||
- **Marketplace** — listings are built with `createAgentService(...)`
|
||||
(`@settlekit/agent-services`), published with `publishAgentService`, and
|
||||
surfaced through `discoverPublishedAgentServices` / `discoverAgentServices`.
|
||||
The agent-readable `§11` metadata (`generateAgentMetadata`) is what an agent
|
||||
reads to pay via x402.
|
||||
- **x402 spend** — each simulated agent invocation runs through
|
||||
`recordAgentUsage` / `agentUsageCost`; per-agent and per-service totals are
|
||||
aggregated with `addMoney` (`@settlekit/common`).
|
||||
- **Reputation** — star ratings are folded with `aggregateAgentReputation`
|
||||
(`ratingAverage`).
|
||||
- **Citation toll** — sources are created with `createSource`
|
||||
(`@settlekit/citation-toll`) into an `InMemorySourceRegistry`, and
|
||||
`computeRoyaltyDistribution` produces the recursive royalty fan-out (depth-0
|
||||
author leg + depth>0 citation legs).
|
||||
- **Attribution** — `detectReuse` (`@settlekit/attribution`) finds the sources an
|
||||
agent's answer was grounded in, and `issueCitationProof` mints a real,
|
||||
HMAC-signed, expiring proof.
|
||||
|
||||
A fixed clock (`2026-06-18T09:00:00Z`) plus fixed integer counts make every
|
||||
Money total, royalty leg, reputation average, and reuse score byte-stable across
|
||||
renders. (The proof `nonce`/`signature` use `randomUUID`, so they are the only
|
||||
non-deterministic fields — by design.) Swap this module for the Pg-backed stores
|
||||
to go live.
|
||||
|
||||
## Pages
|
||||
|
||||
| Route | Surface |
|
||||
| ------------ | ----------------------------------------------------------------- |
|
||||
| `/` | Console overview — agents, services, x402 spend, citations, proofs |
|
||||
| `/agents` | Autonomous agents — budget cap, requests, USDC spent, proofs |
|
||||
| `/services` | Discovered agent-services — price, network, reputation, x402 meta |
|
||||
| `/citations` | Worked example — reuse detection, recursive toll, proof-of-citation |
|
||||
|
||||
## Develop
|
||||
|
||||
```bash
|
||||
pnpm --filter @settlekit/agent-services... build # build domain deps' dist/
|
||||
pnpm --filter @settlekit/agent-console dev # http://localhost:3008
|
||||
```
|
||||
|
||||
## Config
|
||||
|
||||
- `CITATION_PROOF_SECRET` — HMAC secret for proof signing (dev fallback provided).
|
||||
- `NEXT_PUBLIC_API_URL` — live API base (default `http://localhost:8787`).
|
||||
- `SETTLEKIT_API_KEY` — server-side Bearer credential for the live `/v1/agents`
|
||||
and `/v1/jobs` calls. Accepts an `sk_live_…` key or the API's
|
||||
`API_BOOTSTRAP_KEY` (which binds `DEFAULT_ORG_ID`). When unset or invalid the
|
||||
API returns 401 and the `/agents` and `/jobs` pages degrade to the seeded
|
||||
LocalPort demo data with a clear "demo data" notice, so offline dev still
|
||||
works.
|
||||
@ -1,320 +0,0 @@
|
||||
import {
|
||||
Card,
|
||||
DataTable,
|
||||
DemoNotice,
|
||||
EmptyState,
|
||||
ErrorBanner,
|
||||
PageHeader,
|
||||
StatCard,
|
||||
StatGrid,
|
||||
StatusBadge,
|
||||
} from "@/components/ui";
|
||||
import { SimpleCreateForm } from "@/components/forms/SimpleCreateForm";
|
||||
import { api } from "@/lib/api";
|
||||
import type { AgentRecord } from "@/lib/agent-economy-types";
|
||||
import {
|
||||
getAgentConsoleContext,
|
||||
getAgentIdentityContext,
|
||||
type AgentIdentityRow,
|
||||
type AgentStat,
|
||||
} from "@/lib/data";
|
||||
import { formatNumber, formatUsdc, shortWallet } from "@/lib/format";
|
||||
|
||||
// Reads are never statically cached: router.refresh() after a mutation must
|
||||
// re-fetch the live list so a newly registered agent appears immediately.
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/**
|
||||
* Register an agent identity through the real API (`POST /v1/agents`). The org
|
||||
* is implicit from the authenticated key — never send a client-supplied
|
||||
* organizationId. Returns an error string, or null on success.
|
||||
*/
|
||||
async function registerAgent(values: Record<string, string>): Promise<string | null> {
|
||||
"use server";
|
||||
const owner = (values.owner ?? "").trim();
|
||||
const metadataUri = (values.metadataUri ?? "").trim();
|
||||
const displayName = (values.displayName ?? "").trim();
|
||||
if (!owner) return "Owner wallet is required.";
|
||||
if (!metadataUri) return "Metadata URI is required.";
|
||||
const { error } = await api.agents.create({
|
||||
owner,
|
||||
metadataUri,
|
||||
...(displayName ? { displayName } : {}),
|
||||
});
|
||||
return error;
|
||||
}
|
||||
|
||||
function reputationLabel(agent: AgentRecord): string {
|
||||
if (agent.reputationCount && agent.reputationCount > 0) {
|
||||
const score = agent.reputationScore ?? 0;
|
||||
return `${score} / 100`;
|
||||
}
|
||||
return "—";
|
||||
}
|
||||
|
||||
/** Live view: real AgentRecord rows from the API. */
|
||||
function LiveAgents({ agents }: { agents: AgentRecord[] }) {
|
||||
const ownerWallets = new Set(agents.map((a) => a.owner)).size;
|
||||
const rated = agents.filter((a) => (a.reputationCount ?? 0) > 0);
|
||||
const avgReputation =
|
||||
rated.length > 0
|
||||
? Math.round(
|
||||
(rated.reduce((acc, a) => acc + (a.reputationScore ?? 0), 0) /
|
||||
rated.length) *
|
||||
10,
|
||||
) / 10
|
||||
: 0;
|
||||
|
||||
return (
|
||||
<>
|
||||
<StatGrid>
|
||||
<StatCard
|
||||
label="Agents registered"
|
||||
value={formatNumber(agents.length)}
|
||||
hint="Live API records"
|
||||
/>
|
||||
<StatCard label="Owner wallets" value={formatNumber(ownerWallets)} />
|
||||
<StatCard
|
||||
label="With feedback"
|
||||
value={`${rated.length} / ${agents.length}`}
|
||||
/>
|
||||
<StatCard
|
||||
label="Avg reputation"
|
||||
value={`${avgReputation} / 100`}
|
||||
hint="Mean feedback score"
|
||||
/>
|
||||
</StatGrid>
|
||||
|
||||
<Card title="Agent identity (ERC-8004)">
|
||||
<DataTable<AgentRecord>
|
||||
rows={agents}
|
||||
getKey={(r) => r.id}
|
||||
columns={[
|
||||
{
|
||||
header: "Agent ID",
|
||||
cell: (r) => <span className="mono">{r.id}</span>,
|
||||
},
|
||||
{
|
||||
header: "Owner",
|
||||
cell: (r) => (
|
||||
<span className="mono" title={r.owner}>
|
||||
{shortWallet(r.owner)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
header: "Name",
|
||||
cell: (r) => (r.displayName ? r.displayName : <span className="muted">—</span>),
|
||||
},
|
||||
{
|
||||
header: "Metadata URI",
|
||||
cell: (r) => (
|
||||
<span className="mono muted" title={r.metadataUri}>
|
||||
{r.metadataUri}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
header: "Reputation",
|
||||
align: "right",
|
||||
cell: (r) => (
|
||||
<span className="mono" style={{ fontWeight: 600 }}>
|
||||
{reputationLabel(r)}{" "}
|
||||
<span className="muted">
|
||||
({formatNumber(r.reputationCount ?? 0)})
|
||||
</span>
|
||||
</span>
|
||||
),
|
||||
},
|
||||
]}
|
||||
empty={
|
||||
<EmptyState
|
||||
title="No agent identities"
|
||||
message="Register an agent below to mint its identity and start recording reputation feedback."
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</Card>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** Offline fallback: deterministic LocalPort demo identities + x402 spend. */
|
||||
async function DemoAgents() {
|
||||
const { agents } = getAgentConsoleContext();
|
||||
const identity = await getAgentIdentityContext();
|
||||
|
||||
return (
|
||||
<>
|
||||
<StatGrid>
|
||||
<StatCard
|
||||
label="Agents registered"
|
||||
value={formatNumber(identity.totals.agentsRegistered)}
|
||||
hint="ERC-8004 identities"
|
||||
/>
|
||||
<StatCard
|
||||
label="Owner wallets"
|
||||
value={formatNumber(identity.totals.ownerWallets)}
|
||||
/>
|
||||
<StatCard
|
||||
label="Validations passed"
|
||||
value={`${identity.totals.validationsPassed} / ${identity.totals.validationsTotal}`}
|
||||
tone={
|
||||
identity.totals.validationsPassed === identity.totals.validationsTotal
|
||||
? "good"
|
||||
: "warn"
|
||||
}
|
||||
/>
|
||||
<StatCard
|
||||
label="Avg reputation"
|
||||
value={`${identity.totals.avgReputation} / 100`}
|
||||
hint="Mean feedback score"
|
||||
/>
|
||||
</StatGrid>
|
||||
|
||||
<Card title="Agent identity (ERC-8004)">
|
||||
<DataTable<AgentIdentityRow>
|
||||
rows={identity.agents}
|
||||
getKey={(r) => r.agentId}
|
||||
columns={[
|
||||
{
|
||||
header: "Agent ID",
|
||||
cell: (r) => <span className="mono">#{r.agentId}</span>,
|
||||
},
|
||||
{
|
||||
header: "Owner",
|
||||
cell: (r) => (
|
||||
<span className="mono" title={r.owner}>
|
||||
{shortWallet(r.owner)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
header: "Metadata URI",
|
||||
cell: (r) => (
|
||||
<span className="mono muted" title={r.metadataUri}>
|
||||
{r.metadataUri}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
header: "Reputation",
|
||||
align: "right",
|
||||
cell: (r) => (
|
||||
<span className="mono" style={{ fontWeight: 600 }}>
|
||||
{r.avgScore} / 100{" "}
|
||||
<span className="muted">({formatNumber(r.feedbackCount)})</span>
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
header: "Validation",
|
||||
align: "right",
|
||||
cell: (r) => <StatusBadge status={r.validationStatus} />,
|
||||
},
|
||||
]}
|
||||
empty={
|
||||
<EmptyState
|
||||
title="No agent identities"
|
||||
message="Register an ERC-8004 agent to see its identity, reputation, and validation status here."
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</Card>
|
||||
|
||||
<Card title="Autonomous spend (x402)">
|
||||
<DataTable<AgentStat>
|
||||
rows={agents}
|
||||
getKey={(r) => r.id}
|
||||
columns={[
|
||||
{ header: "Agent", cell: (r) => <span style={{ fontWeight: 600 }}>{r.name}</span> },
|
||||
{
|
||||
header: "Budget cap",
|
||||
align: "right",
|
||||
cell: (r) => <span className="mono">{formatUsdc(r.budgetUsdc)}</span>,
|
||||
},
|
||||
{ header: "Services", align: "right", cell: (r) => <span className="mono">{formatNumber(r.servicesUsed)}</span> },
|
||||
{ header: "Requests", align: "right", cell: (r) => <span className="mono">{formatNumber(r.requests)}</span> },
|
||||
{
|
||||
header: "Spent (x402)",
|
||||
align: "right",
|
||||
cell: (r) => (
|
||||
<span className="mono" style={{ fontWeight: 600 }}>
|
||||
{formatUsdc(r.spent.amount)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
header: "Budget used",
|
||||
align: "right",
|
||||
cell: (r) => {
|
||||
const pct = Math.round(r.budgetUsedPct * 100);
|
||||
const tone = pct >= 80 ? "badge-bad" : pct >= 50 ? "badge-warn" : "badge-good";
|
||||
return <span className={`badge ${tone}`}>{pct}%</span>;
|
||||
},
|
||||
},
|
||||
{
|
||||
header: "Proofs",
|
||||
align: "right",
|
||||
cell: (r) => <span className="mono">{formatNumber(r.proofsPresented)}</span>,
|
||||
},
|
||||
]}
|
||||
empty={<EmptyState title="No agents" message="Register an autonomous agent to see its x402 spend and proofs here." />}
|
||||
/>
|
||||
</Card>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default async function AgentsPage() {
|
||||
const result = await api.agents.list();
|
||||
// Fall back to the deterministic demo context when the API is unreachable
|
||||
// (error) or returns no records, so offline dev still renders.
|
||||
const live = !result.error && result.data.length > 0;
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title="Agents"
|
||||
description="Agent identity (ERC-8004) and autonomous spend. Each agent holds an identity with reputation feedback, a budget cap, and pays per call via x402."
|
||||
/>
|
||||
|
||||
{live ? null : <ErrorBanner error={result.error} />}
|
||||
{live ? null : <DemoNotice />}
|
||||
|
||||
{live ? <LiveAgents agents={result.data} /> : <DemoAgents />}
|
||||
|
||||
<Card title="Register an agent">
|
||||
<p className="muted">
|
||||
Register an agent identity in the SettleKit registry. The organization
|
||||
is taken from the server API key — no org field is required.
|
||||
</p>
|
||||
<SimpleCreateForm
|
||||
submitLabel="Register agent"
|
||||
successMessage="Agent registered."
|
||||
action={registerAgent}
|
||||
fields={[
|
||||
{
|
||||
name: "owner",
|
||||
label: "Owner wallet",
|
||||
required: true,
|
||||
placeholder: "0x…",
|
||||
hint: "The wallet that owns this agent identity.",
|
||||
},
|
||||
{
|
||||
name: "metadataUri",
|
||||
label: "Metadata URI",
|
||||
required: true,
|
||||
placeholder: "ipfs://agent/metadata.json",
|
||||
},
|
||||
{
|
||||
name: "displayName",
|
||||
label: "Display name (optional)",
|
||||
placeholder: "Atlas Researcher",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</Card>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@ -1,15 +0,0 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { detectGroundingForText } from "@/lib/data";
|
||||
|
||||
// Attribution + node:crypto require the Node runtime (not edge).
|
||||
export const runtime = "nodejs";
|
||||
|
||||
// Run reuse detection over the demo source corpus. The same call the
|
||||
// citation-toll sidecar exposes at POST /attribution/detect.
|
||||
export async function POST(request: Request) {
|
||||
const body = (await request.json().catch(() => null)) as { text?: string } | null;
|
||||
if (body === null || typeof body.text !== "string") {
|
||||
return NextResponse.json({ error: "text required" }, { status: 400 });
|
||||
}
|
||||
return NextResponse.json({ data: detectGroundingForText(body.text) });
|
||||
}
|
||||
@ -1,126 +0,0 @@
|
||||
import { Card, DataTable, EmptyState, PageHeader } from "@/components/ui";
|
||||
import { ReuseDetector } from "@/components/ReuseDetector";
|
||||
import { getAgentConsoleContext, type RoyaltyLegRow } from "@/lib/data";
|
||||
import { formatUsdc, shortWallet } from "@/lib/format";
|
||||
|
||||
export default function CitationsPage() {
|
||||
const { citations } = getAgentConsoleContext();
|
||||
const { proof } = citations;
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title="Citations & proofs"
|
||||
description="When an agent is grounded in a gated source, the citation toll fans the payment out recursively through the lineage — then the agent receives a signed proof-of-citation it can present downstream."
|
||||
/>
|
||||
|
||||
<Card title="Try it — detect grounding in the corpus">
|
||||
<ReuseDetector />
|
||||
</Card>
|
||||
|
||||
<Card title={`Recursive royalty split — "${citations.sourceTitle}"`}>
|
||||
<p className="muted" style={{ marginTop: 0 }}>
|
||||
One paid access fans out across the citation lineage: the accessed work's author (depth 0)
|
||||
keeps its share, and a recursive cut routes to every source it cites.
|
||||
</p>
|
||||
<div className="detail-grid" style={{ marginBottom: 16 }}>
|
||||
<dt>Gross toll</dt>
|
||||
<dd className="mono">{formatUsdc(citations.gross.amount)}</dd>
|
||||
<dt>Platform fee</dt>
|
||||
<dd className="mono">{formatUsdc(citations.platformFee.amount)}</dd>
|
||||
<dt>Distributable</dt>
|
||||
<dd className="mono">{formatUsdc(citations.distributable.amount)}</dd>
|
||||
</div>
|
||||
<DataTable<RoyaltyLegRow>
|
||||
rows={citations.legs}
|
||||
getKey={(r) => `${r.sourceId}-${r.depth}`}
|
||||
columns={[
|
||||
{
|
||||
header: "Tier",
|
||||
cell: (r) => (
|
||||
<span className="badge badge-neutral">
|
||||
{r.depth === 0 ? "Author" : `Citation · L${r.depth}`}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{ header: "Source", cell: (r) => r.sourceTitle },
|
||||
{ header: "Wallet", cell: (r) => <span className="mono">{shortWallet(r.wallet)}</span> },
|
||||
{
|
||||
header: "Amount",
|
||||
align: "right",
|
||||
cell: (r) => (
|
||||
<span className="mono" style={{ color: "var(--good)", fontWeight: 600 }}>
|
||||
+{formatUsdc(r.amount.amount)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
]}
|
||||
empty={<EmptyState title="No legs" message="This source has no royalty distribution." />}
|
||||
/>
|
||||
</Card>
|
||||
|
||||
<Card title="Worked example — reuse detection">
|
||||
<p className="muted" style={{ marginTop: 0 }}>
|
||||
An agent produced this answer:
|
||||
</p>
|
||||
<blockquote
|
||||
style={{
|
||||
margin: "0 0 16px",
|
||||
padding: "12px 14px",
|
||||
borderLeft: "3px solid var(--accent)",
|
||||
background: "var(--bg-elevated)",
|
||||
borderRadius: "var(--radius-sm)",
|
||||
}}
|
||||
>
|
||||
{citations.answer}
|
||||
</blockquote>
|
||||
|
||||
<div className="detail-grid">
|
||||
<dt>Grounded</dt>
|
||||
<dd>
|
||||
<span className={`badge ${citations.grounded ? "badge-good" : "badge-neutral"}`}>
|
||||
{citations.grounded ? "yes" : "no"}
|
||||
</span>
|
||||
</dd>
|
||||
<dt>Grounded in</dt>
|
||||
<dd>
|
||||
{citations.matches.length > 0
|
||||
? citations.matches.map((m) => (
|
||||
<span key={m.sourceId} className="badge badge-good" style={{ marginRight: 6 }}>
|
||||
{m.title} · {(m.score * 100).toFixed(0)}%
|
||||
</span>
|
||||
))
|
||||
: "—"}
|
||||
</dd>
|
||||
<dt>Toll owed</dt>
|
||||
<dd className="mono">{formatUsdc(citations.tollOwedUsdc)}</dd>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<Card title="Proof-of-citation">
|
||||
<p className="muted" style={{ marginTop: 0 }}>
|
||||
After settling, the agent receives a signed, expiring, replay-protected token it presents
|
||||
downstream. Anyone holding the secret can verify it without re-querying the chain.
|
||||
</p>
|
||||
<div className="detail-grid">
|
||||
<dt>Agent</dt>
|
||||
<dd className="mono">{proof.agent}</dd>
|
||||
<dt>Access</dt>
|
||||
<dd className="mono">{proof.accessId}</dd>
|
||||
<dt>Sources</dt>
|
||||
<dd className="mono">{proof.sourceIds.length > 0 ? proof.sourceIds.join(", ") : "—"}</dd>
|
||||
<dt>Amount</dt>
|
||||
<dd className="mono">{proof.amountUsdc ? formatUsdc(proof.amountUsdc) : "—"}</dd>
|
||||
<dt>Issued</dt>
|
||||
<dd className="mono">{proof.issuedAt}</dd>
|
||||
<dt>Expires</dt>
|
||||
<dd className="mono">{proof.expiresAt ?? "never"}</dd>
|
||||
<dt>Signature</dt>
|
||||
<dd className="mono" style={{ wordBreak: "break-all", color: "var(--text-muted)" }}>
|
||||
{proof.signature}
|
||||
</dd>
|
||||
</div>
|
||||
</Card>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@ -1,771 +0,0 @@
|
||||
:root {
|
||||
/* STATEMENT — greenbar ledger palette (see @settlekit/ui) */
|
||||
--bg: #ebede4;
|
||||
--bg-panel: #f3f4ec;
|
||||
--bg-elevated: #dde3d1;
|
||||
--border: #cdd3c5;
|
||||
--border-strong: #b4bca9;
|
||||
--text: #18211c;
|
||||
--text-muted: #45524b;
|
||||
--text-dim: #79847c;
|
||||
--accent: #1e40a2;
|
||||
--accent-hover: #16306f;
|
||||
--accent-soft: rgba(30, 64, 162, 0.1);
|
||||
--good: #2c6e49;
|
||||
--good-soft: rgba(44, 110, 73, 0.12);
|
||||
--warn: #9a6a18;
|
||||
--warn-soft: rgba(154, 106, 24, 0.12);
|
||||
--bad: #a33a2b;
|
||||
--bad-soft: rgba(163, 58, 43, 0.1);
|
||||
--radius: 4px;
|
||||
--radius-sm: 3px;
|
||||
--font-sans: var(--font-archivo), "Archivo", system-ui, -apple-system,
|
||||
"Segoe UI", Roboto, sans-serif;
|
||||
--font-mono: var(--font-mono-plex), "IBM Plex Mono", ui-monospace, "SF Mono",
|
||||
Menlo, Consolas, monospace;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html,
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font-family: var(--font-sans);
|
||||
font-size: 14px;
|
||||
line-height: 1.5;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
a {
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
code {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.85em;
|
||||
background: var(--bg-elevated);
|
||||
padding: 1px 5px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
/* ---------- App shell ---------- */
|
||||
.app-shell {
|
||||
display: grid;
|
||||
grid-template-columns: 248px 1fr;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.sidebar {
|
||||
background: var(--bg-panel);
|
||||
border-right: 1px solid var(--border);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
height: 100vh;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.sidebar-brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
font-weight: 700;
|
||||
font-size: 16px;
|
||||
padding: 18px 20px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.sidebar-logo {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.sidebar-nav {
|
||||
padding: 12px 12px 24px;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.nav-group {
|
||||
margin-bottom: 18px;
|
||||
}
|
||||
|
||||
.nav-group-title {
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.06em;
|
||||
font-size: 10px;
|
||||
font-weight: 600;
|
||||
color: var(--text-dim);
|
||||
padding: 6px 10px;
|
||||
}
|
||||
|
||||
.nav-link {
|
||||
display: block;
|
||||
padding: 7px 10px;
|
||||
border-radius: var(--radius-sm);
|
||||
color: var(--text-muted);
|
||||
font-size: 13px;
|
||||
transition: background 0.12s, color 0.12s;
|
||||
}
|
||||
|
||||
.nav-link:hover {
|
||||
background: var(--bg-elevated);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.nav-link.active {
|
||||
background: var(--accent-soft);
|
||||
color: var(--accent);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.sidebar-footer {
|
||||
padding: 14px 20px;
|
||||
border-top: 1px solid var(--border);
|
||||
font-size: 11px;
|
||||
color: var(--text-dim);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.sidebar-signout {
|
||||
display: inline-block;
|
||||
align-self: flex-start;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: var(--text-muted);
|
||||
padding: 4px 0;
|
||||
}
|
||||
|
||||
.sidebar-signout:hover {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
/* ---------- Auth shell ---------- */
|
||||
.auth-shell {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 100vh;
|
||||
padding: 32px 20px;
|
||||
}
|
||||
|
||||
.auth-shell-inner {
|
||||
width: 100%;
|
||||
max-width: 400px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 22px;
|
||||
}
|
||||
|
||||
.auth-brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 10px;
|
||||
font-weight: 700;
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.auth-heading {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.auth-heading .page-title {
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
.auth-card {
|
||||
background: var(--bg-panel);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
padding: 24px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 18px;
|
||||
}
|
||||
|
||||
.auth-card .form {
|
||||
max-width: none;
|
||||
}
|
||||
|
||||
.auth-method-toggle {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.auth-alt {
|
||||
text-align: center;
|
||||
font-size: 13px;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.auth-alt a {
|
||||
color: var(--accent);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.main {
|
||||
padding: 28px 32px 64px;
|
||||
max-width: 1180px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* ---------- Page header ---------- */
|
||||
.page-header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.page-title {
|
||||
font-size: 22px;
|
||||
font-weight: 700;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.page-desc {
|
||||
color: var(--text-muted);
|
||||
margin: 4px 0 0;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
/* ---------- Cards & stats ---------- */
|
||||
.card {
|
||||
background: var(--bg-panel);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
padding: 20px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.card-title {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
margin: 0 0 14px;
|
||||
}
|
||||
|
||||
.stat-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
|
||||
gap: 14px;
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.stat-card {
|
||||
background: var(--bg-panel);
|
||||
border: 1px solid var(--border);
|
||||
border-left: 3px solid var(--border-strong);
|
||||
border-radius: var(--radius);
|
||||
padding: 16px 18px;
|
||||
}
|
||||
|
||||
.stat-card.tone-good {
|
||||
border-left-color: var(--good);
|
||||
}
|
||||
.stat-card.tone-warn {
|
||||
border-left-color: var(--warn);
|
||||
}
|
||||
.stat-card.tone-bad {
|
||||
border-left-color: var(--bad);
|
||||
}
|
||||
.stat-card.tone-default {
|
||||
border-left-color: var(--accent);
|
||||
}
|
||||
|
||||
.stat-label {
|
||||
font-size: 12px;
|
||||
color: var(--text-muted);
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.stat-value {
|
||||
font-size: 24px;
|
||||
font-weight: 700;
|
||||
letter-spacing: -0.01em;
|
||||
}
|
||||
|
||||
.stat-hint {
|
||||
font-size: 11px;
|
||||
color: var(--text-dim);
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
/* ---------- Tables ---------- */
|
||||
.table-wrap {
|
||||
overflow-x: auto;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
}
|
||||
|
||||
.data-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.data-table th {
|
||||
text-align: left;
|
||||
font-weight: 600;
|
||||
color: var(--text-muted);
|
||||
padding: 10px 14px;
|
||||
background: var(--bg-elevated);
|
||||
border-bottom: 1px solid var(--border);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.data-table td {
|
||||
padding: 11px 14px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.data-table tr:last-child td {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.data-table tbody tr:hover {
|
||||
background: var(--bg-elevated);
|
||||
}
|
||||
|
||||
.ta-right {
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.mono {
|
||||
font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
/* ---------- Badges ---------- */
|
||||
.badge {
|
||||
display: inline-block;
|
||||
padding: 2px 9px;
|
||||
border-radius: 999px;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
text-transform: capitalize;
|
||||
border: 1px solid transparent;
|
||||
}
|
||||
|
||||
.badge-good {
|
||||
background: var(--good-soft);
|
||||
color: var(--good);
|
||||
}
|
||||
.badge-warn {
|
||||
background: var(--warn-soft);
|
||||
color: var(--warn);
|
||||
}
|
||||
.badge-bad {
|
||||
background: var(--bad-soft);
|
||||
color: var(--bad);
|
||||
}
|
||||
.badge-neutral {
|
||||
background: var(--bg-elevated);
|
||||
color: var(--text-muted);
|
||||
border-color: var(--border);
|
||||
}
|
||||
|
||||
/* ---------- Buttons ---------- */
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 8px 14px;
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
border: 1px solid var(--border-strong);
|
||||
background: var(--bg-elevated);
|
||||
color: var(--text);
|
||||
transition: background 0.12s, border-color 0.12s;
|
||||
}
|
||||
|
||||
.btn:hover {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background: var(--accent);
|
||||
border-color: var(--accent);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
background: var(--accent-hover);
|
||||
}
|
||||
|
||||
.btn:disabled {
|
||||
opacity: 0.55;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
/* ---------- Empty / error states ---------- */
|
||||
.empty-state {
|
||||
text-align: center;
|
||||
padding: 48px 24px;
|
||||
border: 1px dashed var(--border-strong);
|
||||
border-radius: var(--radius);
|
||||
background: var(--bg-panel);
|
||||
}
|
||||
|
||||
.empty-icon {
|
||||
font-size: 28px;
|
||||
color: var(--text-dim);
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.empty-title {
|
||||
font-weight: 600;
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.empty-message {
|
||||
color: var(--text-muted);
|
||||
max-width: 420px;
|
||||
margin: 6px auto 0;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.empty-action {
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.error-banner {
|
||||
background: var(--bad-soft);
|
||||
border: 1px solid rgba(240, 99, 99, 0.4);
|
||||
color: var(--bad);
|
||||
padding: 10px 14px;
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: 12px;
|
||||
margin-bottom: 18px;
|
||||
}
|
||||
|
||||
.demo-notice {
|
||||
background: var(--warn-soft);
|
||||
border: 1px solid rgba(154, 106, 24, 0.4);
|
||||
color: var(--warn);
|
||||
padding: 10px 14px;
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: 12px;
|
||||
margin-bottom: 18px;
|
||||
}
|
||||
|
||||
.advance-job {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
/* ---------- Sub navigation ---------- */
|
||||
.subnav {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
margin-bottom: 22px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.subnav-link {
|
||||
padding: 8px 14px;
|
||||
font-size: 13px;
|
||||
color: var(--text-muted);
|
||||
border-bottom: 2px solid transparent;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.subnav-link:hover {
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
/* ---------- Forms ---------- */
|
||||
.form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
max-width: 640px;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.field label {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.field-hint {
|
||||
font-size: 12px;
|
||||
color: var(--text-dim);
|
||||
}
|
||||
|
||||
.input,
|
||||
.select,
|
||||
.textarea {
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius-sm);
|
||||
color: var(--text);
|
||||
padding: 9px 11px;
|
||||
font-size: 13px;
|
||||
font-family: inherit;
|
||||
}
|
||||
|
||||
.input:focus,
|
||||
.select:focus,
|
||||
.textarea:focus {
|
||||
outline: none;
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.textarea {
|
||||
resize: vertical;
|
||||
min-height: 80px;
|
||||
}
|
||||
|
||||
.form-row {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.form-row > .field {
|
||||
flex: 1;
|
||||
min-width: 160px;
|
||||
}
|
||||
|
||||
.form-message {
|
||||
font-size: 13px;
|
||||
padding: 8px 12px;
|
||||
border-radius: var(--radius-sm);
|
||||
}
|
||||
|
||||
.form-message.ok {
|
||||
background: var(--good-soft);
|
||||
color: var(--good);
|
||||
}
|
||||
|
||||
.form-message.err {
|
||||
background: var(--bad-soft);
|
||||
color: var(--bad);
|
||||
}
|
||||
|
||||
/* ---------- Choice grid (product builder) ---------- */
|
||||
.choice-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.choice {
|
||||
text-align: left;
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius);
|
||||
padding: 14px 16px;
|
||||
cursor: pointer;
|
||||
transition: border-color 0.12s, background 0.12s;
|
||||
}
|
||||
|
||||
.choice:hover {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.choice.selected {
|
||||
border-color: var(--accent);
|
||||
background: var(--accent-soft);
|
||||
}
|
||||
|
||||
.choice-title {
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.choice-desc {
|
||||
font-size: 12px;
|
||||
color: var(--text-muted);
|
||||
margin-top: 3px;
|
||||
}
|
||||
|
||||
.step-label {
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
color: var(--accent);
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.builder-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 10px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
/* ---------- Misc ---------- */
|
||||
.muted {
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.dim {
|
||||
color: var(--text-dim);
|
||||
}
|
||||
.row-between {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
.tag-list {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.tag {
|
||||
background: var(--bg-elevated);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 4px;
|
||||
padding: 1px 7px;
|
||||
font-size: 11px;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.detail-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 160px 1fr;
|
||||
gap: 10px 18px;
|
||||
font-size: 13px;
|
||||
}
|
||||
.detail-grid dt {
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.detail-grid dd {
|
||||
margin: 0;
|
||||
font-weight: 500;
|
||||
}
|
||||
.breadcrumb {
|
||||
font-size: 12px;
|
||||
color: var(--text-dim);
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
.breadcrumb a:hover {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
/* ---------- Button variants ---------- */
|
||||
.btn-ghost {
|
||||
background: transparent;
|
||||
border-color: var(--border-strong);
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.btn-ghost:hover {
|
||||
color: var(--text);
|
||||
border-color: var(--accent);
|
||||
}
|
||||
.btn-sm {
|
||||
padding: 5px 11px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
/* ---------- Onboarding checklist ---------- */
|
||||
.onboarding {
|
||||
border-color: var(--accent);
|
||||
background: var(--bg-panel);
|
||||
border-left: 3px solid var(--accent);
|
||||
}
|
||||
.onboarding-head {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
}
|
||||
.onboarding-pct {
|
||||
font-size: 22px;
|
||||
font-weight: 700;
|
||||
color: var(--accent);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.onboarding-progress {
|
||||
height: 6px;
|
||||
border-radius: 999px;
|
||||
background: var(--bg-elevated);
|
||||
overflow: hidden;
|
||||
margin: 14px 0 18px;
|
||||
}
|
||||
.onboarding-progress-fill {
|
||||
height: 100%;
|
||||
background: var(--accent);
|
||||
border-radius: 999px;
|
||||
transition: width 0.3s ease;
|
||||
}
|
||||
.onboarding-steps {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
.onboarding-step {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 12px 14px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--bg-elevated);
|
||||
}
|
||||
.onboarding-step.next {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
.onboarding-step.done {
|
||||
opacity: 0.7;
|
||||
}
|
||||
.onboarding-check {
|
||||
flex: 0 0 22px;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 999px;
|
||||
font-size: 13px;
|
||||
background: var(--bg-panel);
|
||||
color: var(--text-dim);
|
||||
}
|
||||
.onboarding-step.done .onboarding-check {
|
||||
background: var(--good-soft);
|
||||
color: var(--good);
|
||||
}
|
||||
.onboarding-step-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
}
|
||||
.onboarding-step-title {
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
}
|
||||
.onboarding-step.done .onboarding-step-title {
|
||||
text-decoration: line-through;
|
||||
text-decoration-color: var(--text-dim);
|
||||
}
|
||||
.onboarding-step-status {
|
||||
font-size: 12px;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
@ -1,269 +0,0 @@
|
||||
import {
|
||||
Card,
|
||||
DemoNotice,
|
||||
ErrorBanner,
|
||||
PageHeader,
|
||||
StatCard,
|
||||
StatGrid,
|
||||
StatusBadge,
|
||||
} from "@/components/ui";
|
||||
import { SimpleCreateForm } from "@/components/forms/SimpleCreateForm";
|
||||
import { AdvanceJobButton } from "@/components/AdvanceJobButton";
|
||||
import { api } from "@/lib/api";
|
||||
import {
|
||||
AMOUNT_USDC_RE,
|
||||
type JobRecord,
|
||||
type JobStatus,
|
||||
} from "@/lib/agent-economy-types";
|
||||
import {
|
||||
getJobLifecycleContext,
|
||||
type JobRow,
|
||||
type JobStep,
|
||||
} from "@/lib/data";
|
||||
import { formatUsdc, humanize, shortWallet } from "@/lib/format";
|
||||
|
||||
// Reads are never statically cached: router.refresh() after a create/advance
|
||||
// must re-fetch the live list so the new/updated job appears immediately.
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/**
|
||||
* Create a job through the real API (`POST /v1/jobs`). The org is implicit from
|
||||
* the authenticated key. amountUsdc is validated against the API's decimal regex
|
||||
* before POST so a bad value surfaces a clear message instead of a Zod 400.
|
||||
*/
|
||||
async function createJob(values: Record<string, string>): Promise<string | null> {
|
||||
"use server";
|
||||
const requester = (values.requester ?? "").trim();
|
||||
const worker = (values.worker ?? "").trim();
|
||||
const amountUsdc = (values.amountUsdc ?? "").trim();
|
||||
if (!requester) return "Requester wallet is required.";
|
||||
if (!worker) return "Worker wallet is required.";
|
||||
if (!AMOUNT_USDC_RE.test(amountUsdc)) {
|
||||
return "Amount must be a decimal with up to 6 decimal places (e.g. 120.00).";
|
||||
}
|
||||
const { error } = await api.jobs.create({ requester, worker, amountUsdc });
|
||||
return error;
|
||||
}
|
||||
|
||||
/** Advance a job to its next forward lifecycle status (guarded by the API). */
|
||||
async function advanceJob(jobId: string, to: JobStatus): Promise<string | null> {
|
||||
"use server";
|
||||
const { error } = await api.jobs.transition(jobId, to);
|
||||
return error;
|
||||
}
|
||||
|
||||
/** Live job card: real JobRecord + an advance control. */
|
||||
function LiveJobCard({ job }: { job: JobRecord }) {
|
||||
return (
|
||||
<Card title={`Job ${job.id}`}>
|
||||
<div className="row-between" style={{ marginBottom: 16 }}>
|
||||
<dl className="detail-grid">
|
||||
<dt>Requester</dt>
|
||||
<dd className="mono" title={job.requester}>
|
||||
{shortWallet(job.requester)}
|
||||
</dd>
|
||||
<dt>Worker</dt>
|
||||
<dd className="mono" title={job.worker}>
|
||||
{shortWallet(job.worker)}
|
||||
</dd>
|
||||
<dt>Escrow amount</dt>
|
||||
<dd className="mono" style={{ fontWeight: 600 }}>
|
||||
{formatUsdc(job.amountUsdc)}
|
||||
</dd>
|
||||
<dt>Status</dt>
|
||||
<dd>
|
||||
<StatusBadge status={job.status} />
|
||||
</dd>
|
||||
{job.deliverableUri ? (
|
||||
<>
|
||||
<dt>Deliverable</dt>
|
||||
<dd className="mono muted" title={job.deliverableUri}>
|
||||
{job.deliverableUri}
|
||||
</dd>
|
||||
</>
|
||||
) : null}
|
||||
</dl>
|
||||
</div>
|
||||
<div className="step-label">Lifecycle</div>
|
||||
<AdvanceJobButton jobId={job.id} status={job.status} action={advanceJob} />
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function LiveJobs({ jobs }: { jobs: JobRecord[] }) {
|
||||
const settled = jobs.filter((j) => j.status === "settled").length;
|
||||
const terminal = new Set<JobStatus>(["settled", "refunded", "cancelled"]);
|
||||
const inFlight = jobs.filter((j) => !terminal.has(j.status)).length;
|
||||
const totalEscrowed = jobs.reduce((acc, j) => acc + Number(j.amountUsdc || 0), 0);
|
||||
|
||||
return (
|
||||
<>
|
||||
<StatGrid>
|
||||
<StatCard label="Jobs total" value={String(jobs.length)} />
|
||||
<StatCard
|
||||
label="Settled"
|
||||
value={String(settled)}
|
||||
tone={jobs.length > 0 && settled === jobs.length ? "good" : "warn"}
|
||||
/>
|
||||
<StatCard
|
||||
label="In flight"
|
||||
value={String(inFlight)}
|
||||
tone={inFlight > 0 ? "warn" : "default"}
|
||||
/>
|
||||
<StatCard
|
||||
label="Total escrowed"
|
||||
value={formatUsdc(String(totalEscrowed))}
|
||||
/>
|
||||
</StatGrid>
|
||||
|
||||
{jobs.map((job) => (
|
||||
<LiveJobCard key={job.id} job={job} />
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/* ---- Demo (offline LocalPort) rendering ---- */
|
||||
|
||||
function stepLabel(step: JobStep): string {
|
||||
if (step.transition === "create") return "Create job";
|
||||
if (step.transition === "evaluate_pass") return "Evaluate (passed)";
|
||||
if (step.transition === "evaluate_fail") return "Evaluate (failed)";
|
||||
return humanize(step.transition);
|
||||
}
|
||||
|
||||
function JobTimeline({ steps }: { steps: JobStep[] }) {
|
||||
return (
|
||||
<ol className="onboarding-steps">
|
||||
{steps.map((step, index) => {
|
||||
const isLast = index === steps.length - 1;
|
||||
const stateClass = isLast ? "next" : "done";
|
||||
return (
|
||||
<li key={`${step.transition}-${step.txHash}`} className={`onboarding-step ${stateClass}`}>
|
||||
<span className="onboarding-check">{isLast ? "•" : "✓"}</span>
|
||||
<div className="onboarding-step-body">
|
||||
<span className="onboarding-step-title">{stepLabel(step)}</span>
|
||||
<span className="mono muted" title={step.txHash}>
|
||||
{step.txHash}
|
||||
</span>
|
||||
</div>
|
||||
<span className="onboarding-step-status">
|
||||
<StatusBadge status={step.status} />
|
||||
</span>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
);
|
||||
}
|
||||
|
||||
function DemoJobCard({ job }: { job: JobRow }) {
|
||||
return (
|
||||
<Card title={`Job ${job.id}`}>
|
||||
<div className="row-between" style={{ marginBottom: 16 }}>
|
||||
<dl className="detail-grid">
|
||||
<dt>Requester</dt>
|
||||
<dd className="mono" title={job.requester}>
|
||||
{shortWallet(job.requester)}
|
||||
</dd>
|
||||
<dt>Worker</dt>
|
||||
<dd className="mono" title={job.worker}>
|
||||
{shortWallet(job.worker)}
|
||||
</dd>
|
||||
<dt>Escrow amount</dt>
|
||||
<dd className="mono" style={{ fontWeight: 600 }}>
|
||||
{formatUsdc(job.amount.amount)}
|
||||
</dd>
|
||||
<dt>Status</dt>
|
||||
<dd>
|
||||
<StatusBadge status={job.status} />
|
||||
</dd>
|
||||
</dl>
|
||||
</div>
|
||||
<div className="step-label">Lifecycle</div>
|
||||
<JobTimeline steps={job.steps} />
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
async function DemoJobs() {
|
||||
const { totals, jobs } = await getJobLifecycleContext();
|
||||
return (
|
||||
<>
|
||||
<StatGrid>
|
||||
<StatCard label="Jobs total" value={String(totals.jobsTotal)} />
|
||||
<StatCard
|
||||
label="Settled"
|
||||
value={String(totals.settled)}
|
||||
tone={totals.settled === totals.jobsTotal ? "good" : "warn"}
|
||||
/>
|
||||
<StatCard
|
||||
label="In flight"
|
||||
value={String(totals.inFlight)}
|
||||
tone={totals.inFlight > 0 ? "warn" : "default"}
|
||||
/>
|
||||
<StatCard
|
||||
label="Total escrowed"
|
||||
value={formatUsdc(totals.totalEscrowed.amount)}
|
||||
/>
|
||||
</StatGrid>
|
||||
|
||||
{jobs.map((job) => (
|
||||
<DemoJobCard key={job.id} job={job} />
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default async function JobsPage() {
|
||||
const result = await api.jobs.list();
|
||||
const live = !result.error && result.data.length > 0;
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title="Jobs"
|
||||
description="ERC-8183 autonomous-agent job lifecycle. A requester funds a USDC escrow, a worker submits a deliverable, an evaluator scores it, and the escrow settles to the worker — each step a guarded transition."
|
||||
/>
|
||||
|
||||
{live ? null : <ErrorBanner error={result.error} />}
|
||||
{live ? null : <DemoNotice />}
|
||||
|
||||
{live ? <LiveJobs jobs={result.data} /> : <DemoJobs />}
|
||||
|
||||
<Card title="Create a job">
|
||||
<p className="muted">
|
||||
Create a job in the SettleKit registry. It starts in the{" "}
|
||||
<code>created</code> state; use the Advance control on each job card to
|
||||
move it forward (created → funded → submitted → evaluated → settled).
|
||||
</p>
|
||||
<SimpleCreateForm
|
||||
submitLabel="Create job"
|
||||
successMessage="Job created."
|
||||
action={createJob}
|
||||
fields={[
|
||||
{
|
||||
name: "requester",
|
||||
label: "Requester wallet",
|
||||
required: true,
|
||||
placeholder: "0x…",
|
||||
},
|
||||
{
|
||||
name: "worker",
|
||||
label: "Worker wallet",
|
||||
required: true,
|
||||
placeholder: "0x…",
|
||||
},
|
||||
{
|
||||
name: "amountUsdc",
|
||||
label: "Escrow amount (USDC)",
|
||||
required: true,
|
||||
placeholder: "120.00",
|
||||
hint: "Decimal with up to 6 decimal places.",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</Card>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@ -1,38 +0,0 @@
|
||||
import type { Metadata } from "next";
|
||||
import type { ReactNode } from "react";
|
||||
import { Archivo, IBM_Plex_Mono } from "next/font/google";
|
||||
import { Sidebar } from "@/components/Sidebar";
|
||||
import "./globals.css";
|
||||
|
||||
const archivo = Archivo({
|
||||
subsets: ["latin"],
|
||||
weight: ["400", "500", "600", "700", "800", "900"],
|
||||
variable: "--font-archivo",
|
||||
display: "swap",
|
||||
});
|
||||
|
||||
const plexMono = IBM_Plex_Mono({
|
||||
subsets: ["latin"],
|
||||
weight: ["400", "500", "600", "700"],
|
||||
variable: "--font-mono-plex",
|
||||
display: "swap",
|
||||
});
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "SettleKit — Agent Console",
|
||||
description:
|
||||
"Watch autonomous agents do commerce: discover agent-services, pay per call via x402, cite the sources they were grounded in, and present signed proofs-of-citation — settled in USDC.",
|
||||
};
|
||||
|
||||
export default function RootLayout({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<html lang="en" className={`${archivo.variable} ${plexMono.variable}`}>
|
||||
<body>
|
||||
<div className="app-shell">
|
||||
<Sidebar />
|
||||
<main className="main">{children}</main>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@ -1,16 +0,0 @@
|
||||
import Link from "next/link";
|
||||
|
||||
export default function NotFound() {
|
||||
return (
|
||||
<div className="empty-state">
|
||||
<div className="empty-icon">∅</div>
|
||||
<div className="empty-title">Page not found</div>
|
||||
<p className="empty-message">No agent, service, or proof lives at this route.</p>
|
||||
<div className="empty-action">
|
||||
<Link className="btn btn-primary" href="/">
|
||||
Back to console
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -1,52 +0,0 @@
|
||||
import { Card, DataTable, EmptyState, PageHeader, StatCard, StatGrid } from "@/components/ui";
|
||||
import { getAgentConsoleContext, type ActivityRow } from "@/lib/data";
|
||||
import { formatNumber, formatUsdc, formatDateTime } from "@/lib/format";
|
||||
|
||||
export default function ConsolePage() {
|
||||
const ctx = getAgentConsoleContext();
|
||||
const { totals, activity } = ctx;
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title="Console"
|
||||
description="Autonomous agents discovering agent-services, paying per call via x402, and citing the sources they were grounded in — settled in USDC."
|
||||
/>
|
||||
|
||||
<StatGrid>
|
||||
<StatCard label="Agents active" value={formatNumber(totals.agentsActive)} tone="good" hint="Autonomous buyers" />
|
||||
<StatCard label="Services discovered" value={formatNumber(totals.servicesDiscovered)} hint="Published to marketplace" />
|
||||
<StatCard label="x402 spend" value={formatUsdc(totals.totalSpend.amount)} tone="good" hint="Across all agents" />
|
||||
<StatCard label="Citations made" value={formatNumber(totals.citationsMade)} hint="Sources grounded in" />
|
||||
<StatCard label="Proofs issued" value={formatNumber(totals.proofsIssued)} hint="Signed proofs-of-citation" />
|
||||
</StatGrid>
|
||||
|
||||
<Card title="Recent agent activity">
|
||||
<DataTable<ActivityRow>
|
||||
rows={activity}
|
||||
getKey={(r) => r.id}
|
||||
columns={[
|
||||
{ header: "Time", cell: (r) => <span className="mono">{formatDateTime(r.createdAt)}</span> },
|
||||
{ header: "Agent", cell: (r) => r.agentName },
|
||||
{ header: "Service", cell: (r) => r.serviceName },
|
||||
{
|
||||
header: "Network",
|
||||
cell: (r) => <span className="badge badge-neutral">{r.network}</span>,
|
||||
},
|
||||
{ header: "Requests", align: "right", cell: (r) => <span className="mono">{formatNumber(r.units)}</span> },
|
||||
{
|
||||
header: "Paid (x402)",
|
||||
align: "right",
|
||||
cell: (r) => (
|
||||
<span className="mono" style={{ fontWeight: 600 }}>
|
||||
{formatUsdc(r.amount.amount)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
]}
|
||||
empty={<EmptyState title="No agent activity" message="When agents invoke a service over x402, their calls will print here." />}
|
||||
/>
|
||||
</Card>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@ -1,98 +0,0 @@
|
||||
import { Card, DataTable, EmptyState, PageHeader } from "@/components/ui";
|
||||
import { getAgentConsoleContext, type ServiceListing } from "@/lib/data";
|
||||
import { formatNumber, formatUsdc } from "@/lib/format";
|
||||
|
||||
/** Render a 0..5 average as filled/empty stars plus the numeric mean. */
|
||||
function Stars({ average, count }: { average: number; count: number }) {
|
||||
const rounded = Math.round(average);
|
||||
const filled = "★".repeat(rounded);
|
||||
const empty = "☆".repeat(Math.max(0, 5 - rounded));
|
||||
return (
|
||||
<span className="mono" title={`${average.toFixed(2)} from ${count} ratings`}>
|
||||
<span style={{ color: "var(--good)" }}>{filled}</span>
|
||||
{empty} {average.toFixed(1)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export default function ServicesPage() {
|
||||
const { services } = getAgentConsoleContext();
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title="Services"
|
||||
description="Agent-services published to the marketplace. Each advertises a machine-readable §11 metadata document so an agent knows how to call and pay for it via x402."
|
||||
/>
|
||||
|
||||
<Card title="Discovered agent-services">
|
||||
<DataTable<ServiceListing>
|
||||
rows={services}
|
||||
getKey={(r) => r.id}
|
||||
columns={[
|
||||
{
|
||||
header: "Service",
|
||||
cell: (r) => (
|
||||
<div>
|
||||
<div style={{ fontWeight: 600 }}>{r.name}</div>
|
||||
<div className="muted" style={{ fontSize: 12 }}>{r.description}</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
header: "Protocol",
|
||||
cell: (r) => (
|
||||
<span className="badge badge-good" title="Payment protocol">
|
||||
{r.paymentProtocol}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
header: "Network",
|
||||
cell: (r) => <span className="badge badge-neutral">{r.network}</span>,
|
||||
},
|
||||
{
|
||||
header: "Price / call",
|
||||
align: "right",
|
||||
cell: (r) => <span className="mono">{formatUsdc(r.priceUsdc)}</span>,
|
||||
},
|
||||
{
|
||||
header: "Reputation",
|
||||
cell: (r) => <Stars average={r.ratingAverage} count={r.ratingCount} />,
|
||||
},
|
||||
{ header: "Requests", align: "right", cell: (r) => <span className="mono">{formatNumber(r.requests)}</span> },
|
||||
{
|
||||
header: "Revenue (x402)",
|
||||
align: "right",
|
||||
cell: (r) => (
|
||||
<span className="mono" style={{ fontWeight: 600 }}>
|
||||
{formatUsdc(r.revenue.amount)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
header: "Endpoint",
|
||||
cell: (r) => (
|
||||
<code className="mono" style={{ fontSize: 12 }}>
|
||||
{shortenEndpoint(r.endpoint)}
|
||||
</code>
|
||||
),
|
||||
},
|
||||
]}
|
||||
empty={
|
||||
<EmptyState
|
||||
title="No services discovered"
|
||||
message="Publish an agent-service to surface it in the discovery feed."
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</Card>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** Drop the scheme and trim a long path so the endpoint fits a table cell. */
|
||||
function shortenEndpoint(endpoint: string): string {
|
||||
const noScheme = endpoint.replace(/^https?:\/\//, "");
|
||||
return noScheme.length <= 40 ? noScheme : `${noScheme.slice(0, 37)}…`;
|
||||
}
|
||||
@ -1,75 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import {
|
||||
isTerminal,
|
||||
nextStatus,
|
||||
type JobStatus,
|
||||
} from "@/lib/agent-economy-types";
|
||||
import { humanize } from "@/lib/format";
|
||||
|
||||
interface AdvanceJobButtonProps {
|
||||
jobId: string;
|
||||
status: JobStatus;
|
||||
/** Server action advancing the job to `to`; returns an error string or null. */
|
||||
action: (jobId: string, to: JobStatus) => Promise<string | null>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Advances a job to its next forward status (created → funded → submitted →
|
||||
* evaluated → settled). Disabled on terminal states. Refreshes server data on
|
||||
* success and surfaces transition errors (e.g. a 409 conflict) inline.
|
||||
*/
|
||||
export function AdvanceJobButton({ jobId, status, action }: AdvanceJobButtonProps) {
|
||||
const router = useRouter();
|
||||
const [pending, setPending] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const to = nextStatus(status);
|
||||
const terminal = isTerminal(status);
|
||||
|
||||
async function onAdvance() {
|
||||
if (to === null) return;
|
||||
setPending(true);
|
||||
setError(null);
|
||||
try {
|
||||
const err = await action(jobId, to);
|
||||
if (err) {
|
||||
setError(err);
|
||||
} else {
|
||||
router.refresh();
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Transition failed");
|
||||
} finally {
|
||||
setPending(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (terminal || to === null) {
|
||||
return (
|
||||
<button className="btn btn-ghost btn-sm" type="button" disabled>
|
||||
No further steps
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="advance-job">
|
||||
<button
|
||||
className="btn btn-primary btn-sm"
|
||||
type="button"
|
||||
onClick={onAdvance}
|
||||
disabled={pending}
|
||||
>
|
||||
{pending ? "Advancing…" : `Advance to ${humanize(to)}`}
|
||||
</button>
|
||||
{error ? (
|
||||
<div className="form-message err" role="alert">
|
||||
{error}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -1,116 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
|
||||
interface Match {
|
||||
sourceId: string;
|
||||
title: string;
|
||||
score: number;
|
||||
matched: number;
|
||||
total: number;
|
||||
wallet?: string;
|
||||
}
|
||||
|
||||
interface DetectResult {
|
||||
grounded: boolean;
|
||||
matches: Match[];
|
||||
quoteUsdc: string;
|
||||
}
|
||||
|
||||
const SAMPLE =
|
||||
"An agent discovers a service, reads its machine-readable metadata, and pays a fraction of a cent per request via x402, settled recursively through the citation lineage.";
|
||||
|
||||
export function ReuseDetector() {
|
||||
const [text, setText] = useState(SAMPLE);
|
||||
const [result, setResult] = useState<DetectResult | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function run() {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await fetch("/api/detect", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ text }),
|
||||
});
|
||||
const json = (await res.json()) as { data?: DetectResult; error?: string };
|
||||
if (!res.ok || json.data === undefined) {
|
||||
setError(json.error ?? "detection failed");
|
||||
setResult(null);
|
||||
} else {
|
||||
setResult(json.data);
|
||||
}
|
||||
} catch {
|
||||
setError("network error");
|
||||
setResult(null);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="form">
|
||||
<div className="field">
|
||||
<label htmlFor="answer">Agent answer</label>
|
||||
<textarea
|
||||
id="answer"
|
||||
className="textarea"
|
||||
rows={4}
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
placeholder="Paste the text an agent produced…"
|
||||
/>
|
||||
<span className="field-hint">
|
||||
We shingle the text and check containment against the source corpus — the same call the
|
||||
citation-toll sidecar exposes at <code>POST /attribution/detect</code>.
|
||||
</span>
|
||||
</div>
|
||||
<div className="builder-actions">
|
||||
<button className="btn btn-primary" onClick={run} disabled={loading || text.trim().length === 0}>
|
||||
{loading ? "Detecting…" : "Detect reuse"}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{error ? <div className="form-message err">{error}</div> : null}
|
||||
|
||||
{result ? (
|
||||
<div style={{ marginTop: 8 }}>
|
||||
<div className="row-between" style={{ marginBottom: 10 }}>
|
||||
<span className={`badge ${result.grounded ? "badge-good" : "badge-neutral"}`}>
|
||||
{result.grounded ? "Grounded in the corpus" : "No grounding detected"}
|
||||
</span>
|
||||
<span className="mono" style={{ fontWeight: 600 }}>
|
||||
Toll owed: {result.quoteUsdc} USDC
|
||||
</span>
|
||||
</div>
|
||||
{result.matches.length > 0 ? (
|
||||
<div className="table-wrap">
|
||||
<table className="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Source</th>
|
||||
<th className="ta-right">Containment</th>
|
||||
<th className="ta-right">Shingles</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{result.matches.map((m) => (
|
||||
<tr key={m.sourceId}>
|
||||
<td>{m.title}</td>
|
||||
<td className="ta-right mono">{(m.score * 100).toFixed(0)}%</td>
|
||||
<td className="ta-right mono">
|
||||
{m.matched}/{m.total}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -1,42 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { NAV_GROUPS } from "@/lib/nav";
|
||||
|
||||
function isActive(pathname: string, href: string): boolean {
|
||||
if (href === "/") return pathname === "/";
|
||||
return pathname === href || pathname.startsWith(`${href}/`);
|
||||
}
|
||||
|
||||
export function Sidebar() {
|
||||
const pathname = usePathname();
|
||||
|
||||
return (
|
||||
<aside className="sidebar">
|
||||
<div className="sidebar-brand">
|
||||
<span className="sidebar-logo">◆</span>
|
||||
<span>SettleKit · Agent Console</span>
|
||||
</div>
|
||||
<nav className="sidebar-nav">
|
||||
{NAV_GROUPS.map((group) => (
|
||||
<div className="nav-group" key={group.title}>
|
||||
<div className="nav-group-title">{group.title}</div>
|
||||
{group.items.map((item) => (
|
||||
<Link
|
||||
key={item.href}
|
||||
href={item.href}
|
||||
className={isActive(pathname, item.href) ? "nav-link active" : "nav-link"}
|
||||
>
|
||||
{item.label}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</nav>
|
||||
<div className="sidebar-footer">
|
||||
<span>Agents that discover, pay via x402, cite & prove · USDC native</span>
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@ -1,123 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
export interface FieldDef {
|
||||
name: string;
|
||||
label: string;
|
||||
type?: "text" | "email" | "number" | "url" | "textarea";
|
||||
placeholder?: string;
|
||||
hint?: string;
|
||||
required?: boolean;
|
||||
options?: { value: string; label: string }[];
|
||||
}
|
||||
|
||||
interface SimpleCreateFormProps {
|
||||
fields: FieldDef[];
|
||||
submitLabel: string;
|
||||
/** Posts via a server action; returns an error string or null on success. */
|
||||
action: (values: Record<string, string>) => Promise<string | null>;
|
||||
successMessage?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generic create form: renders typed inputs, POSTs through a server action,
|
||||
* shows inline success/error, and refreshes server data on success.
|
||||
*/
|
||||
export function SimpleCreateForm({
|
||||
fields,
|
||||
submitLabel,
|
||||
action,
|
||||
successMessage = "Created successfully.",
|
||||
}: SimpleCreateFormProps) {
|
||||
const router = useRouter();
|
||||
const [values, setValues] = useState<Record<string, string>>({});
|
||||
const [pending, setPending] = useState(false);
|
||||
const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
function update(name: string, value: string) {
|
||||
setValues((prev) => ({ ...prev, [name]: value }));
|
||||
}
|
||||
|
||||
async function onSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setPending(true);
|
||||
setMessage(null);
|
||||
try {
|
||||
const error = await action(values);
|
||||
if (error) {
|
||||
setMessage({ ok: false, text: error });
|
||||
} else {
|
||||
setMessage({ ok: true, text: successMessage });
|
||||
setValues({});
|
||||
router.refresh();
|
||||
}
|
||||
} catch (err) {
|
||||
setMessage({
|
||||
ok: false,
|
||||
text: err instanceof Error ? err.message : "Request failed",
|
||||
});
|
||||
} finally {
|
||||
setPending(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form className="form" onSubmit={onSubmit}>
|
||||
{fields.map((f) => (
|
||||
<div className="field" key={f.name}>
|
||||
<label htmlFor={f.name}>{f.label}</label>
|
||||
{f.options ? (
|
||||
<select
|
||||
id={f.name}
|
||||
className="select"
|
||||
value={values[f.name] ?? ""}
|
||||
required={f.required}
|
||||
onChange={(e) => update(f.name, e.target.value)}
|
||||
>
|
||||
<option value="">Select…</option>
|
||||
{f.options.map((o) => (
|
||||
<option key={o.value} value={o.value}>
|
||||
{o.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
) : f.type === "textarea" ? (
|
||||
<textarea
|
||||
id={f.name}
|
||||
className="textarea"
|
||||
placeholder={f.placeholder}
|
||||
value={values[f.name] ?? ""}
|
||||
required={f.required}
|
||||
onChange={(e) => update(f.name, e.target.value)}
|
||||
/>
|
||||
) : (
|
||||
<input
|
||||
id={f.name}
|
||||
className="input"
|
||||
type={f.type ?? "text"}
|
||||
placeholder={f.placeholder}
|
||||
value={values[f.name] ?? ""}
|
||||
required={f.required}
|
||||
onChange={(e) => update(f.name, e.target.value)}
|
||||
/>
|
||||
)}
|
||||
{f.hint ? <span className="field-hint">{f.hint}</span> : null}
|
||||
</div>
|
||||
))}
|
||||
{message ? (
|
||||
<div className={`form-message ${message.ok ? "ok" : "err"}`}>
|
||||
{message.text}
|
||||
</div>
|
||||
) : null}
|
||||
<div className="builder-actions">
|
||||
<button className="btn btn-primary" type="submit" disabled={pending}>
|
||||
{pending ? "Saving…" : submitLabel}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@ -1,197 +0,0 @@
|
||||
// Presentational primitives shared across pages. Server-component friendly
|
||||
// (no client hooks) so they can render inside server components.
|
||||
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
export function PageHeader({
|
||||
title,
|
||||
description,
|
||||
action,
|
||||
}: {
|
||||
title: string;
|
||||
description?: string;
|
||||
action?: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="page-header">
|
||||
<div>
|
||||
<h1 className="page-title">{title}</h1>
|
||||
{description ? <p className="page-desc">{description}</p> : null}
|
||||
</div>
|
||||
{action ? <div className="page-action">{action}</div> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Card({
|
||||
children,
|
||||
title,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
title?: string;
|
||||
}) {
|
||||
return (
|
||||
<section className="card">
|
||||
{title ? <h2 className="card-title">{title}</h2> : null}
|
||||
{children}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export function StatCard({
|
||||
label,
|
||||
value,
|
||||
hint,
|
||||
tone = "default",
|
||||
}: {
|
||||
label: string;
|
||||
value: string;
|
||||
hint?: string;
|
||||
tone?: "default" | "good" | "warn" | "bad";
|
||||
}) {
|
||||
return (
|
||||
<div className={`stat-card tone-${tone}`}>
|
||||
<div className="stat-label">{label}</div>
|
||||
<div className="stat-value">{value}</div>
|
||||
{hint ? <div className="stat-hint">{hint}</div> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function StatGrid({ children }: { children: ReactNode }) {
|
||||
return <div className="stat-grid">{children}</div>;
|
||||
}
|
||||
|
||||
const STATUS_TONES: Record<string, string> = {
|
||||
succeeded: "good",
|
||||
active: "good",
|
||||
paid: "good",
|
||||
granted: "good",
|
||||
published: "good",
|
||||
approved: "good",
|
||||
enabled: "good",
|
||||
assigned: "good",
|
||||
pending: "warn",
|
||||
trialing: "warn",
|
||||
in_transit: "warn",
|
||||
retrying: "warn",
|
||||
past_due: "warn",
|
||||
funded: "warn",
|
||||
submitted: "warn",
|
||||
evaluated: "warn",
|
||||
settled: "good",
|
||||
open: "warn",
|
||||
created: "neutral",
|
||||
draft: "neutral",
|
||||
failed: "bad",
|
||||
canceled: "bad",
|
||||
cancelled: "bad",
|
||||
revoked: "bad",
|
||||
refunded: "bad",
|
||||
expired: "bad",
|
||||
disabled: "bad",
|
||||
};
|
||||
|
||||
export function StatusBadge({ status }: { status: string }) {
|
||||
const tone = STATUS_TONES[status] ?? "neutral";
|
||||
const label = status.replace(/_/g, " ");
|
||||
return <span className={`badge badge-${tone}`}>{label}</span>;
|
||||
}
|
||||
|
||||
export function EmptyState({
|
||||
title,
|
||||
message,
|
||||
action,
|
||||
}: {
|
||||
title: string;
|
||||
message: string;
|
||||
action?: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="empty-state">
|
||||
<div className="empty-icon">∅</div>
|
||||
<div className="empty-title">{title}</div>
|
||||
<p className="empty-message">{message}</p>
|
||||
{action ? <div className="empty-action">{action}</div> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBanner({ error }: { error: string | null }) {
|
||||
if (!error) return null;
|
||||
return (
|
||||
<div className="error-banner" role="alert">
|
||||
<strong>API unavailable.</strong> {error}. Showing empty state — start the
|
||||
API at <code>NEXT_PUBLIC_API_URL</code> to load live data.
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function DemoNotice({ message }: { message?: string }) {
|
||||
return (
|
||||
<div className="demo-notice" role="status">
|
||||
<strong>Demo data.</strong>{" "}
|
||||
{message ??
|
||||
"The SettleKit API is unreachable, so this page is showing seeded LocalPort demo data. Start the API and set SETTLEKIT_API_KEY to load live records."}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function DataTable<T>({
|
||||
columns,
|
||||
rows,
|
||||
getKey,
|
||||
empty,
|
||||
}: {
|
||||
columns: { header: string; cell: (row: T) => ReactNode; align?: "right" }[];
|
||||
rows: T[];
|
||||
getKey: (row: T) => string;
|
||||
empty: ReactNode;
|
||||
}) {
|
||||
if (rows.length === 0) return <>{empty}</>;
|
||||
return (
|
||||
<div className="table-wrap">
|
||||
<table className="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
{columns.map((c) => (
|
||||
<th key={c.header} className={c.align === "right" ? "ta-right" : ""}>
|
||||
{c.header}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((row) => (
|
||||
<tr key={getKey(row)}>
|
||||
{columns.map((c) => (
|
||||
<td
|
||||
key={c.header}
|
||||
className={c.align === "right" ? "ta-right" : ""}
|
||||
>
|
||||
{c.cell(row)}
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function SubNav({
|
||||
items,
|
||||
}: {
|
||||
items: { label: string; href: string }[];
|
||||
}) {
|
||||
return (
|
||||
<div className="subnav">
|
||||
{items.map((i) => (
|
||||
<a key={i.href} href={i.href} className="subnav-link">
|
||||
{i.label}
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -1,78 +0,0 @@
|
||||
// Local mirror of the live API row shapes for the agent economy
|
||||
// (`/v1/agents`, `/v1/jobs`). These mirror @settlekit/persistence's
|
||||
// agent-economy-store so lib/api.ts and the pages can type the live API rows
|
||||
// without taking a runtime dependency on the persistence package (which is not
|
||||
// a dependency of agent-console). Keep in sync with
|
||||
// packages/persistence/src/agent-economy-store.ts.
|
||||
|
||||
/** Job lifecycle status (mirrors @settlekit/erc8183 + the API state machine). */
|
||||
export type JobStatus =
|
||||
| "created"
|
||||
| "funded"
|
||||
| "submitted"
|
||||
| "evaluated"
|
||||
| "settled"
|
||||
| "refunded"
|
||||
| "cancelled";
|
||||
|
||||
/** A registered agent identity record returned by `/v1/agents`. */
|
||||
export interface AgentRecord {
|
||||
id: string;
|
||||
organizationId: string;
|
||||
owner: string;
|
||||
metadataUri: string;
|
||||
displayName?: string;
|
||||
/** Average reputation score (0–100) across recorded feedback. */
|
||||
reputationScore?: number;
|
||||
/** Number of feedback entries recorded. */
|
||||
reputationCount?: number;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
/** An agent job record returned by `/v1/jobs`. */
|
||||
export interface JobRecord {
|
||||
id: string;
|
||||
organizationId: string;
|
||||
requester: string;
|
||||
worker: string;
|
||||
amountUsdc: string;
|
||||
status: JobStatus;
|
||||
deliverableUri?: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Forward-only "advance" path for the AdvanceJobButton, mirroring the legal
|
||||
* happy-path transitions enforced by the API's NEXT state machine
|
||||
* (apps/api/src/routes/jobs.ts): created → funded → submitted → evaluated →
|
||||
* settled. Statuses absent from this map (settled/refunded/cancelled) are
|
||||
* terminal for the purposes of the advance control.
|
||||
*/
|
||||
export const NEXT_STATUS: Readonly<Partial<Record<JobStatus, JobStatus>>> = {
|
||||
created: "funded",
|
||||
funded: "submitted",
|
||||
submitted: "evaluated",
|
||||
evaluated: "settled",
|
||||
};
|
||||
|
||||
/** Terminal job states — the advance control is disabled on these. */
|
||||
export const TERMINAL_STATUSES: ReadonlySet<JobStatus> = new Set<JobStatus>([
|
||||
"settled",
|
||||
"refunded",
|
||||
"cancelled",
|
||||
]);
|
||||
|
||||
/** The next forward status for the advance control, or null if terminal. */
|
||||
export function nextStatus(status: JobStatus): JobStatus | null {
|
||||
return NEXT_STATUS[status] ?? null;
|
||||
}
|
||||
|
||||
/** True when a job can no longer be advanced (terminal or no forward edge). */
|
||||
export function isTerminal(status: JobStatus): boolean {
|
||||
return TERMINAL_STATUSES.has(status) || nextStatus(status) === null;
|
||||
}
|
||||
|
||||
/** Decimal-USDC validation matching the API's `^\d+(\.\d{1,6})?$` regex. */
|
||||
export const AMOUNT_USDC_RE = /^\d+(\.\d{1,6})?$/;
|
||||
@ -1,130 +0,0 @@
|
||||
// Real HTTP client for the SettleKit API (`/v1/agents`, `/v1/jobs`).
|
||||
//
|
||||
// SERVER-ONLY. The agent-console has no login/session UI, so — unlike the
|
||||
// dashboard, which authenticates with the merchant's `sk_session` cookie — this
|
||||
// client authenticates with a server-side API key from the environment
|
||||
// (`SETTLEKIT_API_KEY`). The API middleware accepts an `sk_live_…` key, a
|
||||
// session token, OR a configured `API_BOOTSTRAP_KEY` (which binds
|
||||
// DEFAULT_ORG_ID) in the Bearer slot, so for local/offline dev setting
|
||||
// SETTLEKIT_API_KEY to the bootstrap key works. When the key is unset (or
|
||||
// invalid) the API returns 401, which the client surfaces as an error and the
|
||||
// pages degrade to the deterministic LocalPort demo fallback.
|
||||
//
|
||||
// `import "server-only"` guards against a client component importing this module
|
||||
// and leaking the API key into the browser bundle. Client components must route
|
||||
// mutations through inline `"use server"` server actions instead.
|
||||
import "server-only";
|
||||
import { API_URL } from "./config";
|
||||
import type { AgentRecord, JobRecord, JobStatus } from "./agent-economy-types";
|
||||
|
||||
export { API_URL };
|
||||
export type { AgentRecord, JobRecord, JobStatus };
|
||||
|
||||
/**
|
||||
* Authorization header derived from the server-side API key. Absent when no key
|
||||
* is configured — the API then rejects the call (401), which pages surface as an
|
||||
* error and degrade to the demo fallback rather than crashing.
|
||||
*/
|
||||
function authHeader(): Record<string, string> {
|
||||
const key = process.env.SETTLEKIT_API_KEY;
|
||||
return key ? { authorization: `Bearer ${key}` } : {};
|
||||
}
|
||||
|
||||
export interface ApiList<T> {
|
||||
data: T[];
|
||||
total: number;
|
||||
empty: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
export interface ApiItem<T> {
|
||||
data: T | null;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
function listResult<T>(data: T[], error: string | null): ApiList<T> {
|
||||
return { data, total: data.length, empty: data.length === 0, error };
|
||||
}
|
||||
|
||||
async function request<T>(
|
||||
path: string,
|
||||
init?: RequestInit,
|
||||
): Promise<{ data: T | null; error: string | null }> {
|
||||
try {
|
||||
const res = await fetch(`${API_URL}${path}`, {
|
||||
...init,
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
...authHeader(),
|
||||
...(init?.headers ?? {}),
|
||||
},
|
||||
// Server components: always fetch fresh data so mutations show up.
|
||||
cache: "no-store",
|
||||
});
|
||||
if (!res.ok) {
|
||||
return { data: null, error: `API ${res.status} ${res.statusText}` };
|
||||
}
|
||||
const body = (await res.json()) as { data?: T } | T;
|
||||
const data =
|
||||
body && typeof body === "object" && "data" in (body as object)
|
||||
? ((body as { data: T }).data ?? null)
|
||||
: (body as T);
|
||||
return { data, error: null };
|
||||
} catch (err) {
|
||||
return {
|
||||
data: null,
|
||||
error: err instanceof Error ? err.message : "Network error",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function getList<T>(path: string): Promise<ApiList<T>> {
|
||||
const { data, error } = await request<T[]>(path);
|
||||
if (error) return listResult<T>([], error);
|
||||
return listResult<T>(Array.isArray(data) ? data : [], null);
|
||||
}
|
||||
|
||||
async function getItem<T>(path: string): Promise<ApiItem<T>> {
|
||||
const { data, error } = await request<T>(path);
|
||||
return { data, error };
|
||||
}
|
||||
|
||||
async function post<T>(path: string, payload: unknown): Promise<ApiItem<T>> {
|
||||
return request<T>(path, { method: "POST", body: JSON.stringify(payload) });
|
||||
}
|
||||
|
||||
export interface RegisterAgentInput {
|
||||
owner: string;
|
||||
metadataUri: string;
|
||||
displayName?: string;
|
||||
}
|
||||
|
||||
export interface CreateJobInput {
|
||||
requester: string;
|
||||
worker: string;
|
||||
/** Decimal USDC string matching `^\d+(\.\d{1,6})?$`. */
|
||||
amountUsdc: string;
|
||||
}
|
||||
|
||||
export const api = {
|
||||
// ---- Agent identities (ERC-8004 mirror) ----
|
||||
agents: {
|
||||
list: () => getList<AgentRecord>("/v1/agents"),
|
||||
get: (id: string) => getItem<AgentRecord>(`/v1/agents/${encodeURIComponent(id)}`),
|
||||
create: (input: RegisterAgentInput) => post<AgentRecord>("/v1/agents", input),
|
||||
feedback: (id: string, score: number) =>
|
||||
post<AgentRecord>(`/v1/agents/${encodeURIComponent(id)}/feedback`, { score }),
|
||||
},
|
||||
|
||||
// ---- Agent jobs (ERC-8183 mirror) ----
|
||||
jobs: {
|
||||
list: () => getList<JobRecord>("/v1/jobs"),
|
||||
get: (id: string) => getItem<JobRecord>(`/v1/jobs/${encodeURIComponent(id)}`),
|
||||
create: (input: CreateJobInput) => post<JobRecord>("/v1/jobs", input),
|
||||
transition: (id: string, to: JobStatus, deliverableUri?: string) =>
|
||||
post<JobRecord>(`/v1/jobs/${encodeURIComponent(id)}/transition`, {
|
||||
to,
|
||||
...(deliverableUri !== undefined ? { deliverableUri } : {}),
|
||||
}),
|
||||
},
|
||||
};
|
||||
@ -1,7 +0,0 @@
|
||||
// Shared, transport-neutral config. Safe to import from BOTH client and server
|
||||
// components (no server-only dependencies live here), unlike `lib/api.ts` which
|
||||
// reads the server-side API key and is therefore server-only.
|
||||
|
||||
/** Base URL of the SettleKit API. */
|
||||
export const API_URL =
|
||||
process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:8787";
|
||||
@ -1,906 +0,0 @@
|
||||
/**
|
||||
* The agent console's data layer.
|
||||
*
|
||||
* This is NOT mocked JSON — it drives the real SettleKit spine so the UI shows
|
||||
* exactly what the domain produces when autonomous agents do commerce:
|
||||
*
|
||||
* - the marketplace is built with @settlekit/agent-services `createAgentService`
|
||||
* + `publishAgentService`, then surfaced via `discoverPublishedAgentServices`;
|
||||
* - every simulated agent invocation runs through `recordAgentUsage` /
|
||||
* `agentUsageCost`, the same per-call x402 metering the gateway uses, and we
|
||||
* aggregate per-agent and per-service spend with `addMoney`;
|
||||
* - reputation is folded from real star ratings with `aggregateAgentReputation`;
|
||||
* - the citation toll uses @settlekit/citation-toll `createSource` +
|
||||
* `computeRoyaltyDistribution`, the same recursive split the toll handler
|
||||
* produces, so a cited source pays its author and fans a share onward to its
|
||||
* own ancestors;
|
||||
* - the proofs panel runs @settlekit/attribution `detectReuse` over the source
|
||||
* corpus and issues a real signed proof-of-citation.
|
||||
*
|
||||
* A fixed clock + fixed integer counts make the dataset deterministic across
|
||||
* renders. The proof `nonce`/`signature` (randomUUID) are the only
|
||||
* non-deterministic fields — by design. Swap this module for the Pg-backed
|
||||
* stores to go live.
|
||||
*/
|
||||
|
||||
import { type Money, type Result, addMoney, isOk, money } from "@settlekit/common";
|
||||
import {
|
||||
type AgentService,
|
||||
type AgentReadableMetadata,
|
||||
type CreateAgentServiceInput,
|
||||
aggregateAgentReputation,
|
||||
agentRequestPrice,
|
||||
agentUsageCost,
|
||||
createAgentService,
|
||||
discoverPublishedAgentServices,
|
||||
generateAgentMetadata,
|
||||
publishAgentService,
|
||||
ratingAverage,
|
||||
recordAgentUsage,
|
||||
} from "@settlekit/agent-services";
|
||||
import {
|
||||
InMemorySourceRegistry,
|
||||
type Citation,
|
||||
type CreateSourceInput,
|
||||
type RoyaltyLeg,
|
||||
type Source,
|
||||
computeRoyaltyDistribution,
|
||||
createSource,
|
||||
} from "@settlekit/citation-toll";
|
||||
import {
|
||||
type CitationProof,
|
||||
type ReuseMatch,
|
||||
detectReuse,
|
||||
issueCitationProof,
|
||||
} from "@settlekit/attribution";
|
||||
import {
|
||||
type AgentIdentity,
|
||||
LocalErc8004Port,
|
||||
configureErc8004,
|
||||
} from "@settlekit/erc8004";
|
||||
import {
|
||||
type Job,
|
||||
type JobStatus,
|
||||
type JobTransition,
|
||||
LocalErc8183Port,
|
||||
configureErc8183,
|
||||
} from "@settlekit/erc8183";
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* Determinism */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
const CLOCK = new Date("2026-06-18T09:00:00.000Z");
|
||||
const ORG_ID = "org_agent_console_demo";
|
||||
const PROOF_SECRET = process.env.CITATION_PROOF_SECRET ?? "dev-citation-proof-secret";
|
||||
|
||||
function sum(amounts: readonly Money[]): Money {
|
||||
return amounts.reduce<Money>((acc, m) => addMoney(acc, m), money("0"));
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* Seed: agent-services published to the marketplace */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
interface ServiceSeed {
|
||||
slug: string;
|
||||
name: string;
|
||||
description: string;
|
||||
endpoint: string;
|
||||
/** Per-request price in USDC major units (<=6dp). */
|
||||
price: string;
|
||||
network: "arc" | "base";
|
||||
inputSchema: Record<string, unknown>;
|
||||
outputSchema?: Record<string, unknown>;
|
||||
/** Star ratings (each an integer in [1,5]) folded into reputation. */
|
||||
ratings: number[];
|
||||
}
|
||||
|
||||
const SERVICE_SEEDS: readonly ServiceSeed[] = [
|
||||
{
|
||||
slug: "embed",
|
||||
name: "NanoEmbed v2",
|
||||
description: "Sub-cent text embeddings priced per request, settled over x402.",
|
||||
endpoint: "https://embed.agents.settlekit.dev/v2/embed",
|
||||
price: "0.0004",
|
||||
network: "base",
|
||||
inputSchema: { type: "object", properties: { text: { type: "string" } }, required: ["text"] },
|
||||
outputSchema: { type: "object", properties: { vector: { type: "array" } } },
|
||||
ratings: [5, 5, 4, 5, 4, 5],
|
||||
},
|
||||
{
|
||||
slug: "rerank",
|
||||
name: "Citation Reranker",
|
||||
description: "Reranks candidate sources by grounding strength for citation tolls.",
|
||||
endpoint: "https://rerank.agents.settlekit.dev/v1/rerank",
|
||||
price: "0.0007",
|
||||
network: "base",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: { query: { type: "string" }, candidates: { type: "array" } },
|
||||
required: ["query", "candidates"],
|
||||
},
|
||||
ratings: [4, 5, 4, 4, 3],
|
||||
},
|
||||
{
|
||||
slug: "summarize",
|
||||
name: "Provenance Summarizer",
|
||||
description: "Summarizes a source and emits the citation lineage it was grounded in.",
|
||||
endpoint: "https://summarize.agents.settlekit.dev/v1/summarize",
|
||||
price: "0.0009",
|
||||
network: "arc",
|
||||
inputSchema: { type: "object", properties: { sourceId: { type: "string" } }, required: ["sourceId"] },
|
||||
ratings: [5, 4, 5, 5],
|
||||
},
|
||||
{
|
||||
slug: "detect",
|
||||
name: "Reuse Detector API",
|
||||
description: "Detects which gated sources an agent answer was grounded in (implicit reuse).",
|
||||
endpoint: "https://detect.agents.settlekit.dev/v1/detect",
|
||||
price: "0.0005",
|
||||
network: "arc",
|
||||
inputSchema: { type: "object", properties: { answer: { type: "string" } }, required: ["answer"] },
|
||||
ratings: [5, 5, 5, 4, 5, 4, 5],
|
||||
},
|
||||
];
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* Seed: autonomous agents that invoke the services */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
interface AgentSeed {
|
||||
id: string;
|
||||
name: string;
|
||||
/** Per-agent monthly x402 budget cap, USDC major units. */
|
||||
budgetUsdc: string;
|
||||
/** Deterministic integer request counts, keyed by service slug. */
|
||||
requests: Record<string, number>;
|
||||
}
|
||||
|
||||
const AGENT_SEEDS: readonly AgentSeed[] = [
|
||||
{
|
||||
id: "agent_atlas",
|
||||
name: "Atlas Researcher",
|
||||
budgetUsdc: "5.000000",
|
||||
requests: { embed: 1800, rerank: 600, summarize: 200, detect: 320 },
|
||||
},
|
||||
{
|
||||
id: "agent_scout",
|
||||
name: "Scout Indexer",
|
||||
budgetUsdc: "2.000000",
|
||||
requests: { embed: 2400, detect: 140 },
|
||||
},
|
||||
{
|
||||
id: "agent_juno",
|
||||
name: "Juno Synthesizer",
|
||||
budgetUsdc: "3.500000",
|
||||
requests: { rerank: 480, summarize: 360, detect: 260 },
|
||||
},
|
||||
];
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* Seed: citeable sources for the citation toll / proof example */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
interface SourceSeed {
|
||||
slug: string;
|
||||
title: string;
|
||||
authorWallet: string;
|
||||
priceUsdc: string;
|
||||
summary: string;
|
||||
body: string;
|
||||
cites?: { slug: string; shareBps: number }[];
|
||||
}
|
||||
|
||||
const SOURCE_SEEDS: readonly SourceSeed[] = [
|
||||
{
|
||||
slug: "primer",
|
||||
title: "The Recursive Settlement Primer",
|
||||
authorWallet: "0xada0000000000000000000000000000000000001",
|
||||
priceUsdc: "0.0009",
|
||||
summary: "Why royalties should follow a work through every hand that cites it.",
|
||||
body:
|
||||
"Royalties should follow a work through every hand that made it. When settlement is sub-cent " +
|
||||
"and gas-free, a citation can pay its source automatically, and that payment can fan out " +
|
||||
"recursively to everything the source itself was grounded in.",
|
||||
},
|
||||
{
|
||||
slug: "x402",
|
||||
title: "Paying Agent-Services over x402",
|
||||
authorWallet: "0xb00000000000000000000000000000000000000b",
|
||||
priceUsdc: "0.0008",
|
||||
summary: "How an agent reads a §11 metadata doc and pays per call via x402.",
|
||||
body:
|
||||
"An agent discovers a service, reads its machine-readable metadata, and pays a fraction of a " +
|
||||
"cent per request via x402. The toll is batched into one on-chain settlement and the recursive " +
|
||||
"split routes a share back to the primer it was grounded in.",
|
||||
cites: [{ slug: "primer", shareBps: 3500 }],
|
||||
},
|
||||
{
|
||||
slug: "tolls",
|
||||
title: "Agent Citation Tolls at the Boundary",
|
||||
authorWallet: "0xc1d000000000000000000000000000000000000c",
|
||||
priceUsdc: "0.0007",
|
||||
summary: "Charging implicit reuse, not just deliberate fetches.",
|
||||
body:
|
||||
"Reuse detection closes the loop: given the text an agent produced, detect which sources it was " +
|
||||
"grounded in and charge the toll, then settle recursively through the citation lineage over x402.",
|
||||
cites: [{ slug: "x402", shareBps: 3000 }],
|
||||
},
|
||||
];
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* Build: marketplace */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
function createServiceOrThrow(input: CreateAgentServiceInput): AgentService {
|
||||
const r = createAgentService(input, CLOCK);
|
||||
if (!isOk(r)) throw new Error(`createAgentService failed in seed: ${r.error.message}`);
|
||||
return r.value;
|
||||
}
|
||||
|
||||
interface BuiltService {
|
||||
seed: ServiceSeed;
|
||||
service: AgentService;
|
||||
}
|
||||
|
||||
function buildMarketplace(): BuiltService[] {
|
||||
return SERVICE_SEEDS.map((seed) => {
|
||||
const created = createServiceOrThrow({
|
||||
organizationId: ORG_ID,
|
||||
merchantId: `mer_${seed.slug}`,
|
||||
productId: `prod_${seed.slug}`,
|
||||
name: seed.name,
|
||||
description: seed.description,
|
||||
endpoint: seed.endpoint,
|
||||
price: seed.price,
|
||||
network: seed.network,
|
||||
inputSchema: seed.inputSchema,
|
||||
...(seed.outputSchema ? { outputSchema: seed.outputSchema } : {}),
|
||||
});
|
||||
return { seed, service: publishAgentService(created) };
|
||||
});
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* Build: source graph (citation toll) */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
function createSourceOrThrow(input: CreateSourceInput): Source {
|
||||
const r = createSource(input, CLOCK);
|
||||
if (!isOk(r)) throw new Error(`createSource failed in seed: ${r.error.message}`);
|
||||
return r.value;
|
||||
}
|
||||
|
||||
function buildRegistry(): { registry: InMemorySourceRegistry; bySlug: Map<string, Source> } {
|
||||
const registry = new InMemorySourceRegistry();
|
||||
const bySlug = new Map<string, Source>();
|
||||
|
||||
// Originals first so derived works can cite their ids.
|
||||
const ordered = [...SOURCE_SEEDS].sort((a, b) => (a.cites ? 1 : 0) - (b.cites ? 1 : 0));
|
||||
for (const seed of ordered) {
|
||||
const cites: Citation[] = (seed.cites ?? []).map((c) => {
|
||||
const parent = bySlug.get(c.slug);
|
||||
if (parent === undefined) throw new Error(`source seed ${seed.slug} cites unknown ${c.slug}`);
|
||||
return { sourceId: parent.id, shareBps: c.shareBps };
|
||||
});
|
||||
const created = createSourceOrThrow({
|
||||
organizationId: ORG_ID,
|
||||
title: seed.title,
|
||||
authorWallet: seed.authorWallet,
|
||||
priceUsdc: seed.priceUsdc,
|
||||
body: seed.body,
|
||||
summary: seed.summary,
|
||||
cites,
|
||||
});
|
||||
registry.add(created);
|
||||
bySlug.set(seed.slug, created);
|
||||
}
|
||||
return { registry, bySlug };
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* Row types exported for the pages */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
export interface ServiceListing {
|
||||
id: string;
|
||||
slug: string;
|
||||
name: string;
|
||||
description: string;
|
||||
endpoint: string;
|
||||
price: string;
|
||||
priceUsdc: string;
|
||||
network: "arc" | "base";
|
||||
paymentProtocol: "x402";
|
||||
ratingAverage: number;
|
||||
ratingCount: number;
|
||||
/** Aggregate requests across all agents against this service. */
|
||||
requests: number;
|
||||
/** Aggregate x402 spend across all agents against this service. */
|
||||
revenue: Money;
|
||||
metadata: AgentReadableMetadata;
|
||||
}
|
||||
|
||||
export interface AgentStat {
|
||||
id: string;
|
||||
name: string;
|
||||
budgetUsdc: string;
|
||||
requests: number;
|
||||
/** Total x402 spend across every service this agent invoked. */
|
||||
spent: Money;
|
||||
/** Fraction of budget consumed, in [0, 1] (clamped). */
|
||||
budgetUsedPct: number;
|
||||
/** Distinct services invoked by this agent. */
|
||||
servicesUsed: number;
|
||||
/** Proofs-of-citation this agent has presented. */
|
||||
proofsPresented: number;
|
||||
}
|
||||
|
||||
export interface ActivityRow {
|
||||
id: string;
|
||||
agentName: string;
|
||||
serviceName: string;
|
||||
network: "arc" | "base";
|
||||
units: number;
|
||||
amount: Money;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface RoyaltyLegRow extends RoyaltyLeg {
|
||||
sourceTitle: string;
|
||||
}
|
||||
|
||||
export interface CitationExample {
|
||||
/** The accessed source whose toll is distributed. */
|
||||
sourceTitle: string;
|
||||
gross: Money;
|
||||
platformFee: Money;
|
||||
distributable: Money;
|
||||
legs: RoyaltyLegRow[];
|
||||
/** Worked reuse-detection example. */
|
||||
answer: string;
|
||||
grounded: boolean;
|
||||
matches: (ReuseMatch & { title: string })[];
|
||||
tollOwedUsdc: string;
|
||||
proof: CitationProof;
|
||||
}
|
||||
|
||||
export interface ConsoleTotals {
|
||||
agentsActive: number;
|
||||
servicesDiscovered: number;
|
||||
totalSpend: Money;
|
||||
citationsMade: number;
|
||||
proofsIssued: number;
|
||||
}
|
||||
|
||||
export interface AgentConsoleContext {
|
||||
totals: ConsoleTotals;
|
||||
agents: AgentStat[];
|
||||
services: ServiceListing[];
|
||||
activity: ActivityRow[];
|
||||
citations: CitationExample;
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* Aggregate everything */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
export function getAgentConsoleContext(): AgentConsoleContext {
|
||||
const built = buildMarketplace();
|
||||
const published = discoverPublishedAgentServices(built.map((b) => b.service));
|
||||
const bySlug = new Map(built.map((b) => [b.seed.slug, b]));
|
||||
|
||||
// Simulate every agent invoking every service it has a request count for.
|
||||
// recordAgentUsage gives us the canonical x402 usage event per (agent, service).
|
||||
const activity: ActivityRow[] = [];
|
||||
const perServiceRequests = new Map<string, number>();
|
||||
const perServiceRevenue = new Map<string, Money>();
|
||||
const agents: AgentStat[] = [];
|
||||
|
||||
let seq = 0;
|
||||
for (const agentSeed of AGENT_SEEDS) {
|
||||
const amounts: Money[] = [];
|
||||
let agentRequests = 0;
|
||||
let servicesUsed = 0;
|
||||
|
||||
for (const [slug, units] of Object.entries(agentSeed.requests)) {
|
||||
const target = bySlug.get(slug);
|
||||
if (target === undefined || units <= 0) continue;
|
||||
const usage = recordAgentUsage(
|
||||
target.service,
|
||||
agentSeed.id,
|
||||
units,
|
||||
new Date(CLOCK.getTime() + seq * 1000),
|
||||
);
|
||||
seq++;
|
||||
servicesUsed++;
|
||||
agentRequests += units;
|
||||
amounts.push(usage.amount);
|
||||
|
||||
perServiceRequests.set(slug, (perServiceRequests.get(slug) ?? 0) + units);
|
||||
perServiceRevenue.set(slug, addMoney(perServiceRevenue.get(slug) ?? money("0"), usage.amount));
|
||||
|
||||
activity.push({
|
||||
id: usage.id,
|
||||
agentName: agentSeed.name,
|
||||
serviceName: target.seed.name,
|
||||
network: target.service.network,
|
||||
units: usage.units,
|
||||
amount: usage.amount,
|
||||
createdAt: usage.createdAt,
|
||||
});
|
||||
}
|
||||
|
||||
const spent = sum(amounts);
|
||||
const budget = Number(agentSeed.budgetUsdc);
|
||||
const budgetUsedPct =
|
||||
budget > 0 ? Math.min(1, Number(spent.amount) / budget) : 0;
|
||||
|
||||
agents.push({
|
||||
id: agentSeed.id,
|
||||
name: agentSeed.name,
|
||||
budgetUsdc: agentSeed.budgetUsdc,
|
||||
requests: agentRequests,
|
||||
spent,
|
||||
budgetUsedPct,
|
||||
servicesUsed,
|
||||
proofsPresented: 0, // filled in below once proofs are known
|
||||
});
|
||||
}
|
||||
|
||||
// Build service listings with real reputation aggregation.
|
||||
const services: ServiceListing[] = built.map((b) => {
|
||||
const reputation = aggregateAgentReputation(b.service.id, b.seed.ratings);
|
||||
return {
|
||||
id: b.service.id,
|
||||
slug: b.seed.slug,
|
||||
name: b.service.name,
|
||||
description: b.service.description,
|
||||
endpoint: b.service.endpoint,
|
||||
price: b.service.price,
|
||||
priceUsdc: agentRequestPrice(b.service.price).amount,
|
||||
network: b.service.network,
|
||||
paymentProtocol: b.service.paymentProtocol,
|
||||
ratingAverage: ratingAverage(reputation.ratingTotal, reputation.ratingCount),
|
||||
ratingCount: reputation.ratingCount,
|
||||
requests: perServiceRequests.get(b.seed.slug) ?? 0,
|
||||
revenue: perServiceRevenue.get(b.seed.slug) ?? money("0"),
|
||||
metadata: generateAgentMetadata(b.service),
|
||||
};
|
||||
});
|
||||
|
||||
const citations = buildCitationExample();
|
||||
|
||||
// Attribute proofs to agents deterministically: the agent named in the proof
|
||||
// plus a fixed deterministic spread across agents for the demo.
|
||||
const proofsIssued = 1;
|
||||
const agentsWithProofs = agents.map((a, i) => ({
|
||||
...a,
|
||||
proofsPresented: i === 0 ? proofsIssued : 0,
|
||||
}));
|
||||
|
||||
const totalSpend = sum(agentsWithProofs.map((a) => a.spent));
|
||||
|
||||
// Most recent activity first.
|
||||
const recentActivity = [...activity]
|
||||
.sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1))
|
||||
.slice(0, 25);
|
||||
|
||||
return {
|
||||
totals: {
|
||||
agentsActive: agentsWithProofs.length,
|
||||
servicesDiscovered: published.length,
|
||||
totalSpend,
|
||||
citationsMade: citations.matches.length,
|
||||
proofsIssued,
|
||||
},
|
||||
agents: agentsWithProofs,
|
||||
services,
|
||||
activity: recentActivity,
|
||||
citations,
|
||||
};
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* Citation worked example (real toll distribution + reuse + signed proof) */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
function candidatesFromRegistry(
|
||||
registry: InMemorySourceRegistry,
|
||||
): { id: string; text: string; wallet: string }[] {
|
||||
return registry.all().map((s) => ({
|
||||
id: s.id,
|
||||
text: [s.title, s.summary, s.body].join(". "),
|
||||
wallet: s.authorWallet,
|
||||
}));
|
||||
}
|
||||
|
||||
function buildCitationExample(): CitationExample {
|
||||
const { registry, bySlug } = buildRegistry();
|
||||
const titleById = new Map(registry.all().map((s) => [s.id, s.title]));
|
||||
|
||||
// The accessed source whose toll fans out recursively (cites -> x402 -> primer).
|
||||
const accessed = bySlug.get("tolls");
|
||||
if (accessed === undefined) throw new Error("citation example: missing accessed source");
|
||||
const distribution = computeRoyaltyDistribution(registry, accessed.id);
|
||||
if (distribution === undefined) throw new Error("citation example: distribution undefined");
|
||||
|
||||
const legs: RoyaltyLegRow[] = distribution.legs.map((leg) => ({
|
||||
...leg,
|
||||
sourceTitle: titleById.get(leg.sourceId) ?? leg.sourceId,
|
||||
}));
|
||||
|
||||
// Reuse detection over the corpus for a representative agent answer.
|
||||
const answer =
|
||||
"Royalties should follow a work through every hand that made it, and when settlement is " +
|
||||
"sub-cent and gas-free a citation can pay its source automatically.";
|
||||
const report = detectReuse(answer, candidatesFromRegistry(registry));
|
||||
const matches = report.matches.map((m) => ({
|
||||
...m,
|
||||
title: titleById.get(m.sourceId) ?? m.sourceId,
|
||||
}));
|
||||
const tollOwed = sum(
|
||||
report.matches.map((m) => {
|
||||
const s = registry.get(m.sourceId);
|
||||
return s !== undefined ? money(s.priceUsdc) : money("0");
|
||||
}),
|
||||
);
|
||||
|
||||
const proof = issueCitationProof(
|
||||
{
|
||||
agent: "agent_atlas",
|
||||
sourceIds: report.matches.map((m) => m.sourceId),
|
||||
accessId: "acc_atlas_1",
|
||||
amountUsdc: tollOwed.amount,
|
||||
ttlSeconds: 3600,
|
||||
},
|
||||
PROOF_SECRET,
|
||||
CLOCK,
|
||||
);
|
||||
|
||||
return {
|
||||
sourceTitle: accessed.title,
|
||||
gross: distribution.gross,
|
||||
platformFee: distribution.platformFee,
|
||||
distributable: distribution.distributable,
|
||||
legs,
|
||||
answer,
|
||||
grounded: report.grounded,
|
||||
matches,
|
||||
tollOwedUsdc: tollOwed.amount,
|
||||
proof,
|
||||
};
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* Interactive helper for the /api/detect route */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
/** Run reuse detection for arbitrary text against the demo source corpus. */
|
||||
export function detectGroundingForText(text: string): {
|
||||
grounded: boolean;
|
||||
matches: (ReuseMatch & { title: string })[];
|
||||
quoteUsdc: string;
|
||||
} {
|
||||
const { registry } = buildRegistry();
|
||||
const report = detectReuse(text, candidatesFromRegistry(registry));
|
||||
const titleById = new Map(registry.all().map((s) => [s.id, s.title]));
|
||||
const matches = report.matches.map((m) => ({
|
||||
...m,
|
||||
title: titleById.get(m.sourceId) ?? m.sourceId,
|
||||
}));
|
||||
const quote = sum(
|
||||
report.matches.map((m) => {
|
||||
const s = registry.get(m.sourceId);
|
||||
return s !== undefined ? money(s.priceUsdc) : money("0");
|
||||
}),
|
||||
);
|
||||
return { grounded: report.grounded, matches, quoteUsdc: quote.amount };
|
||||
}
|
||||
|
||||
/* ========================================================================== */
|
||||
/* ERC-8004 — agent identity, reputation & validation */
|
||||
/* ========================================================================== */
|
||||
|
||||
/*
|
||||
* These builders drive the REAL @settlekit/erc8004 / @settlekit/erc8183 clients
|
||||
* over their deterministic LOCAL ports (no chain, no Date.now, no Math.random).
|
||||
* Every client method is async and returns a Result, so the builders are async
|
||||
* and unwrap each Result with isOk — throwing inside the seed on failure, the
|
||||
* same discipline buildMarketplace() uses with createServiceOrThrow.
|
||||
*
|
||||
* resolveAgent caveat: LocalErc8004Port.findAgentId returns the FIRST agent for
|
||||
* an owner, so we instantiate ONE port per distinct owner to keep every minted
|
||||
* identity resolvable by its owner wallet.
|
||||
*/
|
||||
|
||||
interface AgentIdentitySeed {
|
||||
/** Owner wallet that mints + owns the identity (one local port per owner). */
|
||||
owner: string;
|
||||
/** Metadata URI describing the agent (validated non-empty by the client). */
|
||||
metadataUri: string;
|
||||
/** Validator wallet that attests the agent (non-empty address). */
|
||||
validator: string;
|
||||
/** Reputation feedback scores, each 0..100, folded into the summary. */
|
||||
ratings: number[];
|
||||
/** Validation request descriptor + verdict response (100 => passed). */
|
||||
validation: { requestUri: string; subject: string; response: number };
|
||||
}
|
||||
|
||||
const AGENT_IDENTITY_SEEDS: readonly AgentIdentitySeed[] = [
|
||||
{
|
||||
owner: "0xa9e0000000000000000000000000000000000a01",
|
||||
metadataUri: "ipfs://agent/atlas-researcher.json",
|
||||
validator: "0xva1d000000000000000000000000000000000001",
|
||||
ratings: [92, 88, 95, 90],
|
||||
validation: {
|
||||
requestUri: "ipfs://validation/atlas-request.json",
|
||||
subject: "atlas-researcher:capability-attestation",
|
||||
response: 100,
|
||||
},
|
||||
},
|
||||
{
|
||||
owner: "0xb70000000000000000000000000000000000000b",
|
||||
metadataUri: "ipfs://agent/scout-indexer.json",
|
||||
validator: "0xva1d000000000000000000000000000000000002",
|
||||
ratings: [78, 84, 80],
|
||||
validation: {
|
||||
requestUri: "ipfs://validation/scout-request.json",
|
||||
subject: "scout-indexer:capability-attestation",
|
||||
response: 60,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
/** One reputation/identity row rendered by the /agents identity table. */
|
||||
export interface AgentIdentityRow {
|
||||
agentId: string;
|
||||
owner: string;
|
||||
metadataUri: string;
|
||||
/** Mean of the recorded feedback scores (0..100), rounded to 1dp. */
|
||||
avgScore: number;
|
||||
feedbackCount: number;
|
||||
/** True when the validator responded with a passing verdict. */
|
||||
validationPassed: boolean;
|
||||
/** Raw validator response (0..100). */
|
||||
validationResponse: number;
|
||||
/** On-chain request hash for the validation. */
|
||||
requestHash: string;
|
||||
/** Status string for the StatusBadge: "granted" (passed) or "pending". */
|
||||
validationStatus: "granted" | "pending";
|
||||
}
|
||||
|
||||
export interface AgentIdentityTotals {
|
||||
agentsRegistered: number;
|
||||
ownerWallets: number;
|
||||
validationsPassed: number;
|
||||
validationsTotal: number;
|
||||
avgReputation: number;
|
||||
}
|
||||
|
||||
export interface AgentIdentityContext {
|
||||
totals: AgentIdentityTotals;
|
||||
agents: AgentIdentityRow[];
|
||||
}
|
||||
|
||||
/** Unwrap an erc8004/erc8183 Result inside a seed, throwing on failure. */
|
||||
function unwrap<T>(label: string, r: Result<T>): T {
|
||||
if (!isOk(r)) throw new Error(`${label} failed in seed: ${r.error.message}`);
|
||||
return r.value;
|
||||
}
|
||||
|
||||
function mean(values: readonly number[]): number {
|
||||
if (values.length === 0) return 0;
|
||||
const total = values.reduce((acc, n) => acc + n, 0);
|
||||
return Math.round((total / values.length) * 10) / 10;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the demo agents through the REAL AgentRegistryClient, record their
|
||||
* reputation feedback, run a validation request/response per agent, and project
|
||||
* the result into rows for the identity view. Deterministic across renders.
|
||||
*/
|
||||
export async function getAgentIdentityContext(): Promise<AgentIdentityContext> {
|
||||
const rows: AgentIdentityRow[] = [];
|
||||
|
||||
for (const seed of AGENT_IDENTITY_SEEDS) {
|
||||
// One port per owner so resolveAgent(owner) maps to THIS agent.
|
||||
const port = new LocalErc8004Port({ owner: seed.owner });
|
||||
const registry = configureErc8004({ port });
|
||||
|
||||
unwrap("registerAgent", await registry.registerAgent({ metadataUri: seed.metadataUri }));
|
||||
|
||||
const identity = unwrap<AgentIdentity | null>(
|
||||
"resolveAgent",
|
||||
await registry.resolveAgent({ owner: seed.owner }),
|
||||
);
|
||||
if (identity === null) throw new Error(`resolveAgent returned null for ${seed.owner}`);
|
||||
|
||||
for (const score of seed.ratings) {
|
||||
unwrap(
|
||||
"giveFeedback",
|
||||
await registry.giveFeedback({
|
||||
agentId: identity.agentId,
|
||||
score,
|
||||
tag: "task_completion",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const request = unwrap(
|
||||
"requestValidation",
|
||||
await registry.requestValidation({
|
||||
agentId: identity.agentId,
|
||||
validator: seed.validator,
|
||||
requestUri: seed.validation.requestUri,
|
||||
subject: seed.validation.subject,
|
||||
}),
|
||||
);
|
||||
unwrap(
|
||||
"respondValidation",
|
||||
await registry.respondValidation({
|
||||
requestHash: request.requestHash,
|
||||
response: seed.validation.response,
|
||||
tag: "capability",
|
||||
}),
|
||||
);
|
||||
const status = unwrap(
|
||||
"getValidationStatus",
|
||||
await registry.getValidationStatus({ requestHash: request.requestHash }),
|
||||
);
|
||||
|
||||
rows.push({
|
||||
agentId: identity.agentId,
|
||||
owner: identity.owner,
|
||||
metadataUri: identity.metadataUri,
|
||||
avgScore: mean(seed.ratings),
|
||||
feedbackCount: seed.ratings.length,
|
||||
validationPassed: status.passed,
|
||||
validationResponse: status.response,
|
||||
requestHash: request.requestHash,
|
||||
validationStatus: status.passed ? "granted" : "pending",
|
||||
});
|
||||
}
|
||||
|
||||
const passed = rows.filter((r) => r.validationPassed).length;
|
||||
return {
|
||||
totals: {
|
||||
agentsRegistered: rows.length,
|
||||
ownerWallets: new Set(rows.map((r) => r.owner)).size,
|
||||
validationsPassed: passed,
|
||||
validationsTotal: rows.length,
|
||||
avgReputation: mean(rows.map((r) => r.avgScore)),
|
||||
},
|
||||
agents: rows,
|
||||
};
|
||||
}
|
||||
|
||||
/* ========================================================================== */
|
||||
/* ERC-8183 — autonomous-agent job lifecycle */
|
||||
/* ========================================================================== */
|
||||
|
||||
interface JobSeed {
|
||||
requester: string;
|
||||
worker: string;
|
||||
/** Decimal USDC (no thousands separators, <=6dp) — matches AMOUNT_RE. */
|
||||
amountUsdc: string;
|
||||
specUri: string;
|
||||
deliverableUri: string;
|
||||
}
|
||||
|
||||
const JOB_SEEDS: readonly JobSeed[] = [
|
||||
{
|
||||
requester: "0xreq0000000000000000000000000000000000001",
|
||||
worker: "0xwrk0000000000000000000000000000000000001",
|
||||
amountUsdc: "120.00",
|
||||
specUri: "ipfs://jobs/spec-corpus-embedding.json",
|
||||
deliverableUri: "ipfs://jobs/deliverable-corpus-embedding.json",
|
||||
},
|
||||
{
|
||||
requester: "0xreq0000000000000000000000000000000000002",
|
||||
worker: "0xwrk0000000000000000000000000000000000002",
|
||||
amountUsdc: "85.50",
|
||||
specUri: "ipfs://jobs/spec-provenance-report.json",
|
||||
deliverableUri: "ipfs://jobs/deliverable-provenance-report.json",
|
||||
},
|
||||
];
|
||||
|
||||
/** One transition in a job's lifecycle timeline. */
|
||||
export interface JobStep {
|
||||
transition: JobTransition | "create";
|
||||
/** Job status AFTER this transition completed. */
|
||||
status: JobStatus;
|
||||
/** Counter-based tx hash from the local port. */
|
||||
txHash: string;
|
||||
}
|
||||
|
||||
/** One job rendered by the /jobs lifecycle view. */
|
||||
export interface JobRow {
|
||||
id: string;
|
||||
requester: string;
|
||||
worker: string;
|
||||
amount: Money;
|
||||
status: JobStatus;
|
||||
steps: JobStep[];
|
||||
}
|
||||
|
||||
export interface JobLifecycleTotals {
|
||||
jobsTotal: number;
|
||||
settled: number;
|
||||
inFlight: number;
|
||||
totalEscrowed: Money;
|
||||
}
|
||||
|
||||
export interface JobLifecycleContext {
|
||||
totals: JobLifecycleTotals;
|
||||
jobs: JobRow[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Drive each demo job through the REAL JobClient happy path —
|
||||
* create -> fund -> submit -> evaluate(passed) -> settle — over the local port,
|
||||
* capturing the tx hash of every step to build a status timeline. Deterministic.
|
||||
*/
|
||||
export async function getJobLifecycleContext(): Promise<JobLifecycleContext> {
|
||||
const port = new LocalErc8183Port();
|
||||
const jobs = configureErc8183({ port });
|
||||
const rows: JobRow[] = [];
|
||||
|
||||
for (const seed of JOB_SEEDS) {
|
||||
const created = unwrap(
|
||||
"createJob",
|
||||
await jobs.createJob({
|
||||
requester: seed.requester,
|
||||
worker: seed.worker,
|
||||
amountUsdc: seed.amountUsdc,
|
||||
specUri: seed.specUri,
|
||||
}),
|
||||
);
|
||||
const jobId = created.jobId;
|
||||
const steps: JobStep[] = [{ transition: "create", status: "created", txHash: created.txHash }];
|
||||
|
||||
const funded = unwrap(
|
||||
"fundEscrow",
|
||||
await jobs.fundEscrow({ jobId, amountUsdc: seed.amountUsdc }),
|
||||
);
|
||||
steps.push({ transition: "fund", status: "funded", txHash: funded.txHash });
|
||||
|
||||
const submitted = unwrap(
|
||||
"submitDeliverable",
|
||||
await jobs.submitDeliverable({ jobId, deliverableUri: seed.deliverableUri }),
|
||||
);
|
||||
steps.push({ transition: "submit", status: "submitted", txHash: submitted.txHash });
|
||||
|
||||
const evaluated = unwrap(
|
||||
"evaluate",
|
||||
await jobs.evaluate({ jobId, passed: true, scoreOrUri: "100" }),
|
||||
);
|
||||
steps.push({ transition: "evaluate_pass", status: "evaluated", txHash: evaluated.txHash });
|
||||
|
||||
const settled = unwrap("settle", await jobs.settle({ jobId }));
|
||||
steps.push({ transition: "settle", status: "settled", txHash: settled.txHash });
|
||||
|
||||
const final = unwrap<Job>("getJob", await jobs.getJob({ jobId }));
|
||||
rows.push({
|
||||
id: final.id,
|
||||
requester: final.requester,
|
||||
worker: final.worker,
|
||||
amount: final.amount,
|
||||
status: final.status,
|
||||
steps,
|
||||
});
|
||||
}
|
||||
|
||||
const settledCount = rows.filter((r) => r.status === "settled").length;
|
||||
const totalEscrowed = sum(rows.map((r) => r.amount));
|
||||
return {
|
||||
totals: {
|
||||
jobsTotal: rows.length,
|
||||
settled: settledCount,
|
||||
inFlight: rows.length - settledCount,
|
||||
totalEscrowed,
|
||||
},
|
||||
jobs: rows,
|
||||
};
|
||||
}
|
||||
@ -1,45 +0,0 @@
|
||||
// Formatting helpers. Money here is a decimal USDC string (the shape the
|
||||
// settlement spine produces, e.g. "0.0008"), not minor units.
|
||||
|
||||
/** Format a decimal USDC string, keeping sub-cent precision when present. */
|
||||
export function formatUsdc(amount: string | null | undefined): string {
|
||||
if (amount == null || amount === "") return "—";
|
||||
const value = Number(amount);
|
||||
if (Number.isNaN(value)) return `${amount} USDC`;
|
||||
const formatted = value.toLocaleString("en-US", {
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 6,
|
||||
});
|
||||
return `${formatted} USDC`;
|
||||
}
|
||||
|
||||
export function formatNumber(n: number | null | undefined): string {
|
||||
if (n == null) return "—";
|
||||
return n.toLocaleString("en-US");
|
||||
}
|
||||
|
||||
/** Render an ISO timestamp as a short readable date-time. */
|
||||
export function formatDateTime(iso: string | null | undefined): string {
|
||||
if (!iso) return "—";
|
||||
const d = new Date(iso);
|
||||
if (Number.isNaN(d.getTime())) return iso;
|
||||
return d.toLocaleString("en-US", {
|
||||
year: "numeric",
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
});
|
||||
}
|
||||
|
||||
/** Title-case a snake_case enum value for display. */
|
||||
export function humanize(value: string | null | undefined): string {
|
||||
if (!value) return "—";
|
||||
return value.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
|
||||
}
|
||||
|
||||
/** Shorten a wallet address for display: 0x1234…abcd. */
|
||||
export function shortWallet(wallet: string): string {
|
||||
if (wallet.length <= 12) return wallet;
|
||||
return `${wallet.slice(0, 6)}…${wallet.slice(-4)}`;
|
||||
}
|
||||
@ -1,37 +0,0 @@
|
||||
// Sidebar navigation for the agent console — the surfaces an operator watching
|
||||
// autonomous agents do commerce (discover, pay via x402, cite, prove) needs.
|
||||
|
||||
export interface NavItem {
|
||||
label: string;
|
||||
href: string;
|
||||
}
|
||||
|
||||
export interface NavGroup {
|
||||
title: string;
|
||||
items: NavItem[];
|
||||
}
|
||||
|
||||
export const NAV_GROUPS: NavGroup[] = [
|
||||
{
|
||||
title: "Operations",
|
||||
items: [
|
||||
{ label: "Console", href: "/" },
|
||||
{ label: "Agents", href: "/agents" },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Agent economy",
|
||||
items: [
|
||||
{ label: "Identity (ERC-8004)", href: "/agents" },
|
||||
{ label: "Jobs (ERC-8183)", href: "/jobs" },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Marketplace",
|
||||
items: [{ label: "Services", href: "/services" }],
|
||||
},
|
||||
{
|
||||
title: "Provenance",
|
||||
items: [{ label: "Citations & proofs", href: "/citations" }],
|
||||
},
|
||||
];
|
||||
5
apps/agent-console/next-env.d.ts
vendored
5
apps/agent-console/next-env.d.ts
vendored
@ -1,5 +0,0 @@
|
||||
/// <reference types="next" />
|
||||
/// <reference types="next/image-types/global" />
|
||||
|
||||
// NOTE: This file should not be edited
|
||||
// see https://nextjs.org/docs/app/building-your-application/configuring/typescript for more information.
|
||||
@ -1,17 +0,0 @@
|
||||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {
|
||||
reactStrictMode: true,
|
||||
// Workspace domain packages ship compiled ESM; transpile them so Next can
|
||||
// bundle them into the server runtime without resolution surprises.
|
||||
transpilePackages: [
|
||||
"@settlekit/agent-services",
|
||||
"@settlekit/attribution",
|
||||
"@settlekit/citation-toll",
|
||||
"@settlekit/common",
|
||||
],
|
||||
env: {
|
||||
NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:8787",
|
||||
},
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
@ -1,31 +0,0 @@
|
||||
{
|
||||
"name": "@settlekit/agent-console",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"description": "SettleKit agent console — visualize autonomous agents discovering agent-services, paying via x402, citing sources, and presenting proofs-of-citation in USDC.",
|
||||
"scripts": {
|
||||
"dev": "next dev -p 3008",
|
||||
"build": "next build",
|
||||
"start": "next start -p 3008",
|
||||
"lint": "next lint",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@settlekit/agent-services": "workspace:*",
|
||||
"@settlekit/attribution": "workspace:*",
|
||||
"@settlekit/citation-toll": "workspace:*",
|
||||
"@settlekit/common": "workspace:*",
|
||||
"@settlekit/erc8004": "workspace:*",
|
||||
"@settlekit/erc8183": "workspace:*",
|
||||
"next": "^14.2.5",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"server-only": "^0.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.14.0",
|
||||
"@types/react": "^18.3.3",
|
||||
"@types/react-dom": "^18.3.0",
|
||||
"typescript": "^5.5.4"
|
||||
}
|
||||
}
|
||||
@ -1,90 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
detectGroundingForText,
|
||||
getAgentConsoleContext,
|
||||
} from "../lib/data";
|
||||
|
||||
const DECIMAL_RE = /^-?\d+(\.\d+)?$/;
|
||||
|
||||
describe("getAgentConsoleContext", () => {
|
||||
it("publishes the seeded agent-services for discovery", () => {
|
||||
const ctx = getAgentConsoleContext();
|
||||
expect(ctx.services.length).toBeGreaterThan(0);
|
||||
expect(ctx.totals.servicesDiscovered).toBe(ctx.services.length);
|
||||
for (const s of ctx.services) {
|
||||
expect(s.paymentProtocol).toBe("x402");
|
||||
expect(["arc", "base"]).toContain(s.network);
|
||||
expect(s.priceUsdc).toMatch(DECIMAL_RE);
|
||||
}
|
||||
});
|
||||
|
||||
it("produces parseable USDC spend per agent", () => {
|
||||
const ctx = getAgentConsoleContext();
|
||||
expect(ctx.agents.length).toBeGreaterThan(0);
|
||||
for (const a of ctx.agents) {
|
||||
expect(a.spent.amount).toMatch(DECIMAL_RE);
|
||||
expect(Number.isNaN(Number(a.spent.amount))).toBe(false);
|
||||
expect(a.budgetUsedPct).toBeGreaterThanOrEqual(0);
|
||||
expect(a.budgetUsedPct).toBeLessThanOrEqual(1);
|
||||
}
|
||||
});
|
||||
|
||||
it("aggregates a total x402 spend across agents", () => {
|
||||
const ctx = getAgentConsoleContext();
|
||||
expect(ctx.totals.totalSpend.amount).toMatch(DECIMAL_RE);
|
||||
expect(Number(ctx.totals.totalSpend.amount)).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("computes a recursive royalty distribution with depth-0 and depth>0 legs", () => {
|
||||
const ctx = getAgentConsoleContext();
|
||||
const legs = ctx.citations.legs;
|
||||
expect(legs.length).toBeGreaterThan(0);
|
||||
expect(legs.some((l) => l.depth === 0)).toBe(true);
|
||||
expect(legs.some((l) => l.depth > 0)).toBe(true);
|
||||
for (const l of legs) {
|
||||
expect(l.amount.amount).toMatch(DECIMAL_RE);
|
||||
}
|
||||
});
|
||||
|
||||
it("grounds the seeded worked example and issues a signed proof", () => {
|
||||
const ctx = getAgentConsoleContext();
|
||||
expect(ctx.citations.grounded).toBe(true);
|
||||
expect(ctx.citations.matches.length).toBeGreaterThan(0);
|
||||
expect(ctx.citations.proof.signature.length).toBeGreaterThan(0);
|
||||
expect(ctx.citations.proof.agent).toBe("agent_atlas");
|
||||
});
|
||||
|
||||
it("is deterministic across renders except for randomly-generated ids", () => {
|
||||
// createSource() mints a random source id per call and issueCitationProof()
|
||||
// a random nonce/signature — both are domain-level randomness. Everything
|
||||
// derived from the fixed CLOCK + seeds (amounts, depths, shares, titles) is
|
||||
// stable, so we compare legs on their value-bearing fields, not the id.
|
||||
const a = getAgentConsoleContext();
|
||||
const b = getAgentConsoleContext();
|
||||
const stableLegs = (legs: typeof a.citations.legs) =>
|
||||
legs.map(({ sourceId, ...rest }) => rest);
|
||||
expect(a.totals.totalSpend.amount).toBe(b.totals.totalSpend.amount);
|
||||
expect(stableLegs(a.citations.legs)).toEqual(stableLegs(b.citations.legs));
|
||||
expect(a.citations.tollOwedUsdc).toBe(b.citations.tollOwedUsdc);
|
||||
expect(a.services.map((s) => s.ratingAverage)).toEqual(
|
||||
b.services.map((s) => s.ratingAverage),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("detectGroundingForText", () => {
|
||||
it("detects grounding for corpus-derived text", () => {
|
||||
const res = detectGroundingForText(
|
||||
"Royalties should follow a work through every hand that made it, and when settlement is sub-cent and gas-free a citation can pay its source automatically.",
|
||||
);
|
||||
expect(res.grounded).toBe(true);
|
||||
expect(res.matches.length).toBeGreaterThan(0);
|
||||
expect(res.quoteUsdc).toMatch(DECIMAL_RE);
|
||||
});
|
||||
|
||||
it("returns no grounding for unrelated text", () => {
|
||||
const res = detectGroundingForText("The quick brown fox jumps over the lazy dog repeatedly.");
|
||||
expect(res.grounded).toBe(false);
|
||||
expect(res.matches.length).toBe(0);
|
||||
});
|
||||
});
|
||||
@ -1,24 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"lib": ["dom", "dom.iterable", "ES2022"],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"jsx": "preserve",
|
||||
"incremental": true,
|
||||
"plugins": [{ "name": "next" }],
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": ["./*"]
|
||||
}
|
||||
},
|
||||
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
@ -1,6 +0,0 @@
|
||||
{
|
||||
"$schema": "https://openapi.vercel.sh/vercel.json",
|
||||
"framework": "nextjs",
|
||||
"installCommand": "corepack enable && pnpm install --frozen-lockfile",
|
||||
"buildCommand": "pnpm --filter @settlekit/agent-console... build"
|
||||
}
|
||||
@ -1 +0,0 @@
|
||||
22
|
||||
@ -2,22 +2,19 @@
|
||||
# Multi-stage build for the SettleKit API (@settlekit/api).
|
||||
# Build context is the monorepo root: `docker build -f apps/api/Dockerfile .`
|
||||
|
||||
# ---- Base: Node 22 + pnpm via Corepack -------------------------------------
|
||||
FROM node:22-alpine AS base
|
||||
# ---- Base: Node 20 + pnpm via Corepack -------------------------------------
|
||||
FROM node:20-alpine AS base
|
||||
ENV PNPM_HOME=/pnpm
|
||||
ENV PATH=$PNPM_HOME:$PATH
|
||||
# Non-interactive build: lets the prod-deps `pnpm install --prod` purge the
|
||||
# modules dir without a TTY prompt (ERR_PNPM_ABORTED_REMOVE_MODULES_DIR_NO_TTY).
|
||||
ENV CI=true
|
||||
RUN corepack enable
|
||||
WORKDIR /app
|
||||
|
||||
# ---- Dependencies: install only the api and its workspace deps (frozen) ----
|
||||
# ---- Dependencies: install the full workspace (frozen) ---------------------
|
||||
FROM base AS deps
|
||||
COPY package.json pnpm-workspace.yaml pnpm-lock.yaml tsconfig.base.json ./
|
||||
COPY packages ./packages
|
||||
COPY apps ./apps
|
||||
RUN pnpm install --frozen-lockfile --filter settlekit --filter "@settlekit/api..."
|
||||
RUN pnpm install --frozen-lockfile
|
||||
|
||||
# ---- Build: compile package deps + the api via tsc project references ------
|
||||
FROM deps AS build
|
||||
@ -47,15 +44,4 @@ COPY --from=prod-deps /app/apps/api/node_modules ./apps/api/node_modules
|
||||
|
||||
WORKDIR /app/apps/api
|
||||
EXPOSE 8787
|
||||
# Apply pending migrations (idempotent), then serve. Render's preDeployCommand
|
||||
# is paid-plan only, so the free API migrates on boot.
|
||||
#
|
||||
# The migration step is `||`, not `&&`: found 2026-11-10 that a stale/
|
||||
# unreachable DATABASE_URL made migration hang (now bounded by
|
||||
# packages/database's DEFAULT_CONNECT_TIMEOUT_SECONDS) and, with the old
|
||||
# `&&` chain, a migration failure meant the server was never even attempted
|
||||
# — one bad DB env var took down the whole container, including endpoints
|
||||
# that don't need the database. Now the server always starts and reports
|
||||
# its own real DB-connectivity error (fast, bounded, visible in logs)
|
||||
# instead of the whole boot silently never finishing.
|
||||
CMD ["sh", "-c", "if [ -n \"$DATABASE_URL\" ]; then node /app/packages/database/dist/cli.js || echo '[migrate] failed or timed out — starting the server anyway so non-DB endpoints still serve'; fi; exec node dist/server.js"]
|
||||
CMD ["node", "dist/server.js"]
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SettleKit REST API — Hono on Node. Mounts real route modules per resource under /v1 backed by the @settlekit domain packages and their in-memory repositories.",
|
||||
"description": "SettleKit REST API \u2014 Hono on Node. Mounts real route modules per resource under /v1 backed by the @settlekit domain packages and their in-memory repositories.",
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"exports": {
|
||||
@ -27,17 +27,21 @@
|
||||
"@settlekit/agent": "workspace:*",
|
||||
"@settlekit/agent-economy": "workspace:*",
|
||||
"@settlekit/agent-services": "workspace:*",
|
||||
"@settlekit/oss-fund": "workspace:*",
|
||||
"@settlekit/api-keys": "workspace:*",
|
||||
"@settlekit/citation-toll": "workspace:*",
|
||||
"@settlekit/arc": "workspace:*",
|
||||
"@settlekit/auth": "workspace:*",
|
||||
"@settlekit/bundles": "workspace:*",
|
||||
"@settlekit/cctp": "workspace:*",
|
||||
"@settlekit/chains": "workspace:*",
|
||||
"@settlekit/circle": "workspace:*",
|
||||
"@settlekit/circle-wallets": "workspace:*",
|
||||
"@settlekit/citation-toll": "workspace:*",
|
||||
"@settlekit/common": "workspace:*",
|
||||
"@settlekit/compliance": "workspace:*",
|
||||
"@settlekit/gateway": "workspace:*",
|
||||
"@settlekit/onchain": "workspace:*",
|
||||
"@settlekit/paymaster": "workspace:*",
|
||||
"@settlekit/stablefx": "workspace:*",
|
||||
"@settlekit/coupons": "workspace:*",
|
||||
"@settlekit/database": "workspace:*",
|
||||
"@settlekit/delivery": "workspace:*",
|
||||
@ -46,48 +50,27 @@
|
||||
"@settlekit/dunning": "workspace:*",
|
||||
"@settlekit/entitlements": "workspace:*",
|
||||
"@settlekit/escrow": "workspace:*",
|
||||
"@settlekit/exports": "workspace:*",
|
||||
"@settlekit/file-delivery": "workspace:*",
|
||||
"@settlekit/gateway": "workspace:*",
|
||||
"@settlekit/github": "workspace:*",
|
||||
"@settlekit/hyperliquid": "workspace:*",
|
||||
"@settlekit/invitations": "workspace:*",
|
||||
"@settlekit/invoices": "workspace:*",
|
||||
"@settlekit/license-keys": "workspace:*",
|
||||
"@settlekit/marketplace-core": "workspace:*",
|
||||
"@settlekit/notifications": "workspace:*",
|
||||
"@settlekit/onchain": "workspace:*",
|
||||
"@settlekit/onchain-billing": "workspace:*",
|
||||
"@settlekit/operator": "workspace:*",
|
||||
"@settlekit/oss-fund": "workspace:*",
|
||||
"@settlekit/paymaster": "workspace:*",
|
||||
"@settlekit/payments": "workspace:*",
|
||||
"@settlekit/payouts": "workspace:*",
|
||||
"@settlekit/persistence": "workspace:*",
|
||||
"@settlekit/platform-billing": "workspace:*",
|
||||
"@settlekit/pricing": "workspace:*",
|
||||
"@settlekit/product-catalog": "workspace:*",
|
||||
"@settlekit/rate-limits": "workspace:*",
|
||||
"@settlekit/refunds": "workspace:*",
|
||||
"@settlekit/saas": "workspace:*",
|
||||
"@settlekit/solana": "workspace:*",
|
||||
"@settlekit/stablefx": "workspace:*",
|
||||
"@settlekit/streaming": "workspace:*",
|
||||
"@settlekit/usage": "workspace:*",
|
||||
"@settlekit/webhooks": "workspace:*",
|
||||
"@settlekit/x402": "workspace:*",
|
||||
"@settlekit/x402-client": "workspace:*",
|
||||
"@settlekit/zcash": "workspace:*",
|
||||
"hono": "^4.12.25",
|
||||
"zod": "^3.24.1",
|
||||
"@settlekit/x402-facilitator": "workspace:*",
|
||||
"@x402/core": "~2.27.0",
|
||||
"@x402/evm": "~2.27.0",
|
||||
"@x402/svm": "~2.27.0",
|
||||
"@x402/hono": "~2.27.0",
|
||||
"@solana/kit": "5.5.1",
|
||||
"mppx": "^0.11.0",
|
||||
"viem": "^2.54.0"
|
||||
"@settlekit/streaming": "workspace:*",
|
||||
"hono": "^4.6.14",
|
||||
"zod": "^3.24.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.14.0",
|
||||
|
||||
@ -1,272 +0,0 @@
|
||||
/**
|
||||
* Agent payments runtime (x402 v2 on every chain + MPP on Tempo), built once
|
||||
* from env at boot and attached to the AppContext.
|
||||
*
|
||||
* Facilitator routing:
|
||||
* - remote (PayAI by default, no key): Solana, Base, Arbitrum
|
||||
* - local (@settlekit/x402-facilitator, relayer hot key): Ethereum,
|
||||
* HyperEVM, Robinhood (+ Tempo Permit2 when explicitly enabled)
|
||||
* A network is offered only when it has a payTo address and a facilitator.
|
||||
*
|
||||
* X402_EVM_PAY_TO / X402_SOLANA_PAY_TO merchant recipients (X402_PAY_TO_<KEY> per network)
|
||||
* X402_NETWORKS networks to offer (default: all routable)
|
||||
* X402_REMOTE_FACILITATOR_URL default https://facilitator.payai.network
|
||||
* X402_REMOTE_FACILITATOR_API_KEY optional bearer for a keyed facilitator
|
||||
* X402_REMOTE_NETWORKS default solana,base,arbitrum
|
||||
* X402_RESEARCH_PRICE sample resource price, USD (default 0.01)
|
||||
* X402_FACILITATOR_TOKEN bearer for POST /v1/x402/facilitator/{verify,settle}
|
||||
* X402_ORGANIZATION_ID org credited for the sample resource
|
||||
* MPP_SECRET_KEY / MPP_TEMPO_RECIPIENT / MPP_REALM Tempo MPP (mppx)
|
||||
* plus @settlekit/x402-facilitator env (X402_RELAYER_PRIVATE_KEY, ...),
|
||||
* SETTLEKIT_CHAIN_ENV / <KEY>_NETWORK and SOLANA_CLUSTER.
|
||||
*/
|
||||
import type { PaymentNetwork } from "@settlekit/common";
|
||||
import { DEFAULT_ORG_ID } from "@settlekit/persistence";
|
||||
import {
|
||||
SOLANA_CAIP2,
|
||||
checkPayTo,
|
||||
getEvmChain,
|
||||
isEvmChainKey,
|
||||
parseChainEnv,
|
||||
readEnv,
|
||||
type ChainEnv,
|
||||
type Env,
|
||||
type EvmChainKey,
|
||||
} from "@settlekit/chains";
|
||||
import { parseSolanaCluster, getSolanaCluster } from "@settlekit/solana";
|
||||
import { PAYAI_FACILITATOR_URL, routeFacilitators, type FacilitatorRoute } from "@settlekit/x402";
|
||||
import {
|
||||
getFacilitatorAsset,
|
||||
loadFacilitatorFromEnv,
|
||||
requirementsExtraFor,
|
||||
type NonceStore,
|
||||
type SettleKitFacilitator,
|
||||
} from "@settlekit/x402-facilitator";
|
||||
import { HTTPFacilitatorClient, type FacilitatorClient } from "@x402/core/server";
|
||||
import type { Network } from "@x402/core/types";
|
||||
import { buildMppRuntime, type MppRuntime } from "./mpp.js";
|
||||
|
||||
export type FacilitatorKind = "remote" | "local";
|
||||
|
||||
/** One network an agent can pay on. */
|
||||
export interface AgentPaymentNetwork {
|
||||
network: PaymentNetwork;
|
||||
caip2: Network;
|
||||
env: ChainEnv;
|
||||
symbol: string;
|
||||
/** Token address (EVM) or mint (Solana). */
|
||||
asset: string;
|
||||
decimals: number;
|
||||
payTo: string;
|
||||
facilitator: FacilitatorKind;
|
||||
/** Requirements `extra` (EIP-712 domain or Permit2 transfer method). */
|
||||
extra: Record<string, unknown>;
|
||||
experimental: boolean;
|
||||
}
|
||||
|
||||
export interface AgentPaymentsRuntime {
|
||||
networks: readonly AgentPaymentNetwork[];
|
||||
/** Network-scoped facilitator clients handed to the x402 resource server. */
|
||||
facilitators: readonly FacilitatorClient[];
|
||||
/** The in-process self-hosted facilitator, when a relayer key is configured. */
|
||||
localFacilitator: SettleKitFacilitator | null;
|
||||
facilitatorToken?: string;
|
||||
/** Sample resource price, decimal USD. */
|
||||
researchPrice: string;
|
||||
/** Organization credited for the sample resource. */
|
||||
organizationId: string;
|
||||
maxTimeoutSeconds: number;
|
||||
/** Why a configured network is not offered. */
|
||||
notes: readonly string[];
|
||||
mpp: MppRuntime | null;
|
||||
}
|
||||
|
||||
export const DEFAULT_REMOTE_NETWORKS: readonly PaymentNetwork[] = ["solana", "base", "arbitrum"];
|
||||
const OFFERABLE: readonly PaymentNetwork[] = ["solana", "base", "arbitrum", "ethereum", "hyperevm", "robinhood", "tempo"];
|
||||
|
||||
function chainEnvFor(env: Env, key: EvmChainKey): ChainEnv {
|
||||
return (
|
||||
parseChainEnv(readEnv(env, `${key.toUpperCase()}_NETWORK`), `${key.toUpperCase()}_NETWORK`) ??
|
||||
parseChainEnv(readEnv(env, "SETTLEKIT_CHAIN_ENV"), "SETTLEKIT_CHAIN_ENV") ??
|
||||
"testnet"
|
||||
);
|
||||
}
|
||||
|
||||
function solanaEnv(env: Env): ChainEnv {
|
||||
const cluster = readEnv(env, "SOLANA_CLUSTER");
|
||||
if (cluster !== undefined) return parseSolanaCluster(cluster) === "mainnet" ? "mainnet" : "testnet";
|
||||
return parseChainEnv(readEnv(env, "SETTLEKIT_CHAIN_ENV"), "SETTLEKIT_CHAIN_ENV") ?? "testnet";
|
||||
}
|
||||
|
||||
function payToFor(env: Env, network: PaymentNetwork): string | undefined {
|
||||
const specific = readEnv(env, `X402_PAY_TO_${network.toUpperCase()}`);
|
||||
if (specific !== undefined) return specific;
|
||||
return network === "solana" ? readEnv(env, "X402_SOLANA_PAY_TO") : readEnv(env, "X402_EVM_PAY_TO");
|
||||
}
|
||||
|
||||
function listEnv(env: Env, key: string, fallback: readonly PaymentNetwork[]): PaymentNetwork[] {
|
||||
const raw = readEnv(env, key);
|
||||
if (raw === undefined) return [...fallback];
|
||||
return raw
|
||||
.split(",")
|
||||
.map((part) => part.trim().toLowerCase())
|
||||
.filter((part): part is PaymentNetwork => (OFFERABLE as readonly string[]).includes(part));
|
||||
}
|
||||
|
||||
/** The remote-facilitated network entry (asset from the registry / Solana cluster). */
|
||||
function remoteNetwork(env: Env, network: PaymentNetwork, payTo: string): AgentPaymentNetwork | string {
|
||||
if (network === "solana") {
|
||||
const chainEnv = solanaEnv(env);
|
||||
const cluster = getSolanaCluster(chainEnv === "mainnet" ? "mainnet" : "devnet");
|
||||
return {
|
||||
network,
|
||||
caip2: SOLANA_CAIP2[chainEnv] as Network,
|
||||
env: chainEnv,
|
||||
symbol: "USDC",
|
||||
asset: cluster.usdcMint,
|
||||
decimals: 6,
|
||||
payTo,
|
||||
facilitator: "remote",
|
||||
extra: {},
|
||||
experimental: false,
|
||||
};
|
||||
}
|
||||
if (!isEvmChainKey(network)) return `${network}: not an x402 network`;
|
||||
const chainEnv = chainEnvFor(env, network);
|
||||
const asset = getFacilitatorAsset(network, chainEnv);
|
||||
if (!asset || asset.transferMethod !== "eip3009") return `${network}: no EIP-3009 asset on ${chainEnv}`;
|
||||
return {
|
||||
network,
|
||||
caip2: asset.caip2,
|
||||
env: chainEnv,
|
||||
symbol: asset.symbol,
|
||||
asset: asset.address,
|
||||
decimals: asset.decimals,
|
||||
payTo,
|
||||
facilitator: "remote",
|
||||
extra: requirementsExtraFor(asset),
|
||||
experimental: false,
|
||||
};
|
||||
}
|
||||
|
||||
export interface LoadAgentPaymentsOptions {
|
||||
/** Inject the local facilitator (tests); defaults to loading it from env. */
|
||||
localFacilitator?: SettleKitFacilitator | null;
|
||||
/** Shared replay store for the local facilitator (Postgres when DATABASE_URL is set). */
|
||||
nonceStore?: NonceStore;
|
||||
/** Boot warnings sink (default console.warn). */
|
||||
warn?: (message: string) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* This deployment's own EVM receiving addresses: X402_EVM_PAY_TO plus every
|
||||
* per-chain X402_PAY_TO_<CHAIN> (Solana excluded; the local relayer is EVM-only).
|
||||
*/
|
||||
export function ownEvmRecipients(env: Env): string[] {
|
||||
return Object.keys(env)
|
||||
.filter((key) => key === "X402_EVM_PAY_TO" || /^X402_PAY_TO_(?!SOLANA$)[A-Z]+$/.test(key))
|
||||
.map((key) => readEnv(env, key))
|
||||
.filter((value): value is string => value !== undefined && /^0x[0-9a-fA-F]{40}$/.test(value));
|
||||
}
|
||||
|
||||
/** Build the runtime from env, or null when no network can be offered and MPP is off. */
|
||||
export function loadAgentPayments(env: Env = process.env, options: LoadAgentPaymentsOptions = {}): AgentPaymentsRuntime | null {
|
||||
const notes: string[] = [];
|
||||
// The relayer only settles to this deployment's own EVM recipients unless
|
||||
// X402_FACILITATOR_ALLOWED_PAY_TO names others (or "*" opens it).
|
||||
const loaded =
|
||||
options.localFacilitator === undefined
|
||||
? loadFacilitatorFromEnv(env, {
|
||||
defaultAllowedPayTo: ownEvmRecipients(env),
|
||||
...(options.nonceStore ? { nonceStore: options.nonceStore } : {}),
|
||||
})
|
||||
: null;
|
||||
const local = options.localFacilitator === undefined ? (loaded?.facilitator ?? null) : options.localFacilitator;
|
||||
if (loaded) {
|
||||
notes.push(...loaded.skipped.map((reason) => `local facilitator skipped ${reason}`));
|
||||
const warn = options.warn ?? ((message: string) => console.warn(`[x402] ${message}`));
|
||||
for (const warning of loaded.warnings) {
|
||||
notes.push(warning);
|
||||
warn(warning);
|
||||
}
|
||||
}
|
||||
|
||||
const wanted = new Set(listEnv(env, "X402_NETWORKS", OFFERABLE));
|
||||
const remoteWanted = listEnv(env, "X402_REMOTE_NETWORKS", DEFAULT_REMOTE_NETWORKS);
|
||||
const networks: AgentPaymentNetwork[] = [];
|
||||
|
||||
for (const asset of local?.assets() ?? []) {
|
||||
if (!wanted.has(asset.network)) continue;
|
||||
const payTo = payToFor(env, asset.network);
|
||||
if (payTo === undefined || !checkPayTo(asset.network, payTo).ok) {
|
||||
notes.push(`${asset.network}: set a valid X402_EVM_PAY_TO or X402_PAY_TO_${asset.network.toUpperCase()}`);
|
||||
continue;
|
||||
}
|
||||
networks.push({
|
||||
network: asset.network,
|
||||
caip2: asset.caip2,
|
||||
env: asset.env,
|
||||
symbol: asset.symbol,
|
||||
asset: asset.address,
|
||||
decimals: asset.decimals,
|
||||
payTo,
|
||||
facilitator: "local",
|
||||
extra: requirementsExtraFor(asset),
|
||||
experimental: asset.experimental,
|
||||
});
|
||||
}
|
||||
|
||||
for (const network of remoteWanted) {
|
||||
if (!wanted.has(network) || networks.some((entry) => entry.network === network)) continue;
|
||||
const payTo = payToFor(env, network);
|
||||
if (payTo === undefined || !checkPayTo(network, payTo).ok) {
|
||||
notes.push(`${network}: set a valid ${network === "solana" ? "X402_SOLANA_PAY_TO" : "X402_EVM_PAY_TO"}`);
|
||||
continue;
|
||||
}
|
||||
const entry = remoteNetwork(env, network, payTo);
|
||||
if (typeof entry === "string") notes.push(entry);
|
||||
else networks.push(entry);
|
||||
}
|
||||
|
||||
const routes: FacilitatorRoute[] = [];
|
||||
const remoteNets = networks.filter((entry) => entry.facilitator === "remote").map((entry) => entry.caip2);
|
||||
if (remoteNets.length > 0) {
|
||||
const apiKey = readEnv(env, "X402_REMOTE_FACILITATOR_API_KEY");
|
||||
const client = new HTTPFacilitatorClient({
|
||||
url: readEnv(env, "X402_REMOTE_FACILITATOR_URL") ?? PAYAI_FACILITATOR_URL,
|
||||
...(apiKey
|
||||
? {
|
||||
createAuthHeaders: async () => {
|
||||
const headers = { Authorization: `Bearer ${apiKey}` };
|
||||
return { verify: headers, settle: headers, supported: headers };
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
routes.push({ name: "remote", client, networks: remoteNets });
|
||||
}
|
||||
const localNets = networks.filter((entry) => entry.facilitator === "local").map((entry) => entry.caip2);
|
||||
if (local && localNets.length > 0) routes.push({ name: "local", client: local, networks: localNets });
|
||||
|
||||
const mpp = buildMppRuntime(env, notes);
|
||||
if (networks.length === 0 && mpp === null && local === null) return null;
|
||||
|
||||
const token = readEnv(env, "X402_FACILITATOR_TOKEN");
|
||||
return {
|
||||
networks,
|
||||
facilitators: routeFacilitators(routes),
|
||||
localFacilitator: local,
|
||||
...(token ? { facilitatorToken: token } : {}),
|
||||
researchPrice: readEnv(env, "X402_RESEARCH_PRICE") ?? "0.01",
|
||||
organizationId: readEnv(env, "X402_ORGANIZATION_ID") ?? DEFAULT_ORG_ID,
|
||||
maxTimeoutSeconds: 300,
|
||||
notes,
|
||||
mpp,
|
||||
};
|
||||
}
|
||||
|
||||
/** The Tempo registry token for `env` (MPP currency). */
|
||||
export function tempoToken(chainEnv: ChainEnv): { address: string; symbol: string; decimals: number; chainId: number } | null {
|
||||
const spec = getEvmChain("tempo", chainEnv);
|
||||
return spec ? { address: spec.token.address, symbol: spec.token.symbol, decimals: spec.token.decimals, chainId: spec.chainId } : null;
|
||||
}
|
||||
@ -1,23 +0,0 @@
|
||||
/**
|
||||
* Delivery actions for an agent purchase (derivation shared with the worker
|
||||
* via `@settlekit/delivery` `deliveryActionsFor`). Actions that need a buyer identity
|
||||
* (GitHub login, Discord user, email) report it as a required field so the
|
||||
* API can reject the request BEFORE any payment is settled.
|
||||
*/
|
||||
import type { DeliveryAction } from "@settlekit/common";
|
||||
import { deliveryActionsFor } from "@settlekit/delivery";
|
||||
|
||||
export { deliveryActionsFor };
|
||||
|
||||
export type BuyerField = "githubUsername" | "discordUserId" | "email";
|
||||
|
||||
/** Buyer fields the actions need to execute. */
|
||||
export function requiredBuyerFields(actions: readonly DeliveryAction[]): BuyerField[] {
|
||||
const fields = new Set<BuyerField>();
|
||||
for (const action of actions) {
|
||||
if (action.type === "github_invite" || action.type === "github_team_add") fields.add("githubUsername");
|
||||
if (action.type === "discord_role_add") fields.add("discordUserId");
|
||||
if (action.type === "email_send") fields.add("email");
|
||||
}
|
||||
return [...fields];
|
||||
}
|
||||
@ -1,217 +0,0 @@
|
||||
/**
|
||||
* Fulfil an agent purchase whose payment has ALREADY settled on-chain
|
||||
* (x402 facilitator settle or MPP receipt):
|
||||
*
|
||||
* 1. the transaction hash is normalized per network and must be unused
|
||||
* (one on-chain transfer backs at most one payment -> 409 otherwise)
|
||||
* 2. the payer becomes (or matches) a customer of the product's org
|
||||
* 3. a confirmed Payment is recorded
|
||||
* 4. an entitlement is granted for the product
|
||||
* 5. the product's delivery actions run inline through the real handler
|
||||
* registry; the run is persisted and its outputs returned as the artifact
|
||||
*
|
||||
* Delivery failures do not undo the payment: the run is stored as failed /
|
||||
* partially_failed and can be retried via POST /v1/delivery-runs/:id/retry.
|
||||
*/
|
||||
import {
|
||||
conflict,
|
||||
generateId,
|
||||
money,
|
||||
toIso,
|
||||
type Customer,
|
||||
type DeliveryPlan,
|
||||
type DeliveryRun,
|
||||
type Entitlement,
|
||||
type Money,
|
||||
type Payment,
|
||||
type PaymentNetwork,
|
||||
type Price,
|
||||
type Product,
|
||||
} from "@settlekit/common";
|
||||
import { DeliveryRunner, type DeliveryContext } from "@settlekit/delivery";
|
||||
import { confirmPayment, recordPendingPayment } from "@settlekit/payments";
|
||||
import { paymentConfirmedWebhook } from "@settlekit/persistence";
|
||||
import type { AppContext } from "../context.js";
|
||||
import { emitWebhook } from "../webhooks/outbox.js";
|
||||
import { assertTxHashUnused, requireTxHash } from "../routes/payment-verification.js";
|
||||
import { deliveryActionsFor } from "./delivery-action.js";
|
||||
|
||||
export type AgentRail = "x402" | "mpp";
|
||||
|
||||
export interface BuyerDetails {
|
||||
email?: string;
|
||||
githubUsername?: string;
|
||||
discordUserId?: string;
|
||||
}
|
||||
|
||||
export interface AgentPurchaseInput {
|
||||
product: Product;
|
||||
price: Price;
|
||||
rail: AgentRail;
|
||||
network: PaymentNetwork;
|
||||
/** Settlement transaction hash / signature reported by the facilitator or MPP receipt. */
|
||||
txHash: string;
|
||||
/** Paying wallet, when known. */
|
||||
payer?: string;
|
||||
/** Token symbol actually paid (USDC, USDG, USDC.e, pathUSD). */
|
||||
assetSymbol: string;
|
||||
buyer: BuyerDetails;
|
||||
}
|
||||
|
||||
export interface DeliveredArtifact {
|
||||
type: string;
|
||||
status: string;
|
||||
output?: Record<string, unknown>;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface AgentPurchaseResult {
|
||||
payment: Payment;
|
||||
entitlement: Entitlement;
|
||||
delivery: { runId: string | null; status: DeliveryRun["status"] | "none"; artifacts: DeliveredArtifact[] };
|
||||
settlement: { rail: AgentRail; network: PaymentNetwork; txHash: string; payer?: string; asset: string };
|
||||
}
|
||||
|
||||
const INLINE_RETRY = { maxAttempts: 2, baseDelayMs: 250 } as const;
|
||||
|
||||
function sameWallet(network: PaymentNetwork, a: string | undefined, b: string): boolean {
|
||||
if (a === undefined) return false;
|
||||
return network === "solana" ? a === b : a.toLowerCase() === b.toLowerCase();
|
||||
}
|
||||
|
||||
async function resolveCustomer(ctx: AppContext, input: AgentPurchaseInput): Promise<Customer> {
|
||||
const organizationId = input.product.organizationId;
|
||||
const payer = input.payer;
|
||||
if (payer) {
|
||||
const [existing] = await ctx.customers.list(
|
||||
(customer) => customer.organizationId === organizationId && sameWallet(input.network, customer.walletAddress, payer),
|
||||
);
|
||||
if (existing) return existing;
|
||||
}
|
||||
const customer: Customer = {
|
||||
id: generateId("customer"),
|
||||
organizationId,
|
||||
email: input.buyer.email ?? "",
|
||||
...(payer ? { walletAddress: payer } : {}),
|
||||
...(input.buyer.githubUsername ? { githubUsername: input.buyer.githubUsername } : {}),
|
||||
...(input.buyer.discordUserId ? { discordUserId: input.buyer.discordUserId } : {}),
|
||||
metadata: { source: `agent_${input.rail}`, network: input.network },
|
||||
createdAt: toIso(new Date()),
|
||||
};
|
||||
return ctx.customers.save(customer);
|
||||
}
|
||||
|
||||
/**
|
||||
* The GitHub App installation for GitHub actions: the product's pinned
|
||||
* `metadata.githubInstallationId`, else the org's connected installation,
|
||||
* else GITHUB_APP_INSTALLATION_ID.
|
||||
*/
|
||||
export async function githubInstallationFor(ctx: Pick<AppContext, "githubInstallations">, product: Product): Promise<number | undefined> {
|
||||
const pinned = product.metadata?.githubInstallationId;
|
||||
if (typeof pinned === "number" && Number.isInteger(pinned) && pinned > 0) return pinned;
|
||||
const [installation] = await ctx.githubInstallations.list((entry) => entry.organizationId === product.organizationId);
|
||||
if (installation) return installation.installationId;
|
||||
const fromEnv = Number(process.env.GITHUB_APP_INSTALLATION_ID);
|
||||
return Number.isInteger(fromEnv) && fromEnv > 0 ? fromEnv : undefined;
|
||||
}
|
||||
|
||||
async function runDelivery(
|
||||
ctx: AppContext,
|
||||
input: AgentPurchaseInput,
|
||||
payment: Payment,
|
||||
entitlement: Entitlement,
|
||||
): Promise<AgentPurchaseResult["delivery"]> {
|
||||
const actions = deliveryActionsFor(input.product);
|
||||
if (actions.length === 0) return { runId: null, status: "none", artifacts: [] };
|
||||
const plan: DeliveryPlan = {
|
||||
id: generateId("deliveryPlan"),
|
||||
organizationId: payment.organizationId,
|
||||
productId: input.product.id,
|
||||
actions,
|
||||
createdAt: toIso(new Date()),
|
||||
};
|
||||
const needsGithub = actions.some((action) => action.type === "github_invite" || action.type === "github_team_add");
|
||||
const githubInstallationId = needsGithub ? await githubInstallationFor(ctx, input.product) : undefined;
|
||||
const deliveryCtx: DeliveryContext = {
|
||||
organizationId: payment.organizationId,
|
||||
customerId: payment.customerId,
|
||||
productId: input.product.id,
|
||||
paymentId: payment.id,
|
||||
entitlementId: entitlement.id,
|
||||
...(githubInstallationId !== undefined ? { githubInstallationId } : {}),
|
||||
...(input.buyer.githubUsername ? { githubUsername: input.buyer.githubUsername } : {}),
|
||||
...(input.buyer.discordUserId ? { discordUserId: input.buyer.discordUserId } : {}),
|
||||
...(input.buyer.email ? { customerEmail: input.buyer.email } : {}),
|
||||
clients: ctx.deliveryClients,
|
||||
};
|
||||
const runner = new DeliveryRunner(ctx.deliveryRegistry, { retry: INLINE_RETRY });
|
||||
const run = await runner.run(plan, deliveryCtx, { paymentId: payment.id, customerId: payment.customerId });
|
||||
const saved = await ctx.deliveryRuns.save(run);
|
||||
return {
|
||||
runId: saved.id,
|
||||
status: saved.status,
|
||||
artifacts: saved.actionRuns.map((actionRun) => ({
|
||||
type: actionRun.action.type,
|
||||
status: actionRun.status,
|
||||
...(actionRun.output ? { output: actionRun.output } : {}),
|
||||
...(actionRun.lastError ? { error: actionRun.lastError } : {}),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Persist the payment. A concurrent request for the same tx hash that won the
|
||||
* race (Postgres unique index on tx_hash) surfaces as 409, never a second delivery.
|
||||
*/
|
||||
async function savePaymentOnce(ctx: AppContext, payment: Payment): Promise<Payment> {
|
||||
try {
|
||||
return await ctx.payments.save(payment);
|
||||
} catch (err) {
|
||||
const winner = payment.txHash ? await ctx.payments.findByTxHash(payment.txHash) : null;
|
||||
if (winner && winner.id !== payment.id) {
|
||||
throw conflict("transaction hash already used by another payment", { txHash: payment.txHash, paymentId: winner.id });
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/** Record, entitle and deliver a settled agent purchase. Throws 409 on a reused tx hash. */
|
||||
export async function fulfilAgentPurchase(ctx: AppContext, input: AgentPurchaseInput): Promise<AgentPurchaseResult> {
|
||||
const txHash = requireTxHash(input.network, input.txHash);
|
||||
await assertTxHashUnused(ctx, txHash);
|
||||
|
||||
const customer = await resolveCustomer(ctx, input);
|
||||
const amount = { amount: money(input.price.amount).amount, currency: input.price.currency } as Money;
|
||||
const pending = recordPendingPayment({
|
||||
organizationId: input.product.organizationId,
|
||||
checkoutSessionId: `${input.rail}:${input.network}:${txHash}`,
|
||||
customerId: customer.id,
|
||||
amount,
|
||||
network: input.network,
|
||||
txHash,
|
||||
});
|
||||
// The facilitator / MPP verifier already waited for the settlement receipt.
|
||||
const payment = await savePaymentOnce(ctx, confirmPayment(pending, txHash, 1, 1));
|
||||
const entitlement = await ctx.entitlements.grantFromPayment({
|
||||
payment,
|
||||
product: input.product,
|
||||
...(input.price.creditsGranted !== undefined ? { creditsRemaining: input.price.creditsGranted } : {}),
|
||||
});
|
||||
const delivery = await runDelivery(ctx, input, payment, entitlement);
|
||||
await emitWebhook(
|
||||
ctx.webhookOutbox,
|
||||
paymentConfirmedWebhook(payment, { productIds: [input.product.id], ...(customer.email ? { customerEmail: customer.email } : {}) }),
|
||||
);
|
||||
return {
|
||||
payment,
|
||||
entitlement,
|
||||
delivery,
|
||||
settlement: {
|
||||
rail: input.rail,
|
||||
network: input.network,
|
||||
txHash,
|
||||
...(input.payer ? { payer: input.payer } : {}),
|
||||
asset: input.assetSymbol,
|
||||
},
|
||||
};
|
||||
}
|
||||
@ -1,75 +0,0 @@
|
||||
/**
|
||||
* Machine Payments Protocol (MPP) runtime for Tempo, via `mppx` (wevm, MIT).
|
||||
*
|
||||
* The agent pays a TIP-20 transfer on Tempo (USDC.e on mainnet, pathUSD on
|
||||
* Moderato) and presents the credential in `Authorization: Payment ...`;
|
||||
* mppx verifies the transfer on-chain (amount, currency, recipient, memo
|
||||
* binding, success, replay) and returns a receipt whose `reference` is the
|
||||
* transaction hash.
|
||||
*
|
||||
* MPP_SECRET_KEY >= 32 bytes; binds challenges (required to enable)
|
||||
* MPP_TEMPO_RECIPIENT merchant address (falls back to X402_PAY_TO_TEMPO / X402_EVM_PAY_TO)
|
||||
* MPP_REALM challenge realm (default "settlekit")
|
||||
* TEMPO_NETWORK / SETTLEKIT_CHAIN_ENV mainnet (USDC.e) | testnet (Moderato pathUSD)
|
||||
*/
|
||||
import { checkPayTo, getEvmChain, parseChainEnv, readEnv, type ChainEnv, type Env } from "@settlekit/chains";
|
||||
import type { Method } from "mppx";
|
||||
import { tempo } from "mppx/server";
|
||||
|
||||
export interface MppRuntime {
|
||||
secretKey: string;
|
||||
realm: string;
|
||||
env: ChainEnv;
|
||||
chainId: number;
|
||||
/** TIP-20 token address the charge is denominated in. */
|
||||
currency: string;
|
||||
symbol: string;
|
||||
decimals: number;
|
||||
recipient: string;
|
||||
/** The server charge method (real `tempo.charge` in production; injectable). */
|
||||
charge: Method.AnyServer;
|
||||
}
|
||||
|
||||
const MIN_SECRET_BYTES = 32;
|
||||
|
||||
/** Build the MPP runtime from env, or null (with a note) when not configured. */
|
||||
export function buildMppRuntime(env: Env, notes: string[]): MppRuntime | null {
|
||||
const secretKey = readEnv(env, "MPP_SECRET_KEY");
|
||||
if (secretKey === undefined) return null;
|
||||
if (Buffer.byteLength(secretKey) < MIN_SECRET_BYTES) {
|
||||
notes.push(`mpp: MPP_SECRET_KEY must be at least ${MIN_SECRET_BYTES} bytes`);
|
||||
return null;
|
||||
}
|
||||
const chainEnv =
|
||||
parseChainEnv(readEnv(env, "TEMPO_NETWORK"), "TEMPO_NETWORK") ??
|
||||
parseChainEnv(readEnv(env, "SETTLEKIT_CHAIN_ENV"), "SETTLEKIT_CHAIN_ENV") ??
|
||||
"testnet";
|
||||
const spec = getEvmChain("tempo", chainEnv);
|
||||
if (!spec) {
|
||||
notes.push(`mpp: no Tempo chain for ${chainEnv}`);
|
||||
return null;
|
||||
}
|
||||
const recipient =
|
||||
readEnv(env, "MPP_TEMPO_RECIPIENT") ?? readEnv(env, "X402_PAY_TO_TEMPO") ?? readEnv(env, "X402_EVM_PAY_TO");
|
||||
if (recipient === undefined || !checkPayTo("tempo", recipient).ok) {
|
||||
notes.push("mpp: set a valid MPP_TEMPO_RECIPIENT");
|
||||
return null;
|
||||
}
|
||||
const charge = tempo.charge({
|
||||
currency: spec.token.address,
|
||||
decimals: spec.token.decimals,
|
||||
recipient: recipient as `0x${string}`,
|
||||
testnet: chainEnv === "testnet",
|
||||
});
|
||||
return {
|
||||
secretKey,
|
||||
realm: readEnv(env, "MPP_REALM") ?? "settlekit",
|
||||
env: chainEnv,
|
||||
chainId: spec.chainId,
|
||||
currency: spec.token.address,
|
||||
symbol: spec.token.symbol,
|
||||
decimals: spec.token.decimals,
|
||||
recipient,
|
||||
charge: charge as unknown as Method.AnyServer,
|
||||
};
|
||||
}
|
||||
@ -1,59 +0,0 @@
|
||||
/**
|
||||
* Everything an agent purchase must satisfy BEFORE a payment challenge is
|
||||
* issued or settled: the product exists and is published, it has a one-time
|
||||
* fixed price, and the buyer supplied every identity its delivery needs.
|
||||
* Failing here costs the agent nothing.
|
||||
*/
|
||||
import { z } from "zod";
|
||||
import { notFound, validationError, type Price, type Product } from "@settlekit/common";
|
||||
import type { AppContext } from "../context.js";
|
||||
import { deliveryActionsFor, requiredBuyerFields } from "./delivery-action.js";
|
||||
import type { BuyerDetails } from "./fulfil.js";
|
||||
|
||||
export const buyerSchema = z
|
||||
.object({
|
||||
email: z.string().email().optional(),
|
||||
githubUsername: z.string().regex(/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/, "must be a GitHub login").optional(),
|
||||
discordUserId: z.string().regex(/^\d{5,25}$/, "must be a Discord user id").optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export interface Purchasable {
|
||||
product: Product;
|
||||
price: Price;
|
||||
buyer: BuyerDetails;
|
||||
}
|
||||
|
||||
/** Parse the optional JSON body of a buy request (empty body = no buyer details). */
|
||||
export async function readBuyer(request: Request): Promise<BuyerDetails> {
|
||||
const text = await request.clone().text();
|
||||
if (text.trim().length === 0) return {};
|
||||
let raw: unknown;
|
||||
try {
|
||||
raw = JSON.parse(text);
|
||||
} catch {
|
||||
throw validationError("request body must be JSON");
|
||||
}
|
||||
const parsed = buyerSchema.safeParse(raw);
|
||||
if (!parsed.success) {
|
||||
throw validationError("invalid buyer details", { issues: parsed.error.issues.map((issue) => issue.message) });
|
||||
}
|
||||
return Object.fromEntries(Object.entries(parsed.data).filter(([, value]) => value !== undefined)) as BuyerDetails;
|
||||
}
|
||||
|
||||
/** Resolve the product, its one-time price and validated buyer details. */
|
||||
export async function resolvePurchasable(ctx: AppContext, productId: string, buyer: BuyerDetails): Promise<Purchasable> {
|
||||
const product = await ctx.products.findById(productId);
|
||||
if (!product || product.status !== "active") throw notFound("product not found", { id: productId });
|
||||
const prices = await ctx.prices.list(
|
||||
(price) => price.productId === productId && price.active && price.interval === "one_time" && !price.usageBased,
|
||||
);
|
||||
const price = prices.sort((a, b) => a.createdAt.localeCompare(b.createdAt))[0];
|
||||
if (!price) throw validationError("product has no active one-time price", { id: productId });
|
||||
|
||||
const missing = requiredBuyerFields(deliveryActionsFor(product)).filter((field) => buyer[field] === undefined);
|
||||
if (missing.length > 0) {
|
||||
throw validationError(`delivery of this product needs: ${missing.join(", ")}`, { missing });
|
||||
}
|
||||
return { product, price, buyer };
|
||||
}
|
||||
@ -1,132 +0,0 @@
|
||||
/**
|
||||
* "Settle first, then deliver" x402 middleware for purchases.
|
||||
*
|
||||
* `@x402/hono`'s `paymentMiddleware` verifies, runs the handler and settles
|
||||
* AFTER it (right for metered content). A purchase must never deliver an
|
||||
* artifact for a payment that has not settled, so this middleware drives the
|
||||
* same `x402HTTPResourceServer` with the `upfront` payment flow: the
|
||||
* facilitator settles BEFORE the handler, the handler reads the settlement
|
||||
* (`c.get("x402Settled")`) to record the payment and deliver, and the
|
||||
* PAYMENT-RESPONSE receipt is echoed on whatever the handler returns.
|
||||
*/
|
||||
import type { Context, MiddlewareHandler } from "hono";
|
||||
import { basePath } from "hono/route";
|
||||
import { HonoAdapter } from "@x402/hono";
|
||||
import {
|
||||
getFacilitatorResponseError,
|
||||
type HTTPRequestContext,
|
||||
type x402HTTPResourceServer,
|
||||
} from "@x402/core/server";
|
||||
import type { PaymentPayload, PaymentRequirements, SettleResponse } from "@x402/core/types";
|
||||
|
||||
/** Hono adapter that keeps the Hono context reachable from dynamic prices. */
|
||||
export class ContextAdapter extends HonoAdapter {
|
||||
constructor(readonly context: Context) {
|
||||
super(context);
|
||||
}
|
||||
}
|
||||
|
||||
export interface SettledPayment {
|
||||
payload: PaymentPayload;
|
||||
requirements: PaymentRequirements;
|
||||
settlement: SettleResponse;
|
||||
}
|
||||
|
||||
export interface SettleFirstVariables {
|
||||
x402Settled?: SettledPayment;
|
||||
}
|
||||
|
||||
function decodedRoutePath(c: Context): string {
|
||||
let path: string;
|
||||
try {
|
||||
path = decodeURIComponent(c.req.path);
|
||||
} catch {
|
||||
path = c.req.path;
|
||||
}
|
||||
let root = "";
|
||||
try {
|
||||
root = basePath(c);
|
||||
} catch {
|
||||
return path;
|
||||
}
|
||||
if (!root || root === "/" || !path.startsWith(root)) return path;
|
||||
if (path === root) return "";
|
||||
return path[root.length] === "/" ? path.slice(root.length) : path;
|
||||
}
|
||||
|
||||
function withHeaders(res: Response, headers: Record<string, string>): Response {
|
||||
const merged = new Headers(res.headers);
|
||||
for (const [key, value] of Object.entries(headers)) merged.set(key, value);
|
||||
return new Response(res.body, { status: res.status, statusText: res.statusText, headers: merged });
|
||||
}
|
||||
|
||||
/** Build the middleware. Routes it guards must declare `extra.paymentFlow: "upfront"`. */
|
||||
export function settleFirstPayment(httpServer: x402HTTPResourceServer): MiddlewareHandler {
|
||||
let init: Promise<void> | null = null;
|
||||
const initialize = async (): Promise<void> => {
|
||||
init ??= httpServer.initialize();
|
||||
try {
|
||||
await init;
|
||||
} catch (error) {
|
||||
init = null;
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
return async (c, next) => {
|
||||
const adapter = new ContextAdapter(c);
|
||||
const context: HTTPRequestContext = {
|
||||
adapter,
|
||||
path: c.req.path,
|
||||
decodedPath: decodedRoutePath(c),
|
||||
method: c.req.method,
|
||||
...(adapter.getHeader("payment-signature") ?? adapter.getHeader("x-payment")
|
||||
? { paymentHeader: (adapter.getHeader("payment-signature") ?? adapter.getHeader("x-payment")) as string }
|
||||
: {}),
|
||||
};
|
||||
if (!httpServer.requiresPayment(context)) return next();
|
||||
|
||||
let result: Awaited<ReturnType<x402HTTPResourceServer["processHTTPRequest"]>>;
|
||||
try {
|
||||
await initialize();
|
||||
result = await httpServer.processHTTPRequest(context);
|
||||
} catch (error) {
|
||||
const facilitatorError = getFacilitatorResponseError(error);
|
||||
if (facilitatorError) return c.json({ error: { code: "facilitator_error", message: facilitatorError.message } }, 502);
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (result.type === "no-payment-required") return next();
|
||||
if (result.type === "payment-error") {
|
||||
const { response } = result;
|
||||
for (const [key, value] of Object.entries(response.headers)) c.header(key, value);
|
||||
if (response.isHtml) return c.html(String(response.body ?? ""), response.status as 402);
|
||||
return c.json(response.body ?? {}, response.status as 402);
|
||||
}
|
||||
|
||||
const settled = result.beforeHandlerSettlement;
|
||||
if (!settled || !settled.result.success) {
|
||||
await result.cancellationDispatcher.cancel({ reason: "after_verify_aborted" });
|
||||
return c.json({ error: { code: "configuration_error", message: "purchase routes must settle before delivery" } }, 500);
|
||||
}
|
||||
c.set("x402Settled" as never, {
|
||||
payload: result.paymentPayload,
|
||||
requirements: settled.requirements,
|
||||
settlement: settled.result,
|
||||
} satisfies SettledPayment as never);
|
||||
|
||||
try {
|
||||
await next();
|
||||
} finally {
|
||||
const echo = await httpServer.processSettlement(
|
||||
result.paymentPayload,
|
||||
result.paymentRequirements,
|
||||
result.declaredExtensions,
|
||||
{ request: context },
|
||||
undefined,
|
||||
settled,
|
||||
);
|
||||
c.res = withHeaders(c.res, echo.headers);
|
||||
}
|
||||
};
|
||||
}
|
||||
@ -1,36 +0,0 @@
|
||||
/**
|
||||
* A payment settled on-chain but fulfilment then failed unexpectedly (not a
|
||||
* domain error such as a reused tx hash). Money has moved, so the settlement
|
||||
* must never be lost silently: emit a structured error line for
|
||||
* reconciliation and hand the agent the transaction so it can prove payment.
|
||||
*/
|
||||
import type { Context } from "hono";
|
||||
import { SettleKitError } from "@settlekit/common";
|
||||
import { error } from "../http/respond.js";
|
||||
|
||||
export interface SettlementRef {
|
||||
rail: "x402" | "mpp";
|
||||
network: string;
|
||||
txHash: string;
|
||||
productId: string;
|
||||
payer?: string;
|
||||
}
|
||||
|
||||
/** Map a fulfilment error to a response, logging settled-but-unfulfilled payments. */
|
||||
export function fulfilmentError(c: Context, err: unknown, settlement: SettlementRef): Response {
|
||||
if (SettleKitError.is(err)) return error(c, err);
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
process.stderr.write(
|
||||
`${JSON.stringify({ ts: new Date().toISOString(), app: "api", level: "error", msg: "agent purchase settled but not fulfilled", ...settlement, error: message })}\n`,
|
||||
);
|
||||
return c.json(
|
||||
{
|
||||
error: {
|
||||
code: "fulfilment_failed",
|
||||
message: "payment settled but fulfilment failed; it has been logged for reconciliation",
|
||||
details: { ...settlement },
|
||||
},
|
||||
},
|
||||
500,
|
||||
);
|
||||
}
|
||||
@ -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,
|
||||
},
|
||||
};
|
||||
}
|
||||
@ -34,8 +34,6 @@ import { saasRoutes } from "./routes/saas.js";
|
||||
import { bundleRoutes } from "./routes/bundles.js";
|
||||
import { deliveryRunRoutes, deliveryActionRoutes } from "./routes/delivery.js";
|
||||
import { agentServiceRoutes } from "./routes/agent-services.js";
|
||||
import { agentRoutes } from "./routes/agents.js";
|
||||
import { jobRoutes } from "./routes/jobs.js";
|
||||
import { marketplaceRoutes } from "./routes/marketplace.js";
|
||||
import { usageRoutes } from "./routes/usage.js";
|
||||
import { analyticsRoutes } from "./routes/analytics.js";
|
||||
@ -45,9 +43,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 +59,6 @@ import { onchainEscrowRoutes } from "./routes/onchain-escrow.js";
|
||||
import { authRoutes } from "./routes/auth.js";
|
||||
import { leptonRoutes } from "./routes/lepton.js";
|
||||
import { fundRoutes } from "./routes/fund.js";
|
||||
import { merchantRoutes } from "./routes/merchant.js";
|
||||
import { publicRoutes } from "./routes/public.js";
|
||||
import { x402AgentRoutes } from "./routes/x402-agent.js";
|
||||
import { mppTempoRoutes } from "./routes/mpp-tempo.js";
|
||||
import { onchainBillingRoutes } from "./routes/onchain-billing.js";
|
||||
import { operatorRoutes } from "./routes/operator.js";
|
||||
|
||||
/** Build the full SettleKit API app. Pass a context to share/isolate state. */
|
||||
export function createApp(ctx: AppContext): Hono<AppEnv> {
|
||||
@ -123,10 +112,6 @@ export function createApp(ctx: AppContext): Hono<AppEnv> {
|
||||
// are mounted outside the API-key guard (humans + AI agents pay per call).
|
||||
app.route("/v1/paid", x402Routes());
|
||||
|
||||
// Agent payments are PUBLIC too: x402 v2 on every chain + MPP on Tempo.
|
||||
app.route("/v1/x402", x402AgentRoutes(ctx.agentPayments));
|
||||
app.route("/v1/mpp", mppTempoRoutes(ctx.agentPayments));
|
||||
|
||||
// Lepton hackathon demo is PUBLIC: self-contained, in-memory nanopayment
|
||||
// modules (agent economy, citation tolls, streaming). No API key, no DB.
|
||||
app.route("/v1/lepton", leptonRoutes());
|
||||
@ -140,11 +125,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>();
|
||||
@ -182,8 +162,6 @@ export function createApp(ctx: AppContext): Hono<AppEnv> {
|
||||
|
||||
// ---- Agent services (plan §26) -----------------------------------------
|
||||
v1.route("/agent-services", agentServiceRoutes());
|
||||
v1.route("/agents", agentRoutes());
|
||||
v1.route("/jobs", jobRoutes());
|
||||
|
||||
// ---- Marketplace (plan §11) --------------------------------------------
|
||||
v1.route("/marketplace", marketplaceRoutes());
|
||||
@ -197,13 +175,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 +184,6 @@ export function createApp(ctx: AppContext): Hono<AppEnv> {
|
||||
// ---- Commerce engines: coupons + invoices ------------------------------
|
||||
v1.route("/coupons", couponRoutes());
|
||||
v1.route("/invoices", invoiceRoutes());
|
||||
// SettleKit's own fee statements for this merchant (platform revenue).
|
||||
v1.route("/billing", billingRoutes());
|
||||
// Accounting exports (CSV, Xero / QuickBooks bank statement imports).
|
||||
v1.route("/exports", exportRoutes());
|
||||
|
||||
// ---- Commerce engines: refunds, dunning, disputes, payouts -------------
|
||||
v1.route("/refunds", refundRoutes());
|
||||
@ -228,7 +197,6 @@ export function createApp(ctx: AppContext): Hono<AppEnv> {
|
||||
v1.route("/mint", mintRoutes());
|
||||
v1.route("/user-wallets", userWalletRoutes());
|
||||
v1.route("/onchain-escrow", onchainEscrowRoutes());
|
||||
v1.route("/onchain-billing", onchainBillingRoutes());
|
||||
// paymaster + gas-station share one router (paths are /paymaster/* and /gas-station/*).
|
||||
v1.route("/", paymasterRoutes());
|
||||
|
||||
|
||||
@ -24,8 +24,6 @@ export function circleChainForNetwork(network: string, defaultChain: string): st
|
||||
return "BASE";
|
||||
case "ethereum":
|
||||
return "ETH";
|
||||
case "solana":
|
||||
return "SOL";
|
||||
default:
|
||||
// Arc (and anything else Circle does not list) screens against the
|
||||
// configured default chain — sanctions hits are address-, not chain-, scoped.
|
||||
|
||||
@ -1,24 +0,0 @@
|
||||
/**
|
||||
* Boot-time chain-id assertion: every enabled EVM chain's RPC must serve the
|
||||
* chain the registry says it does. A mismatch refuses to boot (a mis-pointed
|
||||
* RPC could otherwise confirm payments made on another chain). An unreachable
|
||||
* RPC only warns: each verifier re-asserts the chain id before it verifies,
|
||||
* so payments on that chain fail closed until the RPC answers correctly.
|
||||
*/
|
||||
import { checkEvmChainIds, type EvmVerifier } from "@settlekit/chains";
|
||||
|
||||
export type BootLog = (message: string, fields: Record<string, unknown>) => void;
|
||||
|
||||
export async function assertChainIdsAtBoot(verifiers: readonly EvmVerifier[], log: BootLog): Promise<void> {
|
||||
const results = await checkEvmChainIds(verifiers);
|
||||
const mismatched = results.filter((result) => result.mismatch);
|
||||
if (mismatched.length > 0) {
|
||||
throw new Error(
|
||||
`Refusing to boot: RPC chain id mismatch for ${mismatched.map((r) => `${r.key} (${r.error ?? "mismatch"})`).join(", ")}`,
|
||||
);
|
||||
}
|
||||
for (const result of results) {
|
||||
if (!result.ok) log("evm rpc unreachable at boot; chain fails closed until it answers", { chain: result.key, error: result.error });
|
||||
}
|
||||
log("evm chains verified", { chains: results.filter((r) => r.ok).map((r) => r.key) });
|
||||
}
|
||||
@ -1,35 +0,0 @@
|
||||
/**
|
||||
* Multi-chain configuration for the API: the enabled EVM chains (see
|
||||
* `loadEvmChains` in @settlekit/chains — SETTLEKIT_CHAIN_ENV,
|
||||
* ENABLED_EVM_CHAINS, per-chain RPC/NETWORK/MIN_CONFIRMATIONS, and the
|
||||
* BASE_RPC_URL / ARC_CHAIN_ID aliases), transparent Zcash and HyperCore
|
||||
* (HYPERCORE_ENABLED / HYPERCORE_NETWORK / HYPERCORE_API_URL). Chain config
|
||||
* errors surface as {@link ConfigError} so boot fails fast.
|
||||
*/
|
||||
|
||||
import {
|
||||
ChainConfigError,
|
||||
loadEvmChains,
|
||||
loadZcashConfig,
|
||||
type EvmChainsConfig,
|
||||
type ZcashConfig,
|
||||
} from "@settlekit/chains";
|
||||
import { loadHyperCoreConfig, type HyperCoreConfig } from "@settlekit/hyperliquid";
|
||||
import { ConfigError } from "./errors.js";
|
||||
|
||||
export interface ChainGroups {
|
||||
evm: EvmChainsConfig;
|
||||
zcash: ZcashConfig | null;
|
||||
hypercore: HyperCoreConfig | null;
|
||||
}
|
||||
|
||||
type Env = Record<string, string | undefined>;
|
||||
|
||||
export function loadChainGroups(env: Env): ChainGroups {
|
||||
try {
|
||||
return { evm: loadEvmChains(env), zcash: loadZcashConfig(env), hypercore: loadHyperCoreConfig(env) };
|
||||
} catch (error) {
|
||||
if (error instanceof ChainConfigError) throw new ConfigError(error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@ -12,19 +12,14 @@
|
||||
*/
|
||||
|
||||
import { getArcChain, isArcAddress, type ArcAddress } from "@settlekit/arc";
|
||||
import {
|
||||
getSolanaCluster,
|
||||
isSolanaAddress,
|
||||
parseSolanaCluster,
|
||||
type SolanaCluster,
|
||||
} from "@settlekit/solana";
|
||||
|
||||
import type { EvmChainsConfig, ZcashConfig } from "@settlekit/chains";
|
||||
import type { HyperCoreConfig } from "@settlekit/hyperliquid";
|
||||
import { ConfigError } from "./errors.js";
|
||||
import { loadChainGroups } from "./chain-env.js";
|
||||
|
||||
export { ConfigError };
|
||||
/** Raised when an environment group is partially set or a value is malformed. */
|
||||
export class ConfigError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = "ConfigError";
|
||||
}
|
||||
}
|
||||
|
||||
type Env = Record<string, string | undefined>;
|
||||
|
||||
@ -42,29 +37,6 @@ export interface ArcConfig {
|
||||
minConfirmations: number;
|
||||
}
|
||||
|
||||
/** Base mainnet chain id and its native Circle USDC contract. */
|
||||
export const BASE_CHAIN_ID = 8453;
|
||||
export const BASE_USDC_ADDRESS: ArcAddress = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
|
||||
|
||||
/**
|
||||
* Legacy Base group, enabled by BASE_RPC_URL (Base mainnet). Verification now
|
||||
* runs from {@link ApiConfig.evm}, where BASE_RPC_URL is an alias for
|
||||
* enabling Base.
|
||||
*/
|
||||
export interface BaseConfig {
|
||||
rpcUrl: string;
|
||||
usdcAddress: ArcAddress;
|
||||
chainId: number;
|
||||
minConfirmations: number;
|
||||
}
|
||||
|
||||
/** Solana USDC verification reader, enabled by SOLANA_CLUSTER. */
|
||||
export interface SolanaConfig {
|
||||
cluster: SolanaCluster;
|
||||
rpcUrl: string;
|
||||
usdcMint: string;
|
||||
}
|
||||
|
||||
/** Circle REST client configuration. */
|
||||
export interface CircleConfig {
|
||||
apiKey: string;
|
||||
@ -166,14 +138,6 @@ export interface ApiConfig {
|
||||
/** Optional integration groups — null when their creds are absent. */
|
||||
database: DatabaseConfig | null;
|
||||
arc: ArcConfig | null;
|
||||
base: BaseConfig | null;
|
||||
/** Enabled EVM chains for payment verification (others fail closed). */
|
||||
evm: EvmChainsConfig;
|
||||
/** Transparent Zcash settlement; null unless ZCASH_ENABLED. */
|
||||
zcash: ZcashConfig | null;
|
||||
/** HyperCore USDC settlement; null unless HYPERCORE_ENABLED. */
|
||||
hypercore: HyperCoreConfig | null;
|
||||
solana: SolanaConfig | null;
|
||||
circle: CircleConfig | null;
|
||||
circleWallets: CircleWalletsConfig | null;
|
||||
gasStation: GasStationConfig | null;
|
||||
@ -187,10 +151,6 @@ export interface ApiConfig {
|
||||
/** Presence flags derived from the groups above. */
|
||||
hasDatabase: boolean;
|
||||
hasArc: boolean;
|
||||
hasBase: boolean;
|
||||
hasZcash: boolean;
|
||||
hasHyperCore: boolean;
|
||||
hasSolana: boolean;
|
||||
hasCircle: boolean;
|
||||
hasCircleWallets: boolean;
|
||||
hasGasStation: boolean;
|
||||
@ -302,41 +262,6 @@ function loadArc(env: Env): ArcConfig | null {
|
||||
};
|
||||
}
|
||||
|
||||
function loadBase(env: Env): BaseConfig | null {
|
||||
const rpcUrl = optionalRaw(env, "BASE_RPC_URL");
|
||||
if (rpcUrl === undefined) return null;
|
||||
return {
|
||||
rpcUrl,
|
||||
usdcAddress: BASE_USDC_ADDRESS,
|
||||
chainId: BASE_CHAIN_ID,
|
||||
minConfirmations: intInRange(env, "BASE_MIN_CONFIRMATIONS", 3, 1, 1_000),
|
||||
};
|
||||
}
|
||||
|
||||
function loadSolana(env: Env): SolanaConfig | null {
|
||||
// Enabled by SOLANA_CLUSTER (mainnet | mainnet-beta | devnet). The RPC URL
|
||||
// and USDC mint default from the cluster; override them for a dedicated RPC
|
||||
// (e.g. Helius). Setting an override without a cluster is a misconfiguration.
|
||||
const clusterRaw = optionalRaw(env, "SOLANA_CLUSTER");
|
||||
if (clusterRaw === undefined) {
|
||||
const stray = presentKeys(env, ["SOLANA_RPC_URL", "SOLANA_USDC_MINT"]);
|
||||
if (stray.length > 0) {
|
||||
throw new ConfigError(`Incomplete solana configuration: set [SOLANA_CLUSTER] or unset [${stray.join(", ")}]`);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
const cluster = parseSolanaCluster(clusterRaw);
|
||||
if (cluster === undefined) {
|
||||
throw new ConfigError(`Environment variable SOLANA_CLUSTER must be mainnet or devnet, got "${clusterRaw}"`);
|
||||
}
|
||||
const known = getSolanaCluster(cluster);
|
||||
const usdcMint = optionalRaw(env, "SOLANA_USDC_MINT") ?? known.usdcMint;
|
||||
if (!isSolanaAddress(usdcMint)) {
|
||||
throw new ConfigError("Environment variable SOLANA_USDC_MINT must be a base58 Solana address");
|
||||
}
|
||||
return { cluster, rpcUrl: optionalRaw(env, "SOLANA_RPC_URL") ?? known.rpcUrl, usdcMint };
|
||||
}
|
||||
|
||||
function loadCircle(env: Env): CircleConfig | null {
|
||||
if (requireComplete("circle", env, ["CIRCLE_API_KEY"]) === "absent") return null;
|
||||
const baseUrl = optionalRaw(env, "CIRCLE_BASE_URL");
|
||||
@ -512,9 +437,6 @@ function assertProductionReady(
|
||||
export function loadConfig(env: Env = process.env): ApiConfig {
|
||||
const database = loadDatabase(env);
|
||||
const arc = loadArc(env);
|
||||
const base = loadBase(env);
|
||||
const chains = loadChainGroups(env);
|
||||
const solana = loadSolana(env);
|
||||
const circle = loadCircle(env);
|
||||
const circleWallets = loadCircleWallets(env);
|
||||
const gasStation = loadGasStation(env);
|
||||
@ -543,11 +465,6 @@ export function loadConfig(env: Env = process.env): ApiConfig {
|
||||
|
||||
database,
|
||||
arc,
|
||||
base,
|
||||
evm: chains.evm,
|
||||
zcash: chains.zcash,
|
||||
hypercore: chains.hypercore,
|
||||
solana,
|
||||
circle,
|
||||
circleWallets,
|
||||
gasStation,
|
||||
@ -560,10 +477,6 @@ export function loadConfig(env: Env = process.env): ApiConfig {
|
||||
|
||||
hasDatabase: database !== null,
|
||||
hasArc: arc !== null,
|
||||
hasBase: base !== null,
|
||||
hasZcash: chains.zcash !== null,
|
||||
hasHyperCore: chains.hypercore !== null,
|
||||
hasSolana: solana !== null,
|
||||
hasCircle: circle !== null,
|
||||
hasCircleWallets: circleWallets !== null,
|
||||
hasGasStation: gasStation !== null,
|
||||
|
||||
@ -1,7 +0,0 @@
|
||||
/** Raised when an environment group is partially set or a value is malformed. */
|
||||
export class ConfigError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = "ConfigError";
|
||||
}
|
||||
}
|
||||
@ -11,9 +11,14 @@
|
||||
* have stores can pass their own sink via {@link BuildIntegrationsOptions}.
|
||||
*/
|
||||
|
||||
import { type DiscordRoleGrant, type GitHubRepoAccessGrant } from "@settlekit/common";
|
||||
import { createArcClient, type ArcClient } from "@settlekit/arc";
|
||||
import type { EvmVerifier } from "@settlekit/chains";
|
||||
import { money, type DiscordRoleGrant, type GitHubRepoAccessGrant } from "@settlekit/common";
|
||||
import {
|
||||
createArcClient,
|
||||
getArcChain,
|
||||
isArcAsset,
|
||||
type ArcAddress,
|
||||
type ArcClient,
|
||||
} from "@settlekit/arc";
|
||||
import { createWalletsClient } from "@settlekit/circle-wallets";
|
||||
import { createScreeningClient, type ScreeningClient } from "@settlekit/compliance";
|
||||
import {
|
||||
@ -35,15 +40,6 @@ import type { DeliveryClients } from "@settlekit/delivery";
|
||||
import type { PaymentVerifier } from "@settlekit/x402";
|
||||
import type { ApiConfig } from "./env.js";
|
||||
import {
|
||||
buildVerifierRegistry,
|
||||
type PaymentVerifiers,
|
||||
type VerifierRegistryDeps,
|
||||
type ZcashRuntime,
|
||||
} from "./verifier-registry.js";
|
||||
|
||||
export type { PaymentVerifiers, ZcashRuntime } from "./verifier-registry.js";
|
||||
import {
|
||||
buildDiscordClient,
|
||||
createDeliveryClients,
|
||||
type DeliveryGrantSink,
|
||||
} from "../wiring/delivery-clients.js";
|
||||
@ -61,15 +57,6 @@ export interface Integrations {
|
||||
discordApi: DiscordApi;
|
||||
/** Arc settlement verifier for x402 paid calls, or null when Arc is unset. */
|
||||
arcVerifier: PaymentVerifier | null;
|
||||
/**
|
||||
* On-chain payment verifiers keyed by network. A network with no entry has
|
||||
* NO way to confirm payments: confirm/observe fail closed for it.
|
||||
*/
|
||||
verifiers: PaymentVerifiers;
|
||||
/** Raw EVM verifiers, for the boot-time chain-id assertion. */
|
||||
evmVerifiers: readonly EvmVerifier[];
|
||||
/** Zcash quote + explorer services, or null when Zcash is disabled. */
|
||||
zcash: ZcashRuntime | null;
|
||||
/** Raw Arc client (verify / fee-estimate / confirmations), or null when unset. */
|
||||
arc: ArcClient | null;
|
||||
/** Real Circle REST client, or null when Circle is unset. */
|
||||
@ -94,8 +81,6 @@ export interface BuildIntegrationsOptions {
|
||||
licenseStore?: LicenseStore;
|
||||
apiKeyStore?: ApiKeyStore;
|
||||
fileGrantStore?: GrantStore;
|
||||
/** Inject chain RPCs / fetch for the verifier registry (tests). */
|
||||
chains?: VerifierRegistryDeps;
|
||||
}
|
||||
|
||||
/** A `DeliveryGrantSink` backed by plain in-memory maps. */
|
||||
@ -124,6 +109,59 @@ function createInMemoryGrantSink(): DeliveryGrantSink {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Build an x402 {@link PaymentVerifier} over a real {@link ArcClient}. Confirms
|
||||
* the proof's transaction transferred at least the advertised amount to the
|
||||
* configured `payTo` address with enough confirmations.
|
||||
*/
|
||||
function buildArcVerifier(arc: ArcClient, minConfirmations: number): PaymentVerifier {
|
||||
const chain = getArcChain(arc.config.chainId);
|
||||
|
||||
return async (proof, requirements) => {
|
||||
if (proof.network !== "arc") {
|
||||
return { ok: false, reason: `Unsupported network: ${proof.network}` };
|
||||
}
|
||||
if (!/^0x[a-fA-F0-9]{64}$/.test(proof.txHash)) {
|
||||
return { ok: false, reason: "Malformed transaction hash" };
|
||||
}
|
||||
|
||||
const txHash = proof.txHash as `0x${string}`;
|
||||
const to = requirements.payTo as ArcAddress;
|
||||
const minAmount = money(requirements.amount, requirements.asset);
|
||||
// Widen to string: requirements.asset is typed as the literal "USDC", but
|
||||
// EURC/USYC settlements flow through the same verifier at runtime.
|
||||
const asset: string = requirements.asset;
|
||||
|
||||
// Resolve which token to look for. USDC uses the configured USDC address;
|
||||
// other Arc stablecoins (EURC/USYC) resolve their contract from the chain
|
||||
// definition so they settle through the same on-chain verification path.
|
||||
let result;
|
||||
if (asset === "USDC") {
|
||||
result = await arc.verifyUsdcTransfer({ txHash, to, minAmount });
|
||||
} else if (chain && isArcAsset(asset) && chain.tokens[asset]) {
|
||||
result = await arc.verifyTokenTransfer({
|
||||
txHash,
|
||||
token: chain.tokens[asset].address,
|
||||
to,
|
||||
minAmount,
|
||||
});
|
||||
} else {
|
||||
return { ok: false, reason: `Unsupported settlement asset on Arc: ${asset}` };
|
||||
}
|
||||
|
||||
if (!result.confirmed) {
|
||||
return { ok: false, reason: `No matching ${asset} transfer found` };
|
||||
}
|
||||
if (result.confirmations < minConfirmations) {
|
||||
return {
|
||||
ok: false,
|
||||
reason: `Insufficient confirmations: ${result.confirmations} < ${minConfirmations}`,
|
||||
};
|
||||
}
|
||||
return { ok: true };
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct the full set of {@link Integrations} from an {@link ApiConfig}.
|
||||
* Each group falls back to its in-memory double when its creds are absent.
|
||||
@ -181,15 +219,11 @@ export function buildIntegrations(
|
||||
: {}),
|
||||
});
|
||||
} else {
|
||||
const inMemory = createInMemoryDeliveryClients({
|
||||
deliveryClients = createInMemoryDeliveryClients({
|
||||
licenseTokenSecret: config.licenseTokenSecret,
|
||||
fileDelivery: config.fileDelivery,
|
||||
...sharedStores,
|
||||
});
|
||||
// A configured Discord bot grants real roles even before GitHub is set up.
|
||||
deliveryClients = config.discord
|
||||
? { ...inMemory, discord: buildDiscordClient({ discordApi, grants: options.grantSink ?? createInMemoryGrantSink() }) }
|
||||
: inMemory;
|
||||
}
|
||||
|
||||
const arcClient = config.arc
|
||||
@ -199,7 +233,8 @@ export function buildIntegrations(
|
||||
chainId: config.arc.chainId,
|
||||
})
|
||||
: null;
|
||||
const registry = buildVerifierRegistry(config, options.chains);
|
||||
const arcVerifier =
|
||||
arcClient && config.arc ? buildArcVerifier(arcClient, config.arc.minConfirmations) : null;
|
||||
|
||||
const circle = config.circle
|
||||
? createCircleClient({
|
||||
@ -239,10 +274,7 @@ export function buildIntegrations(
|
||||
deliveryClients,
|
||||
githubAccessClient,
|
||||
discordApi,
|
||||
arcVerifier: registry.arcVerifier,
|
||||
verifiers: registry.verifiers,
|
||||
evmVerifiers: registry.evmVerifiers,
|
||||
zcash: registry.zcash,
|
||||
arcVerifier,
|
||||
arc: arcClient,
|
||||
circle,
|
||||
payoutExecutor,
|
||||
|
||||
@ -1,181 +0,0 @@
|
||||
/**
|
||||
* The per-network on-chain verifier registry.
|
||||
*
|
||||
* One {@link SettlementVerifier} per ENABLED network: every EVM chain from
|
||||
* `config.evm` (Arc included), Solana when SOLANA_CLUSTER is set, Zcash
|
||||
* when ZCASH_ENABLED and HyperCore when HYPERCORE_ENABLED. A network without an entry fails closed — a tx hash
|
||||
* alone can never confirm a payment on it.
|
||||
*/
|
||||
|
||||
import { ARC_TESTNET, type FullEvmRpc } from "@settlekit/arc";
|
||||
import {
|
||||
createChainRpc,
|
||||
createEvmSettlementVerifier,
|
||||
createEvmVerifier,
|
||||
createZcashSettlementVerifier,
|
||||
type EvmChainKey,
|
||||
type EvmChainRuntimeConfig,
|
||||
type EvmVerifier,
|
||||
type SettlementVerifier,
|
||||
type ZcashConfig,
|
||||
} from "@settlekit/chains";
|
||||
import { toBaseUnits, type PaymentNetwork } from "@settlekit/common";
|
||||
import { createHyperCoreClient, createHyperCoreSettlementVerifier, type HyperliquidTransport } from "@settlekit/hyperliquid";
|
||||
import {
|
||||
createKitSolanaRpc,
|
||||
createSolanaPaymentVerifier,
|
||||
isSolanaSignature,
|
||||
verifySplTransfer,
|
||||
type SolanaRpc,
|
||||
} from "@settlekit/solana";
|
||||
import {
|
||||
createBlockchairExplorer,
|
||||
createCoinbaseSource,
|
||||
createKrakenSource,
|
||||
type FetchLike,
|
||||
type PriceSource,
|
||||
type ZcashExplorer,
|
||||
type ZcashNetwork,
|
||||
} from "@settlekit/zcash";
|
||||
import type { PaymentVerifier } from "@settlekit/x402";
|
||||
import type { ApiConfig } from "./env.js";
|
||||
|
||||
/** Per-network verifier registry (absent network = fail closed). */
|
||||
export type PaymentVerifiers = Readonly<Partial<Record<PaymentNetwork, SettlementVerifier>>>;
|
||||
|
||||
/** Zcash services used at checkout creation (quote lock) and verification. */
|
||||
export interface ZcashRuntime {
|
||||
network: ZcashNetwork;
|
||||
explorer: ZcashExplorer;
|
||||
/** Primary first (Coinbase), then fallbacks/cross-checks (Kraken). */
|
||||
priceSources: readonly PriceSource[];
|
||||
quoteTtlSec: number;
|
||||
minConfirmations: number;
|
||||
}
|
||||
|
||||
export interface VerifierRegistry {
|
||||
verifiers: PaymentVerifiers;
|
||||
/** The raw EVM verifiers, for the boot-time chain-id assertion. */
|
||||
evmVerifiers: readonly EvmVerifier[];
|
||||
/** x402 view of the Arc verifier (the x402 routes settle on Arc). */
|
||||
arcVerifier: PaymentVerifier | null;
|
||||
zcash: ZcashRuntime | null;
|
||||
}
|
||||
|
||||
export interface VerifierRegistryDeps {
|
||||
/** Inject RPCs per chain (tests); defaults to viem over the configured URL. */
|
||||
evmRpcs?: Partial<Record<EvmChainKey, FullEvmRpc>>;
|
||||
/** Inject the Solana RPC (tests); defaults to @solana/kit over the configured URL. */
|
||||
solanaRpc?: SolanaRpc;
|
||||
/** fetch used by Zcash price sources and the explorer. */
|
||||
fetch?: FetchLike;
|
||||
/** Hyperliquid API transport (tests inject recorded ledgers). */
|
||||
hypercoreTransport?: HyperliquidTransport;
|
||||
}
|
||||
|
||||
function buildEvm(chain: EvmChainRuntimeConfig, rpc: FullEvmRpc): { primary: EvmVerifier; settlement: SettlementVerifier } {
|
||||
const primary = createEvmVerifier({
|
||||
spec: chain.spec,
|
||||
rpc,
|
||||
minConfirmations: chain.minConfirmations,
|
||||
tokenAddress: chain.tokenAddress,
|
||||
});
|
||||
// Arc also settles EURC / USYC (x402 calls): same rules, their own contracts.
|
||||
const extra: Record<string, EvmVerifier> =
|
||||
chain.key === "arc"
|
||||
? {
|
||||
EURC: createEvmVerifier({ spec: chain.spec, rpc, minConfirmations: chain.minConfirmations, tokenAddress: ARC_TESTNET.tokens.EURC.address }),
|
||||
USYC: createEvmVerifier({ spec: chain.spec, rpc, minConfirmations: chain.minConfirmations, tokenAddress: ARC_TESTNET.tokens.USYC.address }),
|
||||
}
|
||||
: {};
|
||||
return { primary, settlement: createEvmSettlementVerifier(primary, extra) };
|
||||
}
|
||||
|
||||
/** Allowed skew between session creation and a routed Solana fill's block time (matches checkout/worker). */
|
||||
export const ROUTED_FILL_SKEW_MS = 120_000;
|
||||
|
||||
/**
|
||||
* A route provider's Solana fill carries no Solana Pay reference, so it is
|
||||
* bound by payTo, mint, amount and block time (>= session creation - skew).
|
||||
*/
|
||||
async function verifyRoutedSolanaFill(
|
||||
rpc: SolanaRpc,
|
||||
mint: string,
|
||||
proof: { txHash: string },
|
||||
requirements: { payTo: string; amount: string; notBefore?: string },
|
||||
): Promise<{ ok: boolean; reason?: string; retryable?: boolean }> {
|
||||
if (!isSolanaSignature(proof.txHash)) return { ok: false, reason: "Malformed Solana transaction signature" };
|
||||
const notBefore = requirements.notBefore ? new Date(requirements.notBefore).getTime() : Number.NaN;
|
||||
if (Number.isNaN(notBefore)) return { ok: false, reason: "routed fill needs the session creation time" };
|
||||
const result = await verifySplTransfer(rpc, {
|
||||
signature: proof.txHash,
|
||||
mint,
|
||||
recipientOwner: requirements.payTo,
|
||||
minAmount: toBaseUnits(requirements.amount),
|
||||
commitment: "confirmed",
|
||||
});
|
||||
if (!result.ok) return { ok: false, reason: result.message, ...(result.reason === "not_found" ? { retryable: true } : {}) };
|
||||
if (result.blockTime === null) return { ok: false, reason: "fill has no block time yet", retryable: true };
|
||||
if (result.blockTime * 1000 < notBefore - ROUTED_FILL_SKEW_MS) return { ok: false, reason: "fill predates the checkout session" };
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
/** Adapt the x402-shaped Solana verifier to the settlement contract. */
|
||||
function solanaVerifier(config: NonNullable<ApiConfig["solana"]>, rpc?: SolanaRpc): SettlementVerifier {
|
||||
const solanaRpc = rpc ?? createKitSolanaRpc(config.rpcUrl);
|
||||
const verify = createSolanaPaymentVerifier({
|
||||
rpc: solanaRpc,
|
||||
mint: config.usdcMint,
|
||||
commitment: "confirmed",
|
||||
});
|
||||
return async (proof, requirements) => {
|
||||
if (proof.network !== "solana" || requirements.network !== "solana") {
|
||||
return { ok: false, reason: `Unsupported network: ${proof.network}` };
|
||||
}
|
||||
if (requirements.routedFill === true) return verifyRoutedSolanaFill(solanaRpc, config.usdcMint, proof, requirements);
|
||||
return verify(
|
||||
{ ...proof, network: "solana" },
|
||||
{ ...requirements, scheme: "x402", network: "solana", asset: requirements.asset as "USDC" },
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
function zcashRuntime(config: ZcashConfig, fetchImpl: FetchLike): ZcashRuntime {
|
||||
return {
|
||||
network: config.network,
|
||||
explorer: createBlockchairExplorer({
|
||||
fetch: fetchImpl,
|
||||
baseUrl: config.explorerUrl,
|
||||
...(config.apiKey ? { apiKey: config.apiKey } : {}),
|
||||
}),
|
||||
priceSources: [createCoinbaseSource(fetchImpl), createKrakenSource(fetchImpl)],
|
||||
quoteTtlSec: config.quoteTtlSec,
|
||||
minConfirmations: config.minConfirmations,
|
||||
};
|
||||
}
|
||||
|
||||
/** Build every enabled network's verifier from `config`. */
|
||||
export function buildVerifierRegistry(config: ApiConfig, deps: VerifierRegistryDeps = {}): VerifierRegistry {
|
||||
const verifiers: Partial<Record<PaymentNetwork, SettlementVerifier>> = {};
|
||||
const evmVerifiers: EvmVerifier[] = [];
|
||||
for (const chain of Object.values(config.evm.enabled)) {
|
||||
if (chain === undefined) continue;
|
||||
const rpc = deps.evmRpcs?.[chain.key] ?? createChainRpc(chain.spec, chain.rpcUrl);
|
||||
const built = buildEvm(chain, rpc);
|
||||
evmVerifiers.push(built.primary);
|
||||
verifiers[chain.key] = built.settlement;
|
||||
}
|
||||
if (config.solana) verifiers.solana = solanaVerifier(config.solana, deps.solanaRpc);
|
||||
|
||||
const zcash = config.zcash ? zcashRuntime(config.zcash, deps.fetch ?? (globalThis.fetch as FetchLike)) : null;
|
||||
if (zcash) {
|
||||
verifiers.zcash = createZcashSettlementVerifier({ explorer: zcash.explorer, minConfirmations: zcash.minConfirmations });
|
||||
}
|
||||
|
||||
if (config.hypercore) {
|
||||
const client = createHyperCoreClient(config.hypercore, deps.hypercoreTransport ? { transport: deps.hypercoreTransport } : {});
|
||||
verifiers.hypercore = createHyperCoreSettlementVerifier(client);
|
||||
}
|
||||
|
||||
return { verifiers, evmVerifiers, arcVerifier: verifiers.arc ?? null, zcash };
|
||||
}
|
||||
@ -155,24 +155,10 @@ import {
|
||||
PgOrgSettingsStore,
|
||||
InMemoryOrgSettingsStore,
|
||||
type OrgSettingsStore,
|
||||
PgAgentRegistryStore,
|
||||
InMemoryAgentRegistryStore,
|
||||
type AgentRegistryStore,
|
||||
PgAgentJobStore,
|
||||
InMemoryAgentJobStore,
|
||||
type AgentJobStore,
|
||||
PgX402NonceStore,
|
||||
} from "@settlekit/persistence";
|
||||
import { loadConfig } from "./config/env.js";
|
||||
import { buildIntegrations, type PaymentVerifiers, type ZcashRuntime } from "./config/integrations.js";
|
||||
import type { EvmVerifier } from "@settlekit/chains";
|
||||
import { buildIntegrations } from "./config/integrations.js";
|
||||
import type { DeliveryGrantSink } from "./wiring/delivery-clients.js";
|
||||
import { loadAgentPayments, type AgentPaymentsRuntime } from "./agent-payments/config.js";
|
||||
import type { OnchainBillingRuntime } from "@settlekit/onchain-billing";
|
||||
import { buildApiOnchainBilling } from "./onchain-billing/runtime.js";
|
||||
import { createWebhookJobStore, createWebhookOutbox } from "./webhooks/outbox.js";
|
||||
import { createFrankfurterSource, type FxRateSource } from "./fx/rates.js";
|
||||
import type { WebhookJobStore, WebhookOutbox } from "@settlekit/persistence";
|
||||
|
||||
/** The fully-wired set of services + stores shared across requests. */
|
||||
export interface AppContext {
|
||||
@ -197,36 +183,19 @@ export interface AppContext {
|
||||
readonly deliveryClients: DeliveryClients;
|
||||
readonly webhookEndpoints: EntityStore<WebhookEndpoint>;
|
||||
readonly webhookEvents: EntityStore<WebhookEvent>;
|
||||
/** Signed seller webhooks (payment / subscription / refund events). */
|
||||
readonly webhookOutbox: WebhookOutbox;
|
||||
/** Per-endpoint delivery log (attempts, retries, resends). */
|
||||
readonly webhookJobs: WebhookJobStore;
|
||||
|
||||
// Access / key services.
|
||||
readonly apiKeys: ApiKeyService;
|
||||
readonly licenses: LicenseService;
|
||||
/** Raw license store (tenant ownership checks on single-license routes). */
|
||||
readonly licenseStore: LicenseStore;
|
||||
readonly files: FileDeliveryService;
|
||||
|
||||
// Authentication (account/session/magic-link) for the public /v1/auth routes.
|
||||
readonly auth: AuthService;
|
||||
readonly agentRegistry: AgentRegistryStore;
|
||||
readonly agentJobs: AgentJobStore;
|
||||
/** HMAC secret used to sign the `sk_session` cookie. */
|
||||
readonly authCookieSecret: string;
|
||||
|
||||
// Integration clients (real when configured; null/in-memory otherwise).
|
||||
readonly arcVerifier: PaymentVerifier | null;
|
||||
/**
|
||||
* On-chain payment verifiers per network. Payment confirm/observe FAIL
|
||||
* CLOSED for a network with no verifier — a tx hash alone never settles.
|
||||
*/
|
||||
readonly verifiers: PaymentVerifiers;
|
||||
/** Enabled EVM chain verifiers (boot asserts each RPC's chain id). */
|
||||
readonly evmVerifiers: readonly EvmVerifier[];
|
||||
/** Zcash quote/explorer services; null when ZCASH_ENABLED is unset. */
|
||||
readonly zcash: ZcashRuntime | null;
|
||||
/** Raw Arc client for verify / fee-estimate / confirmations. */
|
||||
readonly arc: ArcClient | null;
|
||||
readonly circle: CircleClient | null;
|
||||
@ -303,12 +272,6 @@ export interface AppContext {
|
||||
readonly payoutStore: PayoutStore;
|
||||
/** Platform take-rate applied to merchant settlements (SettleKit revenue). */
|
||||
readonly platformFeeSchedule: PlatformFeeSchedule;
|
||||
/** x402 (every chain) + MPP (Tempo) agent payments; null when unconfigured. */
|
||||
readonly agentPayments: AgentPaymentsRuntime | null;
|
||||
/** Onchain subscriptions, Base escrow and per-network refunds; null when unconfigured. */
|
||||
readonly onchainBilling: OnchainBillingRuntime | null;
|
||||
/** Live FX rates for fiat-priced products (frankfurter, ECB rates). */
|
||||
readonly fxRates: FxRateSource;
|
||||
}
|
||||
|
||||
/** Pick the Postgres implementation when `db` is set, else the in-memory one. */
|
||||
@ -420,11 +383,7 @@ export async function createContext(): Promise<AppContext> {
|
||||
...(process.env.MERCHANT_WEBSITE ? { website: process.env.MERCHANT_WEBSITE } : {}),
|
||||
};
|
||||
|
||||
const webhookEndpointStore = pick<EntityStore<WebhookEndpoint>>(db, (d) => new PgWebhookEndpointStore(d), () => new InMemoryEntityStore<WebhookEndpoint>());
|
||||
const webhookEventStore = pick<EntityStore<WebhookEvent>>(db, (d) => new PgWebhookEventStore(d), () => new InMemoryEntityStore<WebhookEvent>());
|
||||
const webhookJobs = createWebhookJobStore(db);
|
||||
|
||||
const base: Omit<AppContext, "onchainBilling"> = {
|
||||
return {
|
||||
db,
|
||||
persistent: db !== null,
|
||||
|
||||
@ -440,14 +399,11 @@ export async function createContext(): Promise<AppContext> {
|
||||
deliveryRuns: pick<EntityStore<DeliveryRun>>(db, (d) => new PgDeliveryRunStore(d), () => new InMemoryEntityStore<DeliveryRun>()),
|
||||
deliveryRegistry: createDefaultRegistry(),
|
||||
deliveryClients: integrations.deliveryClients,
|
||||
webhookEndpoints: webhookEndpointStore,
|
||||
webhookEvents: webhookEventStore,
|
||||
webhookJobs,
|
||||
webhookOutbox: createWebhookOutbox(db, webhookEndpointStore, webhookEventStore, webhookJobs),
|
||||
webhookEndpoints: pick<EntityStore<WebhookEndpoint>>(db, (d) => new PgWebhookEndpointStore(d), () => new InMemoryEntityStore<WebhookEndpoint>()),
|
||||
webhookEvents: pick<EntityStore<WebhookEvent>>(db, (d) => new PgWebhookEventStore(d), () => new InMemoryEntityStore<WebhookEvent>()),
|
||||
|
||||
apiKeys: new ApiKeyService(apiKeyStore),
|
||||
licenses: new LicenseService(licenseStore, { tokenSecret: config.licenseTokenSecret }),
|
||||
licenseStore,
|
||||
files: new FileDeliveryService(grantStore, {
|
||||
baseUrl: config.fileDelivery.baseUrl,
|
||||
secret: config.fileDelivery.secret,
|
||||
@ -455,36 +411,10 @@ export async function createContext(): Promise<AppContext> {
|
||||
defaultMaxDownloads: config.fileDelivery.defaultMaxDownloads,
|
||||
}),
|
||||
|
||||
auth: new AuthService(pick<AuthStore>(db, (d) => new PgAuthStore(d), () => new InMemoryAuthStore()), {
|
||||
// SIWE binding: when AUTH_SIWE_DOMAIN is set, wallet sign-in rejects any
|
||||
// signed message whose domain differs (EIP-4361 cross-site replay guard).
|
||||
// AUTH_SIWE_CHAIN_IDS (comma-separated) optionally restricts chains.
|
||||
...(process.env.AUTH_SIWE_DOMAIN ? { siweDomain: process.env.AUTH_SIWE_DOMAIN } : {}),
|
||||
...(process.env.AUTH_SIWE_CHAIN_IDS
|
||||
? {
|
||||
siweChainIds: process.env.AUTH_SIWE_CHAIN_IDS.split(",")
|
||||
.map((s) => Number.parseInt(s.trim(), 10))
|
||||
.filter((n) => Number.isFinite(n)),
|
||||
}
|
||||
: {}),
|
||||
}),
|
||||
auth: new AuthService(pick<AuthStore>(db, (d) => new PgAuthStore(d), () => new InMemoryAuthStore())),
|
||||
authCookieSecret: config.authCookieSecret,
|
||||
|
||||
agentRegistry: pick<AgentRegistryStore>(
|
||||
db,
|
||||
(d) => new PgAgentRegistryStore(d),
|
||||
() => new InMemoryAgentRegistryStore(),
|
||||
),
|
||||
agentJobs: pick<AgentJobStore>(
|
||||
db,
|
||||
(d) => new PgAgentJobStore(d),
|
||||
() => new InMemoryAgentJobStore(),
|
||||
),
|
||||
|
||||
arcVerifier: integrations.arcVerifier,
|
||||
verifiers: integrations.verifiers,
|
||||
evmVerifiers: integrations.evmVerifiers,
|
||||
zcash: integrations.zcash,
|
||||
arc: integrations.arc,
|
||||
circle: integrations.circle,
|
||||
payoutExecutor: integrations.payoutExecutor,
|
||||
@ -571,13 +501,7 @@ export async function createContext(): Promise<AppContext> {
|
||||
payouts: new PayoutService(payoutStore, () => generateId("payoutWallet")),
|
||||
payoutStore,
|
||||
platformFeeSchedule,
|
||||
agentPayments: loadAgentPayments(process.env, db ? { nonceStore: new PgX402NonceStore(db) } : {}),
|
||||
fxRates: createFrankfurterSource({
|
||||
...(process.env.FX_RATES_URL ? { baseUrl: process.env.FX_RATES_URL } : {}),
|
||||
...(process.env.FX_RATES_TTL_SECONDS ? { ttlMs: Number(process.env.FX_RATES_TTL_SECONDS) * 1000 } : {}),
|
||||
}),
|
||||
};
|
||||
return { ...base, onchainBilling: await buildApiOnchainBilling(base) };
|
||||
}
|
||||
|
||||
/** Hono `Variables` binding: the context is attached to every request. */
|
||||
@ -587,9 +511,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,
|
||||
);
|
||||
}
|
||||
|
||||
@ -10,7 +10,6 @@
|
||||
* which the middleware binds explicitly.
|
||||
*/
|
||||
import type { Context } from "hono";
|
||||
import { notFound, type Payment, type Subscription } from "@settlekit/common";
|
||||
import { DEFAULT_ORG_ID } from "@settlekit/persistence";
|
||||
import type { AppEnv } from "../context.js";
|
||||
|
||||
@ -18,65 +17,3 @@ import type { AppEnv } from "../context.js";
|
||||
export function requireOrg(c: Context<AppEnv>): string {
|
||||
return c.get("organizationId") ?? DEFAULT_ORG_ID;
|
||||
}
|
||||
|
||||
/** Anything stamped with the tenant that owns it. */
|
||||
export interface TenantOwned {
|
||||
readonly organizationId: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ownership guard for single-resource routes that load a record by an opaque
|
||||
* id. Returns the record when it belongs to the authenticated org; otherwise
|
||||
* throws `not_found` — deliberately 404, never 403, so a caller cannot probe
|
||||
* which ids exist in other tenants.
|
||||
*/
|
||||
export function requireOwned<T extends TenantOwned>(
|
||||
c: Context<AppEnv>,
|
||||
resource: T | null | undefined,
|
||||
label: string,
|
||||
id: string,
|
||||
): T {
|
||||
if (!resource || resource.organizationId !== requireOrg(c)) {
|
||||
throw notFound(`${label} not found`, { id });
|
||||
}
|
||||
return resource;
|
||||
}
|
||||
|
||||
/** Whether `resource` belongs to the authenticated org (no throw). */
|
||||
export function isOwned(c: Context<AppEnv>, resource: TenantOwned | null | undefined): boolean {
|
||||
return resource !== null && resource !== undefined && resource.organizationId === requireOrg(c);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a payment by id and require it belongs to the caller's org. Used by the
|
||||
* payment routes and by resources that hang off a payment (refunds, disputes).
|
||||
*/
|
||||
export async function requireOwnedPayment(c: Context<AppEnv>, paymentId: string): Promise<Payment> {
|
||||
return requireOwned(c, await c.get("ctx").payments.findById(paymentId), "payment", paymentId);
|
||||
}
|
||||
|
||||
/** Load a subscription by id, requiring it belongs to the caller's org. */
|
||||
export async function ownedSubscription(c: Context<AppEnv>, subscriptionId: string): Promise<Subscription> {
|
||||
return requireOwned(c, await c.get("ctx").subscriptions.findById(subscriptionId), "subscription", subscriptionId);
|
||||
}
|
||||
|
||||
/** Ids of every payment owned by the caller's org (for scoping list reads). */
|
||||
export async function ownedPaymentIds(c: Context<AppEnv>): Promise<Set<string>> {
|
||||
const payments = await c.get("ctx").payments.listByOrganization(requireOrg(c));
|
||||
return new Set(payments.map((p) => p.id));
|
||||
}
|
||||
|
||||
/** Ids of every subscription owned by the caller's org (for scoping list reads). */
|
||||
export async function ownedSubscriptionIds(c: Context<AppEnv>): Promise<Set<string>> {
|
||||
const subs = await c.get("ctx").subscriptions.listByOrganization(requireOrg(c));
|
||||
return new Set(subs.map((s) => s.id));
|
||||
}
|
||||
|
||||
/** Keep only records stamped with the caller's org. */
|
||||
export function scopeToOrg<T extends { readonly organizationId?: string | null }>(
|
||||
c: Context<AppEnv>,
|
||||
records: readonly T[],
|
||||
): T[] {
|
||||
const org = requireOrg(c);
|
||||
return records.filter((r) => r.organizationId === org);
|
||||
}
|
||||
|
||||
@ -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();
|
||||
|
||||
@ -64,22 +64,14 @@ export function requestIdMiddleware(): MiddlewareHandler {
|
||||
|
||||
/**
|
||||
* A per-instance fixed-window rate limiter keyed by API key (falling back to the
|
||||
* client IP). General limit is `RATE_LIMIT_PER_MINUTE` (default 600); the auth
|
||||
* subtree (`/v1/auth/*`, e.g. unauthenticated wallet-nonce issuance) gets a much
|
||||
* stricter `AUTH_RATE_LIMIT_PER_MINUTE` (default 20) in its own bucket to stop
|
||||
* nonce-spam / credential-stuffing. Set `RATE_LIMIT_ENABLED=false` to disable.
|
||||
* Only `/health` and paid (x402) routes are exempt — payment is their gate.
|
||||
*
|
||||
* `X-Forwarded-For` is attacker-spoofable unless the API sits behind a trusted
|
||||
* proxy that sets it authoritatively; it is only honored when `TRUST_PROXY`
|
||||
* is true (default true, since the API deploys behind Render/Vercel). When
|
||||
* false, only `x-real-ip` is used so a client cannot forge its limiter bucket.
|
||||
* client IP). Limit is `RATE_LIMIT_PER_MINUTE` (default 600); set
|
||||
* `RATE_LIMIT_ENABLED=false` to disable. Returns 429 with `Retry-After` and a
|
||||
* standard `{ error }` envelope when exceeded. Health, auth, and paid (x402)
|
||||
* routes are exempt — payment is their gate.
|
||||
*/
|
||||
export function rateLimitMiddleware(): MiddlewareHandler {
|
||||
const enabled = (process.env.RATE_LIMIT_ENABLED ?? "true").toLowerCase() !== "false";
|
||||
const limit = intEnv("RATE_LIMIT_PER_MINUTE", 600);
|
||||
const authLimit = intEnv("AUTH_RATE_LIMIT_PER_MINUTE", 20);
|
||||
const trustProxy = (process.env.TRUST_PROXY ?? "true").toLowerCase() !== "false";
|
||||
const windowMs = 60_000;
|
||||
const windows = new Map<string, RateLimitWindow>();
|
||||
|
||||
@ -92,31 +84,27 @@ export function rateLimitMiddleware(): MiddlewareHandler {
|
||||
return async (c, next) => {
|
||||
if (!enabled) return next();
|
||||
const path = c.req.path;
|
||||
if (path === "/health" || path.startsWith("/v1/paid")) {
|
||||
if (path === "/health" || path.startsWith("/v1/auth") || path.startsWith("/v1/paid")) {
|
||||
return next();
|
||||
}
|
||||
|
||||
const ip =
|
||||
(trustProxy ? c.req.header("x-forwarded-for")?.split(",")[0]?.trim() : undefined) ??
|
||||
c.req.header("x-forwarded-for")?.split(",")[0]?.trim() ??
|
||||
c.req.header("x-real-ip") ??
|
||||
"unknown";
|
||||
const isAuth = path.startsWith("/v1/auth");
|
||||
// Auth routes get a stricter limit in a SEPARATE bucket (prefix "auth:") so
|
||||
// they cannot be starved by — or starve — the general per-caller budget.
|
||||
const effectiveLimit = isAuth ? authLimit : limit;
|
||||
const key = (isAuth ? "auth:" : "") + callerKey(c.req.header("authorization"), ip);
|
||||
const key = callerKey(c.req.header("authorization"), ip);
|
||||
|
||||
const now = new Date();
|
||||
const existing = windows.get(key);
|
||||
const window: RateLimitWindow =
|
||||
existing && new Date(existing.resetsAt).getTime() > now.getTime()
|
||||
? existing
|
||||
: { key, limit: effectiveLimit, used: 0, resetsAt: new Date(now.getTime() + windowMs).toISOString() };
|
||||
: { key, limit, used: 0, resetsAt: new Date(now.getTime() + windowMs).toISOString() };
|
||||
|
||||
if (!rateLimitAllows(window, 1, now)) {
|
||||
const retryAfter = Math.max(1, Math.ceil((new Date(window.resetsAt).getTime() - now.getTime()) / 1000));
|
||||
c.header("Retry-After", String(retryAfter));
|
||||
c.header("X-RateLimit-Limit", String(effectiveLimit));
|
||||
c.header("X-RateLimit-Limit", String(limit));
|
||||
c.header("X-RateLimit-Remaining", "0");
|
||||
return c.json(
|
||||
{ error: { code: "rate_limited", message: `Rate limit exceeded. Retry in ${retryAfter}s.` } },
|
||||
@ -126,8 +114,8 @@ export function rateLimitMiddleware(): MiddlewareHandler {
|
||||
|
||||
const updated = consumeRateLimit(window, 1);
|
||||
windows.set(key, updated);
|
||||
c.header("X-RateLimit-Limit", String(effectiveLimit));
|
||||
c.header("X-RateLimit-Remaining", String(Math.max(0, effectiveLimit - updated.used)));
|
||||
c.header("X-RateLimit-Limit", String(limit));
|
||||
c.header("X-RateLimit-Remaining", String(Math.max(0, limit - updated.used)));
|
||||
await next();
|
||||
};
|
||||
}
|
||||
|
||||
@ -1,73 +0,0 @@
|
||||
/**
|
||||
* Delivery for onchain subscriptions (API side): on the first successful
|
||||
* charge and on reactivation, run the product's delivery actions (GitHub
|
||||
* invite / team, Discord role, file grant, license / API key, ...) through the
|
||||
* real handler registry — the same runner agent purchases use — and persist
|
||||
* the run so POST /v1/delivery-runs/:id/retry can re-drive failed actions.
|
||||
*
|
||||
* Idempotent per charge: a run already recorded for the charge's payment id
|
||||
* is never repeated.
|
||||
*/
|
||||
import { generateId, toIso, type DeliveryPlan, type Entitlement } from "@settlekit/common";
|
||||
import { DeliveryRunner, deliveryActionsFor, type DeliveryContext } from "@settlekit/delivery";
|
||||
import type { AccessDelivery } from "@settlekit/onchain-billing";
|
||||
import type { AppContext } from "../context.js";
|
||||
import { githubInstallationFor } from "../agent-payments/fulfil.js";
|
||||
|
||||
const INLINE_RETRY = { maxAttempts: 2, baseDelayMs: 250 } as const;
|
||||
|
||||
type DeliveryDeps = Omit<AppContext, "onchainBilling">;
|
||||
|
||||
/** The active entitlement for the subscription's product, granting one when missing. */
|
||||
async function ensureEntitlement(ctx: DeliveryDeps, delivery: AccessDelivery): Promise<Entitlement | undefined> {
|
||||
const sub = delivery.subscription;
|
||||
const existing = (await ctx.entitlementRepo.listByCustomer(sub.customerId)).find(
|
||||
(e) => e.productId === sub.productId && e.status === "active",
|
||||
);
|
||||
if (existing) return existing;
|
||||
if (!sub.subscriptionId) return undefined;
|
||||
const [subscription, product] = await Promise.all([ctx.subscriptions.findById(sub.subscriptionId), ctx.products.findById(sub.productId)]);
|
||||
if (!subscription || !product) return undefined;
|
||||
return ctx.entitlements.grantFromSubscription({ subscription, product });
|
||||
}
|
||||
|
||||
export async function deliverOnchainSubscription(ctx: DeliveryDeps, delivery: AccessDelivery): Promise<void> {
|
||||
const sub = delivery.subscription;
|
||||
const product = await ctx.products.findById(sub.productId);
|
||||
if (!product) return;
|
||||
const actions = deliveryActionsFor(product);
|
||||
if (actions.length === 0) return;
|
||||
const already = await ctx.deliveryRuns.list((run) => run.paymentId === delivery.paymentId);
|
||||
if (already.length > 0) return;
|
||||
|
||||
const entitlement = await ensureEntitlement(ctx, delivery);
|
||||
if (!entitlement) throw new Error(`no entitlement to deliver against for ${sub.id}`);
|
||||
const customer = await ctx.customers.findById(sub.customerId);
|
||||
const needsGithub = actions.some((action) => action.type === "github_invite" || action.type === "github_team_add");
|
||||
const githubInstallationId = needsGithub ? await githubInstallationFor(ctx, product) : undefined;
|
||||
const email = customer?.email || sub.customerEmail;
|
||||
|
||||
const plan: DeliveryPlan = {
|
||||
id: generateId("deliveryPlan"),
|
||||
organizationId: sub.organizationId,
|
||||
productId: product.id,
|
||||
actions,
|
||||
createdAt: toIso(new Date()),
|
||||
};
|
||||
const deliveryCtx: DeliveryContext = {
|
||||
organizationId: sub.organizationId,
|
||||
customerId: sub.customerId,
|
||||
productId: product.id,
|
||||
paymentId: delivery.paymentId,
|
||||
entitlementId: entitlement.id,
|
||||
...(githubInstallationId !== undefined ? { githubInstallationId } : {}),
|
||||
...(customer?.githubUsername ? { githubUsername: customer.githubUsername } : {}),
|
||||
...(customer?.discordUserId ? { discordUserId: customer.discordUserId } : {}),
|
||||
...(email ? { customerEmail: email } : {}),
|
||||
emailVariables: { reason: delivery.reason, onchainSubscriptionId: sub.id },
|
||||
clients: ctx.deliveryClients,
|
||||
};
|
||||
const runner = new DeliveryRunner(ctx.deliveryRegistry, { retry: INLINE_RETRY });
|
||||
const run = await runner.run(plan, deliveryCtx, { paymentId: delivery.paymentId, customerId: sub.customerId });
|
||||
await ctx.deliveryRuns.save(run);
|
||||
}
|
||||
@ -1,86 +0,0 @@
|
||||
/**
|
||||
* API-side onchain billing: the shared @settlekit/onchain-billing runtime over
|
||||
* the API's stores (Postgres when DATABASE_URL is set — the SAME tables the
|
||||
* worker's subscription-charge job reads), with access hooks writing the
|
||||
* API's subscription / entitlement / payment repositories. The API charges
|
||||
* period 0 right after a grant is accepted; the worker charges the rest.
|
||||
*/
|
||||
import { DunningService } from "@settlekit/dunning";
|
||||
import {
|
||||
InMemoryOnchainBillingStore,
|
||||
buildOnchainBilling,
|
||||
createAccessHooks,
|
||||
type OnchainBillingRuntime,
|
||||
} from "@settlekit/onchain-billing";
|
||||
import {
|
||||
DEFAULT_MERCHANT_ID,
|
||||
PgOnchainBillingStore,
|
||||
emitWebhookSafely,
|
||||
paymentConfirmedWebhook,
|
||||
subscriptionChargedWebhook,
|
||||
} from "@settlekit/persistence";
|
||||
import { createHyperCoreClient, createHyperCoreUsdSender, loadHyperCoreConfig, type HyperCoreUsdSender } from "@settlekit/hyperliquid";
|
||||
import type { AppContext } from "../context.js";
|
||||
import { deliverOnchainSubscription } from "./delivery.js";
|
||||
|
||||
export async function buildApiOnchainBilling(
|
||||
ctx: Omit<AppContext, "onchainBilling">,
|
||||
env: Readonly<Record<string, string | undefined>> = process.env,
|
||||
): Promise<OnchainBillingRuntime | null> {
|
||||
const hooks = createAccessHooks({
|
||||
async getSubscription(id) {
|
||||
return (await ctx.subscriptions.findById(id)) ?? undefined;
|
||||
},
|
||||
async saveSubscription(subscription) {
|
||||
await ctx.subscriptions.save(subscription);
|
||||
},
|
||||
async entitlementsFor(customerId, productId) {
|
||||
return (await ctx.entitlementRepo.listByCustomer(customerId)).filter((e) => e.productId === productId);
|
||||
},
|
||||
async saveEntitlement(entitlement) {
|
||||
await ctx.entitlementRepo.save(entitlement);
|
||||
},
|
||||
async savePayment(payment) {
|
||||
await ctx.payments.save(payment);
|
||||
},
|
||||
async queueDelivery(delivery) {
|
||||
await deliverOnchainSubscription(ctx, delivery);
|
||||
},
|
||||
async onCharged(sub, charge, period, paymentId) {
|
||||
await emitWebhookSafely(ctx.webhookOutbox, subscriptionChargedWebhook(sub, charge, period, paymentId));
|
||||
const payment = paymentId ? await ctx.payments.findById(paymentId) : null;
|
||||
if (payment) {
|
||||
await emitWebhookSafely(
|
||||
ctx.webhookOutbox,
|
||||
paymentConfirmedWebhook(payment, { productIds: [sub.productId], ...(sub.customerEmail ? { customerEmail: sub.customerEmail } : {}) }),
|
||||
);
|
||||
}
|
||||
},
|
||||
}, {
|
||||
onError: (message, meta) => console.warn(`[onchain-billing] ${message}`, meta),
|
||||
});
|
||||
const hypercoreRefunds = hyperCoreRefundSender(env);
|
||||
return buildOnchainBilling({
|
||||
env,
|
||||
store: ctx.db ? new PgOnchainBillingStore(ctx.db) : new InMemoryOnchainBillingStore(),
|
||||
dunning: new DunningService(ctx.dunningStore),
|
||||
checkouts: ctx.checkouts,
|
||||
email: ctx.email,
|
||||
merchantId: DEFAULT_MERCHANT_ID,
|
||||
hooks,
|
||||
...(hypercoreRefunds ? { hypercoreRefunds } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* HyperCore refunds: an operator-signed `usdSend` from the onchain billing
|
||||
* operator key (HYPERCORE_REFUND_PRIVATE_KEY overrides it), when HyperCore is
|
||||
* enabled. The account must hold USDC on HyperCore to refund from.
|
||||
*/
|
||||
function hyperCoreRefundSender(env: Readonly<Record<string, string | undefined>>): HyperCoreUsdSender | undefined {
|
||||
const config = loadHyperCoreConfig(env);
|
||||
const key = env.HYPERCORE_REFUND_PRIVATE_KEY?.trim() || env.ONCHAIN_BILLING_OPERATOR_PRIVATE_KEY?.trim();
|
||||
if (!config || !key) return undefined;
|
||||
if (!/^0x[0-9a-fA-F]{64}$/.test(key)) throw new Error("HYPERCORE_REFUND_PRIVATE_KEY must be a 0x-prefixed 32-byte hex key");
|
||||
return createHyperCoreUsdSender({ client: createHyperCoreClient(config), privateKey: key as `0x${string}` });
|
||||
}
|
||||
@ -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 },
|
||||
});
|
||||
}
|
||||
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