railyard/apps/mint/README.md
caelum0x 6c7def969d feat(mint): seller-own payments, a connect page, products and checkouts on the seller's account, and signed entitlement events (PY2.3)
VC6 and dispatch contract 5.5, Mint side:
- mint-payments/src/seller: the seller's own Dodo account (their key on
  their account for products, checkouts and the payment lookup a refund or
  dispute needs; their webhook secret verifies their events) and Stripe
  Connect (OAuth, direct charges on the connected account with no fee and no
  transfer; off until OD-9: all three MINT_STRIPE_CONNECT_* or nothing).
  Credentials sealed with AES-256-GCM (ring, already in the lock), bound to
  the seller so a sealed value cannot move to another row.
- mint-server/src/seller.rs: POST /mint/v1/sellers/{seller}/connect (a one-
  time, 15-minute link), GET seller, products (create, list),
  checkout-sessions, entitlements; the processor webhooks
  (/mint/webhooks/seller/{product}/{seller}/dodo, /mint/webhooks/stripe-connect)
  become entitlement.granted / entitlement.revoked (refund, dispute,
  cancelled, expired), recorded once per provider event and delivered
  Standard Webhooks signed to the calling product with backoff. Product keys
  in MINT_SELLER_PRODUCTS_JSON keep callers apart; an event whose metadata
  names another seller changes nothing.
- seller_page.rs: the connect page, the only place a key is typed; the
  default screen has no key field (Stripe is a button, Dodo keys sit under
  Advanced, closed); no scripts; strict CSP.
- Invariant: no ledger handle anywhere in seller payments; the test runs a
  sale through the served router and finds no journal entry and no account.
- Storage: mint-store SellerStore + MemorySellerStore; Postgres PgSeller and
  migration 0014_seller_payments (idempotent).

Tests: mint-payments 84 (seller 8), mint-server 18 lib + seller 3 + the rest
green, mint-store green, live PG seller + mirror 2/2 on a scratch cluster with
0001-0014 applied; clippy clean on the new files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 01:11:06 +03:00

287 lines
16 KiB
Markdown

# 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:
```bash
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:
```bash
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.
```bash
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:
```bash
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](../../docs/mint/PLAN.md)** — architecture, crates, phases, invariants, product surfaces.
- **[docs/mint/AITP-402-SPEC.md](../../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](../../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).
## Portfolio mirror (Wave P PY1.5)
Scribase, Menivor and Rally record every paid event their payment provider
sent them: `POST /v1/mirror/events` `{provider, provider_event_id, kind:
payment|refund|dispute, amount_micros, currency, customer_ref,
occurred_at_ms}` with `x-api-key` set to that product's mirror key. A replay of
the same provider event is answered `200 {duplicate: true}` and changes
nothing; `GET /v1/mirror/events` lists only the calling product's records.
Mirror records live beside the ledger (`mint_mirror_events`, migration 0013)
and the mirror has no handle on it: no balance moves, no funds are held, and
Mint never starts a payout of anyone's money here.
Each record is delivered to every configured endpoint as a Standard Webhooks
signed `mirror.recorded` event (the outbox `mint_mirror_deliveries`), every 15
seconds, retried with backoff from 30 s up to 6 h until a 2xx.
| Env | What |
|---|---|
| `MINT_MIRROR_KEYS_JSON` | `[{"product":"scribase","key":"<24+ chars>"}, ...]` (secret) |
| `MINT_EVENT_WEBHOOKS_JSON` | `[{"name","url":"https://...","secret":"whsec_...","products":["scribase"]}]` (secret) |
| `MINT_SELLER_PRODUCTS_JSON` | Seller-own payments (Wave P PY2.3): `[{"product":"scribase","key":"<24+ chars>","webhook_url":"https://...","webhook_secret":"whsec_..."}]`, one entry per calling product (secret) |
| `MINT_SELLER_SEAL_KEY` | base64 of 32 random bytes; seals each seller's payment key at rest (secret). Unset: seller payments answer 503 |
| `MINT_PUBLIC_URL` | Mint's public base, for connect links and the webhook address a seller pastes in their Dodo dashboard |
| `MINT_STRIPE_CONNECT_CLIENT_ID`, `MINT_STRIPE_PLATFORM_SECRET_KEY`, `MINT_STRIPE_CONNECT_WEBHOOK_SECRET` | Stripe Connect for sellers, only once owner decision OD-9 allows it; all three or it stays off (secrets) |