caelum0x fa38f74233 feat(mint): shadow mode and /metrics with nightly receipt-chain verify (RY-MT1)
- MINT_SHADOW=1 installs a ramp that refuses every deposit and every payout
  (checked before any burn), so Mint can run on its production Postgres with no
  money moving. Startup is refused in shadow mode when a payment provider or
  MINT_DEV_FUNDING=1 is configured, so no hosted checkout can take money that
  would never be credited.
- GET /metrics (Prometheus text): readiness, journal, reserve, open holds and
  micros, hold-expiry sweep lag, pending payouts, and the full receipt hash-chain
  plus signature verification (first scrape, then every 24 h in the background).
  Bearer token via MINT_METRICS_TOKEN; without it, proxied requests get 404.
- Tests: shadow refuses mint and redeem with balances unchanged, ledger and
  /readyz still serve, metrics gauges, chain verify 1 and 0, token and proxy
  gating, sweep lag on an expired hold; ramp-choice unit tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 02:04:30 +03:00
..
2026-08-25 03:09:58 +03:00

apps/mint — AI Token settlement layer

Status: implemented standalone Rust workspace. Eleven crates compile and the workspace test suite passes. It remains excluded from the root desktop Cargo workspace; run validation from apps/mint with cargo test --workspace.

Run the product

For a disposable local ledger:

cd apps/mint
MINT_API_KEY=local-secret MINT_ALLOW_INMEMORY=1 cargo run -p mint-server
curl http://127.0.0.1:8080/healthz

Production requires DATABASE_URL, MINT_API_KEY, and a unique 32-byte MINT_SIGNING_KEY encoded as hex. The server refuses to use its deterministic development signer when Postgres is configured. AITP-402 payers need their Ed25519 verifying key registered: POST /v1/payer-keys {"payer":"acct_customer","pubkey_id":"key_1","public_key_hex":"<64 hex chars>"} (admin), listed with GET /v1/payer-keys?payer= and revoked with POST /v1/payer-keys/{payer}/{pubkey_id}/revoke, or from the console's Payer keys tab. No restart is needed; other instances pick changes up within one background sweep. An optional static bootstrap set can still be supplied, and a key revoked in the DB is refused even if it is listed there:

export MINT_PAYER_KEYS_JSON='[{"payer":"acct_customer","pubkey_id":"key_1","public_key_hex":"<64 hex chars>"}]'

Background sweeps (every MINT_SWEEP_INTERVAL_MS, default 60000; disable with MINT_SWEEP_DISABLED=1) refresh every pending payout from its provider, release OPEN holds past their deadline, and reload the payer-key registry. AITP-402 hold settlements expire at the challenge expiry plus MINT_AITP_HOLD_TTL_MS (default 15 minutes) unless the merchant captures or releases them first; POST /v1/holds accepts an optional expires_in_ms.

The server runs migrations at startup. Payment on-ramp adapters are activated by their provider environment variables; with none configured, deposit confirmation uses the development ramp and must not be treated as production funding.

Fund an account

POST /v1/checkouts creates a provider-hosted checkout for an existing Mint account. The amount must be positive whole USD cents expressed as integer microdollars. Mint binds the account ID into provider metadata; the provider's verified webhook is the only operation that credits the account.

curl --fail-with-body http://127.0.0.1:8080/v1/checkouts \
  -H "x-api-key: $MINT_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"provider":"stripe","account_id":"acct_customer","amount_micros":20000000,
       "success_url":"https://app.example.com/billing/success",
       "cancel_url":"https://app.example.com/billing"}'

success_url / cancel_url are optional per request; otherwise Mint uses MINT_CHECKOUT_SUCCESS_URL / MINT_CHECKOUT_CANCEL_URL, then its own hosted /checkout/success and /checkout/cancel pages under MINT_PUBLIC_URL.

Configure at least one checkout-capable provider and its webhook secret:

Provider Keys Notes
Stripe STRIPE_API_KEY, STRIPE_WEBHOOK_SECRET credits on payment_intent.succeeded
PayPal PAYPAL_CLIENT_ID, PAYPAL_CLIENT_SECRET, PAYPAL_WEBHOOK_ID, MINT_PUBLIC_URL buyer returns to /checkout/paypal/return, which captures and credits (order id = deposit ref)
Creem CREEM_API_KEY, CREEM_WEBHOOK_SECRET, CREEM_PRODUCT_ID, optional CREEM_UNIT_PRICE_CENTS (default 100) a fixed-price credit product bought in units; amount must be a multiple of the unit price
Polar POLAR_ACCESS_TOKEN, POLAR_WEBHOOK_SECRET, POLAR_PRODUCT_ID the product must be custom-price ("pay what you want")
USDC USDC_RPC_URL, COINBASE_COMMERCE_API_KEY, COINBASE_COMMERCE_WEBHOOK_SECRET
Iyzico IYZICO_API_KEY, IYZICO_SECRET_KEY, IYZICO_WEBHOOK_SECRET

