Paid, hosted product at menivor.com, now retired as a company project. Fresh squashed history of the cleaned working tree (secret-scanned, no .env, no customer data, no outreach logs). Built on MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
14 KiB
apps/mint — Implementation plan (deep)
Third Mint doc.
PLAN.md= architecture/phases;AITP-402-SPEC.md= wire protocol; this = the build-grade detail: schema, per-phase task lists, wallet integration/migration, reserve reconciliation, fee economics, threat model, compliance tiers, reconciliation/SLOs, and the conformance suite.
1. Postgres schema (append-only core)
Neon/Postgres. The journal is truth; balances are cached projections
rebuildable from it. Amounts are BIGINT microdollars (µ$), 1 AIT = 1e6 µ$.
-- Accounts & keys ------------------------------------------------------------
create table accounts (
id text primary key, -- acct_01J… (ULID)
kind smallint not null, -- 0 user 1 org 2 agent 3 provider 4 model 5 treasury
owner_ref text, -- external owner (user id, model slug…)
status smallint not null default 0, -- 0 active 1 frozen 2 closed
created_at timestamptz not null default now()
);
create table account_keys (
id text primary key, -- key_…
account_id text not null references accounts(id),
pubkey bytea not null, -- ed25519 public key
custody smallint not null, -- 0 platform(KMS) 1 self
revoked_at timestamptz
);
create table addresses (
address text primary key, -- ait1…
account_id text not null references accounts(id),
purpose text,
created_at timestamptz not null default now()
);
-- The journal: append-only, double-entry -------------------------------------
create table journal (
seq bigserial primary key, -- global monotonic
op text not null, -- transfer|hold.create|hold.capture|…
op_hash bytea not null,
idem_key text not null,
account_id text not null references accounts(id),
counter_id text references accounts(id), -- other side (nullable for mint/redeem→reserve)
delta_micros bigint not null, -- signed; Σ over an op == 0 (incl. reserve)
ref text, -- hold_id/stream_id/resource
ts timestamptz not null default now()
);
create unique index journal_idem on journal (idem_key); -- idempotency
create index journal_acct on journal (account_id, seq);
-- Projections (rebuildable) --------------------------------------------------
create table balances (
account_id text primary key references accounts(id),
available_micros bigint not null default 0, -- spendable
held_micros bigint not null default 0, -- reserved by open holds/streams
updated_seq bigint not null default 0
);
-- Holds / streams / allowances ----------------------------------------------
create table holds (
id text primary key, account_id text not null, amount_micros bigint not null,
captured_micros bigint not null default 0, status smallint not null, ref text,
created_at timestamptz not null default now(), closed_at timestamptz );
create table streams (
id text primary key, from_id text not null, to_id text not null,
rate_micros bigint not null, unit text not null, cap_micros bigint not null,
settled_micros bigint not null default 0, last_seq bigint not null default 0,
status smallint not null, created_at timestamptz not null default now() );
create table allowances (
id text primary key, account_id text not null, key_id text not null,
limit_micros bigint not null, spent_micros bigint not null default 0,
window_start timestamptz, window_secs int, scope jsonb, revoked_at timestamptz );
-- Receipts: hash-linked, per account ----------------------------------------
create table receipts (
account_id text not null, seq bigint not null, -- per-account seq
journal_seq bigint not null references journal(seq),
balance_after_micros bigint not null,
prev_hash bytea not null, hash bytea not null, sig bytea not null,
ts timestamptz not null default now(),
primary key (account_id, seq) );
-- Reserve & ramps ------------------------------------------------------------
create table reserve_ledger (
seq bigserial primary key, kind text not null, -- deposit|payout|adjust|chargeback
amount_micros bigint not null, source text, -- stripe:pi_…|web3:0x…
journal_seq bigint, ts timestamptz not null default now() );
create table deposits (
id text primary key, source text not null, external_ref text unique not null,
amount_micros bigint not null, fx_note text, account_id text not null,
minted_journal_seq bigint, status smallint not null );
-- Replay protection ----------------------------------------------------------
create table nonces ( account_id text, nonce text, expiry timestamptz,
primary key (account_id, nonce) );
Append-only guarantee: journal, receipts, reserve_ledger get no
UPDATE/DELETE grants for the app role; corrections are compensating entries.
2. Per-phase task breakdown (AP0 → AP6)
Each phase = its own recon→design→build→review→fix workflow, TDD, gate must pass.
AP0 — Ledger core
mint-core:Micros(i64)newtype (checked add/sub, no float),AccountId,Address(bech32 encode/decode + checksum), error enum.mint-store: schema migrations; append-only journal writer; balance projector (apply on write + rebuild-from-journal); 2-account lock ordering.mint-ledger:transfer, account/address create, balance read.- Property tests: 1M random transfers → conservation, double-entry, non-negative.
- Gate: rebuild balances from journal == live projection, bit-exact.
AP1 — Holds & success-only
hold.create/capture/release, idempotency,capture ≤ held, partial capture releases remainder. Streams deferred.- Gate: fault-injection matrix (crash between capture and receipt, double capture, release-after-capture) never violates invariants; failure never captures.
AP2 — Receipts & verifiability
mint-receipts: per-account hash chain (prev_hash), server signature, merkle root job,/receipts/audit,/reserveproof, offline verifier lib.- Gate: any mutation to a historical row is detected by chain + merkle.
AP3 — AITP-402 + allowances
mint-protocol: challenge/authorize/verify, nonce store, expiry, replay reject.allowance.grant/spend; per-key velocity limits.- Gate: conformance vectors (§9) pass; an agent completes an
aitp-holdpaid call with capture-on-success and release-on-failure.
AP4 — Streams + reserve/mint/redeem
mint-stream: open/tick/close metered settlement, monotonic seq, cap.mint-reserve:mint(deposit-gated),redeem(KYC/limit-gated), Stripe +relay-web3bridge; chargeback/refund compensating flow.- Gate: mint/redeem/stream storm keeps
Σ balances + Σ holds == reserve.
AP5 — Clients & unify
mint-sdk(Rust + generated Python). Wirerelay-billingandapps/apiwallet to settle via Mint holds/captures (dual-write → cutover, §3).- Gate: a ReelForge render and a Relay completion both settle through Mint; legacy ledger and Mint agree to the µ$.
AP6 — Governance/GA
- Orgs/treasuries, team budgets, dispute/refund console, sanctions screening, OTel dashboards, solvency status page, blue-green, load/chaos.
- Gate: SLOs green (§8); chaos suite zero invariant violations.
3. Integration & migration (wrap → dual-write → cutover)
Existing money surfaces (apps/api microdollar wallet, gateway provisioning,
relay-billing) become Mint clients without a big-bang rewrite:
- Wrap: create a Mint
accountper existing wallet; import current balance as amintagainst a migration reserve entry (reconciled to real backing). - Dual-write: each existing debit ALSO issues a Mint
hold→capture. A nightly reconciler asserts legacy balance == Mint available; alerts on drift. Legacy stays authoritative during this window. - Cutover: once drift == 0 for N days, flip authority to Mint; legacy ledger
becomes read-only history.
relay-billingand the ReelForge wallet callmint-sdkdirectly (holdat job start,captureonCOMPLETED,releaseon failure — success-only is now native).
Client SDK surface (both langs): create_hold(account, amount, ref),
capture(hold, actual), release(hold), transfer(from,to,amount),
open_stream(...), spend_allowance(...), verify_aitp(auth). Injectable
transport (fake in tests) — same discipline as the Python provider adapters.
4. Reserve, treasury & ramp reconciliation
- Mint only on confirmed deposit: Stripe
payment_intent.succeeded(webhook, idempotent onexternal_ref) or a confirmed crypto deposit fromrelay-web3→depositsrow →mintop crediting the user + areserve_ledger.deposit. - Refund / chargeback: compensating
reserve_ledger.chargeback+ a clawback transfer (or negative-balance freeze if already spent → collections path). Never edit history. - Redeem/payout:
redeemburns AIT,reserve_ledger.payout, off-ramp via Stripe Connect / crypto; gated by KYC tier + daily/rolling limits. - Float invariant (continuously checked):
reserve_backing (bank+processor+crypto) ≥ Σ outstanding AIT. Alarm if the cushion drops below a configurable buffer. - Money never created except via
mint; everymint/redeemmoves reserve in lockstep so §6.1 conservation holds by construction.
5. Fee economics (exact µ$ math)
Let provider_cost = upstream µ$ for a call, markup_bps, byok_fee_bps,
creator_bps (revenue share to a model/provider payout address).
- Platform-credit call (we pay upstream):
charge = provider_cost + ceil(provider_cost × markup_bps / 10_000)→ split: provider_cost → cost-of-goods; markup → platform treasury;creator_split = floor(charge × creator_bps / 10_000)→ model author address. - BYOK call (user's own upstream key): upstream billed to the user directly;
Mint charges only
ceil(list_price × byok_fee_bps / 10_000)platform fee. - Rounding: always integer µ$; round the platform's take toward the platform by ≤1 µ$ (documented), never overcharge the user beyond the ceil rule.
- All splits are journal transfers → auditable, and creator payouts settle to
an
ait1…4model address (ties into ReelForge clipmarket CPM + Relay model revenue share — one payout rail).
6. Threat model & key custody
| Threat | Control |
|---|---|
| Double-spend / race | per-account serialized apply (ordered seq), row locks, available_micros check in the same tx |
| Replay | single-use nonces (kept until expiry) + idem_key unique index |
| Forged authorization | ed25519 verify vs registered account_keys.pubkey; expiry window |
| Insider ledger tampering | append-only grants (no UPDATE/DELETE), hash-linked receipts, merkle root published, external anchor optional |
| Key theft (platform custody) | signing keys in KMS/HSM, envelope-encrypted, never in app memory beyond a signing call; per-account key rotation |
| Account takeover | freeze status halts debits; velocity limits; step-up on redeem |
| Reserve drain | mint gated on confirmed deposit only; float alarm; redeem KYC/limits |
| Negative balance via concurrency | balance check + hold reservation atomic in the apply tx |
| Idempotency conflict | same idem_key different body → 409 idempotency_conflict |
Custody default = platform-managed (KMS); self-custody keys optional for agents/enterprises that sign client-side.
7. Compliance tiers
- Legal posture: AIT is a closed-loop, prepaid, 1:1-redeemable credit — positioned to fall under closed-loop/limited-purpose exemptions, not a security or a money-transmission product. Confirm per jurisdiction with counsel before GA (this doc is not legal advice).
- KYC tiers: T0 spend-only (no payout); T1 email+card (low payout cap); T2 full KYC (higher caps, creator payouts, redeem). Sanctions/PEP screening on every payout address; block on hit.
- Tax: creator/model-author payouts tracked for 1099/DAC7-style reporting; redeem records retained.
- Data: ledger retained (financial record); PII minimized; per-key ZDR flags respected for inference content (a Relay concern, not the ledger).
8. Observability, reconciliation & SLOs
- Metrics (OTel): apply-latency p50/p99, journal write TPS, projection lag, hold open→capture time, verify() latency, mint/redeem volume, float cushion, drift (legacy vs Mint) during dual-write.
- Recon jobs: (a) balance-from-journal rebuild vs projection (hourly);
(b)
Σ balances+holdsvs reserve (continuous); (c) receipt chain integrity + merkle root (per epoch); (d) legacy↔Mint drift (nightly, dual-write phase). - SLOs: apply p99 < 10 ms · verify p99 < 15 ms · projection lag < 1 s · zero conservation/chain violations (page immediately) · float cushion ≥ buffer.
9. Conformance & property suite
- AITP-402 test vectors (
mint-testkitgolden files): canonical challenge → authorization → verify, including: happy transfer, happy hold+capture, hold+release-on-failure, expired auth, replayed nonce, bad signature, allowance exceeded, idempotent retry. Any client (Rust/Python/agent) runs the vectors to claim compliance. - Property tests: random op storms preserve conservation, double-entry,
non-negativity,
capture ≤ held, stream monotonicity, chain integrity. - Chaos: kill mid-apply / mid-capture / mid-mint; partition the store; assert exactly-once via idem keys and no invariant breakage on recovery.
10. Open decisions (need a call before / during build)
- Custody default — platform-KMS only at launch, or offer self-custody keys
for agents in AP3? (Affects
account_keys.custody+ signing path.) - Address encoding — bech32
ait1…(chosen here) vs opaque ULID handle. Bech32 gives the web3 feel + checksum; confirm. - Merkle anchoring — internal merkle root only, or optionally anchor the periodic root to a public chain / RFC-3161 timestamp for external tamper-proof?
- Redeem rails — Stripe Connect payout, crypto off-ramp, or both; and the KYC-tier caps.
- Fee defaults — launch
markup_bps,byok_fee_bps,creator_bpsvalues. - Multi-currency display — µ$ ledger is USD; show localized currency at UI via FX, or keep USD-only pre-GA?