Mobile IAP providers confirm store purchases but do not expose this arbitrary hosted-checkout route.

Cash out, payouts and reconciliation

POST /v1/redeem burns AIT and pays out. The payout is checked for routability BEFORE the burn (known active <provider>: prefix on payout_ref, a payout-capable provider, a destination kind it supports, whole cents): an unroutable payout returns 422 payout_unroutable and nothing is burned. Destinations: {"kind":"stripe","account":"acct_…"}, {"kind":"paypal","email":"…"}, {"kind":"crypto","chain":"ethereum","address":"0x…"}.

Every payout attempt is persisted:

  • GET /v1/payouts?status=failed|pending|paid&account_id=&cursor= — the payout log;
  • GET /v1/payouts/{payout_ref} — one payout (pending ones are refreshed from the provider: PayPal batch status, on-chain receipt);
  • POST /v1/payouts/{payout_ref}/retry — re-send a failed payout with the same provider idempotency key (paid/pending payouts are never re-sent);
  • POST /v1/payouts/{payout_ref}/cancel {"note":…} (admin) — abandon a failed payout and re-credit the burned amount (a compensating mint tagged <payout_ref>#cancel); status becomes cancelled;
  • POST /v1/payouts/{payout_ref}/mark-paid {"provider_ref":…} (admin) — record an out-of-band settlement (manual wire) of a failed/pending payout;
  • GET /v1/reconciliation — per-provider deposits minted vs. burns vs. payout outcomes (net of cancellations and claw-backs), the burned-but-unpaid worklist, the chargeback shortfall and the supply identity check.

Reconciliation against provider reports

Import the provider's own books and match them against the ledger:

  • POST /v1/reconciliation/reports (admin) {"provider":"stripe","label":"itemized.csv","content":"<csv or json>","amount_unit":"major|cents|micros","reference_column":"payment_intent_id"} — parses a CSV (Stripe itemized balance / payouts export, PayPal settlement report, …) or a JSON array / {data:[…]} list, stores the lines and returns the match. Columns are detected by name (payment_intent_id, transaction_id, tx_hash, id … / amount, gross … / type, reporting_category … / created, date …);
  • GET /v1/reconciliation/reports, GET /v1/reconciliation/reports/{id} (re-matched live), DELETE /v1/reconciliation/reports/{id}.

Each line is matched, amount_mismatch, status_mismatch (provider paid, Mint still unpaid), missing_in_mint, reversal_unrecorded (a provider refund or chargeback Mint has not clawed back) or informational (fees); Mint movements inside the report period that the report lacks are listed as missing_at_provider.

Refunds and chargebacks

A refund or dispute of a deposit Mint already minted must be clawed back or the supply stops being backed. The provider webhooks on the same /v1/deposits/{provider}/webhook route do this automatically:

Provider Events Amount
Stripe charge.refunded, charge.dispute.created, charge.dispute.funds_withdrawn cumulative amount_refunded / disputed amount
PayPal PAYMENT.CAPTURE.REFUNDED, PAYMENT.CAPTURE.REVERSED, CUSTOMER.DISPUTE.CREATED cumulative total_refunded_amount / dispute_amount; the order id is resolved from the capture
Creem refund.created, dispute.created transaction.refunded_amount (else refund_amount) / disputed amount
Polar order.refunded cumulative refunded_amount
RevenueCat CANCELLATION with cancel_reason=CUSTOMER_SUPPORT the refunded price, else the whole purchase
Adapty subscription_refunded, non_subscription_purchase_refunded price_usd, else the whole purchase

USDC transfers are final. Iyzico refunds, and anything a webhook missed, are recorded by operators (or from an imported provider report):

  • POST /v1/reversals {"deposit_ref":"stripe:pi_…","amount_micros":…,"reason":"refund|dispute"} (admin) — burns what the account still holds (even when frozen), up to the cumulative reversed amount; any remainder is a shortfall;
  • GET /v1/reversals?status=shortfall, POST /v1/reversals/{deposit_ref}/retry, POST /v1/reversals/{deposit_ref}/write-off.

KYC onboarding

  • GET /v1/accounts/{id}/kyc — provider-verified status (unverified, pending, approved, declined, or unavailable with no provider);
  • POST /v1/accounts/{id}/kyc/session {"return_url":"https://…"} — starts a hosted Persona inquiry (needs PERSONA_INQUIRY_TEMPLATE_ID) or Stripe Identity session and returns its URL.

Statements and accounts

  • GET /v1/accounts?after=&limit= — accounts with live balances and status;
  • GET /v1/accounts/{id} — kind, owner ref, creation time, status, balance;
  • POST /v1/accounts/{id}/freeze | /unfreeze | /close (admin) — a frozen account cannot send (transfers, holds, streams, allowances, AITP, redeem: 403 account_frozen) but still receives deposits; a closed account can do neither (403 account_closed) and only a zero-balance account can be closed (409 account_not_empty);
  • GET /v1/accounts/{id}/statement?from_ms=&to_ms= — opening balance, every entry with its signed delta, credit/debit totals and closing balance;
  • GET /v1/accounts/{id}/receipts?after_seq=&limit=&from_ms=&to_ms= — a page of the hash-linked receipt chain;
  • GET /v1/accounts/{id}/holds?status=open|captured|released (with each hold's expires_at_ms), /streams?status=open|closed and /allowances?status=active|all — what keeps the held balance up and blocks a close.

Operator console

GET /admin serves the operator console: reserve and solvency, Merkle audit root, reconciliation; accounts (create, freeze / unfreeze / close, receive addresses, operator transfers, redeem, statements, signed receipt chain, per-account open holds / streams / allowances with release / close / revoke, KYC); payouts (retry, cancel and re-credit, mark paid); funding (hosted checkouts, manual deposit-gated mint); provider report import with discrepancy review and one-click claw-back; refunds and chargebacks; API key and AITP payer-key management. It holds no data itself; every panel calls the API with the operator's X-API-Key.

API keys

MINT_API_KEY is the master key. Give each consuming service its own scoped key instead:

export MINT_API_KEYS_JSON='[
  {"name":"ledgerline","key":"<32+ random chars>","scopes":["read","spend"]},
  {"name":"abacus","key":"<32+ random chars>","scopes":["read","spend"]},
  {"name":"autogtm","key":"<32+ random chars>","scopes":["read","accounts","spend","funding"]}
]'

Scopes: read (all GETs), accounts, spend (transfers/holds/streams/ allowances/AITP), funding (checkouts, mint), payouts (redeem, retry), admin (lifecycle, cancellations, reports, reversals, key management). Rotate a key by adding the new one under the same name, redeploying callers, then removing the old one.

Add "accounts":["acct_…"] to restrict a key to specific accounts: it may then only move money out of, fund, redeem from and read those accounts, and it is refused on global views (account listing, audit log, reconciliation) and on every admin route.

Keys can also be managed at runtime from the console or the API (GET /v1/keys, POST /v1/keys {"name","scopes","accounts"?}, POST /v1/keys/{id}/revoke, all admin). Only the SHA-256 of the secret is stored; the secret is returned once at creation.

Mint turns AI credits into a first-class transferable token (AIT) — sendable/receivable/deliverable between accounts, agents, providers, and models — with web3 mechanics and zero crypto (addresses, signed transfers, conservation-of-supply, verifiable hash-linked receipts; fiat-backed, off-chain, no gas). It's meant to become the canonical settlement layer that ReelForge (apps/api), Relay (apps/relay), and desktop all spend on.

Create a shareable receive address with POST /v1/accounts/{account_id}/addresses, then pass the returned ait1… value as to in POST /v1/transfers. An address is routing only: Mint resolves it to the authoritative recipient before committing the ledger operation, while the sender remains an authorized acct_… supplied by the trusted product backend. Transfer responses contain the exact signed sender receipt plus a privacy-safe mint-transfer-attestation-v1; exact idempotent replay returns the same evidence. The Rust, Python, and TypeScript SDKs all require that proof shape. The dynamic-language clients additionally reject a nominally successful response when its sender, amount, operation, or journal sequence does not match the submitted transfer. Cryptographic acceptance still requires an operator-pinned key from the public rotation document; discovery alone is not a trust decision.

Design docs (source of truth)

  • docs/mint/PLAN.md — architecture, crates, phases, invariants, product surfaces.
  • docs/mint/AITP-402-SPEC.md — the wire protocol: AIT unit, addresses, ledger ops, the AITP-402 payment handshake, hash-linked receipts.
  • docs/mint/IMPLEMENTATION.md — build-grade detail: Postgres schema, per-phase task lists, wallet integration/migration, reserve reconciliation, fee math, threat model, compliance tiers, SLOs, conformance suite.

Implemented crates

mint-core · mint-ledger · mint-payments · mint-protocol · mint-receipts · mint-reserve · mint-server · mint-store · mint-store-postgres · mint-stream · mint-sdk

Product gaps

Payer-key and API-key rotation is config-and-restart rather than an authenticated control plane, and scoped keys are per-capability rather than per-account. Redemption fails closed until a real KYC provider is configured: set MINT_KYC_PROVIDER=persona|stripe_identity plus the provider key (PERSONA_API_KEY / STRIPE_API_KEY) to install the VerifiedKycGate, which authorizes each cash-out against the account's provider-verified identity and a per-tx payout ceiling; with nothing configured every redeem is denied and no fake verification is ever used in production. Cash redemption also depends on a payout-capable provider (USDC pays out an ERC-20 transfer to the configured token contract; Creem and mobile IAP are deposit-only). The longer-term custody, anchoring, fee, and multi-currency decisions remain in IMPLEMENTATION.md.

Product family

ReelForge (video) · Relay (inference gateway, apps/relay) · Mint (this). All inherit ADR-0001 (integer-microdollar money) + ADR-0002 (success-only billing).